Exemple #1
0
int main(int argc, char **argv) {
  int optc;
  char *table;
  set_program_name(argv[0]);
  while ((optc = getopt_long(argc, argv, "hv", longopts, NULL)) != -1) {
    switch (optc) {
      case 'v':
        version_etc(stdout, program_name, PACKAGE_NAME, VERSION, AUTHORS, (char *)NULL);
        exit(EXIT_SUCCESS);
        break;
      case 'h':
        print_help();
        exit(EXIT_SUCCESS);
        break;
      default:
        fprintf (stderr, "Try `%s --help' for more information.\n", program_name);
        exit(EXIT_FAILURE);
        break; }}
  if (optind != argc - 1) {
    if (optind < argc - 1)
      fprintf(stderr, "%s: extra operand: %s\n", program_name, argv[optind + 1]);
    else
      fprintf(stderr, "%s: no table specified\n", program_name);
    fprintf(stderr, "Try `%s --help' for more information.\n", program_name);
    exit(EXIT_FAILURE); }
  table = argv[optind];
  if (!lou_getTable(table)) {
    lou_free();
    exit(EXIT_FAILURE); }
  main_loop(table);
  lou_free();
  exit(EXIT_SUCCESS);
}
Exemple #2
0
int
main (int argc, char **argv)
{
  /* Recognize --help or --version only if it's the only command-line
     argument.  */
  if (argc == 2)
    {
      initialize_main (&argc, &argv);
      set_program_name (argv[0]);
      setlocale (LC_ALL, "");
      bindtextdomain (PACKAGE, LOCALEDIR);
      textdomain (PACKAGE);

      atexit (close_stdout);

      if (STREQ (argv[1], "--help"))
        usage (EXIT_STATUS);

      if (STREQ (argv[1], "--version"))
        version_etc (stdout, PROGRAM_NAME, PACKAGE_NAME, Version, AUTHORS,
                     (char *) NULL);
    }

  exit (EXIT_STATUS);
}
int
main (int argc, char **argv)
{
  int optc;
  
  set_program_name (argv[0]);

  while ((optc = getopt_long (argc, argv, "hvfb", longopts, NULL)) != -1)
    switch (optc)
      {
      /* --help and --version exit immediately, per GNU coding standards.  */
      case 'v':
        version_etc (stdout, program_name, PACKAGE_NAME, VERSION, AUTHORS, (char *) NULL);
        exit (EXIT_SUCCESS);
        break;
      case 'h':
        print_help ();
        exit (EXIT_SUCCESS);
        break;
      case 'f':
	forward_flag = 1;
        break;
      case 'b':
	backward_flag = 1;
        break;
      default:
	fprintf (stderr, "Try `%s --help' for more information.\n",
		 program_name);
	exit (EXIT_FAILURE);
        break;
      }

  if (forward_flag && backward_flag)
    {
      fprintf (stderr, "%s: specify either -f or -b but not both\n", 
	       program_name);
      fprintf (stderr, "Try `%s --help' for more information.\n",
               program_name);
      exit (EXIT_FAILURE);
    }

  if (optind != argc - 1)
    {
      /* Print error message and exit.  */
      if (optind < argc - 1)
	fprintf (stderr, "%s: extra operand: %s\n",
		 program_name, argv[optind + 1]);
      else
	fprintf (stderr, "%s: no table specified\n", 
		 program_name);
      fprintf (stderr, "Try `%s --help' for more information.\n",
               program_name);
      exit (EXIT_FAILURE);
    }

  /* assume forward translation by default */
  translate_input (!backward_flag, argv[optind]);
  exit (EXIT_SUCCESS);
}
int
main (int argc _GL_UNUSED, char **argv)
{
  set_program_name (argv[0]);
  version_etc (stdout, "test-version-etc", "dummy", "0", AUTHORS,
               (const char *) NULL);
  return 0;
}
Exemple #5
0
void
psktool_version (void)
{
  const char *p = PACKAGE_NAME;
  if (strcmp (gnutls_check_version (NULL), PACKAGE_VERSION) != 0)
    p = PACKAGE_STRING;
  version_etc (stdout, "psktool", p, gnutls_check_version (NULL),
	       "Nikos Mavrogiannopoulos", (char *) NULL);
}
Exemple #6
0
int
main (int argc, char **argv)
{
  const TranslationTableHeader *table;
  int optc;

  set_program_name (argv[0]);

  while ((optc = getopt_long (argc, argv, "hvq", longopts, NULL)) != -1)
    switch (optc)
      {
      /* --help and --version exit immediately, per GNU coding standards.  */
      case 'v':
        version_etc (stdout, program_name, PACKAGE_NAME, VERSION, AUTHORS, (char *) NULL);
        exit (EXIT_SUCCESS);
        break;
      case 'h':
        print_help ();
        exit (EXIT_SUCCESS);
        break;
      case 'q':
	quiet_flag = 1;
        break;
      default:
	fprintf (stderr, "Try `%s --help' for more information.\n",
		 program_name);
	exit (EXIT_FAILURE);
        break;
      }

  if (optind != argc - 1)
    {
      /* Print error message and exit.  */
      if (optind < argc - 1)
	fprintf (stderr, "%s: extra operand: %s\n",
		 program_name, argv[optind + 1]);
      else
	fprintf (stderr, "%s: no table specified\n", 
		 program_name);
      fprintf (stderr, "Try `%s --help' for more information.\n",
               program_name);
      exit (EXIT_FAILURE);
    }

  if (!(table = lou_getTable (argv[optind])))
    {
      lou_free ();
      exit (EXIT_FAILURE);
    }
  if (quiet_flag == 0)
    fprintf (stderr, "No errors found.\n");
  lou_free ();
  exit (EXIT_SUCCESS);
}
static void
version (void)
{
  char *p;
  int l = -1;

  if (strcmp (pskc_check_version (NULL), PSKC_VERSION) != 0)
    l = asprintf (&p, "PSKC Toolkit libpskc.so %s pskc.h %s",
		  pskc_check_version (NULL), PSKC_VERSION);
  else if (strcmp (PSKC_VERSION, PACKAGE_VERSION) != 0)
    l = asprintf (&p, "PSKC Toolkit %s", pskc_check_version (NULL));
  version_etc (stdout, "pskctool", l == -1 ? "PSKC Toolkit" : p,
	       PACKAGE_VERSION, "Simon Josefsson", (char *) NULL);
  if (l != -1)
    free (p);

  exit (EXIT_SUCCESS);
}
int
main (int argc, char **argv)
{
  program_name = argv[0];
  setlocale (LC_ALL, "");
  bindtextdomain (PACKAGE, LOCALEDIR);
  textdomain (PACKAGE);

  atexit (close_stdout);

  /* Recognize --help or --version only if it's the only command-line
     argument and if POSIXLY_CORRECT is not set.  */
  if (argc == 2 && getenv ("POSIXLY_CORRECT") == NULL)
    {
      if (STREQ (argv[1], "--help"))
	usage (EXIT_SUCCESS);

      if (STREQ (argv[1], "--version"))
	version_etc (stdout, PROGRAM_NAME, GNU_PACKAGE, VERSION, AUTHORS);
    }

  exit (EXIT_FAILURE);
}
Exemple #9
0
int
main (int argc, char **argv)
{
  int mode = 0;
  char *configFileList = NULL;
  char *inputFileName = "stdin";
  char *outputFileName = "stdout";
  char tempFileName[MAXNAMELEN];
  char logFileName[MAXNAMELEN];
  char whichProc = 0;
  char *configSettings = NULL;
  FILE *inputFile = NULL;
  FILE *tempFile;
  int ch = 0;
  int pch = 0;
  int nch = 0;
  int charsRead = 0;
  int k;
  UserData *ud;

  int optc;
  lbu_setLogLevel(LOU_LOG_WARN);
  lou_setLogLevel(LOU_LOG_WARN);
  set_program_name (argv[0]);
  logFileName[0] = 0;
  
  while ((optc =
	  getopt_long (argc, argv, "hvf:brpPtlw:TC:", longopts, NULL)) != 
	  -1)
    switch (optc)
      {
	/* --help and --version exit immediately, per GNU coding standards.  */
      case 'v':
	version_etc (stdout, program_name, PACKAGE_NAME, VERSION, AUTHORS,
		     (char *) NULL);
	exit (EXIT_SUCCESS);
	break;
      case 'h':
	print_help ();
	exit (EXIT_SUCCESS);
	break;
      case 'l':
	strcpy (logFileName, "file2brl.log");
	break;
      case 't':
	mode |= htmlDoc;
	break;
      case 'f':
	configFileList = optarg;
	break;
      case 'b':
      case 'p':
      case 'P':
      case 'r':
      case 'T':
      case '0':
	whichProc = optc;
	break;
      case 'C':
	if (configSettings == NULL)
	  {
	    configSettings = malloc (BUFSIZE);
	    configSettings[0] = 0;
	  }
	strcat (configSettings, optarg);
	strcat (configSettings, "\n");
	break;
       case 'w':
        lbu_setWriteablePath (optarg);
        break;
      default:
	fprintf (stderr, "Try `%s --help' for more information.\n",
		 program_name);
	exit (EXIT_FAILURE);
	break;
      }

  if (optind < argc)
    {
      if (optind == argc - 1)
	{
	  inputFileName = argv[optind];
	}
      else if (optind == argc - 2)
	{
	  if (strcmp (argv[optind], "-") != 0)
	    inputFileName = argv[optind];
	  outputFileName = argv[optind + 1];
	}
      else
	{
	  fprintf (stderr, "%s: extra operand: %s\n",
		   program_name, argv[optind + 2]);
	  fprintf (stderr, "Try `%s --help' for more information.\n",
		   program_name);
	  exit (EXIT_FAILURE);
	}
    }

  if (whichProc == 0)
    whichProc = '0';
  if (logFileName[0] != 0)
  {
  strcpy (logFileName, lbu_getWriteablePath());
  strcat (logFileName, "file2brl.log");
  }
  if (configSettings != NULL)
    for (k = 0; configSettings[k]; k++)
      if (configSettings[k] == '=' && configSettings[k - 1] != ' ')
	configSettings[k] = ' ';
  if (configFileList == NULL)
    configFileList = "preferences.cfg";
  if ((ud = lbu_initialize (configFileList, logFileName, 
  configSettings)) == NULL)
    exit (EXIT_FAILURE);
  if (strcmp (inputFileName, "stdin") != 0)
    {
      if (!(inputFile = fopen (inputFileName, "r")))
	{
	  logMessage (LOU_LOG_FATAL, "Can't open input file %s.\n", inputFileName);
	  exit (EXIT_FAILURE);
	}
    }
  else
    inputFile = stdin;
  /*Create somewhat edited temporary file to facilitate use of stdin. */
  strcpy (tempFileName, lbu_getWriteablePath ());
  strcat (tempFileName, "file2brl.temp");
  if (!(tempFile = fopen (tempFileName, "w")))
    {
      logMessage (LOU_LOG_FATAL, "Can't open temporary file.\n");
      exit (EXIT_FAILURE);
    }
  if (whichProc == 'p')
    {
      int ppch = 0;
      int firstCh = 0;
      int skipit = 0;
      while ((ch = fgetc (inputFile)) != EOF)
	{
	  if (firstCh == 0)
	    firstCh = ch;
	  if (ch == 12 || ch == 13)
	    continue;
	  if (ch == '<' && firstCh == '<')
	    {
	      skipit = 1;
	      continue;
	    }
	  if (skipit)
	    {
	      if (ch == '>')
		skipit = 0;
	      continue;
	    }
	  if (ch == '-')
	    {
	      nch = fgetc (inputFile);
	      if (nch == 10)
		continue;
	      ungetc (nch, inputFile);
	    }
	  if (!((pch == 10 && ch == 10) || (ppch == 10 && pch == 10)))
	    {
	      if (ch <= 32 && pch <= 32)
		continue;
	      if (!
		  (pch == 10 && ((ppch >= 97 && ppch <= 122) || ppch == ',')))
		{
		  if (pch == 10 && ch < 97)
		    fputc (10, tempFile);
		}
	    }
	  ppch = pch;
	  pch = ch;
	  fputc (ch, tempFile);
	  charsRead++;
	}
    }
  else
    while ((ch = fgetc (inputFile)) != EOF)
      {
	if (charsRead == 0 && ch <= ' ')
	  continue;
	if (ch == 13)
	  continue;
	if (charsRead == 0)
	  {
	    if (ch != '<' && whichProc == '0')
	      whichProc = 'T';
	    nch = fgetc (inputFile);
	    if (!(mode & htmlDoc) && whichProc == '0' && nch != '?')
	      fprintf (tempFile, "%s\n", ud->xml_header);
	  }
	if (pch == '>' && ch == '<')
	  fputc (10, tempFile);
	if (whichProc == 'P' && ch == 10 && pch != 10)
	  fputc (10, tempFile);
	fputc (ch, tempFile);
	pch = ch;
	charsRead++;
	if (charsRead == 1)
	  {
	    fputc (nch, tempFile);
	    charsRead++;
	  }
      }
  fclose (tempFile);
  if (inputFile != stdin)
    fclose (inputFile);
  if (charsRead > 2)
    switch (whichProc)
      {
      case 'b':
	if (!lbu_backTranslateFile (configFileList, tempFileName,
				    outputFileName, logFileName, configSettings,
				    mode))
	  exit (EXIT_FAILURE);
	break;
      case 'r':
	{
	  char temp2FileName[MAXNAMELEN];
	  strcpy (temp2FileName, lbu_getWriteablePath ());
	  strcat (temp2FileName, "file2brl2.temp");
	  if (!lbu_backTranslateFile (configFileList, tempFileName,
				      temp2FileName, logFileName,
				      configSettings, mode))
	    exit (EXIT_FAILURE);
	  if (ud->back_text == html)
	    if (!lbu_translateFile (configFileList, temp2FileName,
				    outputFileName, logFileName, configSettings,
				    mode))
	      exit (EXIT_FAILURE);
	  else
	    if (!lbu_translateTextFile (configFileList, temp2FileName,
					outputFileName, logFileName,
					configSettings, mode))
	      exit (EXIT_FAILURE);
	}
	break;
      case 'p':
	if (!lbu_translateTextFile (configFileList, tempFileName,
				    outputFileName, logFileName, configSettings,
				    mode))
	  exit (EXIT_FAILURE);
	break;
      case 'T':
	if (!lbu_translateTextFile (configFileList, tempFileName,
				    outputFileName,
				    logFileName, configSettings, mode))
	  exit (EXIT_FAILURE);
	break;
      case 't':
      case '0':
	if (!lbu_translateFile (configFileList, tempFileName, outputFileName,
				logFileName, configSettings, mode))
	  exit (EXIT_FAILURE);
	break;
      default:
	logMessage (LOU_LOG_FATAL, "Program bug %c\n", whichProc);
	break;
      }
  lbu_free ();
  if (configSettings != NULL)
    free (configSettings);
  return 0;
}
Exemple #10
0
int
main(int argc, char **argv)
{
    int c;
    bool list_mode = false;
    bool extract_mode = false;
    bool create_mode = false;
    FILE *in;
    char *inname;
    int raw_filec = 0;
    char** raw_filev = 0;

    set_program_name(argv[0]);

#ifdef ENABLE_NLS
    if (setlocale(LC_ALL, "") == NULL)
	warn(_("%s: cannot set locale: %s"), program_name, errstr);
    if (bindtextdomain(PACKAGE, LOCALEDIR) == NULL)
	warn(_("%s: bindtextdomain failed: %s"), program_name, errstr);
    if (textdomain(PACKAGE) == NULL)
	warn(_("%s: cannot set message domain: %s"), program_name, errstr);
#endif

    while ((c = getopt_long(argc, argv, short_opts, long_opts, NULL)) != -1) {
	switch (c) {
	case 'x':
	    extract_mode = true;
	    break;
	case 'l':
	    list_mode = true;
	    break;
	case 'c':
	    create_mode = true;
	    break;
	case VERSION_OPT:
	    version_etc(stdout, PROGRAM, PACKAGE, VERSION, "Oskar Liljeblad", NULL);
	    exit(0);
	case HELP_OPT:
	    display_help();
	    exit(0);
	case 'o':
	    output = optarg;
	    break;
	case 'i':
	    if (!parse_int32(optarg, &image_index) || image_index < 0)
		die(_("invalid index value: %s"), optarg);
	    break;
	case 'w':
	    if (!parse_int32(optarg, &width) || width < 0)
		die(_("invalid width value: %s"), optarg);
	    break;
	case 'h':
	    if (!parse_int32(optarg, &height) || height < 0)
		die(_("invalid height value: %s"), optarg);
	    break;
	case 'p':
	    if (!parse_int32(optarg, &palettesize) || palettesize < 0)
		die(_("invalid palette-size value: %s"), optarg);
	    break;
	case 'b':
	    if (!parse_int32(optarg, &bitdepth) || bitdepth < 0)
		die(_("invalid bit-depth value: %s"), optarg);
	    break;
        /*case 'm':
            if (!parse_uint32(optarg, &minbitdepth))
                die(_("invalid minimum bit-depth value: %s"), optarg);
            break;*/
	case 'X':
	    if (!parse_int32(optarg, &hotspot_x) || hotspot_x < 0)
		die(_("invalid hotspot-x value: %s"), optarg);
	    hotspot_x_set = true;
	    break;
	case 'Y':
	    if (!parse_int32(optarg, &hotspot_y) || hotspot_y < 0)
		die(_("invalid hotspot-y value: %s"), optarg);
	    hotspot_y_set = true;
	    break;
	case 't':
	    if (!parse_int32(optarg, &alpha_threshold) || alpha_threshold < 0)
		die(_("invalid alpha-threshold value: %s"), optarg);
	    break;
	case 'r':
	    raw_filev = realloc (raw_filev, (raw_filec+1)*sizeof (char*));
	    raw_filev[raw_filec] = optarg;
	    raw_filec++;
	    break;
	case ICON_OPT:
	    icon_only = true;
	    break;
	case CURSOR_OPT:
	    cursor_only = true;
	    break;
	case '?':
	    exit(1);
	}
    }

    if (extract_mode + create_mode + list_mode > 1)
	die(_("multiple commands specified"));
    if (extract_mode + create_mode + list_mode == 0) {
	warn(_("missing argument"));
	display_help();
	exit (1);
    }
    if (icon_only && cursor_only)
	die(_("only one of --icon and --cursor may be specified"));

    if (list_mode) {
	if (argc-optind <= 0)
	    die(_("missing file argument"));
	for (c = optind ; c < argc ; c++) {
	    if (open_file_or_stdin(argv[c], &in, &inname)) {
		if (!extract_icons(in, inname, true, NULL, filter))
		    exit(1);
		if (in != stdin)
		    fclose(in);
	    }
	}
    }

    if (extract_mode) {
	if (argc-optind <= 0)
	    die(_("missing arguments"));

        for (c = optind ; c < argc ; c++) {
            int matched;

	    if (open_file_or_stdin(argv[c], &in, &inname)) {
	        matched = extract_icons(in, inname, false, extract_outfile_gen, filter);
	        if (matched == -1)
	            exit(1);
                if (matched == 0)
                    fprintf(stderr, _("%s: no images matched\n"), inname);
                if (in != stdin)
                    fclose(in);
            }
        }
    }

    if (create_mode) {
        if (argc-optind+raw_filec <= 0)
	    die(_("missing arguments"));
        if (!create_icon(argc-optind, argv+optind, raw_filec, raw_filev, create_outfile_gen, (icon_only ? true : !cursor_only), hotspot_x, hotspot_y, alpha_threshold, bitdepth))
            exit(1);
    }

    exit(0);
}
Exemple #11
0
int
main (int argc, char **argv)
{
  widechar inbuf[BUFSIZE];
  char hyphens[BUFSIZE];
  int inlen;
  int k;
  int optc;

  set_program_name (argv[0]);

  while ((optc = getopt_long (argc, argv, "hv", longopts, NULL)) != -1)
    switch (optc)
      {
      /* --help and --version exit immediately, per GNU coding standards.  */
      case 'v':
        version_etc (stdout, program_name, PACKAGE_NAME, VERSION, AUTHORS, (char *) NULL);
        exit (EXIT_SUCCESS);
        break;
      case 'h':
        print_help ();
        exit (EXIT_SUCCESS);
        break;
      default:
	fprintf (stderr, "Try `%s --help' for more information.\n",
		 program_name);
	exit (EXIT_FAILURE);
        break;
      }

  if (optind < argc)
    {
      /* Print error message and exit.  */
      fprintf (stderr, "%s: extra operand: %s\n",
	       program_name, argv[optind]);
      fprintf (stderr, "Try `%s --help' for more information.\n",
               program_name);
      exit (EXIT_FAILURE);
    }

  validTable = NULL;
  mode = 0;

  while (1)
    {
      getCommands ();
      printf ("Type something, press enter, and view the results.\n");
      printf ("A blank line returns to command entry.\n");
      while (1)
	{
	  inlen = getInput ();
	  if (inlen == 0)
	    break;
	  for (k = 0; k < inlen; k++)
	    inbuf[k] = inputBuffer[k];
	  if (!lou_hyphenate (table, inbuf, inlen, hyphens, mode))
	    {
	      printf ("Hyphenation error\n");
	      continue;
	    }
	  printf ("Hyphenation mask: %s\n", hyphens);
	  printf ("Hyphenated word: ");
	  for (k = 0; k < inlen; k++)
	    {
	      if (hyphens[k] == '1')
		printf ("-");
	      printf ("%c", inbuf[k]);
	    }
	  printf ("\n");
	}
    }
  lou_free ();
  return 0;
}
int
main (int argc, char *argv[])
{
  struct gengetopt_args_info args_info;
  char *secret;
  size_t secretlen = 0;
  int rc;
  size_t window;
  uint64_t moving_factor;
  unsigned digits;
  char otp[10];
  time_t now, when, t0, time_step_size;
  int totpflags = 0;

  set_program_name (argv[0]);

  if (cmdline_parser (argc, argv, &args_info) != 0)
    return EXIT_FAILURE;

  if (args_info.version_given)
    {
      char *p;
      int l = -1;

      if (strcmp (oath_check_version (NULL), OATH_VERSION) != 0)
	l = asprintf (&p, "OATH Toolkit liboath.so %s oath.h %s",
		      oath_check_version (NULL), OATH_VERSION);
      else if (strcmp (OATH_VERSION, PACKAGE_VERSION) != 0)
	l = asprintf (&p, "OATH Toolkit %s",
		      oath_check_version (NULL), OATH_VERSION);
      version_etc (stdout, "oathtool", l == -1 ? "OATH Toolkit" : p,
		   PACKAGE_VERSION, "Simon Josefsson", (char *) NULL);
      if (l != -1)
	free (p);
      return EXIT_SUCCESS;
    }

  if (args_info.help_given)
    usage (EXIT_SUCCESS);

  if (args_info.inputs_num == 0)
    {
      cmdline_parser_print_help ();
      emit_bug_reporting_address ();
      return EXIT_SUCCESS;
    }

  rc = oath_init ();
  if (rc != OATH_OK)
    error (EXIT_FAILURE, 0, "liboath initialization failed: %s",
	   oath_strerror (rc));

  if (args_info.base32_flag)
    {
      rc = oath_base32_decode (args_info.inputs[0],
			       strlen (args_info.inputs[0]),
			       &secret, &secretlen);
      if (rc != OATH_OK)
	error (EXIT_FAILURE, 0, "base32 decoding failed: %s",
	       oath_strerror (rc));
    }
  else
    {
      secretlen = 1 + strlen (args_info.inputs[0]) / 2;
      secret = malloc (secretlen);
      if (!secret)
	error (EXIT_FAILURE, errno, "malloc");

      rc = oath_hex2bin (args_info.inputs[0], secret, &secretlen);
      if (rc != OATH_OK)
	error (EXIT_FAILURE, 0, "hex decoding of secret key failed");
    }

  if (args_info.counter_orig)
    moving_factor = args_info.counter_arg;
  else
    moving_factor = 0;

  if (args_info.digits_orig)
    digits = args_info.digits_arg;
  else
    digits = 6;

  if (args_info.window_orig)
    window = args_info.window_arg;
  else
    window = 0;

  if (digits != 6 && digits != 7 && digits != 8)
    error (EXIT_FAILURE, 0, "only digits 6, 7 and 8 are supported");

  if (validate_otp_p (args_info.inputs_num) && !args_info.digits_orig)
    digits = strlen (args_info.inputs[1]);
  else if (validate_otp_p (args_info.inputs_num) && args_info.digits_orig &&
	   args_info.digits_arg != strlen (args_info.inputs[1]))
    error (EXIT_FAILURE, 0,
	   "given one-time password has bad length %d != %ld",
	   args_info.digits_arg, strlen (args_info.inputs[1]));

  if (args_info.inputs_num > 2)
    error (EXIT_FAILURE, 0, "too many parameters");

  if (args_info.verbose_flag)
    {
      char *tmp;

      tmp = malloc (2 * secretlen + 1);
      if (!tmp)
	error (EXIT_FAILURE, errno, "malloc");

      oath_bin2hex (secret, secretlen, tmp);

      printf ("Hex secret: %s\n", tmp);
      free (tmp);

      rc = oath_base32_encode (secret, secretlen, &tmp, NULL);
      if (rc != OATH_OK)
	error (EXIT_FAILURE, 0, "base32 encoding failed: %s",
	       oath_strerror (rc));

      printf ("Base32 secret: %s\n", tmp);
      free (tmp);

      if (args_info.inputs_num == 2)
	printf ("OTP: %s\n", args_info.inputs[1]);
      printf ("Digits: %d\n", digits);
      printf ("Window size: %ld\n", window);
    }

  if (args_info.totp_given)
    {
      now = time (NULL);
      when = parse_time (args_info.now_arg, now);
      t0 = parse_time (args_info.start_time_arg, now);
      time_step_size = parse_duration (args_info.time_step_size_arg);

      if (when == BAD_TIME)
	error (EXIT_FAILURE, 0, "cannot parse time `%s'", args_info.now_arg);

      if (t0 == BAD_TIME)
	error (EXIT_FAILURE, 0, "cannot parse time `%s'",
	       args_info.start_time_arg);

      if (time_step_size == BAD_TIME)
	error (EXIT_FAILURE, 0, "cannot parse time `%s'",
	       args_info.time_step_size_arg);

      if (strcmp (args_info.totp_arg, "sha256") == 0)
	totpflags = OATH_TOTP_HMAC_SHA256;
      else if (strcmp (args_info.totp_arg, "sha512") == 0)
	totpflags = OATH_TOTP_HMAC_SHA512;

      if (args_info.verbose_flag)
	verbose_totp (t0, time_step_size, when);
    }
  else
    {
      if (args_info.verbose_flag)
	verbose_hotp (moving_factor);
    }

  if (generate_otp_p (args_info.inputs_num) && !args_info.totp_given)
    {
      size_t iter = 0;

      do
	{
	  rc = oath_hotp_generate (secret,
				   secretlen,
				   moving_factor + iter,
				   digits,
				   false, OATH_HOTP_DYNAMIC_TRUNCATION, otp);
	  if (rc != OATH_OK)
	    error (EXIT_FAILURE, 0,
		   "generating one-time password failed (%d)", rc);

	  printf ("%s\n", otp);
	}
      while (window - iter++ > 0);
    }
  else if (generate_otp_p (args_info.inputs_num) && args_info.totp_given)
    {
      size_t iter = 0;

      do
	{
	  rc = oath_totp_generate2 (secret,
				    secretlen,
				    when + iter * time_step_size,
				    time_step_size, t0, digits, totpflags,
				    otp);
	  if (rc != OATH_OK)
	    error (EXIT_FAILURE, 0,
		   "generating one-time password failed (%d)", rc);

	  printf ("%s\n", otp);
	}
      while (window - iter++ > 0);
    }
  else if (validate_otp_p (args_info.inputs_num) && !args_info.totp_given)
    {
      rc = oath_hotp_validate (secret,
			       secretlen,
			       moving_factor, window, args_info.inputs[1]);
      if (rc == OATH_INVALID_OTP)
	error (EXIT_OTP_INVALID, 0,
	       "password \"%s\" not found in range %ld .. %ld",
	       args_info.inputs[1],
	       (long) moving_factor, (long) moving_factor + window);
      else if (rc < 0)
	error (EXIT_FAILURE, 0,
	       "validating one-time password failed (%d)", rc);
      printf ("%d\n", rc);
    }
  else if (validate_otp_p (args_info.inputs_num) && args_info.totp_given)
    {
      rc = oath_totp_validate4 (secret,
				secretlen,
				when,
				time_step_size,
				t0,
				window,
				NULL, NULL, totpflags, args_info.inputs[1]);
      if (rc == OATH_INVALID_OTP)
	error (EXIT_OTP_INVALID, 0,
	       "password \"%s\" not found in range %ld .. %ld",
	       args_info.inputs[1],
	       (long) ((when - t0) / time_step_size - window / 2),
	       (long) ((when - t0) / time_step_size + window / 2));
      else if (rc < 0)
	error (EXIT_FAILURE, 0,
	       "validating one-time password failed (%d)", rc);
      printf ("%d\n", rc);
    }

  free (secret);
  oath_done ();

  return EXIT_SUCCESS;
}
Exemple #13
0
int
main (int argc, char **argv)
{
    uint32_t c;
    char *config_file;
    bool custom_config;
    char *tmpdir;
    struct sigaction sigact;

    set_quoting_style(NULL, escape_quoting_style);

    if (setlocale(LC_ALL, "") == NULL)
        warn(_("%s: Cannot set locale: %s\n"), argv[0], errstr);
#ifdef ENABLE_NLS
    if (bindtextdomain(PACKAGE, LOCALEDIR) == NULL)
        warn(_("%s: Cannot bind message domain: %s\n"), argv[0], errstr);
    if (textdomain(PACKAGE) == NULL)
        warn(_("%s: Cannot set message domain: %s\n"), argv[0], errstr);
#endif

    custom_config = false;
    get_package_file("config", &config_file);

    while (true) {
        c = getopt_long(argc, argv, short_opts, long_opts, NULL);
        if (c == -1)
            break;

        switch (c) {
        case 'c': /* --config */
            custom_config = true;
            free(config_file);
            config_file = xstrdup(optarg);
            break;
        case 'n': /* --no-config */
            free(config_file);
            config_file = NULL;
            break;
        case HELP_OPT: /* --help */
            printf(_("Usage: %s [OPTION]...\n"), quotearg(argv[0]));
            puts(_("Start microdc, a command-line based Direct Connect client.\n"));
            printf(_("  -n, --no-config  do not read config file on startup\n"));
            printf(_("      --help       display this help and exit\n"));
            printf(_("      --version    output version information and exit\n"));
            printf(_("\nReport bugs to <%s>.\n"), PACKAGE_BUGREPORT);
            exit(EXIT_SUCCESS);
        case VERSION_OPT: /* --version */
            version_etc(stdout, NULL, PACKAGE, VERSION, /*"Oskar Liljeblad",*/ "Vladimir Chugunov", NULL);
            exit(EXIT_SUCCESS);
        default:
            exit(EXIT_FAILURE);
        }
    }

    if (pipe(signal_pipe) < 0) {
        warn(_("Cannot create pipe pair - %s\n"), errstr);
        goto cleanup;
    }

    main_process_id = getpid();
    sigact.sa_handler = signal_received;
    if (sigemptyset(&sigact.sa_mask) < 0) {
        warn(_("Cannot empty signal set - %s\n"), errstr);
        goto cleanup;
    }
    sigact.sa_flags = SA_RESTART;
#ifdef HAVE_STRUCT_SIGACTION_SA_RESTORER
    sigact.sa_restorer = NULL;
#endif
    /* Note: every signal registered with a non-ignore action here must
     * also be registered in user.c, either with an action or as ignored.
     */
    if (sigaction(SIGINT,  &sigact, NULL) < 0 ||
            sigaction(SIGTERM, &sigact, NULL) < 0 ||
            sigaction(SIGUSR1, &sigact, NULL) < 0 ||
            sigaction(SIGCHLD, &sigact, NULL) < 0) {
        warn(_("Cannot register signal handler - %s\n"), errstr);
        goto cleanup;
    }
    sigact.sa_handler = SIG_IGN;
    if (sigaction(SIGPIPE, &sigact, NULL) < 0) {
        warn(_("Cannot register signal handler - %s\n"), errstr);
        goto cleanup;
    }

    FD_ZERO(&read_fds);
    FD_ZERO(&write_fds);
    FD_SET(signal_pipe[0], &read_fds);
    /*FD_SET(STDIN_FILENO, &read_fds);*/

    hub_recvq = byteq_new(128);
    hub_sendq = byteq_new(128);
    user_conns = hmap_new();
    hub_users = hmap_new();
    pending_userinfo = hmap_new();

    set_main_charset("");
    set_hub_charset("");
    set_fs_charset("");

    user_conn_unknown_free = ptrv_new();
    delete_files = ptrv_new();
    delete_dirs = ptrv_new();
    search_udpmsg_out = ptrv_new();
    our_searches = ptrv_new();
    search_recvq = byteq_new(8192); // same size as DC++
    my_nick = xstrdup(PACKAGE);
    my_description = xstrdup("");
    my_email = xstrdup("");
    my_speed = xstrdup("56Kbps");
    my_tag = xasprintf("%s V:%s", PACKAGE, VERSION);
    download_dir = xstrdup(".");
    tmpdir = tempdir();
    if (tmpdir == NULL) {
        warn(_("Cannot find directory for temporary files - %s\n"), errstr);
        goto cleanup;
    }
    {
        char *filename = xasprintf("%s.%d", PACKAGE, getpid());
        listing_dir = catfiles(tmpdir, filename);
        free(filename);
    }
    ptrv_append(delete_dirs, xstrdup(listing_dir));
    is_active = false;
    listen_port = 0;
    if (!local_file_list_update_init())
        goto cleanup;
    if (!set_active(false, listen_port))
        goto cleanup;
    if (!enable_search())
        goto cleanup;
    my_ul_slots = 3;

    if (!lookup_init())
        goto cleanup;
    if (!file_list_parse_init())
        goto cleanup;
    command_init();

    if (!local_file_list_init()) {
        goto cleanup;
    }

    if (config_file != NULL) {
        run_script(config_file, !custom_config);
        free(config_file);
        config_file = NULL;
    }

    screen_prepare();

    while (running) {
        fd_set res_read_fds;
        fd_set res_write_fds;
        int res;
        struct timeval tv;
        tv.tv_sec = 1;
        tv.tv_usec = 0;

        screen_redisplay_prompt();

        res_read_fds = read_fds;
        res_write_fds = write_fds;
        res = TEMP_FAILURE_RETRY(select(FD_SETSIZE, &res_read_fds, &res_write_fds, NULL, &tv));
        if (res < 0) {
            warn(_("Cannot select - %s\n"), errstr);
            break;
        }

        if (running && FD_ISSET(signal_pipe[0], &res_read_fds))
            read_signal_input();
        if (running && FD_ISSET(STDIN_FILENO, &res_read_fds))
            screen_read_input();
        if (running && listen_socket >= 0 && FD_ISSET(listen_socket, &res_read_fds))
            handle_listen_connection();
        if (running && hub_socket >= 0 && FD_ISSET(hub_socket, &res_read_fds))
            hub_input_available();
        if (running && hub_socket >= 0 && FD_ISSET(hub_socket, &res_write_fds))
            hub_now_writable();
        if (running)
            check_hub_activity();
        if (running && search_socket >= 0 && FD_ISSET(search_socket, &res_read_fds))
            search_input_available();
        if (running && search_socket >= 0 && FD_ISSET(search_socket, &res_write_fds))
            search_now_writable();
        if (running && FD_ISSET(lookup_request_mq->fd, &res_write_fds))
            lookup_request_fd_writable();
        if (running && FD_ISSET(lookup_result_mq->fd, &res_read_fds))
            lookup_result_fd_readable();
        if (running && FD_ISSET(parse_request_mq->fd, &res_write_fds))
            parse_request_fd_writable();
        if (running && FD_ISSET(parse_result_mq->fd, &res_read_fds))
            parse_result_fd_readable();
        if (running && FD_ISSET(update_request_mq->fd, &res_write_fds))
            update_request_fd_writable();
        if (running && FD_ISSET(update_result_mq->fd, &res_read_fds))
            update_result_fd_readable();

        if (running) {
            HMapIterator it;

            hmap_iterator(user_conns, &it);
            while (running && it.has_next(&it)) {
                DCUserConn *uc = (DCUserConn*) it.next(&it);
                if (uc->put_mq != NULL && FD_ISSET(uc->put_mq->fd, &res_write_fds))
                    user_request_fd_writable(uc);
                if (uc->get_mq != NULL && FD_ISSET(uc->get_mq->fd, &res_read_fds))
                    user_result_fd_readable(uc);
            }
        }
    }

cleanup:

    hub_disconnect();
    screen_finish();
    command_finish();
    local_file_list_update_finish();
    file_list_parse_finish();
    lookup_finish();

    byteq_free(hub_recvq);
    byteq_free(hub_sendq);
    hmap_free(hub_users); /* Emptied by hub_disconnect */
    hmap_free(pending_userinfo); /* Emptied by hub_disconnect */

    byteq_free(search_recvq);

    ptrv_foreach(user_conn_unknown_free, free);
    ptrv_free(user_conn_unknown_free);

    ptrv_foreach(search_udpmsg_out, free);
    ptrv_free(search_udpmsg_out);

    ptrv_foreach(our_searches, (PtrVForeachCallback) free_search_request);
    ptrv_free(our_searches);

    hmap_foreach_value(user_conns, (void (*) (void*)) user_conn_cancel);
    /* XXX: follow up and wait for user connections to die? */
    hmap_free(user_conns);

    if (our_filelist != NULL)
        filelist_free(our_filelist);

    set_main_charset(NULL);
    set_hub_charset(NULL);
    set_fs_charset(NULL);

    free(hub_name);
    free(my_nick);
    free(my_description);
    free(my_email);
    free(my_speed);
    free(my_tag);
    free(download_dir);
    free(listing_dir);

    if (delete_files != NULL) {
        for (c = 0; c < delete_files->cur; c++) {
            char *filename = (char*) delete_files->buf[c];
            struct stat st;

            if (stat(filename, &st) < 0) {
                if (errno != ENOENT)
                    warn(_("%s: Cannot get file status - %s\n"), quotearg(filename), errstr);
                free(filename);
                continue;
            }
            if (unlink(filename) < 0)
                warn(_("%s: Cannot remove file - %s\n"), quotearg(filename), errstr);
            free(filename);
        }
        ptrv_free(delete_files);
    }

    if (delete_dirs != NULL) {
        for (c = 0; c < delete_dirs->cur; c++) {
            char *filename = (char*) delete_dirs->buf[c];
            struct stat st;

            if (stat(filename, &st) < 0) {
                if (errno != ENOENT)
                    warn(_("%s: Cannot get file status - %s\n"), quotearg(filename), errstr);
                free(filename);
                continue;
            }
            if (rmdir(filename) < 0)
                warn(_("%s: Cannot remove file - %s\n"), quotearg(filename), errstr);
            free(filename);
        }
        ptrv_free(delete_dirs);
    }

    if (search_socket >= 0 && close(search_socket) < 0)
        warn(_("Cannot close search results socket - %s\n"), errstr);
    if (listen_socket >= 0 && close(listen_socket) < 0)
        warn(_("Cannot close user connections socket - %s\n"), errstr);
    if (signal_pipe[0] >= 0 && close(signal_pipe[0]) < 0)
        warn(_("Cannot close signal pipe - %s\n"), errstr);
    if (signal_pipe[1] >= 0 && close(signal_pipe[1]) < 0)
        warn(_("Cannot close signal pipe - %s\n"), errstr);

    free(config_file);

    exit(EXIT_SUCCESS);
}
Exemple #14
0
int
main (int argc, char *argv[])
{
  struct gengetopt_args_info args;
  time_t starttime, endtime, renew_till;
  Shishi *sh;
  int rc;

  setlocale (LC_ALL, "");
  bindtextdomain (PACKAGE, LOCALEDIR);
  textdomain (PACKAGE);
  set_program_name (argv[0]);

  if (cmdline_parser (argc, argv, &args) != 0)
    usage (EXIT_FAILURE);

  if (args.version_given)
    {
      version_etc (stdout, "shishi", PACKAGE_NAME, VERSION,
		   "Simon Josefsson", (char *) NULL);
      return EXIT_SUCCESS;
    }

  if (args.inputs_num > 2 ||
      args.destroy_given + args.list_given + args.renew_given > 1)
    {
      error (0, 0, _("too many arguments"));
      usage (EXIT_FAILURE);
    }

  if (args.help_given)
    usage (EXIT_SUCCESS);

  rc = shishi_init_with_paths (&sh, args.ticket_file_arg,
			       args.system_configuration_file_arg,
			       args.configuration_file_arg);
  if (rc == SHISHI_HANDLE_ERROR)
    error (EXIT_FAILURE, 0, _("Could not initialize libshishi."));

  rc = shishi_cfg_clientkdcetype_set (sh, args.encryption_type_arg);
  if (rc != SHISHI_OK)
    error (EXIT_FAILURE, 0, _("Could not set encryption types: %s"),
	   shishi_strerror (rc));

  if (args.inputs_num > 0)
    {
      rc = shishi_parse_name (sh, args.inputs[0],
			      (args.client_name_arg ? NULL :
			       &args.client_name_arg),
			      (args.realm_arg ? NULL : &args.realm_arg));

      if (rc != SHISHI_OK)
	error (EXIT_FAILURE, 0,
	       _("Could not parse client principal \"%s\": %s"),
	       args.inputs[0], shishi_strerror (rc));
    }

  if (args.inputs_num > 1)
    {
      rc = shishi_parse_name (sh, args.inputs[1],
			      (args.server_name_arg ? NULL :
			       &args.server_name_arg),
			      (args.realm_arg ? NULL : &args.realm_arg));

      if (rc != SHISHI_OK)
	error (EXIT_FAILURE, 0,
	       _("Could not parse server principal \"%s\": %s"),
	       args.inputs[1], shishi_strerror (rc));
    }

  rc = shishi_cfg (sh, args.library_options_arg);
  if (rc != SHISHI_OK)
    error (EXIT_FAILURE, 0, _("Could not read library options: %s"),
	   shishi_strerror (rc));

  if (args.verbose_given > 0)
    shishi_cfg (sh, "verbose");
  if (args.verbose_given > 1)
    shishi_cfg (sh, "verbose-noise");
  if (args.verbose_given > 2)
    shishi_cfg (sh, "verbose-asn1");
  if (args.verbose_given > 3)
    shishi_cfg (sh, "verbose-crypto");
  if (args.verbose_given > 4)
    shishi_cfg (sh, "verbose-crypto-noise");

  if (args.starttime_arg)
    {
      starttime = shishi_get_date (args.starttime_arg, NULL);
      if (starttime == -1)
	error (EXIT_FAILURE, 0, _("Invalid --starttime date `%s'"),
	       args.starttime_arg);
    }
  else
    starttime = time (NULL);

  if (args.endtime_arg)
    {
      endtime = shishi_get_date (args.endtime_arg, &starttime);
      if (endtime == -1)
	error (EXIT_FAILURE, 0, _("Invalid --endtime date `%s'"),
	       args.starttime_arg);
    }
  else
    endtime = 0;

  if (args.renew_till_arg)
    {
      renew_till = shishi_get_date (args.renew_till_arg, &starttime);
      if (renew_till == -1)
	error (EXIT_FAILURE, 0, _("Invalid --renew-till date `%s'"),
	       args.renew_till_arg);
    }
  else
    renew_till = 0;

  if (args.client_name_arg)
    shishi_principal_default_set (sh, args.client_name_arg);

  if (args.realm_arg)
    shishi_realm_default_set (sh, args.realm_arg);

  if (!args.ticket_granter_arg)
    asprintf (&args.ticket_granter_arg, "krbtgt/%s",
	      shishi_realm_default (sh));

  if (args.list_flag)
    {
      if (!args.quiet_flag)
	printf (_("Tickets in `%s':\n"), shishi_tkts_default_file (sh));

      rc = shishi_tkts_print_for_service (shishi_tkts_default (sh),
					  stdout, args.server_name_arg);
      if (rc != SHISHI_OK)
	error (EXIT_FAILURE, 0, _("Could not list tickets: %s"),
	       shishi_strerror (rc));
    }
  else if (args.destroy_flag)
    {
      int i, removed = 0;

      for (i = 0; i < shishi_tkts_size (shishi_tkts_default (sh)); i++)
	{
	  if (args.server_name_arg &&
	      !shishi_tkt_server_p (shishi_tkts_nth (shishi_tkts_default (sh),
						     i),
				    args.server_name_arg))
	    continue;

	  if (args.verbose_given)
	    {
	      printf (_("Removing ticket:\n"));
	      shishi_tkt_pretty_print (shishi_tkts_nth
				       (shishi_tkts_default (sh), i), stdout);
	    }

	  rc = shishi_tkts_remove (shishi_tkts_default (sh), i);
	  if (rc != SHISHI_OK)
	    error (EXIT_FAILURE, 0, _("Could not destroy ticket %d:\n%s"), i,
		   shishi_strerror (rc));

	  i--;
	  removed++;
	}

      if (!args.quiet_flag)
	{
	  if (removed == 0)
	    printf (_("No tickets removed.\n"));
	  else
	    printf (ngettext ("%d ticket removed.\n",
			      "%d tickets removed.\n", removed), removed);
	}
    }
  else if (args.renew_given)
    {
      error (EXIT_FAILURE, 0, "Command --renew not implemented.");
    }
  else
    {
      Shishi_tkt *tkt;
      Shishi_tkts_hint hint;

      memset (&hint, 0, sizeof (hint));
      hint.client = args.client_name_arg;
      hint.server = args.server_name_arg ? args.server_name_arg :
	args.ticket_granter_arg;
      hint.starttime = starttime;
      hint.endtime = endtime;
      hint.renew_till = renew_till;
      if (args.renewable_flag)
	hint.tktflags |= SHISHI_TICKETFLAGS_RENEWABLE;
      if (args.proxiable_flag)
	hint.tktflags |= SHISHI_TICKETFLAGS_PROXIABLE;
      if (args.proxy_flag)
	hint.tktflags |= SHISHI_TICKETFLAGS_PROXY;
      if (args.forwardable_flag)
	hint.tktflags |= SHISHI_TICKETFLAGS_FORWARDABLE;
      if (args.forwarded_flag)
	hint.tktflags |= SHISHI_TICKETFLAGS_FORWARDED;

      tkt = shishi_tkts_get (shishi_tkts_default (sh), &hint);
      if (!tkt)
	error (EXIT_FAILURE, 0, _("Could not get ticket as `%s' for `%s'."),
	       hint.client ? hint.client : shishi_principal_default (sh),
	       hint.server);

      shishi_tkt_pretty_print (tkt, stdout);
    }

  shishi_tkts_expire (shishi_tkts_default (sh));

  if (args.ticket_write_file_arg)
    shishi_tkts_default_file_set (sh, args.ticket_write_file_arg);

  shishi_done (sh);

  return EXIT_SUCCESS;
}
Exemple #15
0
int
main (int argc, char *argv[])
{
  int opt;
  char const *prog;

  exit_failure = EXIT_TROUBLE;
  initialize_main (&argc, &argv);
  program_name = argv[0];
  setlocale (LC_ALL, "");
  bindtextdomain (PACKAGE, LOCALEDIR);
  textdomain (PACKAGE);
  c_stack_action (cleanup);

  prog = getenv ("EDITOR");
  if (prog)
    editor_program = prog;

  diffarg (DEFAULT_DIFF_PROGRAM);

  /* parse command line args */
  while ((opt = getopt_long (argc, argv, "abBdEHiI:lo:stvw:W", longopts, 0))
	 != -1)
    {
      switch (opt)
	{
	case 'a':
	  diffarg ("-a");
	  break;

	case 'b':
	  diffarg ("-b");
	  break;

	case 'B':
	  diffarg ("-B");
	  break;

	case 'd':
	  diffarg ("-d");
	  break;

	case 'E':
	  diffarg ("-E");
	  break;

	case 'H':
	  diffarg ("-H");
	  break;

	case 'i':
	  diffarg ("-i");
	  break;

	case 'I':
	  diffarg ("-I");
	  diffarg (optarg);
	  break;

	case 'l':
	  diffarg ("--left-column");
	  break;

	case 'o':
	  output = optarg;
	  break;

	case 's':
	  suppress_common_lines = true;
	  break;

	case 't':
	  diffarg ("-t");
	  break;

	case 'v':
	  version_etc (stdout, "sdiff", PACKAGE_NAME, PACKAGE_VERSION,
		       "Thomas Lord", (char *) 0);
	  check_stdout ();
	  return EXIT_SUCCESS;

	case 'w':
	  diffarg ("-W");
	  diffarg (optarg);
	  break;

	case 'W':
	  diffarg ("-w");
	  break;

	case DIFF_PROGRAM_OPTION:
	  diffargv[0] = optarg;
	  break;

	case HELP_OPTION:
	  usage ();
	  check_stdout ();
	  return EXIT_SUCCESS;

	case STRIP_TRAILING_CR_OPTION:
	  diffarg ("--strip-trailing-cr");
	  break;

	case TABSIZE_OPTION:
	  diffarg ("--tabsize");
	  diffarg (optarg);
	  break;

	default:
	  try_help (0, 0);
	}
    }

  if (argc - optind != 2)
    {
      if (argc - optind < 2)
	try_help ("missing operand after `%s'", argv[argc - 1]);
      else
	try_help ("extra operand `%s'", argv[optind + 2]);
    }

  if (! output)
    {
      /* easy case: diff does everything for us */
      if (suppress_common_lines)
	diffarg ("--suppress-common-lines");
      diffarg ("-y");
      diffarg ("--");
      diffarg (argv[optind]);
      diffarg (argv[optind + 1]);
      diffarg (0);
      execvp (diffargv[0], (char **) diffargv);
      perror_fatal (diffargv[0]);
    }
  else
    {
      char const *lname, *rname;
      FILE *left, *right, *out, *diffout;
      bool interact_ok;
      struct line_filter lfilt;
      struct line_filter rfilt;
      struct line_filter diff_filt;
      bool leftdir = diraccess (argv[optind]);
      bool rightdir = diraccess (argv[optind + 1]);

      if (leftdir & rightdir)
	fatal ("both files to be compared are directories");

      lname = expand_name (argv[optind], leftdir, argv[optind + 1]);
      left = ck_fopen (lname, "r");
      rname = expand_name (argv[optind + 1], rightdir, argv[optind]);
      right = ck_fopen (rname, "r");
      out = ck_fopen (output, "w");

      diffarg ("--sdiff-merge-assist");
      diffarg ("--");
      diffarg (argv[optind]);
      diffarg (argv[optind + 1]);
      diffarg (0);

      trapsigs ();

#if ! (HAVE_WORKING_FORK || HAVE_WORKING_VFORK)
      {
	size_t cmdsize = 1;
	char *p, *command;
	int i;

	for (i = 0;  diffargv[i];  i++)
	  cmdsize += quote_system_arg (0, diffargv[i]) + 1;
	command = p = xmalloc (cmdsize);
	for (i = 0;  diffargv[i];  i++)
	  {
	    p += quote_system_arg (p, diffargv[i]);
	    *p++ = ' ';
	  }
	p[-1] = 0;
	errno = 0;
	diffout = popen (command, "r");
	if (! diffout)
	  perror_fatal (command);
	free (command);
      }
#else
      {
	int diff_fds[2];
# if HAVE_WORKING_VFORK
	sigset_t procmask;
	sigset_t blocked;
# endif

	if (pipe (diff_fds) != 0)
	  perror_fatal ("pipe");

# if HAVE_WORKING_VFORK
	/* Block SIGINT and SIGPIPE.  */
	sigemptyset (&blocked);
	sigaddset (&blocked, SIGINT);
	sigaddset (&blocked, SIGPIPE);
	sigprocmask (SIG_BLOCK, &blocked, &procmask);
# endif
	diffpid = vfork ();
	if (diffpid < 0)
	  perror_fatal ("fork");
	if (! diffpid)
	  {
	    /* Alter the child's SIGINT and SIGPIPE handlers;
	       this may munge the parent.
	       The child ignores SIGINT in case the user interrupts the editor.
	       The child does not ignore SIGPIPE, even if the parent does.  */
	    if (initial_handler (handler_index_of_SIGINT) != SIG_IGN)
	      signal_handler (SIGINT, SIG_IGN);
	    signal_handler (SIGPIPE, SIG_DFL);
# if HAVE_WORKING_VFORK
	    /* Stop blocking SIGINT and SIGPIPE in the child.  */
	    sigprocmask (SIG_SETMASK, &procmask, 0);
# endif
	    close (diff_fds[0]);
	    if (diff_fds[1] != STDOUT_FILENO)
	      {
		dup2 (diff_fds[1], STDOUT_FILENO);
		close (diff_fds[1]);
	      }

	    execvp (diffargv[0], (char **) diffargv);
	    _exit (errno == ENOENT ? 127 : 126);
	  }

# if HAVE_WORKING_VFORK
	/* Restore the parent's SIGINT and SIGPIPE behavior.  */
	if (initial_handler (handler_index_of_SIGINT) != SIG_IGN)
	  signal_handler (SIGINT, catchsig);
	if (initial_handler (handler_index_of_SIGPIPE) != SIG_IGN)
	  signal_handler (SIGPIPE, catchsig);
	else
	  signal_handler (SIGPIPE, SIG_IGN);

	/* Stop blocking SIGINT and SIGPIPE in the parent.  */
	sigprocmask (SIG_SETMASK, &procmask, 0);
# endif

	close (diff_fds[1]);
	diffout = fdopen (diff_fds[0], "r");
	if (! diffout)
	  perror_fatal ("fdopen");
      }
#endif

      lf_init (&diff_filt, diffout);
      lf_init (&lfilt, left);
      lf_init (&rfilt, right);

      interact_ok = interact (&diff_filt, &lfilt, lname, &rfilt, rname, out);

      ck_fclose (left);
      ck_fclose (right);
      ck_fclose (out);

      {
	int wstatus;
	int werrno = 0;

#if ! (HAVE_WORKING_FORK || HAVE_WORKING_VFORK)
	wstatus = pclose (diffout);
	if (wstatus == -1)
	  werrno = errno;
#else
	ck_fclose (diffout);
	while (waitpid (diffpid, &wstatus, 0) < 0)
	  if (errno == EINTR)
	    checksigs ();
	  else
	    perror_fatal ("waitpid");
	diffpid = 0;
#endif

	if (tmpname)
	  {
	    unlink (tmpname);
	    tmpname = 0;
	  }

	if (! interact_ok)
	  exiterr ();

	check_child_status (werrno, wstatus, EXIT_FAILURE, diffargv[0]);
	untrapsig (0);
	checksigs ();
	exit (WEXITSTATUS (wstatus));
      }
    }
  return EXIT_SUCCESS;			/* Fool `-Wall'.  */
}
Exemple #16
0
int
main (int argc, char *argv[])
{
  static const struct option long_options[] = {
    {"help", no_argument, 0, 'h'},
    {"version", no_argument, 0, 'v'},
    {"check", no_argument, 0, 'c'},
    {"output", required_argument, 0, 'o'},
    {0, 0, 0, 0}
  };
  int option_index = 0;
  int option_result;
  char *outputFileName = NULL;
  char *inputFileAsnName = NULL;
  char *inputFileAssignmentName = NULL;
  int checkSyntaxOnly = 0;
  asn1_node definitions = NULL;
  asn1_node structure = NULL;
  char errorDescription[ASN1_MAX_ERROR_DESCRIPTION_SIZE];
  int asn1_result = ASN1_SUCCESS;
  FILE *outputFile;
  FILE *inputFile;
  char varName[1024];
  char value[1024];
  unsigned char *der = NULL;
  int der_len;
  int k;
  int last_ra;

  set_program_name (argv[0]);

  opterr = 0;			/* disable error messages from getopt */

  while (1)
    {

      option_result =
	getopt_long (argc, argv, "hvco:", long_options, &option_index);

      if (option_result == -1)
	break;

      switch (option_result)
	{
	case 'h':		/* HELP */
	  free (outputFileName);
	  usage (EXIT_SUCCESS);
	  break;
	case 'v':		/* VERSION */
	  version_etc (stdout, program_name, PACKAGE, VERSION,
		       "Fabio Fiorina", NULL);
	  free (outputFileName);
	  exit (0);
	  break;
	case 'c':		/* CHECK SYNTAX */
	  checkSyntaxOnly = 1;
	  break;
	case 'o':		/* OUTPUT */
	  outputFileName = (char *) malloc (strlen (optarg) + 1);
	  strcpy (outputFileName, optarg);
	  break;
	case '?':		/* UNKNOW OPTION */
	  free (outputFileName);
	  fprintf (stderr,
		   "asn1Coding: option '%s' not recognized or without argument.\n\n",
		   argv[optind - 1]);
	  usage (EXIT_FAILURE);
	  break;
	default:
	  fprintf (stderr,
		   "asn1Coding: ?? getopt returned character code Ox%x ??\n",
		   option_result);
	}
    }

  if (optind == argc || optind == argc - 1)
    {
      free (outputFileName);
      fputs ("asn1Coding: input files missing\n", stderr);
      usage (EXIT_FAILURE);
    }

  inputFileAsnName = (char *) malloc (strlen (argv[optind]) + 1);
  strcpy (inputFileAsnName, argv[optind]);

  inputFileAssignmentName = (char *) malloc (strlen (argv[optind + 1]) + 1);
  strcpy (inputFileAssignmentName, argv[optind + 1]);

  asn1_result =
    asn1_parser2tree (inputFileAsnName, &definitions, errorDescription);

  switch (asn1_result)
    {
    case ASN1_SUCCESS:
      fputs ("Parse: done.\n", stderr);
      break;
    case ASN1_FILE_NOT_FOUND:
      fprintf (stderr, "asn1Coding: FILE %s NOT FOUND\n", inputFileAsnName);
      break;
    case ASN1_SYNTAX_ERROR:
    case ASN1_IDENTIFIER_NOT_FOUND:
    case ASN1_NAME_TOO_LONG:
      fprintf (stderr, "asn1Coding: %s\n", errorDescription);
      break;
    default:
      fprintf (stderr, "libtasn1 ERROR: %s\n", asn1_strerror (asn1_result));
    }

  if (asn1_result != ASN1_SUCCESS)
    {
      free (inputFileAsnName);
      free (inputFileAssignmentName);
      exit (1);
    }


  inputFile = fopen (inputFileAssignmentName, "r");

  if (inputFile == NULL)
    {
      fprintf (stderr, "asn1Coding: file '%s' not found\n",
	       inputFileAssignmentName);
      free (inputFileAsnName);
      free (inputFileAssignmentName);
      exit (1);
    }


  putc ('\n', stderr);

  while ((last_ra = readAssignment (inputFile, varName, value))
	 == ASSIGNMENT_SUCCESS)
    {
      fprintf (stderr, "var=%s, value=%s\n", varName, value);
      if (structure == NULL)
	{
	  asn1_result = asn1_create_element (definitions, value, &structure);
	}
      else
        {
	  if (strcmp(value, "(NULL)") == 0)
	    asn1_result = asn1_write_value (structure, varName, NULL, 0);
	  else
	    asn1_result = asn1_write_value (structure, varName, value, 0);
	}

      if (asn1_result != ASN1_SUCCESS)
	{
	  fprintf (stderr, "libtasn1 ERROR: %s\n",
		   asn1_strerror (asn1_result));

	  asn1_delete_structure (&definitions);
	  asn1_delete_structure (&structure);

	  free (inputFileAsnName);
	  free (inputFileAssignmentName);

	  fclose (inputFile);
	  exit (1);
	}
    }
  if (last_ra != ASSIGNMENT_EOF)
    {
      fprintf (stderr, "asn1Coding: error reading assignment file\n");
      exit (1);
    }
  fclose (inputFile);

  putc ('\n', stderr);
  asn1_print_structure (stderr, structure, "", ASN1_PRINT_NAME_TYPE_VALUE);

  der_len = 0;
  asn1_result = asn1_der_coding (structure, "", der, &der_len,
				 errorDescription);
  if (asn1_result == ASN1_MEM_ERROR)
    {
      der = malloc (der_len);
      asn1_result = asn1_der_coding (structure, "", der, &der_len,
				     errorDescription);
    }
  fprintf (stderr, "\nCoding: %s\n\n", asn1_strerror (asn1_result));
  if (asn1_result != ASN1_SUCCESS)
    {
      fprintf (stderr, "asn1Coding: %s\n", errorDescription);

      free (der);

      asn1_delete_structure (&definitions);
      asn1_delete_structure (&structure);

      free (inputFileAsnName);
      free (inputFileAssignmentName);

      exit (1);
    }

  /* Print the 'Certificate1' DER encoding */
  fprintf (stderr, "-----------------\nNumber of bytes=%i\n", der_len);
  for (k = 0; k < der_len; k++)
    fprintf (stderr, "%02x ", der[k]);
  fputs ("\n-----------------\n", stderr);

  asn1_delete_structure (&definitions);
  asn1_delete_structure (&structure);

  if (!checkSyntaxOnly)
    {
      if (outputFileName == NULL)
	createFileName (inputFileAssignmentName, &outputFileName);

      fprintf (stderr, "\nOutputFile=%s\n", outputFileName);

      outputFile = fopen (outputFileName, "w");

      if (outputFile == NULL)
	{
	  fprintf (stderr,
		   "asn1Coding: output file '%s' not available\n",
		   outputFileName);
	  free (der);
	  free (inputFileAsnName);
	  free (inputFileAssignmentName);
	  free (outputFileName);
	  exit (1);
	}

      for (k = 0; k < der_len; k++)
	fprintf (outputFile, "%c", der[k]);
      fclose (outputFile);
      fputs ("\nWriting: done.\n", stderr);
    }

  free (der);

  free (inputFileAsnName);
  free (inputFileAssignmentName);
  free (outputFileName);

  exit (0);
}
Exemple #17
0
int main(int argc , char **argv ) 
{ int optc ;
  _Bool ok ;
  _Bool delim_specified ;
  char *spec_list_string ;
  char *tmp ;
  char *tmp___0 ;
  char *tmp___1 ;
  size_t tmp___2 ;
  char *tmp___3 ;
  char *tmp___4 ;
  char *tmp___5 ;
  char *tmp___6 ;
  char *tmp___7 ;
  _Bool tmp___8 ;
  _Bool tmp___9 ;
  int *tmp___10 ;
  int tmp___11 ;
  int tmp___12 ;

  {
  delim_specified = (_Bool)0;
  set_program_name((char const   *)*(argv + 0));
  setlocale(6, "");
  bindtextdomain("coreutils", "/usr/local/share/locale");
  textdomain("coreutils");
  atexit(& close_stdout);
  operating_mode = (enum operating_mode )0;
  suppress_non_delimited = (_Bool)0;
  delim = (unsigned char )'\000';
  have_read_stdin = (_Bool)0;
  while (1) {
    optc = getopt_long(argc, (char * const  *)argv, "b:c:d:f:ns", longopts, (int *)((void *)0));
    if (! (optc != -1)) {
      break;
    } else {

    }
    switch (optc) {
    case 98: 
    case 99: 
    if ((unsigned int )operating_mode != 0U) {
      while (1) {
        tmp = gettext("only one type of list may be specified");
        error(0, 0, (char const   *)tmp);
        usage(1);
        break;
      }
    } else {

    }
    operating_mode = (enum operating_mode )1;
    spec_list_string = optarg;
    break;
    case 102: 
    if ((unsigned int )operating_mode != 0U) {
      while (1) {
        tmp___0 = gettext("only one type of list may be specified");
        error(0, 0, (char const   *)tmp___0);
        usage(1);
        break;
      }
    } else {

    }
    operating_mode = (enum operating_mode )2;
    spec_list_string = optarg;
    break;
    case 100: 
    if ((int )*(optarg + 0) != 0) {
      if ((int )*(optarg + 1) != 0) {
        while (1) {
          tmp___1 = gettext("the delimiter must be a single character");
          error(0, 0, (char const   *)tmp___1);
          usage(1);
          break;
        }
      } else {

      }
    } else {

    }
    delim = (unsigned char )*(optarg + 0);
    delim_specified = (_Bool)1;
    break;
    case 128: 
    output_delimiter_specified = (_Bool)1;
    if ((int )*(optarg + 0) == 0) {
      output_delimiter_length = 1UL;
    } else {
      tmp___2 = strlen((char const   *)optarg);
      output_delimiter_length = tmp___2;
    }
    output_delimiter_string = xstrdup((char const   *)optarg);
    break;
    case 110: 
    break;
    case 115: 
    suppress_non_delimited = (_Bool)1;
    break;
    case 129: 
    complement = (_Bool)1;
    break;
    case -130: 
    usage(0);
    break;
    case -131: 
    version_etc(stdout, "cut", "GNU coreutils", Version, "David M. Ihnat", "David MacKenzie", "Jim Meyering", (char *)((void *)0));
    exit(0);
    break;
    default: 
    usage(1);
    }
  }
  if ((unsigned int )operating_mode == 0U) {
    while (1) {
      tmp___3 = gettext("you must specify a list of bytes, characters, or fields");
      error(0, 0, (char const   *)tmp___3);
      usage(1);
      break;
    }
  } else {

  }
  if ((int )delim != 0) {
    if ((unsigned int )operating_mode != 2U) {
      while (1) {
        tmp___4 = gettext("an input delimiter may be specified only when operating on fields");
        error(0, 0, (char const   *)tmp___4);
        usage(1);
        break;
      }
    } else {

    }
  } else {

  }
  if (suppress_non_delimited) {
    if ((unsigned int )operating_mode != 2U) {
      while (1) {
        tmp___5 = gettext("suppressing non-delimited lines makes sense\n\tonly when operating on fields");
        error(0, 0, (char const   *)tmp___5);
        usage(1);
        break;
      }
    } else {

    }
  } else {

  }
  if (output_delimiter_specified) {
    range_start_ht = hash_initialize(31UL, (Hash_tuning const   *)((void *)0), & hash_int, & hash_compare_ints, (void (*)(void * ))((void *)0));
    if ((unsigned long )range_start_ht == (unsigned long )((void *)0)) {
      xalloc_die();
    } else {

    }
  } else {

  }
  tmp___8 = set_fields((char const   *)spec_list_string);
  if (! tmp___8) {
    if ((unsigned int )operating_mode == 2U) {
      while (1) {
        tmp___6 = gettext("missing list of fields");
        error(0, 0, (char const   *)tmp___6);
        usage(1);
        break;
      }
    } else {
      while (1) {
        tmp___7 = gettext("missing list of positions");
        error(0, 0, (char const   *)tmp___7);
        usage(1);
        break;
      }
    }
  } else {

  }
  if (! delim_specified) {
    delim = (unsigned char )'\t';
  } else {

  }
  if ((unsigned long )output_delimiter_string == (unsigned long )((void *)0)) {
    dummy[0] = (char )delim;
    dummy[1] = (char )'\000';
    output_delimiter_string = dummy;
    output_delimiter_length = 1UL;
  } else {

  }
  if (optind == argc) {
    ok = cut_file("-");
  } else {
    ok = (_Bool)1;
    while (optind < argc) {
      tmp___9 = cut_file((char const   *)*(argv + optind));
      ok = (_Bool )((int )ok & (int )tmp___9);
      optind ++;
    }
  }
  if (range_start_ht) {
    hash_free(range_start_ht);
  } else {

  }
  if (have_read_stdin) {
    tmp___11 = fclose(stdin);
    if (tmp___11 == -1) {
      tmp___10 = __errno_location();
      error(0, *tmp___10, "-");
      ok = (_Bool)0;
    } else {

    }
  } else {

  }
  if (ok) {
    tmp___12 = 0;
  } else {
    tmp___12 = 1;
  }
  exit(tmp___12);
}
}
Exemple #18
0
int
main (int argc, char **argv)
{
  char *charbuf;
  widechar inbuf[BUFSIZE];
  widechar transbuf[BUFSIZE];
  widechar outbuf[BUFSIZE];
  int outputPos[BUFSIZE];
  int inputPos[BUFSIZE];
  int inlen;
  int translen;
  int outlen;
  int cursorPos = -1;
  int realInlen = 0;
  int k;
  int optc;

  set_program_name (argv[0]);

  while ((optc = getopt_long (argc, argv, "hv", longopts, NULL)) != -1)
    switch (optc)
      {
      /* --help and --version exit immediately, per GNU coding standards.  */
      case 'v':
        version_etc (stdout, program_name, PACKAGE_NAME, VERSION, AUTHORS, (char *) NULL);
        exit (EXIT_SUCCESS);
        break;
      case 'h':
        print_help ();
        exit (EXIT_SUCCESS);
        break;
      default:
	fprintf (stderr, "Try `%s --help' for more information.\n",
		 program_name);
	exit (EXIT_FAILURE);
        break;
      }

  if (optind < argc)
    {
      /* Print error message and exit.  */
      fprintf (stderr, "%s: extra operand: %s\n",
	       program_name, argv[optind]);
      fprintf (stderr, "Try `%s --help' for more information.\n",
               program_name);
      exit (EXIT_FAILURE);
    }

  validTable = NULL;
  enteredCursorPos = -1;
  mode = 0;
  while (1)
    {
      getCommands ();
      printf ("Type something, press enter, and view the results.\n");
      printf ("A blank line returns to command entry.\n");
      if (minimalist)
	while (1)
	  {
	    translen = outputSize;
	    outlen = outputSize;
	    inlen = getInput ();
	    if (inlen == 0)
	      break;
	    if (!(realInlen = extParseChars (inputBuffer, inbuf)))
	      break;
	    inlen = realInlen;
	    if (!lou_translateString (table, inbuf, &inlen, transbuf,
				      &translen, NULL, NULL, 0))
	      break;
	    transbuf[translen] = 0;
	    printf ("Translation:\n");
	    charbuf = showString (transbuf, translen);
	    k = strlen (charbuf) - 1;
	    charbuf[k] = 0;
	    printf ("%s\n", &charbuf[1]);
	    if (showSizes)
	      printf ("input length = %d; output length = %d\n", inlen,
		      translen);
	    lou_backTranslateString (table, transbuf, &translen, outbuf,
				     &outlen, NULL, NULL, 0);
	    printf ("Back-translation:\n");
	    charbuf = showString (outbuf, outlen);
	    k = strlen (charbuf) - 1;
	    charbuf[k] = 0;
	    printf ("%s\n", &charbuf[1]);
	    if (showSizes)
	      printf ("input length = %d; output length = %d.\n", translen,
		      outlen);
	    if (outlen == realInlen)
	      {
		for (k = 0; k < realInlen; k++)
		  if (inbuf[k] != outbuf[k])
		    break;
		if (k == realInlen)
		  printf ("Perfect roundtrip!\n");
	      }
	  }
      else
	while (1)
	  {
	    for (k = 0; k < strlen (enteredEmphasis); k++)
	      emphasis[k] = (formtype) enteredEmphasis[k];
	    emphasis[k] = 0;
	    strcpy (spacing, enteredSpacing);
	    cursorPos = enteredCursorPos;
	    inlen = getInput ();
	    if (inlen == 0)
	      break;
	    outlen = outputSize;
	    if (backOnly)
	      {
	    if (!(translen = extParseChars (inputBuffer, transbuf)))
	      break;
	    inlen = realInlen;
	      }
	    else
	      {
		translen = outputSize;
	    if (!(realInlen = extParseChars (inputBuffer, inbuf)))
	      break;
	    inlen = realInlen;
		if (!lou_translate (table, inbuf, &inlen, transbuf,
				    &translen, emphasis, spacing,
				    &outputPos[0], &inputPos[0], &cursorPos,
				    mode))
		  break;
		transbuf[translen] = 0;
		if (mode & dotsIO)
		  {
		    printf ("Translation dot patterns:\n");
		    printf ("%s\n", showDots (transbuf, translen));
		  }
		else
		  {
		    printf ("Translation:\n");
		    charbuf = showString (transbuf, translen);
		    k = strlen (charbuf) - 1;
		    charbuf[k] = 0;
		    printf ("%s\n", &charbuf[1]);
		    if (showSizes)
		      printf ("input length = %d; output length = %d\n",
			      inlen, translen);
		  }
	      }
	    if (cursorPos != -1)
	      printf ("Cursor position: %d\n", cursorPos);
	    if (enteredSpacing[0])
	      printf ("Returned spacing: %s\n", spacing);
	    if (showPositions)
	      {
		printf ("Output positions:\n");
		for (k = 0; k < inlen; k++)
		  printf ("%d ", outputPos[k]);
		printf ("\n");
		printf ("Input positions:\n");
		for (k = 0; k < translen; k++)
		  printf ("%d ", inputPos[k]);
		printf ("\n");
	      }
	    if (!forwardOnly)
	      {
		if (!lou_backTranslate (table, transbuf, &translen,
					outbuf, &outlen,
					emphasis, spacing, &outputPos[0],
					&inputPos[0], &cursorPos, mode))
		  break;
		printf ("Back-translation:\n");
		charbuf = showString (outbuf, outlen);		k = 
		strlen (charbuf) - 1;
		charbuf[k] = 0;
		printf ("%s\n", &charbuf[1]);
		if (showSizes)
		  printf ("input length = %d; output length = %d\n",
			  translen, outlen);
		if (cursorPos != -1)
		  printf ("Cursor position: %d\n", cursorPos);
		if (enteredSpacing[0])
		  printf ("Returned spacing: %s\n", spacing);
		if (showPositions)
		  {
		    printf ("Output positions:\n");
		    for (k = 0; k < translen; k++)
		      printf ("%d ", outputPos[k]);
		    printf ("\n");
		    printf ("Input positions:\n");
		    for (k = 0; k < outlen; k++)
		      printf ("%d ", inputPos[k]);
		    printf ("\n");
		  }
	      }
	    if (!(forwardOnly || backOnly))
	      {
		if (outlen == realInlen)
		  {
		    for (k = 0; k < realInlen; k++)
		      if (inbuf[k] != outbuf[k])
			break;
		    if (k == realInlen)
		      printf ("Perfect roundtrip!\n");
		  }
	      }
	  }
    }
  lou_free ();
  exit (EXIT_SUCCESS);
}
Exemple #19
0
int
main (int argc, char *argv[])
{
  Gsasl *ctx = NULL;
  int res;
  char *in;
  char *connect_hostname = NULL;
  char *connect_service = NULL;
#ifdef HAVE_LIBGNUTLS
  gnutls_anon_client_credentials anoncred;
  gnutls_certificate_credentials x509cred;
#endif

  set_program_name (argv[0]);
  setlocale (LC_ALL, "");
  bindtextdomain (PACKAGE, LOCALEDIR);
  textdomain (PACKAGE);

  /* This is necessary for modern MinGW compilers that provide working
     getaddrinfo function, which results in gnulib not detecting that
     it is broken.  The proper fix is for gnulib to wrap the
     getaddrinfo call and initialize Windows sockets in the
     wrapper.  */
  (void) gl_sockets_startup (SOCKETS_1_1);

  if (cmdline_parser (argc, argv, &args_info) != 0)
    return EXIT_FAILURE;

  if (args_info.version_given)
    {
      const char *p = PACKAGE_NAME;
      if (strcmp (gsasl_check_version (NULL), PACKAGE_VERSION) != 0)
	p = PACKAGE_STRING;
      version_etc (stdout, "gsasl", p, gsasl_check_version (NULL),
		   "Simon Josefsson", (char *) NULL);
      return EXIT_SUCCESS;
    }

  if (args_info.help_given)
    usage (EXIT_SUCCESS);

  if (!(args_info.client_flag || args_info.client_given) &&
      !args_info.server_given &&
      !args_info.client_mechanisms_flag && !args_info.server_mechanisms_flag)
    {
      error (0, 0, _("missing argument"));
      usage (EXIT_FAILURE);
    }

  if ((args_info.x509_cert_file_arg && !args_info.x509_key_file_arg) ||
      (!args_info.x509_cert_file_arg && args_info.x509_key_file_arg))
    error (EXIT_FAILURE, 0,
	   _("need both --x509-cert-file and --x509-key-file"));

  if (args_info.starttls_flag && args_info.no_starttls_flag)
    error (EXIT_FAILURE, 0,
	   _("cannot use both --starttls and --no-starttls"));

  if (args_info.smtp_flag && args_info.imap_flag)
    error (EXIT_FAILURE, 0, _("cannot use both --smtp and --imap"));

  if (!args_info.connect_given && args_info.inputs_num == 0 &&
      !args_info.client_given && !args_info.server_given &&
      !args_info.client_mechanisms_flag && !args_info.server_mechanisms_flag)
    {
      cmdline_parser_print_help ();
      emit_bug_reporting_address ();
      return EXIT_SUCCESS;
    }

  if (args_info.connect_given)
    {
      if (strrchr (args_info.connect_arg, ':'))
	{
	  connect_hostname = xstrdup (args_info.connect_arg);
	  *strrchr (connect_hostname, ':') = '\0';
	  connect_service =
	    xstrdup (strrchr (args_info.connect_arg, ':') + 1);
	}
      else
	{
	  connect_hostname = xstrdup (args_info.connect_arg);
	  if (args_info.smtp_flag)
	    connect_service = xstrdup ("smtp");
	  else
	    connect_service = xstrdup ("imap");
	}
    }
  else if (args_info.inputs_num > 0)
    {
      connect_hostname = args_info.inputs[0];
      if (args_info.inputs_num > 1)
	connect_service = args_info.inputs[1];
      else if (args_info.smtp_flag)
	connect_service = xstrdup ("smtp");
      else
	connect_service = xstrdup ("imap");
    }

  if (connect_service && !args_info.smtp_flag && !args_info.imap_flag)
    {
      if (strcmp (connect_service, "25") == 0 ||
	  strcmp (connect_service, "smtp") == 0)
	args_info.smtp_flag = 1;
      else
	args_info.imap_flag = 1;
    }

  if (args_info.imap_flag && !args_info.service_given)
    args_info.service_arg = xstrdup ("imap");

  if (args_info.smtp_flag && !args_info.service_given)
    args_info.service_arg = xstrdup ("smtp");

  if (args_info.imap_flag || args_info.smtp_flag)
    args_info.no_client_first_flag = 1;

  if (connect_hostname && !args_info.hostname_arg)
    args_info.hostname_arg = xstrdup (connect_hostname);

  if (!isatty (STDOUT_FILENO))
    setvbuf (stdout, NULL, _IOLBF, BUFSIZ);

  res = gsasl_init (&ctx);
  if (res != GSASL_OK)
    error (EXIT_FAILURE, 0, _("initialization failure: %s"),
	   gsasl_strerror (res));

  gsasl_callback_set (ctx, callback);

  if (args_info.client_mechanisms_flag || args_info.server_mechanisms_flag)
    {
      char *mechs;

      if (args_info.client_mechanisms_flag)
	res = gsasl_client_mechlist (ctx, &mechs);
      else
	res = gsasl_server_mechlist (ctx, &mechs);

      if (res != GSASL_OK)
	error (EXIT_FAILURE, 0, _("error listing mechanisms: %s"),
	       gsasl_strerror (res));

      if (!args_info.quiet_given)
	{
	  if (args_info.client_mechanisms_flag)
	    fprintf (stderr,
		     _("This client supports the following mechanisms:\n"));
	  else
	    fprintf (stderr,
		     _("This server supports the following mechanisms:\n"));
	}

      fprintf (stdout, "%s\n", mechs);

      free (mechs);

      return EXIT_SUCCESS;
    }

  if (args_info.connect_given || args_info.inputs_num > 0)
    {
      struct addrinfo hints;
      struct addrinfo *ai0, *ai;

      memset (&hints, 0, sizeof (hints));
      hints.ai_flags = AI_CANONNAME;
      hints.ai_socktype = SOCK_STREAM;
      res = getaddrinfo (connect_hostname, connect_service, &hints, &ai0);
      if (res != 0)
	error (EXIT_FAILURE, 0, "%s: %s", connect_hostname,
	       gai_strerror (res));

      for (ai = ai0; ai; ai = ai->ai_next)
	{
	  fprintf (stderr, "Trying %s...\n", quote (ai->ai_canonname ?
						    ai->ai_canonname :
						    connect_hostname));

	  sockfd = socket (ai->ai_family, ai->ai_socktype, ai->ai_protocol);
	  if (sockfd < 0)
	    {
	      error (0, errno, "socket");
	      continue;
	    }

	  if (connect (sockfd, ai->ai_addr, ai->ai_addrlen) < 0)
	    {
	      int save_errno = errno;
	      close (sockfd);
	      sockfd = -1;
	      error (0, save_errno, "connect");
	      continue;
	    }
	  break;
	}

      if (sockfd < 0)
	error (EXIT_FAILURE, errno, "socket");

      freeaddrinfo (ai);
    }

  if (!greeting ())
    return 1;

#ifdef HAVE_LIBGNUTLS
  if (sockfd && !args_info.no_starttls_flag &&
      (args_info.starttls_flag || has_starttls ()))
    {
      res = gnutls_global_init ();
      if (res < 0)
	error (EXIT_FAILURE, 0, _("GnuTLS global initialization failed: %s"),
	       gnutls_strerror (res));

      res = gnutls_init (&session, GNUTLS_CLIENT);
      if (res < 0)
	error (EXIT_FAILURE, 0, _("GnuTLS initialization failed: %s"),
	       gnutls_strerror (res));

      res = gnutls_set_default_priority (session);
      if (res < 0)
	error (EXIT_FAILURE, 0, _("setting GnuTLS defaults failed: %s"),
	       gnutls_strerror (res));

      res = gnutls_anon_allocate_client_credentials (&anoncred);
      if (res < 0)
	error (EXIT_FAILURE, 0,
	       _("allocating anonymous GnuTLS credential: %s"),
	       gnutls_strerror (res));

      res = gnutls_credentials_set (session, GNUTLS_CRD_ANON, anoncred);
      if (res < 0)
	error (EXIT_FAILURE, 0, _("setting anonymous GnuTLS credential: %s"),
	       gnutls_strerror (res));

      res = gnutls_certificate_allocate_credentials (&x509cred);
      if (res < 0)
	error (EXIT_FAILURE, 0, _("allocating X.509 GnuTLS credential: %s"),
	       gnutls_strerror (res));

      if (args_info.x509_cert_file_arg && args_info.x509_key_file_arg)
	res = gnutls_certificate_set_x509_key_file
	  (x509cred, args_info.x509_cert_file_arg,
	   args_info.x509_key_file_arg, GNUTLS_X509_FMT_PEM);
      if (res != GNUTLS_E_SUCCESS)
	error (EXIT_FAILURE, 0, _("loading X.509 GnuTLS credential: %s"),
	       gnutls_strerror (res));

      if (args_info.x509_ca_file_arg)
	{
	  res = gnutls_certificate_set_x509_trust_file
	    (x509cred, args_info.x509_ca_file_arg, GNUTLS_X509_FMT_PEM);
	  if (res < 0)
	    error (EXIT_FAILURE, 0, _("no X.509 CAs found: %s"),
		   gnutls_strerror (res));
	  if (res == 0)
	    error (EXIT_FAILURE, 0, _("no X.509 CAs found"));
	}

      res = gnutls_credentials_set (session, GNUTLS_CRD_CERTIFICATE,
				    x509cred);
      if (res < 0)
	error (EXIT_FAILURE, 0, _("setting X.509 GnuTLS credential: %s"),
	       gnutls_strerror (res));

      if (args_info.priority_arg)
	{
	  const char *err_pos;

	  res = gnutls_priority_set_direct (session, args_info.priority_arg,
					    &err_pos);
	  if (res < 0)
	    error (EXIT_FAILURE, 0,
		   _("setting GnuTLS cipher priority (%s): %s\n"),
		   gnutls_strerror (res), err_pos);
	}

      gnutls_transport_set_ptr (session, (gnutls_transport_ptr)
				(unsigned long) sockfd);

      if (!starttls ())
	return 1;

      res = gnutls_handshake (session);
      if (res < 0)
	error (EXIT_FAILURE, 0, _("GnuTLS handshake failed: %s"),
	       gnutls_strerror (res));

      if (args_info.x509_ca_file_arg)
	{
	  unsigned int status;

	  res = gnutls_certificate_verify_peers2 (session, &status);
	  if (res < 0)
	    error (EXIT_FAILURE, 0, _("verifying peer certificate: %s"),
		   gnutls_strerror (res));

	  if (status & GNUTLS_CERT_INVALID)
	    error (EXIT_FAILURE, 0, _("server certificate is not trusted"));

	  if (status & GNUTLS_CERT_SIGNER_NOT_FOUND)
	    error (EXIT_FAILURE, 0,
		   _("server certificate hasn't got a known issuer"));

	  if (status & GNUTLS_CERT_REVOKED)
	    error (EXIT_FAILURE, 0, _("server certificate has been revoked"));

	  if (status != 0)
	    error (EXIT_FAILURE, 0,
		   _("could not verify server certificate (rc=%d)"), status);
	}

#if HAVE_GNUTLS_SESSION_CHANNEL_BINDING
      if (!args_info.no_cb_flag)
	{
	  gnutls_datum cb;

	  res = gnutls_session_channel_binding (session,
						GNUTLS_CB_TLS_UNIQUE, &cb);
	  if (res != GNUTLS_E_SUCCESS)
	    error (EXIT_FAILURE, 0, _("getting channel binding failed: %s"),
		   gnutls_strerror (res));

	  res = gsasl_base64_to ((char *) cb.data, cb.size,
				 &b64cbtlsunique, NULL);
	  if (res != GSASL_OK)
	    error (EXIT_FAILURE, 0, "%s", gsasl_strerror (res));
	}
#endif

      using_tls = true;
    }
#endif

  if (args_info.client_flag || args_info.client_given
      || args_info.server_given)
    {
      char *out;
      char *b64output;
      size_t output_len;
      size_t b64output_len;
      const char *mech;
      Gsasl_session *xctx = NULL;

      if (!select_mechanism (&in))
	return 1;

      mech = gsasl_client_suggest_mechanism (ctx, in);
      if (mech == NULL)
	{
	  fprintf (stderr, _("Cannot find mechanism...\n"));
	  return 0;
	}

      if (args_info.mechanism_arg)
	mech = args_info.mechanism_arg;

      if (!authenticate (mech))
	return 1;

      /* Authenticate using mechanism */

      if (args_info.server_flag)
	res = gsasl_server_start (ctx, mech, &xctx);
      else
	res = gsasl_client_start (ctx, mech, &xctx);
      if (res != GSASL_OK)
	error (EXIT_FAILURE, 0, _("mechanism unavailable: %s"),
	       gsasl_strerror (res));

      in = NULL;
      out = NULL;

      if (!args_info.server_flag && args_info.no_client_first_flag)
	{
	  res = GSASL_NEEDS_MORE;
	  goto no_client_first;
	}

      do
	{
	  int res2;

	  res = gsasl_step64 (xctx, in, &out);
	  if (res != GSASL_NEEDS_MORE && res != GSASL_OK)
	    break;

	  if (!step_send (out))
	    return 1;

	no_client_first:
	  if (!args_info.quiet_given &&
	      !args_info.imap_flag && !args_info.smtp_flag)
	    {
	      if (args_info.server_flag)
		fprintf (stderr, _("Enter base64 authentication data "
				   "from client (press RET if none):\n"));
	      else
		fprintf (stderr, _("Enter base64 authentication data "
				   "from server (press RET if none):\n"));
	    }

	  /* Return 1 on token, 2 on protocol success, 3 on protocol fail, 0 on
	     errors. */
	  res2 = step_recv (&in);
	  if (!res2)
	    return 1;
	  if (res2 == 3)
	    error (EXIT_FAILURE, 0, _("server error"));
	  if (res2 == 2)
	    break;
	}
      while (args_info.imap_flag || args_info.smtp_flag
	     || res == GSASL_NEEDS_MORE);

      if (res != GSASL_OK)
	error (EXIT_FAILURE, 0, _("mechanism error: %s"),
	       gsasl_strerror (res));

      if (!args_info.quiet_given)
	{
	  if (args_info.server_flag)
	    fprintf (stderr, _("Server authentication "
			       "finished (client trusted)...\n"));
	  else
	    fprintf (stderr, _("Client authentication "
			       "finished (server trusted)...\n"));
	  fflush (stderr);
	}

      /* Transfer application payload */
      if (args_info.application_data_flag)
	{
	  struct pollfd pfd[2];
	  char *sockbuf = NULL;
	  /* we read chunks of 1000 bytes at a time */
	  size_t sockpos = 0, sockalloc = 0, sockalloc1 = 1000;

	  /* Setup pollfd structs... */
	  pfd[0].fd = STDIN_FILENO;
	  pfd[0].events = POLLIN;
	  if (sockfd)
	    {
	      pfd[1].fd = sockfd;
	      pfd[1].events = POLLIN;
	    }

	  if (!args_info.quiet_given)
	    {
	      fprintf (stderr,
		       _("Enter application data (EOF to finish):\n"));
	      fflush (stderr);
	    }

	  while (1)
	    {
	      int rc;

	      pfd[0].revents = 0;
	      pfd[1].revents = 0;

	      rc = poll (pfd, sockfd ? 2 : 1, -1);
	      if (rc < 0 && errno == EINTR)
		continue;

	      /* Always check for errors */
	      if (rc < 0)
		error (EXIT_FAILURE, errno, "poll");

	      /* We got data to read from stdin.. */
	      if ((pfd[0].revents & (POLLIN | POLLERR)) == POLLIN)
		{
		  char *line = NULL;
		  size_t n;
		  ssize_t len;

		  len = getline (&line, &n, stdin);
		  if (len <= 0)
		    break;

		  if (args_info.imap_flag || args_info.smtp_flag)
		    {
		      if (len < 2 || strcmp (&line[len - 2], "\r\n") != 0)
			{
			  line = xrealloc (line, len + 2);
			  line[len - 1] = '\r';
			  line[len] = '\n';
			  line[len + 1] = '\0';
			  len++;
			}
		    }
		  else
		    {
		      len--;
		      line[len] = '\0';
		    }

		  res = gsasl_encode (xctx, line, len, &out, &output_len);
		  if (res != GSASL_OK)
		    break;

		  if (sockfd)
		    {
#ifdef HAVE_LIBGNUTLS
		      if (using_tls)
			len = gnutls_record_send (session, out, output_len);
		      else
#endif
			len = write (sockfd, out, output_len);
		      if (len != output_len)
			error (EXIT_FAILURE, errno, "write");
		    }
		  else if (!(strlen (line) == output_len &&
			     memcmp (line, out, output_len) == 0))
		    {
		      res = gsasl_base64_to (out, output_len,
					     &b64output, &b64output_len);
		      if (res != GSASL_OK)
			break;

		      if (!args_info.quiet_given)
			fprintf (stderr, _("Base64 encoded application "
					   "data to send:\n"));
		      fprintf (stdout, "%s\n", b64output);

		      free (b64output);
		    }

		  free (line);
		  free (out);
		}
	      /* If there was an error, quit.  */
	      else if (pfd[0].revents & (POLLERR | POLLHUP))
		{
		  error (0, 0, "poll stdin");
		  break;
		}

	      /* We got data to read from the socket.. */
	      if (sockfd && (pfd[1].revents & (POLLIN | POLLERR)) == POLLIN)
		{
		  ssize_t len;

		  if (sockalloc == sockpos)
		    sockbuf = x2realloc (sockbuf, &sockalloc1);
		  sockalloc = sockalloc1;

#ifdef HAVE_LIBGNUTLS
		  if (using_tls)
		    len = gnutls_record_recv (session, &sockbuf[sockpos],
					      sockalloc - sockpos);
		  else
#endif
		    len = recv (sockfd, &sockbuf[sockpos],
				sockalloc - sockpos, 0);
		  if (len <= 0)
		    break;

		  sockpos += len;

		  res = gsasl_decode (xctx, sockbuf, sockpos,
				      &out, &output_len);
		  if (res == GSASL_NEEDS_MORE)
		    {
#define MAX_INPUT_SIZE	0x100000
		      if (sockpos > MAX_INPUT_SIZE)
			error (EXIT_FAILURE, 0,
			       _("SASL record too large: %zu\n"), sockpos);
		      continue;
		    }
		  if (res != GSASL_OK)
		    break;

		  free (sockbuf);
		  sockbuf = NULL;
		  sockpos = 0;
		  sockalloc = 0;
		  sockalloc1 = 1000;

		  printf ("%.*s", (int) output_len, out);
		  free (out);
		}
	      /* If there was an error, quit.  */
	      else if (pfd[1].revents & (POLLERR | POLLHUP))
		{
		  error (0, 0, "poll socket");
		  break;
		}
	    }

	  if (res != GSASL_OK)
	    error (EXIT_FAILURE, 0, _("encoding error: %s"),
		   gsasl_strerror (res));
	}

      if (!args_info.quiet_given)
	fprintf (stderr, _("Session finished...\n"));

      if (!logout ())
	return 1;

      gsasl_finish (xctx);
    }

  if (sockfd)
    {
#ifdef HAVE_LIBGNUTLS
      if (using_tls)
	{
	  res = gnutls_bye (session, GNUTLS_SHUT_RDWR);
	  if (res < 0)
	    error (EXIT_FAILURE, 0,
		   _("terminating GnuTLS session failed: %s"),
		   gnutls_strerror (res));

	}
#endif
      shutdown (sockfd, SHUT_RDWR);
      close (sockfd);
    }

  gsasl_done (ctx);

#ifdef HAVE_LIBGNUTLS
  if (using_tls)
    {
      gnutls_deinit (session);
      gnutls_anon_free_client_credentials (anoncred);
      gnutls_certificate_free_credentials (x509cred);
      gnutls_global_deinit ();
    }
#endif

  return 0;
}