Ejemplo n.º 1
0
int
main(int ac, char **av)
{
    char *id = NULL;
    int i;
    int r = 0;

    LoadDiabloConfig(ac, av);

    for (i = 1; i < ac; ++i) {
	char *ptr = av[i];

	if (*ptr != '-') {
	    id = ptr;
	} else {
	    ptr += 2;
	    switch(ptr[-1]) {
	    case 'C':
		if (*ptr == 0)
		    ++i;
		break;
	    case 'f':
		ScanFile = *ptr ? ptr : ptr + 1;
		ScanOpt = 1;
		break;
	    case 'h':
		DHistoryPat = *ptr ? ptr : ptr + 1;
		break;
	    case 'q':
		QuietOpt = 1;
		break;
	    case 's':
		ScanOpt = 1;
		break;
	    case 'V':
		PrintVersion();
		break;
	    default:
		Usage();
	    }
	}
    }

    if (ScanOpt == 0 && id == NULL)
	Usage();

    HistoryOpen(NULL, HGF_READONLY);
    LoadSpoolCtl(0, 1);

    if (ScanOpt == 0) {
	r += DILookup(id);
    } else {
	char buf[1024];
	FILE *f;

	if (ScanFile == NULL)
	    f = stdin;
	else
	    f = fopen(ScanFile, "r");
	if (f == NULL) {
	    fprintf(stderr, "Unable to open %s (%s)\n", ScanFile, strerror(errno));
	    exit(1);
	}
	while (fgets(buf, sizeof(buf), f) != NULL) {
	    char *p = strrchr(buf, ' ');

	    if (p) {
		*p++ = '\0';
		printf("%s", buf);
	    }
	    else 
		p = buf;
	    r += DILookup(p);
	}
	if (ScanFile != NULL)
	    fclose(f);
    }
    return(r);
}
void
GetOptions
	(
	const JSize			argc,
	char*				argv[],
	JPtrArray<JString>*	inputFileList,
	JString*			dataVarName,
	JString*			outputFileName,
	JString*			databaseFileName,
	JBoolean*			debug
	)
{
	inputFileList->CleanOut();
	dataVarName->Clear();
	outputFileName->Clear();
	databaseFileName->Clear();
	*debug = kJFalse;

	JIndex index = 1;
	while (index < argc)
		{
		if (JIsVersionRequest(argv[index]))
			{
			PrintVersion();
			exit(0);
			}
		else if (JIsHelpRequest(argv[index]))
			{
			PrintHelp();
			exit(0);
			}

		else if (strcmp(argv[index], "--code") == 0)
			{
			JCheckForValues(2, &index, argc, argv);
			*dataVarName    = argv[index];
			*outputFileName = argv[index+1];
			index++;
			}

		else if (strcmp(argv[index], "--db") == 0)
			{
			JCheckForValues(1, &index, argc, argv);
			*databaseFileName = argv[index];
			}

		else if (strcmp(argv[index], "--debug") == 0)
			{
			*debug = kJTrue;
			}

		else if (argv[index][0] == '-')
			{
			cerr << argv[0] << ": unknown command line option: " << argv[index] << endl;
			}

		else
			{
			JString* inputFileName = new JString(argv[index]);
			assert( inputFileName != NULL );

			if (inputFileName->EndsWith("~") ||
				inputFileName->BeginsWith("#"))
				{
				delete inputFileName;
				}
			else
				{
				inputFileList->Append(inputFileName);
				}
			}

		index++;
		}

	if (inputFileList->IsEmpty())
		{
		cerr << argv[0] << ": no input files" << endl;
		exit(1);
		}
}
Ejemplo n.º 3
0
Archivo: main.c Proyecto: Airr/osxutils
int main (int argc, const char * argv[]) 
{
	OSErr		err = noErr;
    int			rc;
    int			optch;
	char		*path;
	FSRef		fileRef;
	int			type;
    static char	optstring[] = "vhxAcmatrRsSdDTCklLoOe";

    while ( (optch = getopt(argc, (char * const *)argv, optstring)) != -1)
    {
        switch(optch)
        {
            case 'v':
                PrintVersion();
                return 0;
                break;
            case 'h':
                PrintHelp();
                return 0;
                break;
			case 'x':
				type = kSuffixHidden;
				break;
			case 'A':
				type = kAppForFile;
				break;
			case 'c':
				type = kDateCreated;
				break;
			case 'm':
				type = kDateModified;
				break;
            case 'a':
				type = kDateAccessed;
				break;
			case 't':
				type = kDateAttrMod;
				break;
			case 'r':
				type = kLogicalResourceForkSize;
				break;
			case 'R':
				type = kPhysicalResourceForkSize;
				break;
			case 's':
				type = kLogicalTotalForkSize;
				break;
			case 'S':
				type = kPhysicalTotalForkSize;
				break;
			case 'd':
				type = kLogicalDataForkSize;
				break;
			case 'D':
				type = kPhysicalDataForkSize;
				break;
			case 'T':
				type = kFileTypeCode;
				break;
			case 'C':
				type = kCreatorTypeCode;
				break;
			case 'k':
				type = kFileKind;
				break;
			case 'l':
				type = kLabelNumeric;
				break;
			case 'L':
				type = kLabelName;
				break;
			case 'o':
				type = kMacOSXComment;
				break;
#if !__LP64__
			case 'O':
				type = kMacOS9Comment;
				break;
#endif
			case 'e':
				type = kAliasOriginal;
				break;
			default: // '?'
                rc = 1;
                PrintUsage();
                return 0;
        }
    }
	
	
    
	//path to file passed as argument
	path = (char *)argv[optind];
	if (path == NULL)
	{
		PrintHelp();
		exit(0);
	}
	
	if (access(path, R_OK|F_OK) == -1)
	{
		perror(path);
		exit(1);
	}
	
	// Get file ref to the file or folder pointed to by the path
    err = FSPathMakeRef((unsigned char *)path, &fileRef, NULL);
	if (err != noErr) 
    {
        fprintf(stderr, "FSPathMakeRef(): Error %d returned when getting file reference for %s\n", err, path);
		exit(1);
    }
	
	switch(type)
	{
		case kSuffixHidden:
			err = PrintIsExtensionHidden(&fileRef);
			break;
		case kAppForFile:
			err = PrintAppWhichOpensFile(&fileRef);
			break;
		case kDateCreated:
			err = PrintDateCreated(&fileRef);
			break;
		case kDateModified:
			err = PrintDateContentModified(&fileRef);
			break;
		case kDateAccessed:
			err = PrintDateLastAccessed(&fileRef);
			break;
		case kDateAttrMod:
			err = PrintDateAttributeModified(&fileRef);
			break;
		case kLogicalResourceForkSize:
			err = PrintResourceForkLogicalSize(&fileRef);
			break;
		case kPhysicalResourceForkSize:
			err = PrintResourceForkPhysicalSize(&fileRef);
			break;
		case kLogicalTotalForkSize:
			err = PrintBothForksLogicalSize(&fileRef);
			break;
		case kPhysicalTotalForkSize:
			err = PrintBothForksPhysicalSize(&fileRef);
			break;
		case kLogicalDataForkSize:
			err = PrintDataForkLogicalSize(&fileRef);
			break;
		case kPhysicalDataForkSize:
			err = PrintDataForkPhysicalSize(&fileRef);
			break;
		case kFileTypeCode:
			err = PrintFileType(&fileRef);
			break;
		case kCreatorTypeCode:
			err = PrintCreatorCode(&fileRef);
			break;
		case kFileKind:
			err = PrintKind(&fileRef);
			break;
		case kLabelNumeric:
			err = PrintLabelNumber(&fileRef);
			break;
		case kLabelName:
			err = PrintLabelName(&fileRef);
			break;
		case kMacOSXComment:
			err = PrintOSXComment(&fileRef);
			break;
#if !__LP64__
		case kMacOS9Comment:
			err = PrintOS9Comment(&fileRef);
			break;
#endif
		case kAliasOriginal:
			err = PrintAliasSource(&fileRef);
			break;
	}
	
	exit(err);

	return err;
}
Ejemplo n.º 4
0
int
main(int ac, char **av)
{
    int r = 0;
    int i;
    char *arg = NULL;
    char *file = NULL;

    LogFo = stderr;

    LoadDiabloConfig(ac, av);

    for (i = 1; i < ac; ++i) {
	char *ptr = av[i];

	if (*ptr != '-') {
	    arg = ptr;
	    continue;
	}
	ptr += 2;
	switch(ptr[-1]) {
	case 'C':
	    if (*ptr == 0)
		++i;
	    break;
	case 'd':
	    DebugOpt = atoi(*ptr ? ptr : av[++i]);
	    break;
	case 'F':
	    ForceOpt = 1;
	    break;
	case 'f':
	    file = (*ptr) ? ptr : av[++i];
	    break;
	case 'H':
	    ShowFileHeader = 1;
	    break;
	case 'h':
	    HeadOnly = 1;
	    break;
	case 'q':
	    QuietOpt = 1;
	    break;
	case 's':
	    StripCR = 0;
	    break;
	case 'V':
	    PrintVersion();
	    break;
	case 'v':
	    VerifyOnly = 1;
	    LogFo = stdout;
	    break;
	default:
	    fprintf(stderr, "dreadart: Illegal option: %s\n", ptr - 2);
	    Usage(av[0]);
	}
    }

    if (arg == NULL && file == NULL)
	Usage(av[0]);

    HistoryOpen(NULL, HGF_READONLY);
    LoadSpoolCtl(0, 1);

    if (arg == NULL) {
	char buf[8192];
	char msgid[MAXMSGIDLEN];
	FILE *fi = (strcmp(file, "-") == 0) ? stdin : fopen(file, "r");

	if (fi) {
	    while (fgets(buf, sizeof(buf), fi) != NULL) {
		hash_t hv;
		char *m;

		if (strncmp(buf, "DUMP ", 5) == 0) {
		    History h = { 0 };
		    if (sscanf(buf + 5, "%s gm=%d ex=%hd boff=%d bsize=%d",
					msgid, &h.gmt, &h.exp,
					&h.boffset, &h.bsize) == 5) {
			char *p;

			h.hv.h1 = (int32)strtoul(msgid, &p, 16);
			if (*p == '.')
			    h.hv.h2 = (int32)strtoul(p + 1, &p, 16);
			if (*p == '.')
			    h.iter = (int16)strtoul(p + 1, NULL, 16);
			r = LookupHash(h.hv, NULL, &h);
		    }
		} else if ((m = strchr(buf, '<')) != NULL) {
		    char *p;
		    if ((p = strchr(m, '>')) == NULL)
			continue;
		    *++p = 0;
		    hv = hhash(m);
		    r = LookupHash(hv, m, NULL);
		} else if (sscanf(buf, "%x.%x", &hv.h1, &hv.h2) == 2) {
		    r = LookupHash(hv, NULL, NULL);
		}
	    }
	    if (fi != stdin)
		fclose(fi);
	} else {
	    fprintf(stderr, "Unable to open %s (%s)\n", file, strerror(errno));
	}
    } else {
	hash_t hv;
	char *msgid = NULL;

	if (arg[0] == '<') {
	    msgid = arg;
	    hv = hhash(arg);
	    r = LookupHash(hv, msgid, NULL);
	} else if (arg[0] == 'D' && arg[1] == '.') {
	    int32 dummy;

	    if (sscanf(arg + 2, "%x/%x.%x", &dummy, &hv.h1, &hv.h2) != 3) {
		fprintf(stderr, "argument error\n");
		exit(1);
	    }
	    r = LookupHash(hv, msgid, NULL);
	} else if (sscanf(arg, "%x.%x", &hv.h1, &hv.h2) == 2) {
	    r = LookupHash(hv, msgid, NULL);
	} else {
	    char fname[PATH_MAX];
	    char *p = fname;
	    History h = { 0 };

	    *p = 0;
	    if (*arg != '/') {
		sprintf(p, "%s/", PatExpand(SpoolHomePat));
		p += strlen(p);
	    }
	    if (sscanf(arg, "%[^:]:%d,%d", p, &h.boffset, &h.bsize) == 3) {
		DumpArticle(fname, &h, NULL);
	    } else {
		printf("Unknown argument: %s\n", arg);
	    }
	}
    }
    exit(r);
}
Ejemplo n.º 5
0
void PrintUsage()
{
int i;

PrintVersion();
fprintf(stdout,"Author: Colum Paget\n");
fprintf(stdout,"Email: [email protected]\n");
fprintf(stdout,"Blog: http://idratherhack.blogspot.com \n");
fprintf(stdout,"\n");
fprintf(stdout,"Usage: movgrab [-t <type>] -a [<username>:<password>] [-p http://username:[email protected]:80 ] [-r] [-b] [-x] [-q] [-st <stream timeout>] [-f <format list>] [-v] [-P] [-Pp] [-o <output file>] [+o <extra output file>] url\n");
fprintf(stdout,"	movgrab -test-sites\n");
fprintf(stdout,"\n'-v'		increases verbosity/debug level\n");
fprintf(stdout,"'-v -v'		prints out all webpages encountered\n");
fprintf(stdout,"'-v -v -v'	maximum debugging\n");
fprintf(stdout,"'-version'		Program version\n");
fprintf(stdout,"'--version'		Program version\n");
fprintf(stdout,"'-T'		Test mode, don't do final download\n");
fprintf(stdout,"'-P <program>'		Player program (e.g. \"mplayer\")\n");
fprintf(stdout,"'-Pp'		Percent download to launch player at (default 25%)\n");
fprintf(stdout,"'-a'		Authentication info in Username:Password format.\n");
fprintf(stdout,"'-q'		QUIET. No progress/informative output.\n");
fprintf(stdout,"'-b'		Background. Fork into background and nohup\n");
fprintf(stdout,"'-p'		address of http/https/sstunnel proxy server in URL format.\n");
fprintf(stdout,"'-proxy'		address of http/https/socks4/socks5/sstunnel proxy server in URL format.\n");
fprintf(stdout,"'-w'		Wait for addresses to be entered on stdin.\n");
fprintf(stdout,"'-st'		Connection inactivity timeout in seconds. Set high for sites that 'throttle'\n");
fprintf(stdout,"'-tw <int>'		Set max width of item title in progress display (Default 50 chars)\n");
fprintf(stdout,"'-t'		specifies website type.\n");
fprintf(stdout,"'-r'		Resume download (only works when writing a single file, not with +o).\n");
fprintf(stdout,"'-f'		specifies preferred video/audio formats for sites that offer more than one\n");
fprintf(stdout,"			example: flv:640x480,flv,mp4,mp3\n");
fprintf(stdout,"			Use -T to get a list of formats the site offers\n");
fprintf(stdout,"			Use * to mean 'any format' (the default)\n");
fprintf(stdout,"			example: flv:640x480,mp4:640x480,*\n");
fprintf(stdout,"'-o'		specifies output file ( '-' for stdout)\n");
fprintf(stdout,"'+o'		add an output file to list of output files ( '-' for stdout)\n");
fprintf(stdout,"'-x'		try to avoid 'family filter' on some sites\n");
fprintf(stdout,"'-n'		For pages with multiple movies (not movie formats, but movies) specifes item selection for download. Argument has the form:\n");
fprintf(stdout,"			-n all		Download all\n");
fprintf(stdout,"			-n 2		Download 2nd item\n");
fprintf(stdout,"			-n 2-5		Download 2nd to 5th item\n");
fprintf(stdout,"			-n 2-		Download from 2nd item onwards\n");
fprintf(stdout,"			-n -8		Download from 1st to 8th item\n");
fprintf(stdout,"-test-sites		Test downloading from each supported website");
fprintf(stdout,"\nThe '-t' argument is optional, Movgrab will try to guess the download type from the provided url.\n\n");

fprintf(stdout,"The url should be that of the page that the movie would normally appear on. Movgrab examines the page for embed tags and other information that would normally cause the movie to play on that page.\n");

fprintf(stdout,"\nDownload types are:\n");
for (i=1; DownloadTypes[i] !=NULL; i++) fprintf(stdout,"%-20s %s\n",DownloadTypes[i],DownloadNames[i]);

fprintf(stdout,"\nThe -proxy argument has the form <protocol>:<username>:<password>@<host>:<port>. So, for example socks4:192.168.1.1:8080 or socks5:user1:[email protected]:5050\n");

fprintf(stdout,"\nIf a website is not in the list, try 'movgrab -t generic <url>'\n");
fprintf(stdout,"\nMovgrab can also be used to stream from internet radio and pipe it into a player. E.g.'\n		movgrab -o - -q -proxy ssltunnel://guest:s3cr3t@sshserver:1022 http://schizoid.in/schizoid-psy.pls | mpg123 -\n");
fprintf(stdout,"\nFeel free to email me and tell me if you've used this software!\n");

fprintf(stdout,"\nThanks for bug reports go to: Philip Pi, Mark Gamar, Rich Kcsa, 'Rampant Badger', 'nibbles', 'deeice', Omair Eshkenazi, Matthias B, Ashish Disawal, Timo Juhani Lindfors, Abhisek Sanyal and others.\n");
fprintf(stdout,"\nSpecial thanks to:\n");
fprintf(stdout,"	'legatvs' for clive (http://clive.sourceforge.net) another downloader into whose code I had to look to figure out how to get youtube and daily motion working again.\n");
fprintf(stdout,"	Robert Crowley (http://oldcoder.org/) For all sorts of bug reports and advice.\n");
}
Ejemplo n.º 6
0
static GenericAgentConfig *CheckOpts(EvalContext *ctx, int argc, char **argv)
{
    extern char *optarg;
    int optindex = 0;
    int c;
    char ld_library_path[CF_BUFSIZE];
    GenericAgentConfig *config = GenericAgentConfigNewDefault(AGENT_TYPE_EXECUTOR);

    while ((c = getopt_long(argc, argv, "dvnKIf:D:N:VxL:hFOV1gMWlC::", OPTIONS, &optindex)) != EOF)
    {
        switch ((char) c)
        {
        case 'l':
            LEGACY_OUTPUT = true;
            break;

        case 'f':

            if (optarg && strlen(optarg) < 5)
            {
                Log(LOG_LEVEL_ERR, " -f used but argument '%s' incorrect", optarg);
                exit(EXIT_FAILURE);
            }

            GenericAgentConfigSetInputFile(config, GetWorkDir(), optarg);
            MINUSF = true;
            break;

        case 'd':
            LogSetGlobalLevel(LOG_LEVEL_DEBUG);
            break;

        case 'K':
            IGNORELOCK = true;
            break;

        case 'D':
            config->heap_soft = StringSetFromString(optarg, ',');
            break;

        case 'N':
            config->heap_negated = StringSetFromString(optarg, ',');
            break;

        case 'I':
            LogSetGlobalLevel(LOG_LEVEL_INFO);
            break;

        case 'v':
            LogSetGlobalLevel(LOG_LEVEL_VERBOSE);
            NO_FORK = true; // TODO: really?
            break;

        case 'n':
            DONTDO = true;
            IGNORELOCK = true;
            EvalContextHeapAddHard(ctx, "opt_dry_run");
            break;

        case 'L':
            snprintf(ld_library_path, CF_BUFSIZE - 1, "LD_LIBRARY_PATH=%s", optarg);
            if (putenv(xstrdup(ld_library_path)) != 0)
            {
            }
            break;

        case 'W':
            WINSERVICE = false;
            break;

        case 'F':
            NO_FORK = true;
            break;

        case 'O':
            ONCE = true;
            NO_FORK = true;
            break;

        case 'V':
            PrintVersion();
            exit(0);

        case 'h':
            PrintHelp("cf-execd", OPTIONS, HINTS, true);
            exit(0);

        case 'M':
            {
                Writer *out = FileWriter(stdout);
                ManPageWrite(out, "cf-execd", time(NULL),
                             CF_EXECD_SHORT_DESCRIPTION,
                             CF_EXECD_MANPAGE_LONG_DESCRIPTION,
                             OPTIONS, HINTS,
                             true);
                FileWriterDetach(out);
                exit(EXIT_SUCCESS);
            }

        case 'x':
            Log(LOG_LEVEL_ERR, "Self-diagnostic functionality is retired.");
            exit(0);

        case 'C':
            if (!GenericAgentConfigParseColor(config, optarg))
            {
                exit(EXIT_FAILURE);
            }
            break;

        default:
            PrintHelp("cf-execd", OPTIONS, HINTS, true);
            exit(1);

        }
    }

    if (!GenericAgentConfigParseArguments(config, argc - optind, argv + optind))
    {
        Log(LOG_LEVEL_ERR, "Too many arguments");
        exit(EXIT_FAILURE);
    }

    return config;
}
Ejemplo n.º 7
0
/*
 * Main program.
 */
int main (int argc, char * argv []) {
  int i,c,k;
  int doDefaultConfig = TRUE;
  int doDefaultProgram = TRUE;
  int printCCTable = FALSE;
  int doDefaultCC = TRUE;
  char * configOverride [NOF_CFG_OVERS];
  int configOverEnd = 0;
  int loadProgram = -1;
  unsigned int randomPreset[9];
  unsigned int defaultPreset[9] = {8,8,8, 0,0,0,0, 0,0};
  unsigned int * presetSelect = defaultPreset;
  char *midnam = NULL;

  char * alternateProgrammeFile = NULL;
  char * alternateConfigFile = NULL;

  memset(&inst, 0, sizeof(b_instance));

  srand ((unsigned int) time (NULL));

  for (i=0;i<AUDIO_CHANNELS; i++)
    jack_port[i] = NULL;
  jack_ports = strdup("system:playback_");

  const char *optstring = "c:CdDhHl:M:p:PrU:V";
  const struct option long_options[] = {
    { "help",       no_argument,       0, 'H' },
    { "program",    required_argument, 0, 'p' },
    { "config",     required_argument, 0, 'c' },
    { "noconfig",   no_argument,       0, 'C' },
    { "dumpcc",     no_argument,       0, 'd' },
    { "noCC",       no_argument,       0, 'D' },
    { "midnam",     required_argument, 0, 'M' },
    { "noprogram",  no_argument,       0, 'P' },
    { "randomize",  no_argument,       0, 'r' },
    { "upper",      required_argument, 0, 'U' },
    { "version",    no_argument,       0, 'V' },
    { 0, 0, 0, 0 }
  };

  while ((c = getopt_long(argc, argv, optstring, long_options, NULL)) != -1) {
    switch (c) {
      case 'c':
	alternateConfigFile = optarg;
	break;
      case 'C':
	doDefaultConfig = FALSE;
	break;
      case 'd':
	printCCTable = TRUE;
	break;
      case 'D':
	doDefaultCC = FALSE;
	break;
      case 'h':
	Usage(0);
	return (0);
	break;
      case 'H':
	Usage(1);
	return (0);
	break;
      case 'l':
	loadProgram = atoi(optarg);
	break;
      case 'M':
	midnam = optarg;
	break;
      case 'r':
	for (k = 0; k < 9; k++)
	  randomPreset[k] = rand () % 9;
	fprintf (stderr,
	    "Random Preset: "
	     "%d%d %d%d%d%d %d%d%d\n",
	     randomPreset[0],
	     randomPreset[1],
	     randomPreset[2],
	     randomPreset[3],
	     randomPreset[4],
	     randomPreset[5],
	     randomPreset[6],
	     randomPreset[7],
	     randomPreset[8]);
	presetSelect = randomPreset;
	break;
      case 'p':
	alternateProgrammeFile = optarg;
	break;
      case 'P':
	doDefaultProgram = FALSE;
	break;
      case 'U':
	parse_preset(defaultPreset, optarg);
	break;
      case 'V':
	PrintVersion();
	return(0);
      default:
	fprintf(stderr, "invalid argument.\n");
	Usage(0);
	return(1);
    }
  }

  for (i = optind; i < argc; ++i) {
    char * av = argv[i];
    if (strchr (av, '=') != NULL) {
      /* Remember this as a config parameter */
      if (configOverEnd < NOF_CFG_OVERS) {
	configOverride[configOverEnd++] = av;
      } else {
	fprintf (stderr,
	    "Too many configuration parameters (%d), please consider using a\n"
	    "configuration file instead of the commandline.\n",
	    NOF_CFG_OVERS);
	return(1);
      }
    }
  }

  /*
   * allocate data structures, instances.
   */
  allocAll();

  /*
   * evaluate configuration
   */

  if (getenv("XDG_CONFIG_HOME")) {
    size_t hl = strlen(getenv("XDG_CONFIG_HOME"));
    defaultConfigFile=(char*) malloc(hl+32);
    defaultProgrammeFile=(char*) malloc(hl+32);
    sprintf(defaultConfigFile, "%s/setBfree/default.cfg", getenv("XDG_CONFIG_HOME"));
    sprintf(defaultProgrammeFile, "%s/setBfree/default.pgm", getenv("XDG_CONFIG_HOME"));
  } else if (getenv("HOME")) {
    size_t hl = strlen(getenv("HOME"));
    defaultConfigFile=(char*) malloc(hl+30);
    defaultProgrammeFile=(char*) malloc(hl+30);
    sprintf(defaultConfigFile, "%s/.config/setBfree/default.cfg", getenv("HOME"));
    sprintf(defaultProgrammeFile, "%s/.config/setBfree/default.pgm", getenv("HOME"));
  }

  /*
   * Here we call modules that need to execute code in order to arrange
   * static initializations that is not practical to achieve in source code.
   */

  initControllerTable (inst.midicfg);
  if (doDefaultCC) {
    midiPrimeControllerMapping (inst.midicfg);
  }

  /*
   * Commandline arguments are parsed. If we are of a mind to try the
   * default configuration file we do that now.
   */

  if (doDefaultConfig == TRUE && defaultConfigFile) {
    if (access (defaultConfigFile, R_OK) == 0) {
      fprintf(stderr, "loading cfg: %s\n", defaultConfigFile);
      parseConfigurationFile (&inst, defaultConfigFile);
    }
  }

  if (alternateConfigFile) {
    if (access (alternateConfigFile, R_OK) == 0) {
      fprintf(stderr, "loading cfg: %s\n", alternateConfigFile);
      parseConfigurationFile (&inst, alternateConfigFile);
    }
  }

  /*
   * Then apply any configuration parameters collected from the commandline.
   * These must be applied last so that they can override the parameters
   * read from the files (if any).
   */

  for (i = 0; i < configOverEnd; i++) {
    parseConfigurationLine (&inst, "commandline argument",
			    0,
			    configOverride[i]);
  }

  /*
   * Having configured the initialization phase we can now actually do it.
   */
#ifndef _WIN32
  if (mlockall (MCL_CURRENT | MCL_FUTURE)) {
    fprintf(stderr, "Warning: Can not lock memory.\n");
  }
#endif

  initAll ();

  /*
   * We are initialized and now load the programme file.
   */

  if (doDefaultProgram == TRUE && defaultProgrammeFile) {
    if (access (defaultProgrammeFile, R_OK) == 0)
      loadProgrammeFile (inst.progs, defaultProgrammeFile);
  } else {
    walkProgrammes(inst.progs, 1); // clear built-in default program
  }
  if (alternateProgrammeFile != NULL)
    loadProgrammeFile (inst.progs, alternateProgrammeFile);

  if (walkProgrammes(inst.progs, 0)) {
    listProgrammes (inst.progs, stderr);
  }

  initMidiTables(inst.midicfg);

  if (printCCTable) {
    listCCAssignments(inst.midicfg, stderr);
  }

  if (midnam) {
    FILE *fp = fopen(midnam, "w");
    if (fp) {
      save_midname(&inst, fp);
      fclose(fp);
    } else {
      fprintf(stderr, "failed to write midnam to '%s'\n", midnam);
    }
  }

  /*
   * With the programmes eager and ready to go, we spawn off the MIDI
   * listener thread. The thread will initialize the MIDI device.
   */
#ifdef HAVE_ASEQ
  pthread_t t_midi;
  if (!use_jack_midi) {
    if (!aseq_open(midi_port)) {
      k = pthread_create(&t_midi, NULL, aseq_run, &inst);
      if (k != 0) {
	fprintf (stderr, "%d : %s\n", k, "pthread_create : MIDIInReader thread");
	return (1);
      }
    } else {
      return (1);
    }
  }
#endif

  setMIDINoteShift (inst.midicfg, 0);

  setDrawBars (&inst, 0, presetSelect);
#if 0 // initial values are assigned in tonegen.c initToneGenerator()
  setDrawBars (&inst, 1, presetSelect); /* 838 000 000 */
  setDrawBars (&inst, 2, presetSelect); /* 86 - */
#endif

  const int pgm_off = inst.progs->MIDIControllerPgmOffset;
  if (loadProgram >= 0 && loadProgram >= pgm_off) {
    installProgram(&inst, (loadProgram - pgm_off));
  }

#ifndef _WIN32
  signal (SIGHUP, catchsig);
  signal (SIGINT, catchsig);
#endif

  connect_jack_ports();

  synth_ready = 1;

  fprintf(stderr,"All systems go. press CTRL-C, or send SIGINT or SIGHUP to terminate\n");

  while (j_client)
  /* jack callback is doing this the work now */
#ifdef _WIN32
    Sleep (1000);
#else
    sleep (1);
#endif

  /* shutdown and cleanup */
#ifdef HAVE_ASEQ
  if (!use_jack_midi) {
    aseq_stop=1;
    pthread_join(t_midi, NULL);
    aseq_close();
  }
#endif

  free(defaultConfigFile);
  free(defaultProgrammeFile);

  free(j_output_bufferptrs);
  free(j_output_port);
  free(midi_port);
  free(jack_ports);
  for (i=0;i<AUDIO_CHANNELS; i++)
    free(jack_port[i]);

  freeAll();
#ifndef _WIN32
  munlockall();
#endif

  fprintf(stderr, "bye\n");
  return 0;
}
Ejemplo n.º 8
0
int CDaemonConsole::Run(int argc, char* argv[])
{
    /* Read command line parameters */

    int cur_arg=1;
    std::string sAction;
    std::string sConfigFile;
    std::string sPrefix;
    eMonitorOption MonitorOption = MO_UNDEFINED;
	bool bRestartedOnCrash = false;
    int nPid = 0;
    CDaemon daemon;
	m_pDaemon = &daemon;
	
    //MessageBoxA(NULL, "", "", 0);

    while(args_left()>0)
    {
        if(cmp_arg("--help"))
        {
            if(args_left()!=1)
            {
                m_sErrorMsg = "Too many parameters for --help command.";
                goto exit;
            }

            sAction += "help";
            break;
        }
		else if(cmp_arg("--test-crash"))
		{
			int* p = NULL;
			*p = 13;
		}
		else if(cmp_arg("-v"))
        {
            if(args_left()!=1)
            {
                m_sErrorMsg = "Too many parameters for -v command.";
                goto exit;
            }

            sAction += "version";
            break;
        }
        else if(cmp_arg("--start"))
        {
            sAction += "start";
        }
        else if(cmp_arg("--stop"))
        {
            sAction += "stop";
        }
#ifdef _WIN32
		else if(cmp_arg("--install"))
        {
            sAction += "install";
        }
        else if(cmp_arg("--remove"))
        {
            sAction += "remove";
        }
        else if(cmp_arg("--restart"))
        {
            sAction += "restart";
        }
		else if(cmp_arg("--run"))
        {
            sAction += "run";
        }
#endif
        else if(cmp_arg("-c") || cmp_arg("--config"))
        {
            skip_arg();
            char* szParam = get_arg();
            if(szParam==NULL)
            {
                m_sErrorMsg = "Exptected configuration file name.";
                goto exit;
            }

            sConfigFile = szParam;
        }
        else if(cmp_arg("--run-as-monitor"))
        {
            skip_arg();
            char* szParam = get_arg();
            if(szParam==NULL)
            {
                m_sErrorMsg = "Exptected PID.";
                goto exit;
            }

            nPid = atoi(szParam);

            MonitorOption = MO_IS_MONITOR;
        }
		else if(cmp_arg("--restart-on-crash"))
        {
            MonitorOption = MO_NO_MONITOR;
			bRestartedOnCrash = TRUE;
        }
        else
        {
            char* szParam = get_arg();
            m_sErrorMsg += "Unexpected parameter: ";
            m_sErrorMsg += szParam;
            goto exit;
        }

        skip_arg();
    }

    if(sAction=="help")
    {
        PrintUsage();
        goto exit;
    }
	else if(sAction=="version")
    {
        PrintVersion();
        goto exit;
    }
#ifdef _WIN32
	else if(sAction=="install")
    {
        if(!sConfigFile.empty())
            daemon.SetConfigFile(sConfigFile);
		return daemon.Install();
    }
	else if(sAction=="remove")
    {
        if(!sConfigFile.empty())
            daemon.SetConfigFile(sConfigFile);
		return daemon.Remove();
    }
	else if(sAction=="run")
    {
        if(!sConfigFile.empty())
            daemon.SetConfigFile(sConfigFile);
        daemon.SetMonitorOption(MonitorOption, nPid);
		daemon.SetErrorRestartFlag(bRestartedOnCrash);

		m_pDaemon = &daemon;
        daemon.Run();
		return 0;
    }
#endif
    else if(sAction=="start")
    {
        if(!sConfigFile.empty())
            daemon.SetConfigFile(sConfigFile);
        daemon.SetMonitorOption(MonitorOption, nPid);
		daemon.SetErrorRestartFlag(bRestartedOnCrash);

		m_pDaemon = &daemon;
        return daemon.Start();
    }
	else if(sAction=="restart")
    {
        if(!sConfigFile.empty())
            daemon.SetConfigFile(sConfigFile);
        if(!sPrefix.empty())
            daemon.SetPrefix(sPrefix);

		m_pDaemon = &daemon;
        return daemon.Restart();
    }
	else if(sAction=="stop")
    {
        if(!sConfigFile.empty())
            daemon.SetConfigFile(sConfigFile);
        if(!sPrefix.empty())
            daemon.SetPrefix(sPrefix);

        return daemon.Stop();
    }
    else
    {
		m_sErrorMsg = "Invalid combination of commands.";

#ifdef _WIN32
		m_pDaemon = &daemon;
		daemon.EnterServiceMain();
#endif

        goto exit;
    }

exit:

	m_pDaemon = NULL;

    return m_sErrorMsg.empty()?0:1;

}
Ejemplo n.º 9
0
int RunDebugger()
{
	if (!gpSrv->DbgInfo.pDebugTreeProcesses)
	{
		gpSrv->DbgInfo.pDebugTreeProcesses = (MMap<DWORD,CEDebugProcessInfo>*)calloc(1,sizeof(*gpSrv->DbgInfo.pDebugTreeProcesses));
		gpSrv->DbgInfo.pDebugTreeProcesses->Init(1024);
	}

	UpdateDebuggerTitle();

	// Если это новая консоль - увеличить ее размер, для удобства
	if (IsWindowVisible(ghConWnd))
	{
		HANDLE hCon = ghConOut;
		CONSOLE_SCREEN_BUFFER_INFO csbi = {};
		GetConsoleScreenBufferInfo(hCon, &csbi);
		if (csbi.dwSize.X < 260)
		{
			COORD crNewSize = {260, 9999};
			SetConsoleScreenBufferSize(ghConOut, crNewSize);
		}
		//if ((csbi.srWindow.Right - csbi.srWindow.Left + 1) < 120)
		//{
		//	COORD crMax = GetLargestConsoleWindowSize(hCon);
		//	if ((crMax.X - 10) > (csbi.srWindow.Right - csbi.srWindow.Left + 1))
		//	{
		//		COORD crSize = {((int)((crMax.X - 15)/10))*10, min(crMax.Y, (csbi.srWindow.Bottom - csbi.srWindow.Top + 1))};
		//		SMALL_RECT srWnd = {0, csbi.srWindow.Top, crSize.X - 1, csbi.srWindow.Bottom};
		//		MONITORINFO mi = {sizeof(mi)};
		//		GetMonitorInfo(MonitorFromWindow(ghConWnd, MONITOR_DEFAULTTONEAREST), &mi);
		//		RECT rcWnd = {}; GetWindowRect(ghConWnd, &rcWnd);
		//		SetWindowPos(ghConWnd, NULL, min(rcWnd.left,(mi.rcWork.left+50)), rcWnd.top, 0,0, SWP_NOSIZE|SWP_NOZORDER);
		//		SetConsoleSize(9999, crSize, srWnd, "StartDebugger");
		//	}
		//}
	}

	// Вывести в консоль информацию о версии.
	PrintVersion();
	#ifdef SHOW_DEBUG_STARTED_MSGBOX
	wchar_t szInfo[128];
	StringCchPrintf(szInfo, countof(szInfo), L"Attaching debugger...\nConEmuC PID = %u\nDebug PID = %u",
	                GetCurrentProcessId(), gpSrv->dwRootProcess);
	MessageBox(GetConEmuHWND(2), szInfo, L"ConEmuC.Debugger", 0);
	#endif

	//if (!DebugActiveProcess(gpSrv->dwRootProcess))
	//{
	//	DWORD dwErr = GetLastError();
	//	_printf("Can't start debugger! ErrCode=0x%08X\n", dwErr);
	//	return CERR_CANTSTARTDEBUGGER;
	//}
	//// Дополнительная инициализация, чтобы закрытие дебагера (наш процесс) не привело
	//// к закрытию "отлаживаемой" программы
	//pfnDebugActiveProcessStop = (FDebugActiveProcessStop)GetProcAddress(GetModuleHandle(L"kernel32.dll"),"DebugActiveProcessStop");
	//pfnDebugSetProcessKillOnExit = (FDebugSetProcessKillOnExit)GetProcAddress(GetModuleHandle(L"kernel32.dll"),"DebugSetProcessKillOnExit");
	//if (pfnDebugSetProcessKillOnExit)
	//	pfnDebugSetProcessKillOnExit(FALSE/*KillOnExit*/);
	//gpSrv->DbgInfo.bDebuggerActive = TRUE;
	//PrintDebugInfo();

	if (gpSrv->DbgInfo.pszDebuggingCmdLine == NULL)
	{
		int iAttachRc = AttachRootProcessHandle();
		if (iAttachRc != 0)
			return iAttachRc;
	}
	else
	{
		_ASSERTE(!gpSrv->DbgInfo.bDebuggerActive);
	}

	_ASSERTE(((gpSrv->hRootProcess!=NULL) || (gpSrv->DbgInfo.pszDebuggingCmdLine!=NULL)) && "Process handle must be opened");

	gpSrv->DbgInfo.hDebugReady = CreateEvent(NULL, FALSE, FALSE, NULL);
	// Перенес обработку отладочных событий в отдельную нить, чтобы случайно не заблокироваться с главной
	gpSrv->DbgInfo.hDebugThread = CreateThread(NULL, 0, DebugThread, NULL, 0, &gpSrv->DbgInfo.dwDebugThreadId);
	HANDLE hEvents[2] = {gpSrv->DbgInfo.hDebugReady, gpSrv->DbgInfo.hDebugThread};
	DWORD nReady = WaitForMultipleObjects(countof(hEvents), hEvents, FALSE, INFINITE);

	if (nReady != WAIT_OBJECT_0)
	{
		DWORD nExit = 0;
		GetExitCodeThread(gpSrv->DbgInfo.hDebugThread, &nExit);
		return nExit;
	}

	gpszRunCmd = (wchar_t*)calloc(1,2);

	if (!gpszRunCmd)
	{
		_printf("Can't allocate 1 wchar!\n");
		return CERR_NOTENOUGHMEM1;
	}

	gpszRunCmd[0] = 0;
	gpSrv->DbgInfo.bDebuggerActive = TRUE;
	return 0;
}
Ejemplo n.º 10
0
/**
Function to parse the command line options.
Responsible to
1. Parse the input values.
2. Print the usage note. 
3. Identify the valdations to be carried out.
4. Type of report needs to be generated.

@internalComponent
@released

@param aArgc - argument count
@param aArgv[] - argument values
*/
ReturnType CmdLineHandler::ProcessCommandLine(unsigned int aArgc, char* aArgv[])
{
	if(aArgc < 2)
	{
		std::cout << PrintVersion().c_str() << std::endl;
		std::cout << PrintUsage().c_str() << std::endl;
		return EQuit;
	}
	ArgumentList argumentList(&aArgv[0], aArgv + aArgc);
	int argCount = argumentList.size();

	 iInputCommand = KToolName;

	for( int i = 1; i < argCount; i++ ) //Skip tool name
	{
		String name = argumentList.at(i);
		iInputCommand += " ";
		iInputCommand += name;
		int longOptionFlag = 0;
		if(IsOption(name, longOptionFlag))
		{
			String optionName;
			bool optionValue = false;
			StringList optionValueList;
			ParseOption(name, optionName, optionValueList, optionValue);
			char shortOption = KNull;
			if(Validate(ReaderUtil::ToLower(optionName), optionValue, optionValueList.size()))
			{
				if(longOptionFlag)
				{
					shortOption = optionName.at(2);
				}
				else
				{
					shortOption = optionName.at(1);
				}
			}

			switch(shortOption)
			{
				case 'q':
					iCommmandFlag |= QuietMode;
					break;
				case 'a':
					iCommmandFlag |= KAll;
					break;
				case 'x':
					iCommmandFlag |= KXmlReport;
					break;
				case 'o':
					iXmlFileName.assign(optionValueList.front());
					NormaliseName();
					break;
				case 's':
					if((optionName == KShortSuppressOption) || (optionName == KLongSuppressOption))
					{
						String value;
						while(optionValueList.size() > 0)
						{
							value = optionValueList.front();
							if(iSuppressVal[value])
							{
								if(iValidations > 0) //Is any check enabled?
								{
									if(iValidations & iSuppressVal[value])
									{
										iValidations ^= iSuppressVal[value]; //Consider only 3 LSB's
									}
								}
								else //Is this valid value?
								{
									iSuppressions |= iSuppressVal[value];
								}
							}
							else
							{
								throw ExceptionReporter(UNKNOWNSUPPRESSVAL,(char*)(optionValueList.front().c_str()));
							}
							optionValueList.pop_front();
						}
					}
					else if(optionName == KLongEnableSidCheck)
					{
						iValidations |= KMarkEnable;
						iValidations |= ESid;
					}
					else if(optionName == KLongSidAllOption)
					{
						iCommmandFlag |= KSidAll;
					}
					break;
				case 'd':
					if(optionName == KLongEnableDbgFlagCheck)
					{
						iValidations |= KMarkEnable;
						iValidations |= EDbg;
						if(optionValueList.size() > 0)
						{
							if(optionValueList.front() == String("true"))
							{
								iDebuggableFlagVal = true;
							}
							else if (optionValueList.front() == String("false"))
							{
								iDebuggableFlagVal = false; 
							}
							else
							{
								throw ExceptionReporter(UNKNOWNDBGVALUE);
							}
						}
					}
					else if (optionName == KLongEnableDepCheck)
					{
						iValidations |= KMarkEnable;
						iValidations |= EDep;
					}
					break;

				case 'e':
					if (optionName == KLongE32InputOption)
					{
						iCommmandFlag |= KE32Input;
					}
					break;

				case 'v':
					if(optionName == KLongVidValOption)
					{
						StringListToUnIntList(optionValueList, iVidValList);
					}
					else if(optionName == KLongEnableVidCheck)
					{
						iValidations |= KMarkEnable;
						iValidations |= EVid;
					}
					else
					{
						iCommmandFlag |= KVerbose;
						/**Initialize ExceptionImplementation class with verbose mode flag
						to print all status information to standard output*/
						ExceptionImplementation::Instance(iCommmandFlag);
					}
					break;
				case 'n':
						iCommmandFlag |= KNoCheck;
					break;
				case 'h':
					std::cout << PrintVersion().c_str() << std::endl;
					std::cout << PrintUsage().c_str() << std::endl;
					return EQuit; //Don't proceed further
			}
		}
		else
		{
			if(!AlreadyReceived(name))
			{
				iImageNameList.push_back(name);
			}
			else
			{
				ExceptionReporter(IMAGENAMEALREADYRECEIVED, (char*)name.c_str()).Report();
			}

			iNoImage = false;
		}
	} //While loop ends here
	if((iCommmandFlag || iValidations || iSuppressions) && iNoImage)
	{
		PrintVersion();
		PrintUsage();
	}
	//Always log the version information into log file
	ExceptionImplementation::Instance(iCommmandFlag)->Log(iVersion);
	ValidateArguments();
	ValidateE32NoCheckArguments();
	if(iCommmandFlag & KE32Input)
	{
		ValidateImageNameList();
	}
	return ESuccess;
}
Ejemplo n.º 11
0
void
R_common_command_line(int *pac, char **argv, Rstart Rp)
{
    int ac = *pac, newac = 1;	/* argv[0] is process name */
    long lval; /* this is only used for ppval, so 32-bit long is fine */
    char *p, **av = argv, msg[1024];
    Rboolean processing = TRUE;

    R_RestoreHistory = 1;
    while(--ac) {
	if(processing && **++av == '-') {
	    if (!strcmp(*av, "--version")) {
		PrintVersion(msg, 1024);
		R_ShowMessage(msg);
		exit(0);
	    }
	    else if(!strcmp(*av, "--args")) {
		/* copy this through for further processing */
		argv[newac++] = *av;
		processing = FALSE;
	    }
	    else if(!strcmp(*av, "--save")) {
		Rp->SaveAction = SA_SAVE;
	    }
	    else if(!strcmp(*av, "--no-save")) {
		Rp->SaveAction = SA_NOSAVE;
	    }
	    else if(!strcmp(*av, "--restore")) {
		Rp->RestoreAction = SA_RESTORE;
	    }
	    else if(!strcmp(*av, "--no-restore")) {
		Rp->RestoreAction = SA_NORESTORE;
		R_RestoreHistory = 0;
	    }
	    else if(!strcmp(*av, "--no-restore-data")) {
		Rp->RestoreAction = SA_NORESTORE;
	    }
	    else if(!strcmp(*av, "--no-restore-history")) {
		R_RestoreHistory = 0;
	    }
	    else if (!strcmp(*av, "--silent") ||
		     !strcmp(*av, "--quiet") ||
		     !strcmp(*av, "-q")) {
		Rp->R_Quiet = TRUE;
	    }
	    else if (!strcmp(*av, "--vanilla")) {
		Rp->SaveAction = SA_NOSAVE; /* --no-save */
		Rp->RestoreAction = SA_NORESTORE; /* --no-restore */
		R_RestoreHistory = 0;     // --no-restore-history (= part of --no-restore)
		Rp->LoadSiteFile = FALSE; /* --no-site-file */
		Rp->LoadInitFile = FALSE; /* --no-init-file */
		Rp->NoRenviron = TRUE;    // --no-environ
#ifdef Win32
		R_LoadRconsole = FALSE;
#endif
	    }
	    else if (!strcmp(*av, "--no-environ")) {
		Rp->NoRenviron = TRUE;
	    }
	    else if (!strcmp(*av, "--verbose")) {
		Rp->R_Verbose = TRUE;
	    }
	    else if (!strcmp(*av, "--slave") ||
		     !strcmp(*av, "-s")) {
		Rp->R_Quiet = TRUE;
		Rp->R_Slave = TRUE;
		Rp->SaveAction = SA_NOSAVE;
	    }
	    else if (!strcmp(*av, "--no-site-file")) {
		Rp->LoadSiteFile = FALSE;
	    }
	    else if (!strcmp(*av, "--no-init-file")) {
		Rp->LoadInitFile = FALSE;
	    }
	    else if (!strcmp(*av, "--debug-init")) {
		Rp->DebugInitFile = TRUE;
	    }
	    else if (!strncmp(*av, "--encoding", 10)) {
		if(strlen(*av) < 12) {
		    if(ac > 1) {ac--; av++; p = *av;} else p = NULL;
		} else p = &(*av)[11];
		if (p == NULL) {
		    R_ShowMessage(_("WARNING: no value given for --encoding"));
		} else {
		    strncpy(R_StdinEnc, p, 30);
		    R_StdinEnc[30] = '\0';
		}
	    }
#ifdef Win32
	    else if (!strcmp(*av, "--no-Rconsole")) {
		R_LoadRconsole = 0;
	    }
#endif
	    else if (!strcmp(*av, "-save") ||
		     !strcmp(*av, "-nosave") ||
		     !strcmp(*av, "-restore") ||
		     !strcmp(*av, "-norestore") ||
		     !strcmp(*av, "-noreadline") ||
		     !strcmp(*av, "-quiet") ||
		     !strcmp(*av, "-nsize") ||
		     !strcmp(*av, "-vsize") ||
		     !strncmp(*av, "--max-nsize", 11) ||
		     !strncmp(*av, "--max-vsize", 11) ||
		     !strcmp(*av, "-V") ||
		     !strcmp(*av, "-n") ||
		     !strcmp(*av, "-v")) {
		snprintf(msg, 1024,
			 _("WARNING: option '%s' no longer supported"), *av);
		R_ShowMessage(msg);
	    }
	    /* mop up --min-[nv]size */
	    else if( !strncmp(*av, "--min-nsize", 11) ||
		     !strncmp(*av, "--min-vsize", 11) ) {
		if(strlen(*av) < 13) {
		    if(ac > 1) {ac--; av++; p = *av;} else p = NULL;
		} else p = &(*av)[12];
		if (p == NULL) {
		    snprintf(msg, 1024,
			     _("WARNING: no value given for '%s'"), *av);
		    R_ShowMessage(msg);
		    break;
		}
		int ierr;
		R_size_t value;
		value = R_Decode2Long(p, &ierr);
		if(ierr) {
		    if(ierr < 0)
			snprintf(msg, 1024,
				 _("WARNING: '%s' value is invalid: ignored"),
				 *av);
		    else
			sprintf(msg,
				_("WARNING: %s: too large and ignored"),
				*av);
		    R_ShowMessage(msg);

		} else {
		    if(!strncmp(*av, "--min-nsize", 11)) Rp->nsize = value;
		    if(!strncmp(*av, "--min-vsize", 11)) Rp->vsize = value;
		}
	    }
	    else if(strncmp(*av, "--max-ppsize", 12) == 0) {
		if(strlen(*av) < 14) {
		    if(ac > 1) {ac--; av++; p = *av;} else p = NULL;
		} else p = &(*av)[13];
		if (p == NULL) {
		    R_ShowMessage(_("WARNING: no value given for '--max-ppsize'"));
		    break;
		}
		lval = strtol(p, &p, 10);
		if (lval < 0)
		    R_ShowMessage(_("WARNING: '--max-ppsize' value is negative: ignored"));
		else if (lval < 10000)
		    R_ShowMessage(_("WARNING: '--max-ppsize' value is too small: ignored"));

		else if (lval > 500000)
		    R_ShowMessage(_("WARNING: '--max-ppsize' value is too large: ignored"));
		else Rp->ppsize = (size_t) lval;
	    }
	    else { /* unknown -option */
		argv[newac++] = *av;
	    }
	}
	else {
	    argv[newac++] = *av;
	}
    }
    *pac = newac;
    return;
}
Ejemplo n.º 12
0
void
ParseOptions
	(
	const JSize	argc,
	char*		argv[],
	JString*	fileName,
	JBoolean*	printInfo,
	int*		transparentColor,
	LaceOption*	interlace,
	JBoolean*	padColormap,
	JBoolean*	blend,
	JFloat*		alpha,
	JRGB*		alphaColor,
	JString*	blendOutput
	)
{
	if (argc == 1)
		{
		PrintHelp();
		exit(0);
		}

	fileName->Clear();
	*printInfo        = kJFalse;
	*transparentColor = kTransparentColorNotSet;
	*interlace        = kIgnoreInterlace;
	*padColormap      = kJFalse;
	*blend            = kJFalse;

	JIndex index = 1;
	while (index < argc)
		{
		if (strcmp(argv[index], "-h") == 0 ||
			strcmp(argv[index], "--help") == 0)
			{
			PrintHelp();
			exit(0);
			}
		else if (strcmp(argv[index], "-v") == 0 ||
				 strcmp(argv[index], "--version") == 0)
			{
			PrintVersion();
			exit(0);
			}

		else if (strcmp(argv[index], "-i") == 0)
			{
			*printInfo = kJTrue;
			}

		else if (strcmp(argv[index], "-t") == 0)
			{
			JCheckForValues(1, &index, argc, argv);
			if (strcmp(argv[index], "none") == 0)
				{
				*transparentColor = kNoTransparentColor;
				}
			else if ('0' <= argv[index][0] && argv[index][0] <= '9')
				{
				*transparentColor = atoi(argv[index]);
				}
			else
				{
				cerr << argv[0] << ": -t requires a number or none" << endl;
				exit(1);
				}
			}

		else if (strcmp(argv[index], "-l") == 0)
			{
			JCheckForValues(1, &index, argc, argv);
			if (strcmp(argv[index], "on") == 0)
				{
				*interlace = kTurnInterlaceOn;
				}
			else if (strcmp(argv[index], "off") == 0)
				{
				*interlace = kTurnInterlaceOff;
				}
			else
				{
				cerr << argv[0] << ": -l requires either on or off" << endl;
				exit(1);
				}
			}

		else if (strcmp(argv[index], "-p") == 0)
			{
			*padColormap = kJTrue;
			}

		else if (strcmp(argv[index], "-b") == 0)
			{
			JCheckForValues(5, &index, argc, argv);
			*blend            = kJTrue;
			*alpha            = atof(argv[index]);
			alphaColor->red   = atoi(argv[index+1]);
			alphaColor->green = atoi(argv[index+2]);
			alphaColor->blue  = atoi(argv[index+3]);
			*blendOutput      = argv[index+4];
			index += 4;
			}

		else if (argv[index][0] == '-')
			{
			cerr << argv[0] << ": unknown option " << argv[index] << endl;
			exit(1);
			}

		else if (fileName->IsEmpty())
			{
			if (!JFileReadable(argv[index]))
				{
				cerr << argv[0] << ": file is unreadable" << endl;
				exit(1);
				}
			if (!JFileWritable(argv[index]))
				{
				cerr << argv[0] << ": file is unwriteable" << endl;
				exit(1);
				}
			*fileName = argv[index];
			}

		else
			{
			cerr << argv[0] << ": too many parameters" << endl;
			exit(1);
			}
		index++;
		}

	if (fileName->IsEmpty())
		{
		cerr << argv[0] << ": no input file specified" << endl;
		exit(1);
		}

	if (argc == 2)
		{
		*printInfo = kJTrue;
		}
}
Ejemplo n.º 13
0
Archivo: cli.cpp Proyecto: selius/ncc
CCompilerParameters CCommandLineInterface::ParseArguments()
{
	if (Args.size() < 2) {
		PrintVersion();
		PrintHelp();
		throw CFatalException(EXIT_CODE_TOO_FEW_ARGUMENTS);
	}

	string CurArg;
	string CurOpt;
	bool OptionsEnd = false;

	for (ArgumentsIterator it = ++Args.begin(); it != Args.end(); ++it) {
		CurArg = *it;
		if (!OptionsEnd && CurArg[0] == '-' && CurArg.length() > 1) {
			if (CurArg == "-v" || CurArg == "--version") {
				PrintVersion();
				throw CFatalException(EXIT_CODE_SUCCESS);
			} else if (CurArg == "-h" || CurArg == "--help") {
				PrintHelp(true);
				throw CFatalException(EXIT_CODE_SUCCESS);
			} else if (CurArg == "-o") {
				RequireArgument(it);

				if (!Parameters.OutputFilename.empty()) {
					throw CFatalException(EXIT_CODE_INVALID_ARGUMENTS, "only one output file could be specified");
				}

				Parameters.OutputFilename = *(++it);
			} else if (CurArg == "-S" || CurArg == "--scan" || CurArg == "-P" || CurArg == "--parse" || CurArg == "-G" || CurArg == "--generate") {
				if (Parameters.CompilerMode != COMPILER_MODE_UNDEFINED) {
					throw CFatalException(EXIT_CODE_INVALID_ARGUMENTS, "only one mode could be specified");
				}

				if (CurArg == "-S" || CurArg == "--scan") {
					Parameters.CompilerMode = COMPILER_MODE_SCAN;
				} else if (CurArg == "-P" || CurArg == "--parse") {
					Parameters.CompilerMode = COMPILER_MODE_PARSE;
				} else if (CurArg == "-G" || CurArg == "--generate") {
					Parameters.CompilerMode = COMPILER_MODE_GENERATE;
				}
			} else if (CurArg == "-T" || CurArg == "--symbol-tables") {
				Parameters.SymbolTables = true;
			} else if (CurArg == "-O" || CurArg == "--optimize") {
				Parameters.Optimize = true;
			} else if (CurArg == "--parser-output-mode") {
				RequireArgument(it);

				string OptValue = *(++it);
				if (OptValue == "linear") {
					Parameters.ParserOutputMode = PARSER_OUTPUT_MODE_LINEAR;
				} else if (OptValue == "tree") {
					Parameters.ParserOutputMode = PARSER_OUTPUT_MODE_TREE;
				} else {
					throw CFatalException(EXIT_CODE_INVALID_ARGUMENTS, "invalid value for " + CurArg + " option");
				}
			} else if (CurArg == "--parser-mode") {
				RequireArgument(it);

				string OptValue = *(++it);
				if (OptValue == "normal") {
					Parameters.ParserMode = PARSER_MODE_NORMAL;
				} else if (OptValue == "expression") {
					Parameters.ParserMode = PARSER_MODE_EXPRESSION;
				} else {
					throw CFatalException(EXIT_CODE_INVALID_ARGUMENTS, "invalid value for " + CurArg + " option");
				}
			} else if (CurArg == "--tree") {
				RequireArgument(it);

				if (!Parameters.TreeFilename.empty()) {
					throw CFatalException(EXIT_CODE_INVALID_ARGUMENTS, "only one tree output file could be specified");
				}

				Parameters.TreeFilename = *(++it);
			} else if (CurArg == "--") {
				OptionsEnd = true;
			} else {
				throw CFatalException(EXIT_CODE_INVALID_ARGUMENTS, "invalid option: " + CurArg);
			}
		} else {
			if (!Parameters.InputFilename.empty()) {
				throw CFatalException(EXIT_CODE_TOO_MANY_INPUT_FILES, "only one input file per run is supported");
			}

			Parameters.InputFilename = CurArg;
		}
	}
	if (Parameters.InputFilename.empty()) {
		throw CFatalException(EXIT_CODE_NO_INPUT_FILE, "no input file");
	}

	if (Parameters.CompilerMode == COMPILER_MODE_UNDEFINED) {
		Parameters.CompilerMode = COMPILER_MODE_GENERATE;	// default mode
	}

	if (Parameters.ParserMode == PARSER_MODE_EXPRESSION && Parameters.CompilerMode != COMPILER_MODE_PARSE) {
		throw CFatalException(EXIT_CODE_INVALID_ARGUMENTS, "expressions-only parser mode can only be selected when compiler mode is parsing");
	}

	if (Parameters.SymbolTables && (Parameters.CompilerMode != COMPILER_MODE_PARSE || Parameters.ParserMode != PARSER_MODE_NORMAL)) {
		throw CFatalException(EXIT_CODE_INVALID_ARGUMENTS, "symbol tables printing can only be enabled when compiler mode is parsing and parser mode is normal");
	}

	if (Parameters.Optimize && Parameters.CompilerMode != COMPILER_MODE_GENERATE) {
		throw CFatalException(EXIT_CODE_INVALID_ARGUMENTS, "optimization can only be enabled when compiler mode is code generation");
	}

	if (!Parameters.TreeFilename.empty() && Parameters.CompilerMode != COMPILER_MODE_GENERATE) {
		throw CFatalException(EXIT_CODE_INVALID_ARGUMENTS, "parse tree can only be written to a separate file when compiler mode is code generation");
	}

	return Parameters;
}
Ejemplo n.º 14
0
int main (int argc, char **argv)
{
	int			i;
	double		time, oldtime;

	PrintVersion();

	if (argc > 1)
	{
		for (i = 1; i < argc; i++)
		{
			if ( !(strcmp(argv[i], "-v")) || !(strcmp(argv[i], "-version" )) ||
				  !(strcmp(argv[i], "--version")) )
			{
				exit(0);
			}
			else if ( !(strcmp(argv[i], "-h")) || !(strcmp(argv[i], "-help" )) ||
				  !(strcmp(argv[i], "--help")) || !(strcmp(argv[i], "-?")) )
			{
				PrintHelp(argv[0]);
				exit (0);
			}
		}
	}

	memset (cwd, 0, sizeof(cwd));
	if (Sys_GetBasedir(argv[0], cwd, sizeof(cwd)) != 0)
		Sys_Error ("Couldn't determine current directory");

	/* initialize the host params */
	memset (&parms, 0, sizeof(parms));
	parms.basedir = cwd;
	parms.userdir = cwd;	/* no userdir on win32 */
	parms.argc = argc;
	parms.argv = argv;
	host_parms = &parms;

	LOG_Init (&parms);

	Sys_Printf("basedir is: %s\n", parms.basedir);
	Sys_Printf("userdir is: %s\n", parms.userdir);

	COM_ValidateByteorder ();

	parms.memsize = STD_MEM_ALLOC;

	i = COM_CheckParm ("-heapsize");
	if (i && i < com_argc-1)
	{
		parms.memsize = atoi (com_argv[i+1]) * 1024;

		if ((parms.memsize > MAX_MEM_ALLOC) && !(COM_CheckParm ("-forcemem")))
		{
			Sys_Printf ("Requested memory (%d Mb) too large, using the default maximum.\n", parms.memsize/(1024*1024));
			Sys_Printf ("If you are sure, use the -forcemem switch.\n");
			parms.memsize = MAX_MEM_ALLOC;
		}
		else if ((parms.memsize < MIN_MEM_ALLOC) && !(COM_CheckParm ("-forcemem")))
		{
			Sys_Printf ("Requested memory (%d Mb) too little, using the default minimum.\n", parms.memsize/(1024*1024));
			Sys_Printf ("If you are sure, use the -forcemem switch.\n");
			parms.memsize = MIN_MEM_ALLOC;
		}
	}

	parms.membase = malloc (parms.memsize);

	if (!parms.membase)
		Sys_Error ("Insufficient memory.\n");

	timeBeginPeriod (1);	/* 1 ms timer precision */
	starttime = timeGetTime ();

	Host_Init();

	oldtime = Sys_DoubleTime ();

	/* main window message loop */
	while (1)
	{
		time = Sys_DoubleTime ();

		if (time - oldtime < sys_ticrate.value )
		{
			Sleep (1);
			continue;
		}

		Host_Frame (time - oldtime);
		oldtime = time;
	}

	return 0;
}
Ejemplo n.º 15
0
int
main(int ac, char **av)
{
    int flags = 0;
    int uflag = 0;
    int aflag = 0;
    uint16 spoolObj = (uint16)-1;
    char *historyFileName = NULL;

    LoadDiabloConfig(ac, av);

    FileAry = calloc(sizeof(char *), FileMax);

    {
	int i;

	for (i = 1; i < ac; ++i) {
	    char *ptr = av[i];

	    if (*ptr != '-') {
		if (FileIdx == FileMax) {
		    FileMax = FileMax * 2;
		    FileAry = realloc(FileAry, sizeof(char *) * FileMax);
		}
		FileAry[FileIdx++] = ptr;
		continue;
	    }
	    ptr += 2;
	    switch(ptr[-1]) {
	    case 'a':
		aflag = 1;
		break;
	    case 'C':
		if (*ptr == 0)
		    ++i;
		break;
	    case 'd':
		DebugOpt = (*ptr) ? strtol(ptr, NULL, 0) : strtol(av[++i], NULL, 0);
		break;
	    case 'e':
		UnExpireOpt = 1;
		break;
	    case 'F':
		historyFileName = (*ptr) ? ptr : av[++i];
		break;
	    case 'f':
		flags |= HGF_FAST | HGF_NOSEARCH;
		break;
	    case 'h':
		NewHSize = bsizetol((*ptr) ? ptr : av[++i]);
		if ((NewHSize ^ (NewHSize - 1)) != (NewHSize << 1) - 1) {
		    fprintf(stderr, "specified history size is not a power of 2\n");
		    exit(1);
		}
		break;
	    case 'n':
		ForReal = 0;
		break;
	    case 'Q':
		RequeueOpt = 1;
		break;
	    case 'q':
		QuietOpt = 1;
		break;
	    case 'S':
		spoolObj = (*ptr) ? strtol(ptr, NULL, 10) : strtol(av[++i], NULL, 10);
		break;
	    case 't':
		    if (*ptr == 'b') {
			ptr++;
			GmtStart = timeConv(*ptr ? ptr : av[++i]);
		    } else if (*ptr == 'e') {
			ptr++;
			GmtEnd = timeConv(*ptr ? ptr : av[++i]);
		    } else {
			fprintf(stderr, "Invalid option: %s\n", &ptr[-2]);
			Usage();
		    }
		break;
	    case 'u':
		uflag = 1;
		break;
	    case 'V':
		PrintVersion();
		break;
	    case 'v':
		VerboseOpt = (*ptr) ? strtol(ptr, NULL, 0) : 1;
		break;
	    default:
		Usage();
	    }
	}
    }

    if (!UnExpireOpt && !aflag && FileIdx == 0 && spoolObj == (uint16)-1)
	Usage();
    if (flags & HGF_FAST || UnExpireOpt) {
	struct stat st;

	if (historyFileName == NULL) {
	    fprintf(stderr, "You cannot run fastmode/unexpire without specifying a filename!\n");
	    exit(1);
	}
	if (stat(historyFileName, &st) == 0 && uflag == 0) {
	    fprintf(stderr, "-f history files may not previously exist unless you also specify -u\n");
	    fprintf(stderr, "WARNING! -f -u is NOT suggested!\n");
	    exit(1);
	}
	if (uflag)
	    flags &= ~HGF_NOSEARCH;
    }

    if (VerboseOpt) {
	if (GmtStart != 0 && GmtEnd != 0)
	    printf("Scanning directories from D.%08x to D.%08x\n", GmtStart, GmtEnd);
	else if (GmtStart == 0 && GmtEnd != 0)
	    printf("Scanning directories from earliest to D.%08x\n", GmtEnd);
	else if (GmtStart != 0 && GmtEnd == 0)
	    printf("Scanning directories from D.%08x to latest\n", GmtStart);
    }
    if (UnExpireOpt) {
	hisfd = open(historyFileName, O_RDWR);
	if (hisfd == -1) {
	    fprintf(stderr, "Unable to open history (%s): %s\n",
					historyFileName, strerror(errno));
	    exit(1);
	}
    }

    LoadSpoolCtl(0, 1);

    if (RequeueOpt) {
	ForReal = 0;
	QuietOpt = 1;
    } else {

	/*
	 * historyFileName can be NULL and causes the default dhistory path
	 * to be used.
	 */

	HistoryOpen(historyFileName, flags);
    }

    {
	int i;

	for (i = 0; i < FileIdx; ++i) {
	    struct stat st;

	    if (VerboseOpt > 1)
		printf("Check: %s\n", FileAry[i]);

	    if (stat(FileAry[i], &st) == 0) {
		if (S_ISDIR(st.st_mode)) {
		    int gmt;

		    if (sscanf(FileAry[i], "D.%x", &gmt) == 1) {
			ScanSpoolDirectory(FileAry[i], gmt, spoolObj);
		    } else {
			fprintf(stderr, "Illegal path format for dir: %s\n",
								FileAry[i]);
		    }
		} else {
		    int gmt;
		    int iter;

		    if (sscanf(FileAry[i], "D.%x/B.%x", &gmt, &iter) == 2) {
			ScanSpoolFile(FileAry[i], gmt, iter, spoolObj);
		    } else {
			fprintf(stderr, "Illegal path format for file: %s\n",
								FileAry[i]);
		    }
		}
	    } else {
		printf("Unable to stat: %s (%s)\n", FileAry[i], strerror(errno));
	    }
	}
    }
    if (aflag || spoolObj != (uint16)-1) {
	ScanSpoolObject(spoolObj);
    }
    printf("diload: %d/%d entries loaded (%d duplicate)\n", LoadCount,
					LoadCount + LoadDupCount, LoadDupCount);

    if (!RequeueOpt) 
    {
	int r = HistoryClose();

	if (r == RCOK)
	    return(0);
	else
	    return(1);
    }
    return(0);
    /* not reached */
}
Ejemplo n.º 16
0
int
main(int ac, char **av)
{
    int LoadArticle = 0;
    int DumpFeeds = 0;
    int SpoolMatch = 0;

    if (ac < 1)
	Usage(av[0]);

    LoadDiabloConfig(ac, av);

    /*
     * Options
     */

    {
	int i;

	for (i = 1; i < ac; ++i) {
	    char *ptr = av[i];

	    if (*ptr != '-')
		continue;
	    ptr += 2;
	    switch(ptr[-1]) {
	    case 'a':
		LoadArticle = 1;
		break;
	    case 'C':
		if (*ptr == 0)
		    ++i;
		break;
	    case 'D':
		if (*ptr == 0) {
		    ++i;
		    ptr = av[i];
		}
		Dist = ptr;
		break;
	    case 'd':
		if (isdigit((int)(unsigned char)*ptr)) {
		    DebugOpt = strtol(ptr, NULL, 0);
		} else {
		    --ptr;
		    while (*ptr == 'd') {
			++DebugOpt;
			++ptr;
		    }
		}
		FeedDebug = 1;
		break;
	    case 'F':
		DumpFeeds = 1;
		break;
	    case 'h':
		HeadOnly = 1;
		break;
	    case 'l':
		if (*ptr == 0) {
		    ++i;
		    ptr = av[i];
		}
		Label = ptr;
		break;
	    case 'M':
		if (*ptr == 0) {
		    ++i;
		    ptr = av[i];
		}
		MessageId = ptr;
		break;
	    case 'N':
		if (*ptr == 0) {
		    ++i;
		    ptr = av[i];
		}
		DNewsfeedsPat = ptr;
		break;
	    case 'n':
		if (*ptr == 0) {
		    ++i;
		    ptr = av[i];
		}
		Newsgroups = ptr;
		break;
	    case 'p':
		if (*ptr == 0) {
		    ++i;
		    ptr = av[i];
		}
		NumPath = ptr;
		break;
	    case 'S':
		Spam = 1;
		break;
	    case 's':
		if (*ptr == 0) {
		    ++i;
		    ptr = av[i];
		}
		Size = ptr;
		break;
	    case 't':
		if (*ptr == 0) {
		    ++i;
		    ptr = av[i];
		}
		ArtType = ArtTypeConv(ptr);
		break;
	    case 'V':
		PrintVersion();
		break;
	    case 'X':
		SpoolMatch = 1;
		break;
	    default:
		Usage(av[0]);
	    }
	}
    }

    LoadNewsFeed(0, 1, Label);

    if (LoadArticle)
	LoadArt();

    if (DumpFeeds) {
	if (Label == NULL)
	    DumpAllFeedInfo(stdout);
	else
	    DumpFeedInfo(stdout, Label);
	exit(0);
    }

    if (Newsgroups == NULL) {
	printf("Missing Newsgroups\n\n");
	Usage(av[0]);
    }

    {
	char artType[32];
	char offSize[64];
	sprintf(artType, "%06x", ArtType);
	sprintf(offSize, "0,%s", Size);

	printf("Matching:\n");
	printf("\tNewsgroups: %s\n", Newsgroups);
	printf("\tDistribution: %s\n", Dist);
	printf("\tSize: %s\n", Size);
	printf("\tMessage-ID: %s\n", MessageId != NULL ? MessageId : "NONE");
	printf("\tNumPath: %s\n", NumPath);
	printf("\tArtType: %s\n", artType);
	printf("\tHeadOnly: %s\n", HeadOnly ? "Yes" : "No");
	printf("\tSpam: %s\n", Spam ? "Yes" : "No");
	if (SpoolMatch) {
	    uint16 Spool;
	    LoadSpoolCtl(0, 1);
	    AllocateSpools(0);
	    Spool = GetSpool(MessageId, Newsgroups, atoi(Size),
                        ArtType, Label, NULL, NULL);
	    printf("\nMatched spool: ");
	    if (Spool == (uint16)-3)
		printf("DontStore\n");
	    else if (Spool == (uint16)-2)
		printf("RejectArt\n");
	    else if (Spool == (uint16)-1)
		printf("NoSpool\n");
	    else
		printf("%02d\n", Spool);
		

	    exit(0);
	}
	FeedWrite(0, fwCallBack, "", "",
			offSize, Newsgroups, NumPath, Dist,
			HeadOnly ? "1" : "0",
			artType, Spam, 0);
    }

    exit(0);
}
Ejemplo n.º 17
0
int main2(int numArgs, const char *args[], char *rs)
{
  CFileSeqInStream inStream;
  CFileOutStream outStream;
  int res;
  int encodeMode = 0;
  Bool modeWasSet = False;
  const char *inputFile = NULL;
  const char *outputFile = "file.tmp";
  int param;
  UInt64 fileSize;

  FileSeqInStream_CreateVTable(&inStream);
  File_Construct(&inStream.file);

  FileOutStream_CreateVTable(&outStream);
  File_Construct(&outStream.file);

  if (numArgs == 1)
  {
    PrintHelp(rs);
    return 0;
  }

  for (param = 1; param < numArgs; param++) {
    if (strcmp(args[param], "-e") == 0 || strcmp(args[param], "-d") == 0) {
      encodeMode = (args[param][1] == 'e');
      modeWasSet = True;
    } else if (strcmp(args[param], "--f86") == 0) {
      mConType = X86Converter;
    } else if (strcmp(args[param], "-o") == 0 ||
               strcmp(args[param], "--output") == 0) {
      if (numArgs < (param + 2)) {
        return PrintUserError(rs);
      }
      outputFile = args[++param];
    } else if (strcmp(args[param], "--debug") == 0) {
      if (numArgs < (param + 2)) {
        return PrintUserError(rs);
      }
      //
      // For now we silently ignore this parameter to achieve command line
      // parameter compatibility with other build tools.
      //
      param++;
    } else if (
                strcmp(args[param], "-h") == 0 ||
                strcmp(args[param], "--help") == 0
              ) {
      PrintHelp(rs);
      return 0;
    } else if (
                strcmp(args[param], "-v") == 0 ||
                strcmp(args[param], "--verbose") == 0
              ) {
      //
      // For now we silently ignore this parameter to achieve command line
      // parameter compatibility with other build tools.
      //
    } else if (
                strcmp(args[param], "-q") == 0 ||
                strcmp(args[param], "--quiet") == 0
              ) {
      mQuietMode = True;
    } else if (strcmp(args[param], "--version") == 0) {
      PrintVersion(rs);
      return 0;
    } else if (inputFile == NULL) {
      inputFile = args[param];
    } else {
      return PrintUserError(rs);
    }
  }

  if ((inputFile == NULL) || !modeWasSet) {
    return PrintUserError(rs);
  }

  {
    size_t t4 = sizeof(UInt32);
    size_t t8 = sizeof(UInt64);
    if (t4 != 4 || t8 != 8)
      return PrintError(rs, "Incorrect UInt32 or UInt64");
  }

  if (InFile_Open(&inStream.file, inputFile) != 0)
    return PrintError(rs, "Can not open input file");

  if (OutFile_Open(&outStream.file, outputFile) != 0)
    return PrintError(rs, "Can not open output file");

  File_GetLength(&inStream.file, &fileSize);

  if (encodeMode)
  {
    if (!mQuietMode) {
      printf("Encoding\n");
    }
    res = Encode(&outStream.s, &inStream.s, fileSize);
  }
  else
  {
    if (!mQuietMode) {
      printf("Decoding\n");
    }
    res = Decode(&outStream.s, &inStream.s, fileSize);
  }

  File_Close(&outStream.file);
  File_Close(&inStream.file);

  if (res != SZ_OK)
  {
    if (res == SZ_ERROR_MEM)
      return PrintError(rs, kCantAllocateMessage);
    else if (res == SZ_ERROR_DATA)
      return PrintError(rs, kDataErrorMessage);
    else if (res == SZ_ERROR_WRITE)
      return PrintError(rs, kCantWriteMessage);
    else if (res == SZ_ERROR_READ)
      return PrintError(rs, kCantReadMessage);
    return PrintErrorNumber(rs, res);
  }
  return 0;
}
Ejemplo n.º 18
0
int main(int argc, char *argv[])
{

	static struct option options[] = 
	{
		{"body", no_argument,NULL,'b'},
		{"version", no_argument,NULL,'V'},
		{"file", required_argument,NULL,'f'},
		{"help",    no_argument,NULL,'h'},
		{"ie", no_argument,NULL,'i'},
		{"mozilla", no_argument,NULL, 'm'},
	};

	FILE *in = 0;
	char opt;
	char *optstring = "imbVhf:";
	char *progname;
	int file_count, fileind, length;
	int file_open = 0;
	char protocol[1024];
	char port[20];
	char path[1024];
	char hostname[1024];
	char fileurl[1024];
	char method[5] = "HEAD";
	char useragent[100] = "Furl/2.1";

	/* Let's see if it works */
	unsigned long ipAddr;
	SOCKET sock;

#ifdef WIN32
	Win32Init();
#endif

	progname = basename(argv[0]);	
	strlwr(progname);

	while ((opt=getopt_long(argc,argv,optstring,options,NULL)) != EOF ) {
		switch (opt) {
			
			case 'i':
				strcpy(useragent, "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;)");
				break;
			case 'm':
				strcpy(useragent, "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.7b) Gecko/20040421");
				break;
			case 'b':
				strcpy(method, "GET");
				break;
			case 'V':
				PrintVersion(progname);
				return 0;

			case 'h':
				PrintUsage(progname);
				return 0;

			case 'f':
				if((in=fopen(optarg, "r")) == NULL) {
					fprintf(stderr,"Bad Magic. Can\'t open specified file %s\n", optarg);
#ifdef WIN32
					Win32Cleanup();
#endif
					exit(1);
				} else {
					file_open = 1;
				}
				break;

			default:
				fprintf(stderr,"Try '%s --help' for more information.\n",progname);
				return 1;
		}
	}
	
	file_count = argc - optind;

	fileind = optind++;

	if((file_count == 0  || file_count > 1) && !file_open) {

		PrintUsage(progname);
#ifdef WIN32
		Win32Cleanup();
#endif
		exit(1);

	} else {

		while(1) {
			if (file_open) {
				if(fgets(fileurl,1022,in) == NULL) {
					if (feof(in)) {
						break;
					} else {
						perror("Bad Magic ");
#ifdef WIN32
						Win32Cleanup();
#endif
						exit(1);
					}
				} else {
					length = strlen(fileurl);
					fileurl[length-1] = '\0';
					fprintf(stdout,"\nURL= %s\n\n", fileurl);
				}	
			} else {
				length = -1;
				strcpy(fileurl, argv[fileind]);
			}
			if (length > 1 || length == -1) {
				if (!parseurl(fileurl,protocol,hostname,port,path,method,useragent)) {

					if (GetAddress(&ipAddr, hostname)) {
						fprintf(stderr,"%s doesn't exist\n",hostname);
						fprintf(stderr,"Try '%s --help' for more information.\n",progname);
					} else {
						sock = CreateSocket(&ipAddr,port);
						if (sock == INVALID_SOCKET) {
							fprintf(stderr,"Bad Magic. Couldn\'t get a socket connection\n");
						} else {
							if (ProcessSocket(sock, path) == SOCKET_ERROR) {
								fprintf(stderr,"Bad Magic. Encountered an error connecting to socket\n");
#ifdef WIN32
								Win32Cleanup();
#endif
								exit(1);
							}								
						}

					}
					
				} else {
					fprintf(stderr,"Protocol not supported\n");
					fprintf(stderr,"Try '%s --help' for more information.\n",progname);
				}
			}
			if (!file_open) {
				break;
			}
		}
	}
#ifdef WIN32
	Win32Cleanup();
#endif
	exit(0);
}
Ejemplo n.º 19
0
int
main(int ac, char **av)
{
    char *qFile = NULL;
    const char *cFile = NULL;
    int oldFormat = 0;

    OpenLog("dspoolout", (DebugOpt > 0 ? LOG_PERROR: 0) | LOG_NDELAY | LOG_PID);
    LoadDiabloConfig(ac, av);

    cFile = DNewsfeedsPat;

    /*
     * Maintain compatability with old format
     */
    {
	struct stat sb;
	if (stat(PatLibExpand(DNNTPSpoolCtlPat), &sb) == 0) {
	    cFile = DNNTPSpoolCtlPat;
	    oldFormat = 1;
	}
    }
    
    /*
     * Shift into the out.going directory
     */

    if (chdir(PatExpand(DQueueHomePat)) != 0) {
	fprintf(stderr, "unable to chdir to %s\n", PatExpand(DQueueHomePat));
	exit(1);
    }

    {
	int i;

	for (i = 1; i < ac; ++i) {
	    char *ptr = av[i];
	    if (*ptr == '-') {
		ptr += 2;
		switch(ptr[-1]) {
		case 'B':
		    if (*ptr == 0)
			ptr = av[++i];
		    OutboundIpStr = malloc(strlen(ptr) + 8);
		    sprintf(OutboundIpStr, "-B%s", ptr);
		    break;
		case 'C':
		    if (*ptr == 0)
			++i;
		    break;
		case 'd':
		    DebugOpt = 1;
		    if (*ptr)
			DebugOpt = strtol(ptr, NULL, 0);
		    break;
		case 'f':
		    cFile = (*ptr) ? ptr : av[++i];
		    break;
		case 'm':
		    MaxRun = strtol((*ptr ? ptr : av[++i]), NULL, 0);
		    break;
		case 'n':
		    ForReal = 0;
		    break;
		case 'p':
		    oldFormat = 1;
		    break;
		case 'q':
		    Quiet = 1;
		    break;
		case 'R':
		    RxBufSize = strtol((*ptr ? ptr : av[++i]), NULL, 0);
		    break;
		case 'Q':
		    TOS = strtol((*ptr ? ptr : av[++i]), NULL, 0);
		    break;
		case 'r':
		    ForceRealTime = 1;
		    break;
		case 's':
		    MinFlushSecs = strtol((*ptr ? ptr : av[++i]), NULL, 0) * 60;
		    break;
		case 'T':
		    TxBufSize = strtol((*ptr ? ptr : av[++i]), NULL, 0);
		    break;
		case 'V':
		    PrintVersion();
		    break;
		case 'v':
		    VerboseOpt = 1;
		    break;
		default:
		    break;
		}
	    } else {
		qFile = ptr;
	    }
	}
    }
    if (DebugOpt && qFile != NULL)
	printf("Processing label: %s\n", qFile);

    if (oldFormat || strstr(PatLibExpand(cFile), "dspoolout") != NULL) {
	    processDspoolout(PatLibExpand(cFile), qFile);
    } else {
	    DNewsfeedsPat = cFile;
	    processDnewsfeeds(qFile);
    }
    return(0);
}
Ejemplo n.º 20
0
int
main(int argc,          // IN
     char *argv[])      // IN
{
#ifdef VM_HAVE_MTAB
   Bool doMtab = TRUE;
#endif
   char c;
   int i;
   int result = EXIT_FAILURE;
   int flags = 0;
   int mntRes = -1;
   char *optionString = NULL;
   const char *shareNameHost = NULL;
   const char *shareNameDir = NULL;
   struct stat statBuf;
   HgfsMountInfo mountInfo;
   char *canonicalizedPath = NULL;
   size_t pathMax;

   thisProgram = argv[0];

   /* Compute the base name of the program, too. */
   thisProgramBase = strrchr(thisProgram, '/');
   if (thisProgramBase != NULL) {
      thisProgramBase++;
   } else {
      thisProgramBase = thisProgram;
   }
   setpwent();

   if (argc < 3) {
      PrintUsage();
   }

   while ((c = getopt(argc, argv, "hno:vV")) != -1) {
      switch (c) {
      case '?':
      case 'h':
         PrintUsage();
#ifdef VM_HAVE_MTAB
      case 'n':
         doMtab = FALSE;
         break;
#endif
      case 'o':
         if (optionString == NULL) {
            optionString = strdup(optarg);
         } else {
            size_t newLength;
            char *savedString = optionString;
            newLength = strlen(optionString) + strlen(",") +
                        strlen(optarg) + sizeof '\0';
            optionString = realloc(optionString, newLength);
            if (optionString != NULL) {
               Str_Strcat(optionString, ",", newLength);
               Str_Strcat(optionString, optarg, newLength);
            } else {
               free(savedString);
            }
         }
         if (optionString == NULL) {
            printf("Error: could not allocate memory for options\n");
            goto out;
         }
         break;
      case 'v':
         beVerbose = TRUE;
         break;
      case 'V':
         PrintVersion();
      default:
         printf("Error: unknown mount option %c\n", c);
         PrintUsage();
      }
   }

   LOG("Original command line: \"%s", thisProgram);
   for (i = 1; i < argc; i++) {
      LOG(" %s", argv[i]);
   }
   LOG("\"\n");

   /* After getopt_long(3), optind is the first non-option argument. */
   shareName = argv[optind];
   mountPoint = argv[optind + 1];

   /*
    * We canonicalize the mount point to avoid any discrepancies between the actual mount
    * point and the listed mount point in /etc/mtab (such discrepancies could prevent
    * umount(8) from removing the mount point from /etc/mtab).
    */
   pathMax = GetPathMax(mountPoint);
   canonicalizedPath = malloc(pathMax * sizeof *canonicalizedPath);
   if (canonicalizedPath == NULL) {
      printf("Error: cannot allocate memory for canonicalized path, "
             "aborting mount\n");
      goto out;
   } else if (!realpath(mountPoint, canonicalizedPath)) {
      perror("Error: cannot canonicalize mount point");
      goto out;
   }
   mountPoint = canonicalizedPath;

   if (!ParseShareName(shareName, &shareNameHost, &shareNameDir)) {
      printf("Error: share name is invalid, aborting mount\n");
      goto out;
   }

   mountInfo.magicNumber = HGFS_SUPER_MAGIC;
   mountInfo.infoSize = sizeof mountInfo;
   mountInfo.version = HGFS_PROTOCOL_VERSION;

#ifndef sun
   mountInfo.fmask = 0;
   mountInfo.dmask = 0;
   mountInfo.uidSet = FALSE;
   mountInfo.gidSet = FALSE;
   mountInfo.ttl = HGFS_DEFAULT_TTL;
#if defined(__APPLE__)
   strlcpy(mountInfo.shareNameHost, shareNameHost, MAXPATHLEN);
   strlcpy(mountInfo.shareNameDir, shareNameDir, MAXPATHLEN);
#else
   mountInfo.shareNameHost = shareNameHost;
   mountInfo.shareNameDir = shareNameDir;
#endif
#endif
   /*
    * Default flags which maybe modified by user passed options.
    */
   mountInfo.flags = HGFS_MNTINFO_SERVER_INO;

   /*
    * This'll write the rest of the options into HgfsMountInfo and possibly
    * modify the flags.
    */
   if (optionString && !ParseOptions(optionString, &mountInfo, &flags)) {
      printf("Error: could not parse options string\n");
      goto out;
   }

   /* Do some sanity checks on our desired mount point. */
   if (stat(mountPoint, &statBuf)) {
      perror("Error: cannot stat mount point");
      goto out;
   }
   if (S_ISDIR(statBuf.st_mode) == 0) {
      printf("Error: mount point \"%s\" is not a directory\n", mountPoint);
      goto out;
   }

   /*
    * Must be root in one flavor or another. If we're suid root, only proceed
    * if the user owns the mountpoint.
    */
   if (geteuid() != 0) {
      printf("Error: either you're not root, or %s isn't installed SUID\n",
             thisProgram);
      goto out;
   } else if (getuid() != 0 && (getuid() != statBuf.st_uid ||
                                (statBuf.st_mode & S_IRWXU) != S_IRWXU)) {
      printf("Error: for user mounts, user must own the mount point\n");
      goto out;
   }

   /* Go! */
#if defined(linux)
   mntRes = mount(shareName, mountPoint, HGFS_NAME, flags, &mountInfo);
#elif defined(__FreeBSD__)
   {
      struct iovec iov[] = {{"fstype", sizeof("fstype")},
                            {HGFS_NAME, sizeof(HGFS_NAME)},
                            {"target", sizeof("target")},
                            {shareName, strlen(shareName) + 1},
                            {"fspath", sizeof("fspath")},
                            {(void *)mountPoint, strlen(mountPoint) + 1},
                            {"uidSet", sizeof("uidSet")},
                            {&mountInfo.uidSet, sizeof(mountInfo.uidSet)},
                            {"uid", sizeof("uid")},
                            {&mountInfo.uid, sizeof(mountInfo.uid)},
                            {"gidSet", sizeof("gidSet")},
                            {&mountInfo.gidSet, sizeof(mountInfo.gidSet)},
                            {"gid", sizeof("gid")},
                            {&mountInfo.gid, sizeof(mountInfo.gid)}};

      mntRes = nmount(iov, ARRAYSIZE(iov), flags);
   }
#elif defined(__APPLE__)
   mntRes = mount(HGFS_NAME, mountPoint, flags, &mountInfo);
#elif defined(sun)
   mntRes = mount(mountPoint, mountPoint, MS_DATA | flags, HGFS_NAME,
                  &mountInfo, sizeof mountInfo);
#endif
   if (mntRes) {
      perror("Error: cannot mount filesystem");
      goto out;
   }
   result = EXIT_SUCCESS;

#ifdef VM_HAVE_MTAB
   if (doMtab) {
      UpdateMtab(&mountInfo, flags);
   }
#endif

  out:
   free(optionString);
   free(canonicalizedPath);
   return result;
}
Ejemplo n.º 21
0
CMainWindow::CMainWindow(CPS2VM& virtualMachine, char* cmdLine) 
: m_virtualMachine(virtualMachine)
, m_recordingAvi(false)
, m_recordBuffer(nullptr)
, m_recordBufferWidth(0)
, m_recordBufferHeight(0)
, m_recordAviMutex(NULL)
, m_frames(0)
, m_drawCallCount(0)
, m_stateSlot(0)
, m_outputWnd(nullptr)
, m_statusBar(nullptr)
, m_accTable(NULL)
{
	m_recordAviMutex = CreateMutex(NULL, FALSE, NULL);

	TCHAR sVersion[256];

	CAppConfig::GetInstance().RegisterPreferenceBoolean(PREF_UI_PAUSEWHENFOCUSLOST, true);

	if(!DoesWindowClassExist(CLSNAME))
	{
		WNDCLASSEX wc;
		memset(&wc, 0, sizeof(WNDCLASSEX));
		wc.cbSize			= sizeof(WNDCLASSEX);
		wc.hCursor			= LoadCursor(NULL, IDC_ARROW);
		wc.hbrBackground	= (HBRUSH)(COLOR_WINDOW); 
		wc.hInstance		= GetModuleHandle(NULL);
		wc.lpszClassName	= CLSNAME;
		wc.lpfnWndProc		= CWindow::WndProc;
		wc.style			= CS_OWNDC | CS_HREDRAW | CS_VREDRAW;
		RegisterClassEx(&wc);
	}

	Create(NULL, CLSNAME, _T(""), WNDSTYLE, Framework::Win32::CRect(0, 0, 640, 480), NULL, NULL);
	SetClassPtr();

#ifdef DEBUGGER_INCLUDED
	CDebugger::InitializeConsole();
#endif

	m_virtualMachine.Initialize();

	SetIcon(ICON_SMALL, LoadIcon(GetModuleHandle(NULL), MAKEINTRESOURCE(IDI_PUREI)));
	SetIcon(ICON_BIG, LoadIcon(GetModuleHandle(NULL), MAKEINTRESOURCE(IDI_PUREI)));

	SetMenu(LoadMenu(GetModuleHandle(NULL), MAKEINTRESOURCE(IDR_MAINWINDOW)));

#ifdef DEBUGGER_INCLUDED
	m_debugger = std::unique_ptr<CDebugger>(new CDebugger(m_virtualMachine));
	m_frameDebugger = std::unique_ptr<CFrameDebugger>(new CFrameDebugger());
	CreateDebugMenu();
#endif

	PrintVersion(sVersion, countof(sVersion));

	m_outputWnd = new COutputWnd(m_hWnd);

	m_statusBar = new Framework::Win32::CStatusBar(m_hWnd);
	m_statusBar->SetParts(2, m_statusBarPanelWidths);
	m_statusBar->SetText(STATUSPANEL,	sVersion);
	m_statusBar->SetText(FPSPANEL,		_T(""));

	//m_virtualMachine.CreateGSHandler(CGSH_Null::GetFactoryFunction());
	m_virtualMachine.CreateGSHandler(CGSH_OpenGLWin32::GetFactoryFunction(m_outputWnd));

	m_virtualMachine.CreatePadHandler(CPH_DirectInput::GetFactoryFunction(m_hWnd));

	m_deactivatePause = false;
	m_pauseFocusLost = CAppConfig::GetInstance().GetPreferenceBoolean(PREF_UI_PAUSEWHENFOCUSLOST);

	m_virtualMachine.m_gs->OnNewFrame.connect(boost::bind(&CMainWindow::OnNewFrame, this, _1));

	SetTimer(m_hWnd, NULL, 1000, NULL);
	//Initialize status bar
	OnTimer(0);

	m_virtualMachine.m_os->OnExecutableChange.connect(boost::bind(&CMainWindow::OnExecutableChange, this));

	CreateStateSlotMenu();
	CreateAccelerators();

	if(strstr(cmdLine, "--cdrom0") != nullptr)
	{
		BootCDROM();
	}
#ifdef DEBUGGER_INCLUDED
	if(strstr(cmdLine, "--debugger") != nullptr)
	{
		ShowDebugger();
	}
	if(strstr(cmdLine, "--framedebugger") != nullptr)
	{
		ShowFrameDebugger();
	}
#endif

	RefreshLayout();

	UpdateUI();
	Center();
	Show(SW_SHOW);
}
Ejemplo n.º 22
0
int main (int argc, char *argv[])
{
  /* variable declarations */
  int ArgIdx;
  int CanSwitchFileMode;
  int ShouldExit;
  int RetVal = 0;
  CFlag *pFlag;
  char *ptr;
#ifdef ENABLE_NLS
  char localedir[1024];

   ptr = getenv("DOS2UNIX_LOCALEDIR");
   if (ptr == NULL)
      strcpy(localedir,LOCALEDIR);
   else
   {
      if (strlen(ptr) < sizeof(localedir))
         strcpy(localedir,ptr);
      else
      {
         fprintf(stderr, "%s", _("dos2unix: error: Value of environment variable DOS2UNIX_LOCALEDIR is too long.\n"));
         strcpy(localedir,LOCALEDIR);
      }
   }

   setlocale (LC_ALL, "");
   bindtextdomain (PACKAGE, localedir);
   textdomain (PACKAGE);
#endif


  /* variable initialisations */
  ArgIdx = 0;
  CanSwitchFileMode = 1;
  ShouldExit = 0;
  pFlag = (CFlag*)malloc(sizeof(CFlag));  
  pFlag->NewFile = 0;
  pFlag->Quiet = 0;
  pFlag->KeepDate = 0;
  pFlag->ConvMode = 0;
  pFlag->NewLine = 0;
  pFlag->Force = 0;
  pFlag->status = 0;
  pFlag->stdio_mode = 1;

  if ( ((ptr=strrchr(argv[0],'/')) == NULL) && ((ptr=strrchr(argv[0],'\\')) == NULL) )
    ptr = argv[0];
  else
    ptr++;

  if ((strcmpi("mac2unix", ptr) == 0) || (strcmpi("mac2unix.exe", ptr) == 0))
    pFlag->ConvMode = 3;

  while ((++ArgIdx < argc) && (!ShouldExit))
  {
    /* is it an option? */
    if (argv[ArgIdx][0] == '-')
    {
      /* an option */
      if ((strcmp(argv[ArgIdx],"-h") == 0) || (strcmp(argv[ArgIdx],"--help") == 0))
      {
        PrintUsage();
        return(0);
      }
      else if ((strcmp(argv[ArgIdx],"-k") == 0) || (strcmp(argv[ArgIdx],"--keepdate") == 0))
        pFlag->KeepDate = 1;
      else if ((strcmp(argv[ArgIdx],"-f") == 0) || (strcmp(argv[ArgIdx],"--force") == 0))
        pFlag->Force = 1;
      else if ((strcmp(argv[ArgIdx],"-q") == 0) || (strcmp(argv[ArgIdx],"--quiet") == 0))
        pFlag->Quiet = 1;
      else if ((strcmp(argv[ArgIdx],"-l") == 0) || (strcmp(argv[ArgIdx],"--newline") == 0))
        pFlag->NewLine = 1;
      else if ((strcmp(argv[ArgIdx],"-V") == 0) || (strcmp(argv[ArgIdx],"--version") == 0))
      {
        PrintVersion();
#ifdef ENABLE_NLS
        PrintLocaledir(localedir);
#endif
        return(0);
      }
      else if ((strcmp(argv[ArgIdx],"-L") == 0) || (strcmp(argv[ArgIdx],"--license") == 0))
      {
        PrintLicense();
        return(0);
      }
      else if ((strcmp(argv[ArgIdx],"-c") == 0) || (strcmp(argv[ArgIdx],"--convmode") == 0))
      {
        if (++ArgIdx < argc)
        {
          if (strcmpi(argv[ArgIdx],"ascii") == 0)
            pFlag->ConvMode = 0;
          else if (strcmpi(argv[ArgIdx], "7bit") == 0)
            pFlag->ConvMode = 1;
          else if (strcmpi(argv[ArgIdx], "iso") == 0)
            pFlag->ConvMode = 2;
          else if (strcmpi(argv[ArgIdx], "mac") == 0)
            pFlag->ConvMode = 3;
          else
          {
            if (!pFlag->Quiet)
              fprintf(stderr, _("dos2unix: invalid %s conversion mode specified\n"),argv[ArgIdx]);
            ShouldExit = 1;
          }
        }
        else
        {
          ArgIdx--;
          if (!pFlag->Quiet)
            fprintf(stderr,_("dos2unix: option '%s' requires an argument\n"),argv[ArgIdx]);
          ShouldExit = 1;
        }
      }

      else if ((strcmp(argv[ArgIdx],"-o") == 0) || (strcmp(argv[ArgIdx],"--oldfile") == 0))
      {
        /* last convert not paired */
        if (!CanSwitchFileMode)
        {
          if (!pFlag->Quiet)
            fprintf(stderr, _("dos2unix: target of file %s not specified in new file mode\n"), argv[ArgIdx-1]);
          ShouldExit = 1;
        }
        pFlag->NewFile = 0;
      }

      else if ((strcmp(argv[ArgIdx],"-n") == 0) || (strcmp(argv[ArgIdx],"--newfile") == 0))
      {
        /* last convert not paired */
        if (!CanSwitchFileMode)
        {
          if (!pFlag->Quiet)
            fprintf(stderr, _("dos2unix: target of file %s not specified in new file mode\n"), argv[ArgIdx-1]);
          ShouldExit = 1;
        }
        pFlag->NewFile = 1;
      }
      else { /* wrong option */
        PrintUsage();
        return(0);
      }
    }
    else
    {
      pFlag->stdio_mode = 0;
      /* not an option */
      if (pFlag->NewFile)
      {
        if (CanSwitchFileMode)
          CanSwitchFileMode = 0;
        else
        {
          RetVal = ConvertDosToUnixNewFile(argv[ArgIdx-1], argv[ArgIdx], pFlag);
          if (pFlag->status & NO_REGFILE)
          {
            if (!pFlag->Quiet)
              fprintf(stderr, _("dos2unix: Skipping %s, not a regular file.\n"), argv[ArgIdx-1]);
          } else if (pFlag->status & BINARY_FILE)
          {
            if (!pFlag->Quiet)
              fprintf(stderr, _("dos2unix: Skipping binary file %s\n"), argv[ArgIdx-1]);
          } else {
            if (!pFlag->Quiet)
              fprintf(stderr, _("dos2unix: converting file %s to file %s in UNIX format ...\n"), argv[ArgIdx-1], argv[ArgIdx]);
            if (RetVal)
            {
              if (!pFlag->Quiet)
                fprintf(stderr, _("dos2unix: problems converting file %s to file %s\n"), argv[ArgIdx-1], argv[ArgIdx]);
              ShouldExit = 1;
            }
          }
          CanSwitchFileMode = 1;
        }
      }
      else
      {
        RetVal = ConvertDosToUnixOldFile(argv[ArgIdx], pFlag);
        if (pFlag->status & NO_REGFILE)
        {
          if (!pFlag->Quiet)
            fprintf(stderr, _("dos2unix: Skipping %s, not a regular file.\n"), argv[ArgIdx]);
        } else if (pFlag->status & BINARY_FILE)
        {
          if (!pFlag->Quiet)
            fprintf(stderr, _("dos2unix: Skipping binary file %s\n"), argv[ArgIdx]);
        } else {
          if (!pFlag->Quiet)
            fprintf(stderr, _("dos2unix: converting file %s to UNIX format ...\n"), argv[ArgIdx]);
          if (RetVal)
          {
            if (!pFlag->Quiet)
              fprintf(stderr, _("dos2unix: problems converting file %s\n"), argv[ArgIdx]);
            ShouldExit = 1;
          }
        }
      }
    }
  }

  /* no file argument, use stdin and stdout */
  if (pFlag->stdio_mode)
  {
    exit(ConvertDosToUnixStdio(pFlag));
  }


  if ((!pFlag->Quiet) && (!CanSwitchFileMode))
  {
    fprintf(stderr, _("dos2unix: target of file %s not specified in new file mode\n"), argv[ArgIdx-1]);
    ShouldExit = 1;
  }
  free(pFlag);
  return (ShouldExit);
}
Ejemplo n.º 23
0
int main(int argc, char* argv[])
{
    signal(SIGPIPE, SIG_IGN);
    const char * strConfigPath = "./conf/"PROJNAME".config.json";
    char configPath[128];
    snprintf(configPath, sizeof(configPath), "%s", strConfigPath);

    char c = '\0';
    while ((c = getopt(argc, argv, "c:vh?")) != -1)
    {
        switch (c)
        {
            case 'c':
                snprintf(configPath, sizeof(configPath), "%s", optarg);
                strConfigPath = configPath;
                break;
            case 'v':
                PrintVersion();
                return 0;
            case 'h':
            case '?':
                PrintHelp();
                return 0;
            default:
                break;
        }
    }
    // read the config and init the process
    myConfig = new Config (configPath);
    if (myConfig == NULL) {
        while(0 != raise(SIGKILL)){}
    }
    ROUTN( "=====================================================================");
    secore* mysecore = new secore(myConfig->PluginConfigPath());
    flexse_plugin* pflexse_plugin = new flexse_plugin(myConfig->PluginConfigPath(), mysecore);
    pthread_t ontime_thread_id;
    pthread_t update_thread_id;
    pthread_t day_merger_thread_id;
    pthread_t his_merger_thread_id;
    // init ontime thread
    MySuicideAssert ( 0 == pthread_create(&ontime_thread_id, NULL, ontime_thread, pflexse_plugin));
    // init update thread
    MySuicideAssert ( 0 == pthread_create(&update_thread_id, NULL, update_thread, pflexse_plugin));
    // init merger thread
    MySuicideAssert ( 0 == pthread_create(&day_merger_thread_id, NULL, day_merger_thread, pflexse_plugin));
    MySuicideAssert ( 0 == pthread_create(&his_merger_thread_id, NULL, his_merger_thread, pflexse_plugin));

    equeue* myequeue = new equeue(myConfig->PollSize(), myConfig->QueryPort());
    // generate service-thread
    thread_data_t* ptd = ServiceThreadInit(myequeue, pflexse_plugin);
    ROUTN( "All Service Threads Init Ok");
    // hold the place and not quit
    myequeue->running();
    for( uint32_t i=0; i<myConfig->ServiceThreadNum(); i++ )
    {
        pthread_join( ptd[i].thandle,NULL );
    }
    pthread_join( ontime_thread_id, NULL );
    pthread_join( update_thread_id, NULL );
    pthread_join( day_merger_thread_id, NULL );
    pthread_join( his_merger_thread_id, NULL );
    delete myConfig;
    delete mysecore;
    delete pflexse_plugin;
    delete myequeue;
    return 0;
}
Ejemplo n.º 24
0
void ParseArguments(int argc, char** argv)
{
char flags[MAX_INPUT_ARGS + 1] = {0,0,0,0};
if (argc > MAX_INPUT_ARGS + 1)
	{
	printf("%s:Too many arguments.", argv[0]);
	PrintHelp();
	exit(-1);
	}

for (int i = 1; i < argc; i++)
	{
	if (!strcmp(argv[i], "-p")||!strcmp(argv[i], "--paranoic"))
		{
		FixFlag = 0;
		Suspicion = 1;
		flags[i] = 1;
		}

	if (!strcmp(argv[i], "-c")||!strcmp(argv[i], "--careless"))
		{
		FixFlag = 1;
		if (getuid())
			{
			Suspicion = -1;
			}
		else
			{
			printf("root shall not be so careless. --normal is used instead.\n");
			Suspicion = 0;
			}
		flags[i] = 1;
		}

	if (!strcmp(argv[i], "-n")||!strcmp(argv[i], "--normal"))
		{
		FixFlag = 1;
		Suspicion = 0;
		flags[i] = 1;
		}

	if (!strcmp(argv[i], "-v")||!strcmp(argv[i], "--version"))
		{
		PrintVersion();
		exit(0);
		}

	if (!strcmp(argv[i], "-h")||!strcmp(argv[i], "--help"))
		{
		PrintHelp();
		exit(0);
		}

	if (!strcmp(argv[i], "-V")||!strcmp(argv[i], "--verbose"))
		{
		Verbose = 1;
		flags[i] = 1;
		}

	}//end of for-cycle
for (int i = 1; i < argc; i++)
	{
	if (!flags[i])
		{
		flags[0]++;
		if (!SourceDirectoryName)
			{
			SourceDirectoryName = argv[i];
			}
		else
			{
			DestinationDirectoryName = argv[i];
			}
		}
	}//we use flags[0] as a counter
if (flags[0]!=2)//source is 1 and destination is 1. if 1+1!=2 - we're messed
	{
	PrintHelp();
	exit(-1);
	}

GlobaliseInput();
if (SourceIncludesDestination())
	{
	printf("Error: source folder contains destination folder");
	exit(-1);
	}
}//end of ParseArguments
Ejemplo n.º 25
0
main(int argc, char *argv[])
{
ListNode *Curr, *Next;
int OverrideType=TYPE_NONE;
char *Tempstr=NULL;
int result;

//HTTPSetFlags(HTTP_NOCOMPRESS);
StdIn=STREAMFromFD(0);
STREAMSetTimeout(StdIn,0);
ParseEnvironmentVariables();

DownloadQueue=ListCreate();
Tempstr=MCopyStr(Tempstr,"Movgrab ",Version,NULL);
HTTPSetUserAgent(Tempstr);
FormatPreference=CopyStr(FormatPreference,"mp4,flv,webm,m4v,mov,mpg,mpeg,wmv,avi,3gp,reference,mp3,m4a,wma,m3u8,m3u8-stream");
AddOutputFile("", TRUE);

ParseCommandLine(argc, argv, DownloadQueue, &OverrideType);
CheckSettings();
if (StrLen(Proxy)) 
{
	if (! SetGlobalConnectionChain(Proxy))
	{
		printf("ERROR: Failed to set proxy settings to '%s'\n",Proxy);
		exit(1);
	}
}



if (Flags & FLAG_PRINT_USAGE) PrintUsage();
else if (Flags & FLAG_PRINT_VERSION) PrintVersion();
else if (! (Flags & FLAG_STDIN))
{
	if (ListSize(DownloadQueue)==0) PrintUsage();
}


while (1)
{
	if ((Flags & FLAG_STDIN) && (ListSize(DownloadQueue)==0) )
	{
		Tempstr=STREAMReadLine(Tempstr,StdIn);
		StripTrailingWhitespace(Tempstr);
		ListAddItem(DownloadQueue,CopyStr(NULL,Tempstr));
	}

	Curr=ListGetNext(DownloadQueue);
	while (Curr)
	{
		if (Flags & FLAG_TEST_SITES)
		{
			fprintf(stderr,"Checking %-20s ",Curr->Tag);
			fflush(NULL);
		}


		result=GrabMovie((char *) Curr->Item,OverrideType);
		Next=ListGetNext(Curr); //must do this after grab movie
																//incase more items added while grabbing

			if (Flags & FLAG_TEST_SITES) 
			{
				if (result) fprintf(stderr," okay\n");
				else fprintf(stderr," BROKEN\n");
			}
			
		ListDeleteNode(Curr);

		Curr=Next;
	}

	if (Flags & FLAG_TEST_SITES) break;
	if (! (Flags & FLAG_STDIN)) break;
}

}
Ejemplo n.º 26
0
/// Application entry point
int main(int argc, char** argv) {
    Config config;
    int option_index = 0;
    bool use_gdbstub = Settings::values.use_gdbstub;
    u32 gdb_port = static_cast<u32>(Settings::values.gdbstub_port);
    char* endarg;
#ifdef _WIN32
    int argc_w;
    auto argv_w = CommandLineToArgvW(GetCommandLineW(), &argc_w);

    if (argv_w == nullptr) {
        LOG_CRITICAL(Frontend, "Failed to get command line arguments");
        return -1;
    }
#endif
    std::string boot_filename;

    static struct option long_options[] = {
        {"gdbport", required_argument, 0, 'g'},
        {"help", no_argument, 0, 'h'},
        {"version", no_argument, 0, 'v'},
        {0, 0, 0, 0},
    };

    while (optind < argc) {
        char arg = getopt_long(argc, argv, "g:hv", long_options, &option_index);
        if (arg != -1) {
            switch (arg) {
            case 'g':
                errno = 0;
                gdb_port = strtoul(optarg, &endarg, 0);
                use_gdbstub = true;
                if (endarg == optarg)
                    errno = EINVAL;
                if (errno != 0) {
                    perror("--gdbport");
                    exit(1);
                }
                break;
            case 'h':
                PrintHelp(argv[0]);
                return 0;
            case 'v':
                PrintVersion();
                return 0;
            }
        } else {
#ifdef _WIN32
            boot_filename = Common::UTF16ToUTF8(argv_w[optind]);
#else
            boot_filename = argv[optind];
#endif
            optind++;
        }
    }

#ifdef _WIN32
    LocalFree(argv_w);
#endif

    Log::Filter log_filter(Log::Level::Debug);
    Log::SetFilter(&log_filter);

    MicroProfileOnThreadCreate("EmuThread");
    SCOPE_EXIT({ MicroProfileShutdown(); });
Ejemplo n.º 27
0
GenericAgentConfig *CheckOpts(int argc, char **argv)
{
    extern char *optarg;
    char ld_library_path[CF_BUFSIZE];
    int optindex = 0;
    int c;
    GenericAgentConfig *config = GenericAgentConfigNewDefault(AGENT_TYPE_SERVER);

    while ((c = getopt_long(argc, argv, "dvIKf:D:N:VSxLFMhAl", OPTIONS, &optindex)) != EOF)
    {
        switch ((char) c)
        {
        case 'l':
            LEGACY_OUTPUT = true;
            break;

        case 'f':

            if (optarg && (strlen(optarg) < 5))
            {
                Log(LOG_LEVEL_ERR, " -f used but argument '%s' incorrect", optarg);
                exit(EXIT_FAILURE);
            }

            GenericAgentConfigSetInputFile(config, GetWorkDir(), optarg);
            MINUSF = true;
            break;

        case 'd':
            LogSetGlobalLevel(LOG_LEVEL_DEBUG);
            NO_FORK = true;

        case 'K':
            IGNORELOCK = true;
            break;

        case 'D':
            config->heap_soft = StringSetFromString(optarg, ',');
            break;

        case 'N':
            config->heap_negated = StringSetFromString(optarg, ',');
            break;

        case 'I':
            LogSetGlobalLevel(LOG_LEVEL_INFO);
            break;

        case 'v':
            LogSetGlobalLevel(LOG_LEVEL_VERBOSE);
            NO_FORK = true;
            break;

        case 'F':
            NO_FORK = true;
            break;

        case 'L':
            Log(LOG_LEVEL_VERBOSE, "Setting LD_LIBRARY_PATH to '%s'", optarg);
            snprintf(ld_library_path, CF_BUFSIZE - 1, "LD_LIBRARY_PATH=%s", optarg);
            putenv(ld_library_path);
            break;

        case 'V':
            PrintVersion();
            exit(0);

        case 'h':
            PrintHelp("cf-serverd", OPTIONS, HINTS, true);
            exit(0);

        case 'M':
            {
                Writer *out = FileWriter(stdout);
                ManPageWrite(out, "cf-serverd", time(NULL),
                             CF_SERVERD_SHORT_DESCRIPTION,
                             CF_SERVERD_MANPAGE_LONG_DESCRIPTION,
                             OPTIONS, HINTS,
                             true);
                FileWriterDetach(out);
                exit(EXIT_SUCCESS);
            }

        case 'x':
            Log(LOG_LEVEL_ERR, "Self-diagnostic functionality is retired.");
            exit(0);
        case 'A':
#ifdef HAVE_AVAHI_CLIENT_CLIENT_H
#ifdef HAVE_AVAHI_COMMON_ADDRESS_H
            Log(LOG_LEVEL_NOTICE, "Generating Avahi configuration file.");
            if (GenerateAvahiConfig("/etc/avahi/services/cfengine-hub.service") != 0)
            {
                exit(1);
            }
            cf_popen("/etc/init.d/avahi-daemon restart", "r", true);
            Log(LOG_LEVEL_NOTICE, "Avahi configuration file generated successfuly.");
            exit(0);
#endif
#endif
            Log(LOG_LEVEL_ERR, "Generating avahi configuration can only be done when avahi-daemon and libavahi are installed on the machine.");
            exit(0);

        case 'C':
            if (!GenericAgentConfigParseColor(config, optarg))
            {
                exit(EXIT_FAILURE);
            }
            break;

        default:
            PrintHelp("cf-serverd", OPTIONS, HINTS, true);
            exit(1);

        }
    }

    if (!GenericAgentConfigParseArguments(config, argc - optind, argv + optind))
    {
        Log(LOG_LEVEL_ERR, "Too many arguments");
        exit(EXIT_FAILURE);
    }

    return config;
}
Ejemplo n.º 28
0
int
main(int argc, char **argv) {
    extern char *optarg;
    extern int optind;
    char *progname = *argv;
    char *HistoryFile;
    int SleepTime = 5;
    int Opened = 0;
    char ch;
    struct stat st;
    int PrevIno = -1;
    int Force = 0;
    char *map = NULL;
    off_t mapsize = 0;
    int All = 0;

    optind = 1;
    while ((ch = getopt(argc, argv, "afsV")) != -1) {
        switch(ch) {
        case 'a':
            All = 1;
            break;
        case 'f':
            Force = 1;
            break;
        case 's':
            SleepTime = strtol(optarg, NULL, 0);
            break;
        case 'V':
            PrintVersion();
            break;
        default:
            usage(argv[0]);
        }
    }

    argv += optind;
    if (*argv == NULL)
        usage(progname);
    HistoryFile = *argv;

    if (!Force && geteuid() != 0) {
        printf("This daemon must be run as root due to the use of mlock()\n");
        printf("which is only allowed to be executed by the root user\n");
        exit(1);
    }

    while (1) {
        if (!Opened) {
            if (stat(HistoryFile, &st) == 0)
                PrevIno = st.st_ino;
            if (All) {
                int fd;
                mapsize = st.st_size;
                fd = open(HistoryFile, O_RDONLY);
                if (fd == -1) {
                    perror("history open");
                    exit(1);
                }
                map = xmap(NULL, mapsize, PROT_READ, MAP_SHARED, fd, 0);
                close(fd);
                mlock(map, mapsize);
            } else {
                HistoryOpen(HistoryFile, HGF_MLOCK);
            }
            Opened = 1;
        }
        sleep(SleepTime);
        if (stat(HistoryFile, &st) != 0 || st.st_ino != PrevIno ||
                (All && st.st_size != mapsize)) {
            if (All && map != NULL) {
                munlock(map, mapsize);
                xunmap((void *)map, mapsize);
            } else {
                HistoryClose();
            }
            Opened = 0;
            printf("New history\n");
        }
    }
}
Ejemplo n.º 29
0
int main(int argc, char *argv[]) {
  std::stringstream ss;
  ss << std::endl << std::endl
     << "  " << argv[0] << " \\" << std::endl
     << "    --output OUTPUT_BC_FILE \\" << std::endl
     << "    --arch ARCH_NAME \\" << std::endl
     << "    --os OS_NAME \\" << std::endl
     << "    --cfg CFG_FILE \\" << std::endl

     // This option is very useful for debugging McSema-lifted bitcode. It
     // injects so-called breakpoint functions before every lifted instruction.
     // For example, the the instruction at PC `0xf00` is lifted, then this
     // option will inject a call to `breakpoint_f00`. With this feature, we
     // can add breakpoints in a debugger on these breakpoint functions, and
     // know that they correspond to locations in the original program.
     << "    [--add_breakpoints] \\" << std::endl

     // This option injects a function call before every lifted instruction.
     // This function is implemented in the McSema runtime and it prints the
     // values of the general purpose registers to `stderr`.
     << "    [--add_reg_tracer] \\" << std::endl

     // This option tells McSema not to optimize the bitcode. This is useful
     // for debugging, especially in conjunction with `--add_breakpoints`.
     << "    [--disable_optimizer] \\" << std::endl

     // This option tells McSema not to lower Remill's memory access intrinsic
     // functions into LLVM `load` and `store` instructions.
     << "    [--keep_memops] \\" << std::endl

     // There are roughly two ways of using McSema-lifted bitcode. The default
     // use case is to compile the bitcode into an executable that behaves like
     // the original program. The other use case is to do some kind of static
     // analysis, e.g. with KLEE. In this use case, calls to external functions
     // are emulated so that we also try to explicitly lift parameter passing.
     // This mode of passing arguments explicitly is enabled by
     // `--explicit_args`, and in situations where we have no knowledge of the
     // argument counts expected by an external function, we fall back on
     // passing `--explicit_args_count` number of arguments to that function.
     << "    [--explicit_args] \\" << std::endl
     << "    [--explicit_args_count NUM_ARGS_FOR_EXTERNALS] \\" << std::endl

     // This option is most useful when using `--explicit_args` (or
     // `--legacy_mode`, which enables `--explicit_args`). In general, McSema
     // doesn't have type information about externals, and so it assumes all
     // externals operate on integer-typed arguments, and return integer values.
     // This is wrong in many ways, but tends to work out about 80% of the time.
     // To get McSema better information about externals, one should create a
     // C or C++ file with the declarations of the externals (perhaps by
     // `#include`ing standard headers). Then, should add to this file something
     // like:
     //         __attribute__((used))
     //         void *__mcsema_used_funcs[] = {
     //           (void *) external_func_name_1,
     //           (void *) external_func_name_2,
     //           ...
     //         };
     // And compile this file to bitcode using `remill-clang-M.m` (Major.minor).
     // This bitcode file will then be the source of type information for
     // McSema.
     << "    [--library BITCODE_FILE] \\" << std::endl

     // Annotate each LLVM IR instruction with some metadata that includes the
     // original program counter. The name of the LLVM metadats is
     // `PC_METADATA_ID`. This is enabled by default with `--legacy_mode`,
     // which sets `--pc_annotation` to be `mcsema_real_eip`.
     << "    [--pc_annotation PC_METADATA_ID] \\" << std::endl

     // Try to produce bitcode that looks like McSema version 1. This enables
     // `--explicit_args` and `--pc_annotation`.
     << "    [--legacy_mode] \\" << std::endl
     
     // Print a list of the instructions that can be lifted.
     << "    [--list-supported]" << std::endl

     // Print the version and exit.
     << "    [--version]" << std::endl
     << std::endl;

  google::InitGoogleLogging(argv[0]);
  google::SetUsageMessage(ss.str());
  google::ParseCommandLineFlags(&argc, &argv, true);

  if (FLAGS_version) {
    PrintVersion();
    return EXIT_SUCCESS;
  }

  CHECK(!FLAGS_os.empty())
      << "Must specify an operating system name to --os.";

  CHECK(!FLAGS_arch.empty())
      << "Must specify a machine code architecture name to --arch.";

  CHECK(!FLAGS_cfg.empty())
      << "Must specify the path to a CFG file to --cfg.";

  mcsema::gContext = new llvm::LLVMContext;

  CHECK(mcsema::InitArch(FLAGS_os, FLAGS_arch))
      << "Cannot initialize for arch " << FLAGS_arch
      << " and OS " << FLAGS_os << std::endl;

  if (FLAGS_legacy_mode) {
    LOG_IF(WARNING, FLAGS_keep_memops)
        << "Disabling --keep_memops in legacy mode.";
    FLAGS_keep_memops = false;

    LOG_IF(WARNING, !FLAGS_explicit_args)
        << "Enabling --explicit_args in legacy mode.";
    FLAGS_explicit_args = true;

    LOG_IF(WARNING, !FLAGS_pc_annotation.empty())
        << "Changing --pc_annotation to mcsema_real_eip in legacy mode.";
    FLAGS_pc_annotation = "mcsema_real_eip";

    LOG_IF(WARNING, FLAGS_disable_optimizer)
        << "Re-enabling the optimizer in legacy mode.";
    FLAGS_disable_optimizer = false;
  }

  auto cfg_module = mcsema::ReadProtoBuf(
      FLAGS_cfg, (mcsema::gArch->address_size / 8));
  mcsema::gModule = remill::LoadTargetSemantics(mcsema::gContext);
  mcsema::gArch->PrepareModule(mcsema::gModule);

  if (FLAGS_list_supported) {
    PrintSupportedInstructions();
  }

  if (!FLAGS_library.empty()) {
    LoadLibraryIntoModule();
  }

  CHECK(mcsema::LiftCodeIntoModule(cfg_module))
      << "Unable to lift CFG from " << FLAGS_cfg << " into module "
      << FLAGS_output;

  if (!FLAGS_library.empty()) {
    UnloadLibraryFromModule();
    gLibrary.reset(nullptr);
  }

  remill::StoreModuleToFile(mcsema::gModule, FLAGS_output);

  google::ShutDownCommandLineFlags();
  google::ShutdownGoogleLogging();

  return EXIT_SUCCESS;
}
Ejemplo n.º 30
0
GenericAgentConfig *CheckOpts(int argc, char **argv)
{
    extern char *optarg;
    char ld_library_path[CF_BUFSIZE];
    int optindex = 0;
    int c;
    GenericAgentConfig *config = GenericAgentConfigNewDefault(AGENT_TYPE_SERVER);

    while ((c = getopt_long(argc, argv, "dvIKf:D:N:VSxLFMhA", OPTIONS, &optindex)) != EOF)
    {
        switch ((char) c)
        {
        case 'f':

            if (optarg && (strlen(optarg) < 5))
            {
                CfOut(OUTPUT_LEVEL_ERROR, "", " -f used but argument \"%s\" incorrect", optarg);
                exit(EXIT_FAILURE);
            }

            GenericAgentConfigSetInputFile(config, GetWorkDir(), optarg);
            MINUSF = true;
            break;

        case 'd':
            config->debug_mode = true;
            NO_FORK = true;

        case 'K':
            IGNORELOCK = true;
            break;

        case 'D':
            config->heap_soft = StringSetFromString(optarg, ',');
            break;

        case 'N':
            config->heap_negated = StringSetFromString(optarg, ',');
            break;

        case 'I':
            INFORM = true;
            break;

        case 'v':
            VERBOSE = true;
            NO_FORK = true;
            break;

        case 'F':
            NO_FORK = true;
            break;

        case 'L':
            CfOut(OUTPUT_LEVEL_VERBOSE, "", "Setting LD_LIBRARY_PATH=%s\n", optarg);
            snprintf(ld_library_path, CF_BUFSIZE - 1, "LD_LIBRARY_PATH=%s", optarg);
            putenv(ld_library_path);
            break;

        case 'V':
            PrintVersion();
            exit(0);

        case 'h':
            Syntax("cf-serverd", OPTIONS, HINTS, ID, true);
            exit(0);

        case 'M':
            ManPage("cf-serverd - CFEngine's server agent", OPTIONS, HINTS, ID);
            exit(0);

        case 'x':
            CfOut(OUTPUT_LEVEL_ERROR, "", "Self-diagnostic functionality is retired.");
            exit(0);
        case 'A':
#ifdef HAVE_AVAHI_CLIENT_CLIENT_H
#ifdef HAVE_AVAHI_COMMON_ADDRESS_H
            printf("Generating Avahi configuration file.\n");
            if (GenerateAvahiConfig("/etc/avahi/services/cfengine-hub.service") != 0)
            {
                exit(1);
            }
            cf_popen("/etc/init.d/avahi-daemon restart", "r", true);
            printf("Avahi configuration file generated successfuly.\n");
            exit(0);
#else
            printf("This option can only be used when avahi-daemon and libavahi are installed on the machine.\n");
#endif
#endif

        default:
            Syntax("cf-serverd", OPTIONS, HINTS, ID, true);
            exit(1);

        }
    }

    if (!GenericAgentConfigParseArguments(config, argc - optind, argv + optind))
    {
        Log(LOG_LEVEL_ERR, "Too many arguments");
        exit(EXIT_FAILURE);
    }

    return config;
}