int main (int argc,char **argv) {
    if(argc==1){
        showhelp();
        return 0;
    }
    
    threshold=0;
    int c;
    char* label_trans=NULL;
    char* label_lists_file=NULL;
    while ( (c = getopt(argc, argv, "t:sh")) != -1) {
        switch (c) {
            case 't' : ///output word lattice
                threshold = atoi(optarg)*1000;
                break;
            case 's':///输出lattice之前输出原句
                sl_decoder_show_sentence=1;
                break;
            case 'h' :
            case '?' : 
            default : 
                showhelp();
                return 1;
        }
    }
    init(argv[optind],argv[optind+1],argv[optind+2]);
    read_stream();
    return 0;
}
Beispiel #2
0
int main(int argc, char **argv) {
	int c, lstate;
	pid_t pid;
	while ((c = getopt(argc, argv, OPTSTR)) != EOF) {
		switch(c) {
			case 'e':
				proggie = malloc(strlen(optarg) + 1);
				if (!proggie) {
					perror("Malloc");
					exit(0);
				}
				strncpy(proggie, optarg, strlen(optarg));
				break;
			case 'd':
				sdevice = malloc(strlen(optarg) + 1);
				if (!sdevice) {
					perror("Malloc");
					exit(0);
				}
				strncpy (sdevice, optarg, strlen(optarg));
				break;
			case 's':
				if (*optarg != 'H' && *optarg != 'h' 
				&& *optarg != 'T' && *optarg != 't') {
					fprintf(stderr,"-s: opção inválida\n\n");
					showhelp();
				} else enab = optarg[0];
				if (enab == 't' || enab == 'T') {
					init_state = VERM;
				}
				break;
			case 'h':
			default:
				showhelp();
				break;
		}
	}
	if (DEBUG) 
		fprintf(stderr,"Porta: %s Programa: %s Status %c \n", sdevice, proggie, enab);
	b_opendev(sdevice); /* Abre a porta serial e inicializa o dispositivo */

#ifdef DAEMON
	if ((pid = fork()) < 0) {
		perror("fork");
		exit(1);
	} else {
		exit(0);			
	}
#endif
	while (1) {				// Loop principal
		if (getpushbutton()) {
			system(proggie);
		}
		usleep(TEMPO);
	}
}
Beispiel #3
0
int main(int argc, char *argv[])
{
	char *cp;
	struct DayDream_Message ddm;
	char ebuf[1024];
	
	while (--argc) {
	cp = *++argv;
		if (*cp == '-') {
			while( *++cp) {
				switch(*cp) {
				case 'p':
					private=1; break;
				case 'r':
					if (--argc < 1) {
						showhelp();
						exit(1);
					}
					receiver=*++argv;
					break;
				case 'f':
					if (--argc < 1) {
						showhelp();
						exit(1);
					}
					author=*++argv;
					break;
				case 's':
					if (--argc < 1) {
						showhelp();
						exit(1);
					}
					subject=*++argv;
					break;
				case 'c':
					if (--argc < 1) {
						showhelp();
						exit(1);
					}
					dconf=atoi(*++argv);
					break;
				case 'b':
					if (--argc < 1) {
						showhelp();
						exit(1);
					}
					dbase=atoi(*++argv);
					break;
				}
				
			}
		} else {
			mfile=cp;
		}	
	}
Beispiel #4
0
void handleoptions(const std::vector<std::string> &options, bool &startup)
{
	Option option;
	std::string val("");

	for(std::vector<std::string>::const_iterator i=options.begin(); i!=options.end(); i++)
	{
		std::string::size_type pos=(*i).find("=");
		if((*i).size()>3 && (*i).substr(0,2)=="--" && pos!=std::string::npos)
		{
			if(option.Get((*i).substr(2,pos-2),val)==true)
			{
				option.Set((*i).substr(2,pos-2),(*i).substr(pos+1));
				startup=false;
			}
		}
		else
		{
			if((*i)=="--help" || (*i)=="-?" || (*i)=="/?")
			{
				showhelp();
				startup=false;
			}
			if((*i)=="--daemon")
			{
				Daemonize();
				global::daemon=true;
			}
		}
	}
}
Beispiel #5
0
//
// main:
int main(int argc, char *argv[])
{
	printf("Commander is a command line parsing module writed by L. Maddalena\n");

	t_commander *cmd = makecommander();
	addparam(cmd, "source");
	addparam(cmd, "destination");
	addoption(cmd, "f", "foo", "the foo parameter", 0, "value");
	addoption(cmd, "g", "gas", "the gas parameter", 0, NULL);
	addoption(cmd, "b", "bar", "the bar parameter", 1, "1|2|3");
	addoption(cmd, "z", "baz", "the baz parameter", 1, "name");
	addoption(cmd, "h", "help", "output usage information", 0, NULL);

	int p = parseargs(cmd, argc, argv);
	
	if(argc == 1)
	{
		showusage(argv[0], cmd);
		return 0;		
	}

	if(p == 0 || strcmp(getoptionbysname("h", cmd)->value, "1") == 0)
	{
		showhelp(argv[0], cmd);
		return 0;		
	}
	
	showreport(cmd);
}
Beispiel #6
0
char startname[65] =  "\x20\x8\DEMONSTRATION VERSION";


/* FUNCTIONS */


void demo()
{
static char *demotext =
"   This is a demonstration version of the Options Analyst.\n"
"In this version you may not save or recall positions to\n"
"disk or alter the stockprice. In the full version, of \n"
"course, there is no such restriction.\n"
"\n"
"   Please make un-altered copies of this program and\n"
"distribute them. This version, however, may be used for \n"
"NON-COMMERCIAL purposes only and remains the property \n"
"of EFAM RESOURCES\n"
"\n"
"   TO BUY YOUR COPY CONTACT : IS2 Pty. Ltd.\n"
"PO. BOX  H37 Australia Square Sydney, N.S.W. 2000.\n"
"Telephone (02) 27 4686  Fax: 27 5898\n"
"                                           PRESS ANY KEY";

showhelp("DEMONSTRATION VERSION",demotext);
}
Beispiel #7
0
void runhelp(const char *filename)
{
   char dp;
   char fullname[HELPDIRLEN+16];

   dp = getdisppage();
   if (dp != HELPPAGE) setdisppage(HELPPAGE);
   cursoroff();
   if (helpbasedir[0] != 0) {
      strcpy(fullname,helpbasedir);
      strcat(fullname,"/");
      strcat(fullname,filename);
      showhelp(fullname);
   }
   else showhelp (filename); // Assume filename is absolute
   if (dp != HELPPAGE) setdisppage(dp);
}
Beispiel #8
0
/**
 * Get index of current option in array options
 * @param opt (i) - returning val of getopt_long
 * @param options (i) - array of options
 * @return index in array
 */
int get_optind(int opt, myoption *options){
	int oind;
	myoption *opts = options;
	assert(opts);
	for(oind = 0; opts->name && opts->val != opt; oind++, opts++);
	if(!opts->name || opts->val != opt) // no such parameter
	showhelp(-1, options);
	return oind;
}
Beispiel #9
0
void main()
{
   int ch,ch1,ch2,ch3;
   fm=fopen("member.dat","a+");
   ft=fopen("trans.dat","a+");
   fb=fopen("book.dat","a+");

   mainscr();

   while(1)
   {
    bk:
    showmenu(mainmenu,5,10,35);
    ch=getchoice(mainmenu,"MBRHE",10,35,5);
   switch(ch)
   {
    case 1:bk1:
	   showmenu(memmenu,4,10,35);
	   ch1=getchoice(memmenu,"ARIB",10,35,4);
	   switch(ch1)
	   {
	     case 1: addmember(); goto bk1;
	     case 2: renewmem();  goto bk1;
	     case 3: memdupid();  goto bk1;
	     case 4: goto bk;
	   }
	   break;
    case 2:bk2:
	   showmenu(bookmenu,4,10,35);
	   ch2=getchoice(bookmenu,"AIRB",10,35,4);
	   switch(ch2)
	   {
	     case 1: addbook(); goto bk2;
	     case 2: issbook(); goto bk2;
	     case 3: retbook(); goto bk2;
	     case 4: goto bk;
	   }
	   break;
    case 3:bk3:
	   showmenu(rptmenu,4,10,35);
	   ch3=getchoice(rptmenu,"MBTB",10,35,4);
	   switch(ch3)
	   {
	     case 1: allmem(); goto bk3;
	     case 2: allbook();goto bk3;
	     case 3: alltransac();goto bk3;
	     case 4: goto bk;
	   }
	   break;
    case 4:
	   showhelp(); break;
    case 5:fclose(ft); fclose(fm); fclose(fb);
	   exit();
   }
  }
}
Beispiel #10
0
/**
 * Parse command line options and return dynamically allocated structure
 *      to global parameters
 * @param argc - copy of argc from main
 * @param argv - copy of argv from main
 * @return allocated structure with global parameters
 */
glob_pars *parse_args(int argc, char **argv){
    void *ptr;
    ptr = memcpy(&G, &Gdefault, sizeof(G)); assert(ptr);
    // format of help: "Usage: progname [args]\n"
    change_helpstring("Usage: %s [args]\n\n\tWhere args are:\n");
    // parse arguments
    parseargs(&argc, &argv, cmdlnopts);
    if(help || argc > 0) showhelp(-1, cmdlnopts);
    return &G;
}
Beispiel #11
0
bool ParseCommandLine(int argc,wchar* argv[])
{

	int cl=argc-2;
	wchar** arg=argv+1;
	while(cl>=0)
	{
		if (stricmp(*arg,"-help")==0)
		{
			int as=showhelp(arg,cl);
			cl-=as;
			arg+=as;
			return true;
		}
		else if (stricmp(*arg,"-config")==0)
		{
			int as=setconfig(arg,cl);
			cl-=as;
			arg+=as;
		}
		else if (stricmp(*arg,"-configfile")==0)
		{
			int as=setconfigfile(arg,cl);
			cl-=as;
			arg+=as;
		}
/*gli		else if (stricmp(*arg,"-slave")==0)
		{
			int as=slave_cmdl(arg,cl);
			cl-=as;
			arg+=as;
		}
		else if (stricmp(*arg,"-serial")==0)
		{
			int as=serial_cmdl(arg,cl);
			cl-=as;
			arg+=as;
		}*/
		else if (stricmp(*arg,"-about")==0)
		{
			printf("nullDC, a Sega Dreamcast Emulator.Made by the nullDC team -- www.emudev.com/nullDC\n");
			printf("Version : " VER_FULLNAME " \n");
			
			return true;
		}
		else
		{
			printf("wtf %s is suposed to do ?\n",*arg);
		}
		arg++;
		cl--;
	}
	printf("\n");
	return false;
}
Beispiel #12
0
bool ParseCommandLine(int argc,wchar* argv[])
{
	int cl=argc-2;
	wchar** arg=argv+1;
	while(cl>=0)
	{
		if (stricmp(*arg,"-help")==0 || stricmp(*arg,"--help")==0)
		{
			showhelp(arg,cl);
			return true;
		}
		if (stricmp(*arg,"-version")==0 || stricmp(*arg,"--version")==0)
		{
			showversion(arg,cl);
			return true;
		}
		else if (stricmp(*arg,"-config")==0 || stricmp(*arg,"--config")==0)
		{
			int as=setconfig(arg,cl);
			cl-=as;
			arg+=as;
		}
		else
		{
			char* extension = strrchr(*arg, '.');

			if (extension
				&& (stricmp(extension, ".cdi") == 0 || stricmp(extension, ".chd") == 0
					|| stricmp(extension, ".gdi") == 0 || stricmp(extension, ".lst") == 0))
			{
				printf("Using '%s' as cd image\n", *arg);
				cfgSetVirtual("config", "image", *arg);
			}
			else if (extension && stricmp(extension, ".elf") == 0)
			{
				printf("Using '%s' as reios elf file\n", *arg);
				cfgSetVirtual("config", "reios.enabled", "1");
				cfgSetVirtual("reios", "ElfFile", *arg);
			}
			else
			{
				printf("wtf %s is supposed to do ?\n",*arg);
			}
		}
		arg++;
		cl--;
	}
	printf("\n");
	return false;
}
Beispiel #13
0
void copyright(void)
{
char *text =
"\n"
"\n"
"                           The\n\n"
"                     OPTIONS ANALYST\n"
"\n\n\n\n"
"                    Copyright (c) 1988\n"
"                 EFAM RESOURCES Pty. Ltd.\n"
"                   All Rights Reserved\n\n"
"  Press Any Key";
showhelp("Version 1.0",text);
}
Beispiel #14
0
static void parse_options(int argc,char *argv[]) {
   int i = 1;
   while (i < argc)
	 {
		/* Help? */
		if (strcmp (argv[i],"-h") == 0)
		  showhelp ();
		/* Level? */
		else if (strcmp (argv[i],"-l") == 0)
		  {
			 i++;
			 if (i >= argc || !str2int (&level,argv[i])) showhelp ();
			 if ((level < MINLEVEL) || (level > MAXLEVEL))
			   {
				  fprintf (stderr,"You must specify a level between %d and %d\n",MINLEVEL,MAXLEVEL);
				  exit (EXIT_FAILURE);
			   }
		  }
		/* Show next? */
		else if (strcmp (argv[i],"-n") == 0)
		  shownext = TRUE;
		else if(strcmp(argv[i],"-d")==0)
		  dottedlines = TRUE;
		else if(strcmp(argv[i], "-b")==0)
		  {
		    i++;
		    if (i >= argc || strlen(argv[i]) < 1) showhelp();
		    blockchar = argv[i][0];
		  }
		else
		  {
			 fprintf (stderr,"Invalid option -- %s\n",argv[i]);
			 showhelp ();
		  }
		i++;
	 }
}
Beispiel #15
0
int
main(int argc, char *argv[])
{
	if (argc != 4 || argv[1][0] != '-' || strlen(argv[1]) != 2)
		{
			showhelp();
			return -1;
		}

	switch (argv[1][1])
		{
			case 'p':
				pack(argv[2], argv[3]);
				break;
			case 'u':
				unpack(argv[2], argv[3]);
				break;
			default:
				showhelp();
				return -1;
		}

	return 0;
}
Beispiel #16
0
int main(int argc, TCHAR * argv[])
{	
	TCHAR pwd[MAX_PATH];
	GetCurrentDirectory(MAX_PATH,pwd);
	vector<string> filesList;
	vector<MemoryStruct> responseList;
	bool success = setupvars(argc,argv);
	
	if (success)
	{
		url  = url + "?username="******"&password="******"&subfolder=" + folder;
		string absFilePath = PathUtil::FullPath(filePattern.c_str()).c_str();		
		
		string targetDir = PathUtil::GetPath(absFilePath.c_str());

		filePattern = absFilePath;

		StringUtil::Replace(filePattern,targetDir,"");
		CUtil::GetFileList(targetDir,filePattern,false,filesList);

		if (filesList.size()<1)
		{
			cout<<"No files to upload."<<endl;
			return 1;
		}

		for(int i=0; i<filesList.size();i++)
		{
			const char* thisFile = filesList.at(i).c_str();
			
			MemoryStruct response = FileUpload::Upload(
				url.c_str(),
				thisFile
				);

			responseList.push_back(response);
			cout << response.memory <<endl;						
		}
		
		return 0;

	}else{

		cout<< "Invalid paramter(s)!"<<endl<<endl;
		showhelp();
		return 1;
	}
}
Beispiel #17
0
void demo1()
{
static char *demo1text =
"   This Function allows tables of values to printed. An   \n"
"initial stockprice is entered, and a stockprice increment.\n"
"These tables show the value of the options for either 5 or\n"
"10 shareprices. This function is useful if you are going\n"
"somewhere where you do not have access to a computer.\n"
"\n"
"   Please make un-altered copies of this program and\n"
"distribute them. This version, however, may be used for \n"
"NON-COMMERCIAL purposes only and remains the property \n"
"of EFAM RESOURCES\n"
"   TO BUY YOUR COPY CONTACT : IS2 Pty. Ltd.\n"
"PO. BOX  H37 Australia Square Sydney, N.S.W. 2000.\n"
"Telephone (02) 27 4686  Fax: 27 5898\n"
"                                           PRESS ANY KEY";

showhelp("DEMONSTRATION VERSION",demo1text);
}
void
parse(int ac, char **av)
{
    char *pt;

    while (--ac > 0){
	pt = *(++av);
	if (*pt != '-') {
	    fprintf(stderr, "Unknown option(%s). Aborted.\n", *av);
	    exit(1);
	}else{
	    switch(*(++pt)) {
		case 't': 	/* option -t */
		    switch(*(++pt)) {
			case 'M':
			    major++;
			    break;
			case 'm':
			    minor++;
			    break;
			case 'r':
			    release++;
			    break;
			default:
			    fprintf(stderr, "Unknown -v parameter (%s). Aborted.\n", *av);
			    exit(1);
		    }
		    break;
		case 'h':	/* help page */
		    showhelp();
		    exit(0);
		default:
		    fprintf(stderr, "Unknown option(%s). Aborted.\n", *av);
		    exit(1);
	    }
	}
    }
}
Beispiel #19
0
int main(void) {

	int ch;

	initscr();

	if((help = newwin(15,70,4,3)) == NULL) {
		addstr("unable to allocate memory");
		endwin();
		return(1);
	}

	mvwaddstr(help,1,1,"Help Menu Screen");
	mvwaddstr(help,9,28,"Press the ~ key to quit");
	mvwaddstr(help,12,28,"Press ENTER to go back");
	box(help, 0, 0);
	refresh();
	noecho();

	do {

		ch = getch();
		refresh();
		
		if(ch == '+') {
			showhelp();
		} else { 
			addch(ch);
		}




	} while (ch != '~');
	endwin();
	return 0;
}
Beispiel #20
0
void mon_help() { showhelp("monitor_keys"); }
Beispiel #21
0
void main_help() { showhelp(); }
Beispiel #22
0
int main(int eargc, char **eargv) {
	char fname[255];
	char *test;
	
	int unnamed=0,listunnamed=0;
	int i;
	
	char *tok;
	char hopt[255];
	char hargs[255];		

	longbase=102.0;
	latbase=12.0;
	range=40;

// Lets do ARGS

	argc=eargc;
	argv=eargv;
	totalitems=0;
	totalcoords=0;
	skippeditems=0;

	if (argc<2 || Check_Param("-h") || Check_Param("-?")) {
		showhelp();
		exit(0);	
	}

	if (Check_Param("-f")) fileoutput=1;		
	if (Check_Param("-un")) listunnamed=1;
	if (fileoutput) {
		printf("Point E00 to Falcon4 features converter v0.1\n");
		printf("(C)opyright 2000 PMC TFW <*****@*****.**>\n");
		printf("http://tactical.nekromantix.com\n");
		printf("--------------------------------------------------\n");
	}	
	
	test=Get_Next_Option();
	while (test) {
		if (strchr(test,'=')) {
		// fixme: "Do not never ever use strtok" !-)
			rmallws(test);
			tok=strtok(test,"=");
			if(!tok) continue;
			strncpy(hopt,tok,254);
			tok=strtok(NULL,"=");
			if (!tok) continue;
			strncpy(hargs,tok,254);
			if (strncmp(hopt,"-range",6)==0) range=atoi(hargs);
			else if (strncmp(test,"-long",5)==0) longbase=atol(hargs);
			else if (strncmp(test,"-lat",4)==0) latbase=atol(hargs);
		}
		test=Get_Next_Option();
	}	

	test=NULL;

	test=Get_Next_Name();
	if(!test) exit(1);
	strncpy(type,test,254);

	test=Get_Next_Name();	
	if(!test) exit(1);
	strncpy(fname,test,254);

	if (fileoutput) printf("Reading E00 point data from: %s\n",fname);

	readstuffs(fname);

	unnamed=0;
	for (i=0;i<coordcount;i++) {
		if(strlen(coords[i].name)>0)
			printf("%s 1 %d,%d %c %s\n",type,(int)coords[i].x,(int)coords[i].y,coords[i].type,coords[i].name);
		else {
			unnamed++;
			if (listunnamed) printf("%s 1 %d,%d %c %s #%d\n",type,(int)coords[i].x,(int)coords[i].y,coords[i].type,type,i+1);
		}
	}

	if (fileoutput) {
		printf("\nTotal %d items (%d unnamed, skipped)\n",coordcount,unnamed);
		printf("Processing completed\n\n");
	}
	return 0;
}
Beispiel #23
0
short play() {

   short c;
   short ret;
   short undolock = 1;		/* locked for undo */

   showscreen();
   tmpsave();
   ret = 0;
   while( ret == 0) {
      	switch( (c = getch())) {
	 	case 'q':    /* quit the game 					*/
	              ret = E_ENDGAME; 
	              break;
	 	case 's':    /* save the games					*/
		      if( (ret = savegame()) == 0)
			 ret = E_SAVED;
		      break;
	 	case '?':    /* show the help file				*/
		      showhelp();
		      showscreen();
		      break;
	 	case CNTL_R: /* refresh the screen 				*/
		      clear();
		      showscreen();
		      break;
	 	case 'c':    /* temporary save					*/
		      tmpsave();
		      break;
	 	case CNTL_U: /* reset to temporary save 			*/
		      tmpreset();
		      undolock = 1;
		      showscreen();
		      break;
	 	case 'U':    /* undo this level 				*/
		      moves = pushes = 0;
		      if( (ret = readscreen()) == 0) {
		         showscreen();
			 undolock = 1;
		      }
		      break;
	 	case 'u':    /* undo last move 				*/
		      if( ! undolock) {
		         undomove();
		         undolock = 1;
		      }
		      break;
	 	case 'k':    /* up 						*/
	 	case 'K':    /* run up 					*/
	 	case CNTL_K: /* run up, stop before object 			*/
	 	case 'j':    /* down 						*/
	 	case 'J':    /* run down 					*/
	 	case CNTL_J: /* run down, stop before object 			*/
	 	case 'l':    /* right 						*/
	 	case 'L':    /* run right 					*/
	 	case CNTL_L: /* run right, stop before object 			*/
	 	case 'h':    /* left 						*/
	 	case 'H':    /* run left 					*/
	 	case CNTL_H: /* run left, stop before object 			*/
		      do {
		         if( (action = testmove( c)) != 0) {
				    lastaction = action;
		            lastppos.x = ppos.x; lastppos.y = ppos.y;
		            lppc = map[ppos.x][ppos.y];
		            lasttpos1.x = tpos1.x; lasttpos1.y = tpos1.y; 
		            ltp1c = map[tpos1.x][tpos1.y];
		            lasttpos2.x = tpos2.x; lasttpos2.y = tpos2.y; 
		            ltp2c = map[tpos2.x][tpos2.y];
		            domove( lastaction); 
		            undolock = 0;
		         }
		      } while( (action != 0) && (! islower( c))
			      && (packets != savepack));
		      break;
	 	default:     helpmessage(); break;
     }
     if( (ret == 0) && (packets == savepack)) {
		 scorelevel = level;
		 scoremoves = moves;
		 scorepushes = pushes;
		 break;
     }
   }
   return( ret);
}
Beispiel #24
0
int main(int argc,char *argv[])
{
  char **files; // Actual file list to work on (stored by findfile loop)
  unsigned short filesnum=0; // Number of strings stored in files array
  unsigned short filesmax=-1; // Max number of files allowed in files array
  unsigned long filelen; // Storage for length of BSP file
  unsigned long year=1970+(time(0)/31536000); // Current year
  struct _finddata_t fd; // Used for findfile
  struct param *param; // Parameter list
  char *arg; // Argument
  char *entbuf; // Entity script storage
  char drive[_MAX_DRIVE]; // Used for building full path name for files
  char dir[_MAX_DIR]; // Used for building full path name for files
  char path[_MAX_PATH]; // Used for building full path name for files
  int index; // Index, multiple uses
  int handle; // Handle for findfile
  int changes; // Number of changes to BSP file that was made
  int filesmodified; // Number of files modified
  int filestotal; // Total files processed
  int fileserrors; // Files with problems
  int fileschanges; // Total changes in all flies
  BSPHEADER hdr; // Header of BSP file
  FILE *hin=0; // BSP file stream

  if(year<2005) // For dodgy clocks :-)
    year=2005;

  printf("EntWiz/%u.%02u (%u-Bit) by MS-Design, Compiled %s\n" // Show info
         "\n",vermaj,vermin,addrlen*8,verdate,year);

  fileschanges=fileserrors=filesmodified=filestotal=0; // Zero stuff

  if(argc==1) // Nothing specified so show help
    return showhelp(*argv);

  for(index=1;index<argc;index++) // Process each command line parameter
  {
    arg=argv[index]; // Set alias

    if(*arg=='/') // Is command switch
    {
      *arg++; // Remove forwardslash

      param=params; // Alias the allowable commands structure

      while(param->name) // Walk through the allowable commands list
      {
        if(strcmp(param->name,arg)) // Compare
        {
          param++;
          continue;
        }
        if(index+param->num+1>argc) // Check if we have enough parameters
        {
          changes=param->num-(argc-(index+param->num-1));
          printf("Need %u more paramete%s for '%s' option\n",changes,changes==1?"r":"rs",arg);
          return 1;
        }
        if(commandsnum==commandsmax) // Make sure we dont go over the limit
        {
          printf("Commands limit of %u reached\n",commandsmax);
          return 1;
        }

        // (Re)allocate address space for commands structure array

        if(!(commands=commandsnum?realloc(commands,(commandsnum+1)*addrlen):malloc(addrlen)))
        {
          printf("Can't (re)alloc %u bytes of address space for commands structure\n",(commandsnum+1)*addrlen);
          return 1;
        }
        if(!(commands[commandsnum]=malloc(sizeof(SCOMMAND)))) // Alloc structure
        {
          printf("Can't allocate %u bytes of memory for command strucutre\n",sizeof(SCOMMAND));
          return 1;
        }

        if(param->num>=1&&verifypattern(index+1,argv[index+1]))
          return 1;
        if(param->num>=2&&verifypattern(index+2,argv[index+2]))
          return 1;
        if(param->num>=3&&verifypattern(index+3,argv[index+3]))
          return 1;

        command=commands[commandsnum++]; // Set alias for structure in array
        command->id=param->id; // Set command and inc num commands
        command->x=command->y=command->z=0; // Nullify X, Y and Z

        if(param->num>=1) // Set X (No need to alloc just alias from argv)
          command->x=argv[index+1];
        if(param->num>=2) // Set Y
          command->y=argv[index+2];
        if(param->num>=3) // Set Z
          command->z=argv[index+3];

        index+=param->num; // Increment index so we dont parse the same stuff

        param++; // Goto the next item in commands structure array;

        *arg=0; // We got a match so make sure to goto the next parameter
        break;
      }

      if(!*arg) // Matched a parameter
        continue;

      printf("%s: Unknown parameter\n",arg);
      return 1;
    }
    else
    {
      // It's a filespec so add it to the fspecs array

      if(fspecsnum==fspecsmax) // Make sure we don't go over the limit
      {
        printf("Limit of %u for file specifications exceeded\n",fspecsmax);
        return 1;
      }

      // Allocate address space for fpsec array

      if(!(fspecs=fspecsnum?realloc(fspecs,(fspecsnum+1)*addrlen):malloc(addrlen)))
      {
        printf("Can't (re)alloc %u bytes of address space for fspec array\n",(fspecsnum+1)*addrlen);
        return 1;
      }

      // Alias it (again, don't need to alloc, just use argv)

      fspecs[fspecsnum++]=arg;
    }
  }

  if(!commandsnum&&!fspecsnum) // This shouldnt happen but just incase
    return showhelp(*argv);

  if(!commandsnum) // No commands were specified
  {
    printf("Nothing to do!\n");
    return 1;
  }
  if(!fspecsnum) // No filespecs specified
  {
    printf("No filenames specified to perform commands on\n");
    return 1;
  }
  for(index=0;index<fspecsnum;index++) // Process filespecs
  {
    if((handle=_findfirst(fspecs[index],&fd))==-1) // Find file/files with wildcards
    {
      printf("%s: No matching files, %s\n",fspecs[index],_sys_errlist[errno]);
      continue;
    }

    _splitpath(fspecs[index],drive,dir,0,0); // Want drive & directory from filespec

    do // Process each file
    {
      if(fd.attrib&_A_SUBDIR) // Ignore directories
        continue;

      *path=0; // Make zero length string for building relative path

      strcpy(path,drive); // Copy drive from fspec
      strcat(path,dir); // Copy directory from fspec
      strcat(path,fd.name); // Copy matching filename

      // Ignore read only files

      if(fd.attrib&_A_RDONLY||fd.attrib&_A_SYSTEM||fd.attrib&_A_HIDDEN)
      {
        printf("%s: File is read-only, skipping\n",path);
        continue;
      }
      if(filesnum==filesmax) // Check we dont go over the limit
      {
        printf("Limit of %u for files count exceeded\n",filesmax);
        return 1;
      }

      // (Re)alloc files array

      if(!(files=filesnum?realloc(files,(filesnum+1)*addrlen):malloc(addrlen)))
      {
        printf("Can't (re)alloc %u bytes of address space for files array\n",(filesnum+1)*addrlen);
        return 1;
      }

      // Duplicate string (need to alloc this time)

      if(!(files[filesnum++]=strdup(path)))
      {
        printf("Can't alloc %u bytes of memory for filename string\n",strlen(files[filesnum-1])+1);
        return 1;
      }
    } while(!_findnext(handle,&fd));
  }

  if(!filesnum) // Stop if we found no valid files
  {
    printf("\nNo matching files\n");
    return 1;
  }

  for(index=0;index<filesnum;index++) // Time to walk through each file now
  {
    entbuf=0; // Holds entity script

    if(hin) // If any existing input handle is open (due to error), close it
      fclose(hin);
    if(entbuf) // Free storage buffer if it hasnt been deallocated (due to error)
      free(entbuf);

    filestotal++; // Increment total number of files processed
    fileserrors++; // Increment errors, (decremented on success)

    arg=files[index]; // Alias current filename

    printf("Processing %s... ",arg); // Tell user whats going on

    if(!(hin=fopen(arg,"rb"))) // Open input file
    {
      printf("Open failure, %s!\n",_sys_errlist[errno]);
      continue;
    }
    if((filelen=ffilelength(hin))<sizeof(BSPHEADER)) // Get file length
    {
      printf("Not a BSP file (filelen[%u]<%u)\n",filelen,sizeof(BSPHEADER));
      continue;
    }
    if(fread(&hdr,sizeof(BSPHEADER),1,hin)<1) // Read BSP header info
    {
      printf("Header read failure, %s!\n",_sys_errlist[errno]);
      continue;
    }
    if(hdr.magic!=BSP_MAGIC) // Check that its a BSP file
    {
      printf("Not a BSP file (%08x!=%08x)!\n",hdr.magic,BSP_MAGIC);
      continue;
    }

    // Make sure location of entity isnt greater then file length

    if(hdr.entloc>filelen)
    {
      printf("BSP corrupted (entloc[%u]>filelen[%u])\n",hdr.entloc,filelen);
      continue;
    }

    // Make sure end location of entity script isnt greater then file length

    if(hdr.entend>filelen)
    {
      printf("BSP corrupted (entloc[%u]+entsiz[%u][=%u]<filelen[%u])\n",hdr.entloc,hdr.entsiz,hdr.entloc+hdr.entsiz,filelen);
      continue;
    }
    if(fseek(hin,hdr.entloc,SEEK_SET)) // Seek to entity data in input file
    {
      printf("Seek to position %u failed, %s!\n",hdr.entloc,_sys_errlist[errno]);
      continue;
    }
    if(!(entbuf=malloc(hdr.entsiz+1))) // Allocate storage for entity script
    {
      printf("Can't alloc %u bytes for ent storage\n",hdr.entsiz+1);
      continue;
    }
    if(fread(entbuf,hdr.entsiz,1,hin)<1) // Read entity script
    {
      printf("Entity data read failure for %u bytes, %s!\n",hdr.entsiz,_sys_errlist[errno]);
      continue;
    }

    entbuf[hdr.entsiz]=0; // Null terminate at end of storage (for str* funcs)

    if(!processcommands(arg,hin,entbuf,&hdr,filelen,&changes)) // Parse script
    {
      if(changes) // BSP was modified
      {
        filesmodified++; // Increment modified counter
        fileschanges+=changes; // Increment total changes
      }
      printf("OK! (%u chang%s)\n",changes,changes==1?"e":"es"); // Tell user
      fileserrors--; // Decrement file errors (incremented at beginning of loop)
    }

    if(entbuf) // Free storage buffer and nullify it so it doesnt get freed again
    {
      free(entbuf);
      entbuf=0;
    }
    if(hin) // Close input file buffer and nullify it so it doesnt get closed again
    {
      fclose(hin);
      hin=0;
    }

    // Goto next file
  }

  printf("\n" // Print summary
         "Result: %u fil%s, %u modificatio%s, %u chang%s and %u erro%s\n"
         "\n"
         "Operation completed!\n",
    filestotal,
    filestotal==1?"e":"es", // Pluralise
    filesmodified,
    filesmodified==1?"n":"ns", // Pluralise
    fileschanges,
    fileschanges==1?"e":"es", // Pluralise
    fileserrors,
    fileserrors==1?"r":"rs"); // Pluralise

  return 0;
}
Beispiel #25
0
int main( int argc, char *argv[] ) {
    if( argc < 3 ) {
        showhelp();
        return Error;
    }

    char *filename( ddl_nullptr ), *exportFilename( ddl_nullptr );
    bool dump( false ), exportToFile( false );
    for ( int i = 1; i < argc; i++) {
        if (0 == strncmp(FileOption, argv[i], strlen(FileOption))) {
            if ((i + 1) >= argc) {
                std::cerr << "No filename specified" << std::endl;
                return Error;
            }

            filename = argv[ i+1 ];
        }

        if (0 == strncmp(DumpOption, argv[ i ], strlen( DumpOption) ) ) {
            dump = true;
        }

        if( 0==strncmp(ExportOption, argv[i], strlen(ExportOption ) ) ) {
            if ((i + 1) >= argc) {
                std::cerr << "No filename for export specified" << std::endl;
                return Error;
            } else {
                exportToFile = true;
                exportFilename = argv[i+1];
            }
        }
    }

    std::cout << "file to import: " << filename << std::endl;

    if(ddl_nullptr == filename ) {
        std::cerr << "Invalid filename." << std::endl;
        return Error;
    }

    FILE *fileStream = fopen( filename, "rb+" );
    if(ddl_nullptr == fileStream ) {
        std::cerr << "Cannot open file " << filename << std::endl;
        return Error;
    }

    // obtain file size:
    fseek( fileStream, 0, SEEK_END );
    const size_t size( ftell( fileStream ) );

    ::rewind( fileStream );

    if( size > 0 ) {
        char *buffer = new char[ size ];
        const size_t readSize( fread( buffer, sizeof( char ), size, fileStream ) );
        assert( readSize == size );
        OpenDDLParser theParser;
        theParser.setBuffer( buffer, size );
        const bool result( theParser.parse() );
        if( !result ) {
            std::cerr << "Error while parsing file " << filename << "." << std::endl;
        } else {
            DDLNode *root = theParser.getRoot();
            if ( dump ) {
                dumpDDLNodeTree(root);
            }
            if ( exportToFile ) {
                OpenDDLExport theExporter;
                theExporter.exportContext( theParser.getContext(), exportFilename );
            }
        }
    }

    return 0;
}
Beispiel #26
0
int parsecmd(int argc, char **argv, DADSM *dadsm) {

        int     util_verbose = 0;       // Hercules dasdutil.c diagnostic level
        int     heads = 15;             // # heads per cylinder on device
        int     extnum = 0;             // extent number for makext()
        int     abscyl = 0;             // absolute CC (default 0)
        int     abshead = 0;            // absolute HH (default 0)
        int     abstrk = 1;             // absolute tracks (default 1)
        int     lrecl = 80;             // default F1 DSCB lrecl

//  Usage: dasdseq [-debug] [-expert] [-ascii] image [sf=shadow] [attr] filespec

    argv++;                             // skip dasdseq command argv[0]
    if ((*argv) && (strcasecmp(*argv, "-debug") == 0)) {
            argv++;
            debug = 1;
            fprintf(stderr, "Command line DEBUG specified\n");
    }
    if ((*argv) && (strcasecmp(*argv, "-expert") == 0)) {
            argv++;
            expert = 1;
            if (debug) fprintf(stderr, "EXPERT mode\n");
    }
    if ((*argv) && (strcasecmp(*argv, "-ascii") == 0)) {
            argv++;
            tran_ascii = 1;
            if (debug) fprintf(stderr, "ASCII translation enabled\n");
    }
    if (*argv) din = *argv++;           // dasd image filename
    if (debug) fprintf(stderr, "IMAGE %s\n", din);
    if (*argv && strlen(*argv) > 3 && !memcmp(*argv, "sf=", 3)) {
        sfn = *argv++;                  // shadow file parm
    } else 
        sfn = NULL;
    if (debug) fprintf(stderr, "SHADOW %s\n", sfn);
    dadsm->f1buf.ds1recfm = 
                RECFM_FORMAT_F | RECFM_BLOCKED; // recfm FB for fbcopy
    if ((*argv) && (strcasecmp(*argv, "-recfm") == 0)) {
        argv++;                                 // skip -recfm
        if ((*argv) && (strcasecmp(*argv, "fb") == 0)) {
            argv++;                             // skip fb
            if (debug) fprintf(stderr, "RECFM fb\n");
        } else {
            argv++;                             // skip bad recfm
            fprintf(stderr, "Unsupported -recfm value %s\n", *argv);
        }
    }
    if ((*argv) && (strcasecmp(*argv, "-lrecl") == 0)) {
        argv++;                                         // skip -lrecl
        if (*argv) lrecl = atoi(*argv++);               // lrecl value
        if (debug) fprintf(stderr, "LRECL %d\n", lrecl);
    }
    dadsm->f1buf.ds1lrecl[0] = lrecl >> 8;      // for fbcopy
    dadsm->f1buf.ds1lrecl[1] = lrecl - ((lrecl >> 8) << 8);
    if ((*argv) && (strcasecmp(*argv, "-heads") == 0)) {
        argv++;                                 // skip -heads
        if (*argv) heads = atoi(*argv++);       // heads value
    }
    if (debug) fprintf(stderr, "HEADS %d\n", heads);
    if ((*argv) && 
        (strcasecmp(*argv, "-abs") == 0)) {
            absvalid = 1;                               // CCHH valid
            while ((*argv) && (strcasecmp(*argv, "-abs") == 0)) {
                argv++;                                 // skip -abs
                abscyl = 0; abshead = 0; abstrk = 1;    // defaults
                if (*argv) abscyl = atoi(*argv++);      // abs cc
                if (*argv) abshead = atoi(*argv++);     // abs hh
                if (*argv) abstrk = atoi(*argv++);      // abs tracks
                // Build extent entry for -abs group
                makext(extnum, heads, 
                        (DSXTENT *) &dadsm->f1ext, abscyl, abshead, abstrk);
                extnum++;
                dadsm->f1buf.ds1noepv = extnum;         // for fbcopy
                if (debug) fprintf(stderr, "Absolute CC %d HH %d tracks %d\n",
                        abscyl, abshead, abstrk);
                if (extnum > MAX_EXTENTS) {
                        fprintf(stderr, "Too many extents, abort\n");
                        exit(3);
                }
                        
            }
//          if (debug) sayext(MAX_EXTENTS, dadsm->f1ext);// show extent table
    }
    if (debug) {
        fprintf(stderr, "parsecmd completed F1 DSCB\n");
        data_dump(&dadsm->f1buf, sizeof(FORMAT1_DSCB));
    }
    if (*argv) argdsn = *argv++;        // [MVS dataset name/]output filename
    if (debug) fprintf(stderr, "DSN %s\n", argdsn);
    if ((*argv) && (            // support deprecated 'ascii' operand
                (strcasecmp(*argv, "ascii") == 0) ||
                (strcasecmp(*argv, "-ascii") == 0)
                )
        ) {
            argv++;
            tran_ascii = 1;
            if (debug) fprintf(stderr, "ASCII translation enabled\n");
    }
    set_verbose_util(0);                // default util verbosity
    if ((*argv) && (strcasecmp(*argv, "verbose") == 0)) {
            local_verbose = 1;
            argv++;
        if (*argv) local_verbose = atoi(*argv++);
        if (*argv) copy_verbose = atoi(*argv++);
        if (*argv) {
            util_verbose = atoi(*argv++);
            set_verbose_util(util_verbose);
            if (debug) fprintf(stderr, "Utility verbose %d\n", util_verbose);
        }
    }

//  If the user specified expert mode without -abs, give help & exit
//  Additionally, if the user has "extra" parms, show help & exit
//  No "extraneous parms" message is issued, since some of the code
//  above forces *argv to be true when it wants help displayed

    if ((argc < 3) || (*argv) || ((expert) && (!absvalid))) {
        showhelp();                     // show syntax before bailing
        exit(2);
    }
    return 0;

} /* parsecmd */
Beispiel #27
0
int	main ( int argc, char ** argv )
{
	int			i,  j;
	int			sockint, sockctl; // For the listening sockets
	struct sockaddr_l2	l2a;
	socklen_t		alen=sizeof(l2a);
	int			sint,  sctl;	  // For the one-session-only
						  // socket descriptor handles
	char			badr[40];
	fd_set			fds;		  // fds for listening sockets
	fd_set			efds;	          // dev-event file descriptors
	int			maxevdevfileno;
	char			skipsdp = 0;	  // On request, disable SDPreg
	struct timeval		tv;		  // Used for "select"
	int			evdevmask = 0;// If restricted to using only one evdev
	int			mutex11 = 0;      // try to "mute" in x11?
	char			*fifoname = NULL; // Filename for fifo, if applicable
	// Parse command line
	for ( i = 1; i < argc; ++i )
	{
		if ( ( 0 == strcmp ( argv[i], "-h"     ) ) ||
		     ( 0 == strcmp ( argv[i], "-?"     ) ) ||
		     ( 0 == strcmp ( argv[i], "--help" ) ) )
		{
			showhelp();
			return	0;
		}
		else if ( ( 0 == strcmp ( argv[i], "-s" ) ) ||
			  ( 0 == strcmp ( argv[i], "--skipsdp" ) ) )
		{
			skipsdp = 1;
		}
		else if ( 0 == strncmp ( argv[i], "-e", 2 ) ) {
			evdevmask |= 1 << atoi(argv[i]+2);
		}
		else if ( 0 == strcmp ( argv[i], "-l" ) )
		{
			return list_input_devices();
		}
		else if ( 0 == strcmp ( argv[i], "-d" ) )
		{
			debugevents = 0xffff;
		}
		else if ( 0 == strcmp ( argv[i], "-x" ) )
		{
			mutex11 = 1;
		}
		else if ( 0 == strncmp ( argv[i], "-f", 2 ) )
		{
			fifoname = argv[i] + 2;
		}
		else
		{
			fprintf ( stderr, "Invalid argument: \'%s\'\n", argv[i]);
			return	1;
		}
	}
	if ( ! skipsdp )
	{
		if ( dosdpregistration() )
		{
			fprintf(stderr,"Failed to register with SDP server\n");
			return	1;
		}
	}
	if ( NULL == fifoname )
	{
		if ( 1 > initevents (evdevmask, mutex11) )
		{
			fprintf ( stderr, "Failed to open event interface files\n" );
			return	2;
		}
	} else {
		if ( 1 > initfifo ( fifoname ) )
		{
			fprintf ( stderr, "Failed to create/open fifo [%s]\n", fifoname );
			return	2;
		}
	}
	maxevdevfileno = add_filedescriptors ( &efds );
	if ( maxevdevfileno <= 0 )
	{
		fprintf ( stderr, "Failed to organize event input.\n" );
		return	13;
	}
	sockint = socket ( AF_BLUETOOTH, SOCK_SEQPACKET, BTPROTO_L2CAP );
	sockctl = socket ( AF_BLUETOOTH, SOCK_SEQPACKET, BTPROTO_L2CAP );
	if ( ( 0 > sockint ) || ( 0 > sockctl ) )
	{
		fprintf ( stderr, "Failed to generate bluetooth sockets\n" );
		return	2;
	}
	if ( btbind ( sockint, PSMHIDINT ) || btbind ( sockctl, PSMHIDCTL ))
	{
		fprintf ( stderr, "Failed to bind sockets (%d/%d) "
				"to PSM (%d/%d)\n",
				sockctl, sockint, PSMHIDCTL, PSMHIDINT );
		return	3;
	}
	if ( listen ( sockint, 1 ) || listen ( sockctl, 1 ) )
	{
		fprintf ( stderr, "Failed to listen on int/ctl BT socket\n" );
		close ( sockint );
		close ( sockctl );
		return	4;
	}
	// Add handlers to catch signals:
	// All do the same, terminate the program safely
	// Ctrl+C will be ignored though (SIGINT) while a connection is active
	signal ( SIGHUP,  &onsignal );
	signal ( SIGTERM, &onsignal );
	signal ( SIGINT,  &onsignal );
	fprintf ( stdout, "The HID-Client is now ready to accept connections "
			"from another machine\n" );
	//i = system ( "stty -echo" );	// Disable key echo to the console
	while ( 0 == prepareshutdown )
	{	// Wait for any shutdown-event to occur
		sint = sctl = 0;
		add_filedescriptors ( &efds );
		tv.tv_sec  = 0;
		tv.tv_usec = 0;
		while ( 0 < (j = select(maxevdevfileno+1,&efds,NULL,NULL,&tv)))
		{	// Collect and discard input data as long as available
			if ( -1 >  ( j = parse_events ( &efds, 0 ) ) )
			{	// LCtrl-LAlt-PAUSE - terminate program
				prepareshutdown = 1;
				break;
			}
			add_filedescriptors ( &efds );
			tv.tv_sec  = 0;
			tv.tv_usec = 500; // minimal delay
		}
		if ( prepareshutdown )
			break;
		connectionok = 0;
		tv.tv_sec  = 1;
		tv.tv_usec = 0;
		FD_ZERO ( &fds );
		FD_SET  ( sockctl, &fds );
		j = select ( sockctl + 1, &fds, NULL, NULL, &tv );
		if ( j < 0 )
		{
			if ( errno == EINTR )
			{	// Ctrl+C ? - handle that elsewhere
				continue;
			}
			fprintf ( stderr, "select() error on BT socket: %s! "
					"Aborting.\n", strerror ( errno ) );
			return	11;
		}
		if ( j == 0 )
		{	// Nothing happened, check for shutdown req and retry
			if ( debugevents & 0x2 )
				fprintf ( stdout, "," );
			continue;
		}
		sctl = accept ( sockctl, (struct sockaddr *)&l2a, &alen );
		if ( sctl < 0 )
		{
			if ( errno == EAGAIN )
			{
				continue;
			}
			fprintf ( stderr, "Failed to get a control connection:"
					" %s\n", strerror ( errno ) );
			continue;
		}
		tv.tv_sec  = 3;
		tv.tv_usec = 0;
		FD_ZERO ( &fds );
		FD_SET  ( sockint, &fds );
		j = select ( sockint + 1, &fds, NULL, NULL, &tv );
		if ( j < 0 )
		{
			if ( errno == EINTR )
			{	// Might have been Ctrl+C
				close ( sctl );
				continue;
			}
			fprintf ( stderr, "select() error on BT socket: %s! "
					"Aborting.\n", strerror ( errno ) );
			return	12;
		}
		if ( j == 0 )
		{
			fprintf ( stderr, "Interrupt connection failed to "
					"establish (control connection already"
					" there), timeout!\n" );
			close ( sctl );
			continue;
		}
		sint = accept ( sockint, (struct sockaddr *)&l2a, &alen );
		if ( sint < 0 )
		{
			close ( sctl );
			if ( errno == EAGAIN )
				continue;
			fprintf ( stderr, "Failed to get an interrupt "
					"connection: %s\n", strerror(errno));
			continue;
		}
		ba2str ( &l2a.l2_bdaddr, badr );
		badr[39] = 0;
		fprintf ( stdout, "Incoming connection from node [%s] "
				"accepted and established.\n", badr );
		tv.tv_sec  = 0;
		tv.tv_usec = 0;
		j = -1;
		add_filedescriptors ( &efds );
		while ( 0 < (j = select(maxevdevfileno+1,&efds,NULL,NULL,&tv)))
		{
			// This loop removes all input garbage that might be
			// already in the queue
			if ( -1 > ( j = parse_events ( &efds, 0 ) ) )
			{	// LCtrl-LAlt-PAUSE - terminate program
				prepareshutdown = 1;
				break;
			}
			add_filedescriptors ( &efds );
			tv.tv_sec  = 0;
			tv.tv_usec = 0;
		}
		if ( prepareshutdown )
			break;
		connectionok = 1;
		memset ( pressedkey, 0, 8 );
		modifierkeys = 0;
		mousebuttons = 0;
		while ( connectionok )
		{
			add_filedescriptors ( &efds );
			tv.tv_sec  = 1;
			tv.tv_usec = 0;
			while ( 0 < ( j = select ( maxevdevfileno + 1, &efds,
							NULL, NULL, &tv ) ) )
			{
				if ( 0 > ( j = parse_events ( &efds, sint ) ) )
				{
					// PAUSE pressed - close connection
					connectionok = 0;
					if ( j < -1 )
					{	// LCtrl-LAlt-PAUSE - terminate
						close ( sint );
						close ( sctl );
						prepareshutdown = 1;
					}
					break;
				}
				add_filedescriptors ( &efds );
				tv.tv_sec  = 1;
				tv.tv_usec = 0;
			}
		}
		connectionok = 0;
		close ( sint );
		close ( sctl );
		sint = sctl =  0;
		fprintf ( stderr, "Connection closed\n" );
		usleep ( 500000 ); // Sleep 0.5 secs between connections
				   // to not be flooded
	}
	//i = system ( "stty echo" );	   // Set console back to normal
	close ( sockint );
	close ( sockctl );
	if ( ! skipsdp )
	{
		sdpunregister ( sdphandle ); // Remove HID info from SDP server
	}
	if ( NULL == fifoname )
	{
		closeevents ();
	} else {
		closefifo ();
	}
	cleanup_stdin ();	   // And remove the input queue from stdin
	fprintf ( stderr, "Stopped hidclient.\n" );
	return	0;
}
Beispiel #28
0
int play() {

   short c;
   short ret;
   short testmove();
   short undolock = 1;         /* locked for undo */

#if ATARIST			/* Mess up keyboard to make cursor keys work */
KEY_TABLES *kbt;
KEY_TABLES old_kbt;
int i;

	kbt = Keytbl(-1, -1, -1);
	old_kbt = *kbt;

	for (i = 0; i < 128; i++) {
		unshifted[i] = kbt->unshifted[i];
		shifted[i] = kbt->shifted[i];
	}

	unshifted[0x48] = 'k';	/* Up */
	unshifted[0x50] = 'j';	/* Down */
	unshifted[0x4b] = 'h';	/* Left */
	unshifted[0x4d] = 'l';	/* Right */
	unshifted[0x61] = 'u';	/* Undo */
	unshifted[0x62] = '?';	/* Help */

	shifted[0x48] = '\013';	/* Up ^K */
	shifted[0x50] = '\012';	/* Down ^J */
	shifted[0x4b] = '\010';	/* Left ^H */
	shifted[0x4d] = '\014';	/* Right ^L */
	shifted[0x61] = 'q';	/* Undo */

	Keytbl(unshifted, shifted, -1);
#endif

   showscreen();
   tmpsave();
   ret = 0;
   while( ret == 0) {
      switch( (c = get_char())) {
        case 'q':    /* quit the game                                  */
				ret = E_ENDGAME;
				break;
        case 's':    /* save the games                                 */
                     if( (ret = savegame()) == 0)
                        ret = E_SAVED;
                     break;
        case '?':    /* show the help file                             */
                     showhelp();
                     showscreen();
                     break;
        case CNTL_R: /* refresh the screen                             */
                     clear();
                     showscreen();
                     break;
        case 'c':    /* temporary save                                 */
                     tmpsave();
                     break;
        case CNTL_U: /* reset to temporary save                        */
                     tmpreset();
                     undolock = 1;
                     showscreen();
                     break;
        case 'U':    /* undo this level                                */
                     moves = pushes = 0;
                     if( (ret = readscreen()) == 0) {
                        showscreen();
                        undolock = 1;
                     }
                     break;
        case 'u':    /* undo last move                                 */
                     if(state_num > 0) {
                        undomove();
                        undolock = 0;	/*1*/
                     }
                     break;
        case 'k':    /* up                                             */
        case 'K':    /* run up                                         */
        case CNTL_K: /* run up, stop before object                     */
        case 'j':    /* down                                           */
        case 'J':    /* run down                                       */
        case CNTL_J: /* run down, stop before object                   */
        case 'l':    /* right                                          */
        case 'L':    /* run right                                      */
        case CNTL_L: /* run right, stop before object                  */
        case 'h':    /* left                                           */
        case 'H':    /* run left                                       */
        case CNTL_H: /* run left, stop before object                   */
                     do {
                        if( (action = testmove( c)) != 0) {
						soko_state *s;
							s = &state[state_num];

                        	s->action = action;
							s->ppos = ppos;
                        	s->lppc = map[ppos.x][ppos.y];
							s->tpos1 = tpos1;
                        	s->ltp1c = map[tpos1.x][tpos1.y];
							s->tpos2 = tpos2;
                        	s->ltp2c = map[tpos2.x][tpos2.y];
                           domove( s->action);
                           undolock = 0;
						   state_num++;
                        }
                     } while( (action != 0) && (! islower( c))
                             && (packets != savepack));
                     break;
        default:     helpmessage(); break;
      }
      if( (ret == 0) && (packets == savepack)) {
        scorelevel = level;
        scoremoves = moves;
        scorepushes = pushes;
        break;
      }
   }
#if ATARIST
	kbt = Keytbl(-1, -1, -1);
	kbt->unshifted = old_kbt.unshifted;
	kbt->shifted = old_kbt.shifted;
/*	Keytbl(old_kbt.unshifted, old_kbt.shifted, old_kbt.capslock);*/
#endif
	return ret;
}
Beispiel #29
0
int
main(int argc, char **argv)
{
    int       result    = -1;
    int       mntflags  = 0;
    int       fd        = -1;
    int32_t   dindex    = -1;
    char     *fdnam     = NULL;
    uint64_t  altflags  = 0ULL;
    char     *mntpath   = NULL;

    int i, ch = '\0', done = 0;
    struct mntopt *mo;
    struct mntval *mv;
    struct statfs statfsb;
    fuse_mount_args args;

    if (!getenv("MOUNT_FUSEFS_CALL_BY_LIB")) {
        showhelp();
        /* NOTREACHED */
    }

    /* Kludge to make "<fsdaemon> --version" happy. */
    if ((argc == 2) &&
        ((!strncmp(argv[1], "--version", strlen("--version"))) ||
         (!strncmp(argv[1], "-v", strlen("-v"))))) {
        showversion(1);
    }

    /* Kludge to make "<fsdaemon> --help" happy. */
    if ((argc == 2) &&
        ((!strncmp(argv[1], "--help", strlen("--help"))) ||
         (!strncmp(argv[1], "-h", strlen("-h"))))) {
        showhelp();
    }

    memset((void *)&args, 0, sizeof(args));

    do {
        for (i = 0; i < 3; i++) {
            if (optind < argc && argv[optind][0] != '-') {
                if (mntpath) {
                    done = 1;
                    break;
                }
                if (fdnam)
                    mntpath = argv[optind];
                else
                    fdnam = argv[optind];
                optind++;
            }
        }

        switch(ch) {
        case 'o':
            getmntopts(optarg, mopts, &mntflags, &altflags);
            for (mv = mvals; mv->mv_mntflag; ++mv) {
                if (!(altflags & mv->mv_mntflag)) {
                    continue;
                }
                for (mo = mopts; mo->m_option; ++mo) {
                    char *p, *q;
                    if (mo->m_flag != mv->mv_mntflag) {
                        continue;
                    }
                    p = strstr(optarg, mo->m_option);
                    if (p) {
                        p += strlen(mo->m_option);
                        q = p;
                        while (*q != '\0' && *q != ',') {
                            q++;
                        }
                        mv->mv_len = q - p + 1;
                        mv->mv_value = malloc(mv->mv_len);
                        memcpy(mv->mv_value, p, mv->mv_len - 1);
                        ((char *)mv->mv_value)[mv->mv_len - 1] = '\0';
                        break;
                    }
                }
            }
            break;

        case '\0':
            break;

        case 'v':
            showversion(1);
            break;

        case '?':
        case 'h':
        default:
            showhelp();
            break;
        }

        if (done) {
            break;
        }

    } while ((ch = getopt(argc, argv, "ho:v")) != -1);

    argc -= optind;
    argv += optind;

    if ((!fdnam) && argc > 0) {
        fdnam = *argv++;
        argc--;
    }

    if (!fdnam) {
        errx(EX_USAGE, "missing " OSXFUSE_DISPLAY_NAME
             " device file descriptor");
    }

    errno = 0;
    fd = (int)strtol(fdnam, NULL, 10);
    if ((errno == EINVAL) || (errno == ERANGE)) {
        errx(EX_USAGE, "invalid name (%s) for " OSXFUSE_DISPLAY_NAME
             " device file descriptor", fdnam);
    }

    signal_fd = fd;

    {
        char  ndev[MAXPATHLEN];
        char *ndevbas;
        struct stat sb;

        if (fstat(fd, &sb) == -1) {
            err(EX_OSERR, "fstat failed for " OSXFUSE_DISPLAY_NAME
                " device file descriptor");
        }
        args.rdev = sb.st_rdev;
        (void)strlcpy(ndev, _PATH_DEV, sizeof(ndev));
        ndevbas = ndev + strlen(_PATH_DEV);
        devname_r(sb.st_rdev, S_IFCHR, ndevbas,
                  (int)(sizeof(ndev) - strlen(_PATH_DEV)));

        if (strncmp(ndevbas, OSXFUSE_DEVICE_BASENAME,
                    strlen(OSXFUSE_DEVICE_BASENAME))) {
            errx(EX_USAGE, "mounting inappropriate device");
        }

        errno = 0;
        dindex = (int)strtol(ndevbas + strlen(OSXFUSE_DEVICE_BASENAME),
                             NULL, 10);
        if ((errno == EINVAL) || (errno == ERANGE) ||
            (dindex < 0) || (dindex > OSXFUSE_NDEVICES)) {
            errx(EX_USAGE, "invalid " OSXFUSE_DISPLAY_NAME
                 " device unit (#%d)\n", dindex);
        }
    }

    signal_idx = dindex;

    atexit(signal_idx_atexit_handler);

    result = check_kext_status();

    switch (result) {

    case 0:
        break;

    case ESRCH:
        errx(EX_UNAVAILABLE, "the " OSXFUSE_DISPLAY_NAME
             " kernel extension is not loaded");
        break;

    case EINVAL:
        errx(EX_UNAVAILABLE, "the loaded " OSXFUSE_DISPLAY_NAME
             " kernel extension has a mismatched version");
        break;

    default:
        errx(EX_UNAVAILABLE, "failed to query the loaded " OSXFUSE_DISPLAY_NAME
             " kernel extension (%d)", result);
        break;
    }

    if ((!mntpath) && argc > 0) {
        mntpath = *argv++;
        argc--;
    }

    if (!mntpath) {
        errx(EX_USAGE, "missing mount point");
    }

    (void)checkpath(mntpath, args.mntpath);

    mntpath = args.mntpath;

    fuse_process_mvals();

    if (statfs(mntpath, &statfsb)) {
        errx(EX_OSFILE, "cannot stat the mount point %s", mntpath);
    }

    if (((strlen(statfsb.f_fstypename) == strlen(OSXFUSE_NAME)) &&
         (strcmp(statfsb.f_fstypename, OSXFUSE_NAME) == 0)) ||
        ((strlen(OSXFUSE_TYPE_NAME_PREFIX) > 0) &&
         (strncmp(statfsb.f_fstypename, OSXFUSE_TYPE_NAME_PREFIX,
                  strlen(OSXFUSE_TYPE_NAME_PREFIX)) == 0))) {
        if (!(altflags & FUSE_MOPT_ALLOW_RECURSION)) {
            errx(EX_USAGE, "mount point %s is itself on a "
                 OSXFUSE_DISPLAY_NAME " volume", mntpath);
        }
    }

    /* allow_root and allow_other checks are done in the kernel. */

    if (altflags & FUSE_MOPT_NO_LOCALCACHES) {
        altflags |= FUSE_MOPT_NO_ATTRCACHE;
        altflags |= FUSE_MOPT_NO_READAHEAD;
        altflags |= FUSE_MOPT_NO_UBC;
        altflags |= FUSE_MOPT_NO_VNCACHE;
    }

    if ((altflags & FUSE_MOPT_NEGATIVE_VNCACHE) &&
        (altflags & FUSE_MOPT_NO_VNCACHE)) {
        errx(EX_USAGE, "'negative_vncache' can't be used with 'novncache'");
    }

    /*
     * 'nosyncwrites' must not appear with either 'noubc' or 'noreadahead'.
     */
    if ((altflags & FUSE_MOPT_NO_SYNCWRITES) &&
        (altflags & (FUSE_MOPT_NO_UBC | FUSE_MOPT_NO_READAHEAD))) {
        errx(EX_USAGE,
             "disabling local caching can't be used with 'nosyncwrites'");
    }

    /*
     * 'nosynconclose' only allowed if 'nosyncwrites' is also there.
     */
    if ((altflags & FUSE_MOPT_NO_SYNCONCLOSE) &&
        !(altflags & FUSE_MOPT_NO_SYNCWRITES)) {
        errx(EX_USAGE, "the 'nosynconclose' option requires 'nosyncwrites'");
    }

    if ((altflags & FUSE_MOPT_DEFAULT_PERMISSIONS) &&
        (altflags & FUSE_MOPT_DEFER_PERMISSIONS)) {
        errx(EX_USAGE,
             "'default_permissions' can't be used with 'defer_permissions'");
    }

    if ((altflags & FUSE_MOPT_AUTO_XATTR) &&
        (altflags & FUSE_MOPT_NATIVE_XATTR)) {
        errx(EX_USAGE,
             "'auto_xattr' can't be used with 'native_xattr'");
    }

    if (daemon_timeout < FUSE_MIN_DAEMON_TIMEOUT) {
        daemon_timeout = FUSE_MIN_DAEMON_TIMEOUT;
    }

    if (daemon_timeout > FUSE_MAX_DAEMON_TIMEOUT) {
        daemon_timeout = FUSE_MAX_DAEMON_TIMEOUT;
    }

    result = ioctl(fd, FUSEDEVIOCGETRANDOM, &drandom);
    if (result) {
        errx(EX_UNAVAILABLE, "failed to negotiate with /dev/"
             OSXFUSE_DEVICE_BASENAME "%d", dindex);
    }

    args.altflags       = altflags;
    args.blocksize      = (uint32_t) blocksize;
    args.daemon_timeout = (uint32_t) daemon_timeout;
    args.fsid           = (uint32_t) fsid;
    args.fssubtype      = (uint32_t) fssubtype;
    args.iosize         = (uint32_t) iosize;
    args.random         = drandom;

    char *daemon_name = NULL;
    char *daemon_path = getenv("MOUNT_OSXFUSE_DAEMON_PATH");
    if (daemon_path) {
        daemon_name = basename(daemon_path);
    }

    if (!fsname) {
        if (daemon_name) {
            snprintf(args.fsname, MAXPATHLEN, "%s@" OSXFUSE_DEVICE_BASENAME
                     "%d", daemon_name, dindex);
        } else {
            snprintf(args.fsname, MAXPATHLEN, "instance@"
                     OSXFUSE_DEVICE_BASENAME "%d", dindex);
        }
    } else {
        snprintf(args.fsname, MAXPATHLEN, "%s", fsname);
    }

    if (fstypename) {
        if (strlen(fstypename) > FUSE_TYPE_NAME_MAXLEN) {
            errx(EX_USAGE, "fstypename can be at most %lu characters",
                 (long unsigned int) FUSE_TYPE_NAME_MAXLEN);
        } else {
            snprintf(args.fstypename, MFSTYPENAMELEN, "%s", fstypename);
        }
    }

    if (!volname) {
        #if __clang__
            #pragma clang diagnostic push
            #pragma clang diagnostic ignored "-Wformat-extra-args"
        #endif

        if (daemon_name) {
            snprintf(args.volname, MAXPATHLEN, OSXFUSE_VOLNAME_DAEMON_FORMAT,
                     dindex, daemon_name);
        } else {
            snprintf(args.volname, MAXPATHLEN, OSXFUSE_VOLNAME_FORMAT, dindex);
        }

        #if __clang__
            #pragma clang diagnostic pop
        #endif
    } else {
        snprintf(args.volname, MAXPATHLEN, "%s", volname);
    }

    /* Finally! */
    result = mount(OSXFUSE_NAME, mntpath, mntflags, (void *)&args);

    if (result < 0) {
        err(EX_OSERR, "failed to mount %s@/dev/" OSXFUSE_DEVICE_BASENAME "%d",
            mntpath, dindex);
    } else {
        const char *dict[][2] = { { kFUSEMountPathKey, mntpath } };
        post_notification(NOTIFICATION_MOUNT, dict, 1);
    }

    signal_idx = -1;

    exit(0);
}
Beispiel #30
0
int main(int argc, char *argv[]) {
    int c;
    char *dir = ".";
    char *outf = NULL;
    char *volname = NULL;
    int verbose = 0;
    char buf[256];
    struct filenode *root;
    struct stat sb;
    int lastoff;
    int i;
    char *p;
    struct aligns *pa, *pa2;
    struct excludes *pe, *pe2;
    FILE *f;

    while((c = getopt(argc, argv, "V:vd:f:ha:A:x:")) != EOF) {
        switch(c) {
            case 'd':
                dir = optarg;
                break;
            case 'f':
                outf = optarg;
                break;
            case 'V':
                volname = optarg;
                break;
            case 'v':
                verbose = 1;
                break;
            case 'h':
                showhelp(argv[0]);
                exit(0);
            case 'a':
                align = strtoul(optarg, NULL, 0);

                if(align < 16 || (align & (align - 1))) {
                    fprintf(stderr, "Align has to be at least 16 bytes and a power of two\n");
                    exit(1);
                }

                break;
            case 'A':
                i = strtoul(optarg, &p, 0);

                if(i < 16 || (i & (i - 1))) {
                    fprintf(stderr, "Align has to be at least 16 bytes and a power of two\n");
                    exit(1);
                }

                if(*p != ',' || !p[1]) {
                    fprintf(stderr, "-A takes N,PATTERN format of argument, where N is a number\n");
                    exit(1);
                }

                /* strlen(p+1) + 1 eq strlen(p) */
                pa = (struct aligns *)malloc(sizeof(*pa) + strlen(p));
                pa->align = i;
                pa->next = NULL;
                strcpy(pa->pattern, p + 1);

                if(!alignlist)
                    alignlist = pa;
                else {
                    for(pa2 = alignlist; pa2->next; pa2 = pa2->next)
                        ;

                    pa2->next = pa;
                }

                break;
            case 'x':
                pe = (struct excludes *)malloc(sizeof(*pe) + strlen(optarg) + 1);
                pe->next = NULL;
                strcpy(pe->pattern, optarg);

                if(!excludelist)
                    excludelist = pe;
                else {
                    for(pe2 = excludelist; pe2->next; pe2 = pe2->next)
                        ;

                    pe2->next = pe;
                }

                break;
            default:
                exit(1);
        }
    }

    if(!volname) {
        sprintf(buf, "rom %08lx", time(NULL));
        volname = buf;
    }

    if(!outf) {
        fprintf(stderr, "%s: you must specify the destination file\n", argv[0]);
        fprintf(stderr, "Try `%s -h' for more information\n", argv[0]);
        exit(1);
    }

    if(strcmp(outf, "-") == 0) {
        f = fdopen(1, "wb");
    }
    else
        f = fopen(outf, "wb");

    if(!f) {
        perror(outf);
        exit(1);
    }

    realbase = strlen(dir);
    root = newnode(dir, volname, 0);
    root->parent = root;
    lastoff = processdir(1, dir, dir, &sb, root, root, spaceneeded(root));
    if(lastoff < 0) {
        fprintf(stderr, "Error while processing directory.\n");
        return 1;
    }

    if(verbose)
        shownode(0, root, stderr);

    if(dumpall(root, lastoff, f)) {
        fprintf(stderr, "Error while dumping!\n");
        return 1;
    }

		return 0;
}