Example #1
0
int
main (int argc, char *argv[])
{
  /* Set global program name that is not polluted with libtool artifacts.  */
  set_program_name (argv[0]);

  setlocale (LC_ALL, "");
  bindtextdomain (PACKAGE, LOCALEBASEDIR);
  textdomain (PACKAGE);

  enum { HELP_OPTION = CHAR_MAX + 1 };

  static const char *options = "a:c:d:vVx";
  static const struct option long_options[] = {
    { "add", 1, 0, 'a' },
    { "connect", 1, 0, 'c' },
    { "domain", 1, 0, 'd' },
    { "echo-keys", 0, 0, 0 },
    { "format", 2, 0, 0 },
    { "help", 0, 0, HELP_OPTION },
    { "keys-from-stdin", 0, 0, 0 },
    { "verbose", 0, 0, 'v' },
    { "version", 0, 0, 'V' },
    { 0, 0, 0, 0 }
  };
  struct drv *drvs = NULL;
  struct drv *drv;
  const char *format = NULL;
  int c;
  int option_index;

  g = guestfs_create ();
  if (g == NULL) {
    fprintf (stderr, _("guestfs_create: failed to create handle\n"));
    exit (EXIT_FAILURE);
  }

  argv[0] = bad_cast (program_name);

  for (;;) {
    c = getopt_long (argc, argv, options, long_options, &option_index);
    if (c == -1) break;

    switch (c) {
    case 0:			/* options which are long only */
      if (STREQ (long_options[option_index].name, "keys-from-stdin")) {
        keys_from_stdin = 1;
      } else if (STREQ (long_options[option_index].name, "echo-keys")) {
        echo_keys = 1;
      } else if (STREQ (long_options[option_index].name, "format")) {
        if (!optarg || STREQ (optarg, ""))
          format = NULL;
        else
          format = optarg;
      } else {
        fprintf (stderr, _("%s: unknown long option: %s (%d)\n"),
                 program_name, long_options[option_index].name, option_index);
        exit (EXIT_FAILURE);
      }
      break;

    case 'a':
      OPTION_a;
      break;

    case 'c':
      OPTION_c;
      break;

    case 'd':
      OPTION_d;
      break;

    case 'v':
      OPTION_v;
      break;

    case 'V':
      OPTION_V;
      break;

    case 'x':
      OPTION_x;
      break;

    case HELP_OPTION:
      usage (EXIT_SUCCESS);

    default:
      usage (EXIT_FAILURE);
    }
  }

  /* Old-style syntax?  There were no -a or -d options in the old
   * virt-cat which is how we detect this.
   */
  if (drvs == NULL) {
    /* argc - 1 because last parameter is the single filename. */
    while (optind < argc - 1) {
      if (strchr (argv[optind], '/') ||
          access (argv[optind], F_OK) == 0) { /* simulate -a option */
        drv = calloc (1, sizeof (struct drv));
        if (!drv) {
          perror ("malloc");
          exit (EXIT_FAILURE);
        }
        drv->type = drv_a;
        drv->a.filename = argv[optind];
        drv->next = drvs;
        drvs = drv;
      } else {                  /* simulate -d option */
        drv = calloc (1, sizeof (struct drv));
        if (!drv) {
          perror ("malloc");
          exit (EXIT_FAILURE);
        }
        drv->type = drv_d;
        drv->d.guest = argv[optind];
        drv->next = drvs;
        drvs = drv;
      }

      optind++;
    }
  }

  /* These are really constants, but they have to be variables for the
   * options parsing code.  Assert here that they have known-good
   * values.
   */
  assert (read_only == 1);
  assert (inspector == 1);
  assert (live == 0);

  /* User must specify at least one filename on the command line. */
  if (optind >= argc || argc - optind < 1)
    usage (EXIT_FAILURE);

  /* User must have specified some drives. */
  if (drvs == NULL)
    usage (EXIT_FAILURE);

  /* Add drives, inspect and mount.  Note that inspector is always true,
   * and there is no -m option.
   */
  add_drives (drvs, 'a');

  if (guestfs_launch (g) == -1)
    exit (EXIT_FAILURE);

  inspect_mount ();

  /* Free up data structures, no longer needed after this point. */
  free_drives (drvs);

  unsigned errors = 0;
  int windows;
  char *root, **roots;

  /* Get root mountpoint.  See: fish/inspect.c:inspect_mount */
  roots = guestfs_inspect_get_roots (g);
  assert (roots);
  assert (roots[0] != NULL);
  assert (roots[1] == NULL);
  root = roots[0];
  free (roots);

  /* Windows?  Special handling is required. */
  windows = is_windows (g, root);

  for (; optind < argc; optind++) {
    char *filename_to_free = NULL;
    const char *filename = argv[optind];

    if (windows) {
      filename = filename_to_free = windows_path (g, root, filename);
      if (filename == NULL) {
        errors++;
        continue;
      }
    }

    if (guestfs_download (g, filename, "/dev/stdout") == -1)
      errors++;

    free (filename_to_free);
  }

  free (root);

  guestfs_close (g);

  exit (errors == 0 ? EXIT_SUCCESS : EXIT_FAILURE);
}
Example #2
0
int main(int argc, char *argv[])
{
    static const struct option long_options[] = {
        /* Target options must come first. */
        {"all", no_argument, NULL, 'a'},
        {"target", required_argument, NULL, 't'},
        {"help", no_argument, NULL, 'h'},

        /* Action options come afterward. */
        {"list", no_argument, NULL, 'l'},
        {"set", required_argument, NULL, 's'},
        {"reopen", no_argument, NULL, 'r'},
        {0, 0, 0, 0},
    };
    char *short_options;

    /* Determine targets. */
    bool ok = true;
    int n_actions = 0;
    struct vlog_client **clients = NULL;
    size_t n_clients = 0;

    set_program_name(argv[0]);
    time_init();

    short_options = long_options_to_short_options(long_options);
    for (;;) {
        int option;
        size_t i;

        option = getopt_long(argc, argv, short_options, long_options, NULL);
        if (option == -1) {
            break;
        }
        if (!strchr("ath", option) && n_clients == 0) {
            ofp_fatal(0, "no targets specified (use --help for help)");
        } else {
            ++n_actions;
        }
        switch (option) {
        case 'a':
            add_all_targets(&clients, &n_clients, &ok);
            break;

        case 't':
            add_target(&clients, &n_clients, optarg, &ok);
            break;

        case 'l':
            for (i = 0; i < n_clients; i++) {
                struct vlog_client *client = clients[i];
                char *reply;

                printf("%s:\n", vlog_client_target(client));
                reply = transact(client, "list", &ok);
                fputs(reply, stdout);
                free(reply);
            }
            break;

        case 's':
            for (i = 0; i < n_clients; i++) {
                struct vlog_client *client = clients[i];
                char *request = xasprintf("set %s", optarg);
                transact_ack(client, request, &ok);
                free(request);
            }
            break;

        case 'r':
            for (i = 0; i < n_clients; i++) {
                struct vlog_client *client = clients[i];
                char *request = xstrdup("reopen");
                transact_ack(client, request, &ok);
                free(request);
            }
            break;

        case 'h':
            usage(argv[0], EXIT_SUCCESS);
            break;

        case '?':
            exit(EXIT_FAILURE);

        default:
            NOT_REACHED();
        }
    }
    if (!n_actions) {
        fprintf(stderr,
                "warning: no actions specified (use --help for help)\n");
    }
    exit(ok ? 0 : 1);
}
Example #3
0
static void
test_netflow_main(int argc, char *argv[])
{
    struct unixctl_server *server;
    enum { MAX_RECV = 1500 };
    const char *target;
    struct ofpbuf buf;
    bool exiting = false;
    int error;
    int sock;
    int n;

    proctitle_init(argc, argv);
    set_program_name(argv[0]);
    parse_options(argc, argv);

    if (argc - optind != 1) {
        ovs_fatal(0, "exactly one non-option argument required "
                  "(use --help for help)");
    }
    target = argv[optind];

    sock = inet_open_passive(SOCK_DGRAM, target, 0, NULL, 0, true);
    if (sock < 0) {
        ovs_fatal(0, "%s: failed to open (%s)", argv[1], ovs_strerror(-sock));
    }

    daemon_save_fd(STDOUT_FILENO);
    daemonize_start();

    error = unixctl_server_create(NULL, &server);
    if (error) {
        ovs_fatal(error, "failed to create unixctl server");
    }
    unixctl_command_register("exit", "", 0, 0, test_netflow_exit, &exiting);

    daemonize_complete();

    ofpbuf_init(&buf, MAX_RECV);
    n = 0;
    for (;;) {
        int retval;

        unixctl_server_run(server);

        ofpbuf_clear(&buf);
        do {
            retval = read(sock, ofpbuf_data(&buf), buf.allocated);
        } while (retval < 0 && errno == EINTR);
        if (retval > 0) {
            ofpbuf_put_uninit(&buf, retval);
            if (n++ > 0) {
                putchar('\n');
            }
            print_netflow(&buf);
            fflush(stdout);
        }

        if (exiting) {
            break;
        }

        poll_fd_wait(sock, POLLIN);
        unixctl_server_wait(server);
        poll_block();
    }
}
Example #4
0
static void
test_jsonrpc_main(int argc, char *argv[])
{
    struct ovs_cmdl_context ctx = { .argc = 0, };
    ovs_cmdl_proctitle_init(argc, argv);
    set_program_name(argv[0]);
    service_start(&argc, &argv);
    parse_options(argc, argv);
    ctx.argc = argc - optind;
    ctx.argv = argv + optind;
    ovs_cmdl_run_command(&ctx, get_all_commands());
}

static void
parse_options(int argc, char *argv[])
{
    enum {
        OPT_BOOTSTRAP_CA_CERT = UCHAR_MAX + 1,
        DAEMON_OPTION_ENUMS,
        SSL_OPTION_ENUMS,
    };
    static const struct option long_options[] = {
        {"verbose", optional_argument, NULL, 'v'},
        {"help", no_argument, NULL, 'h'},
        DAEMON_LONG_OPTIONS,
        {"bootstrap-ca-cert", required_argument, NULL, OPT_BOOTSTRAP_CA_CERT},
        STREAM_SSL_LONG_OPTIONS,
        {NULL, 0, NULL, 0},
    };
    char *short_options = ovs_cmdl_long_options_to_short_options(long_options);

    for (;;) {
        int c = getopt_long(argc, argv, short_options, long_options, NULL);
        if (c == -1) {
            break;
        }

        switch (c) {
        case 'h':
            usage();

        case 'v':
            vlog_set_verbosity(optarg);
            break;

        DAEMON_OPTION_HANDLERS

        STREAM_SSL_OPTION_HANDLERS

        case OPT_BOOTSTRAP_CA_CERT:
            stream_ssl_set_ca_cert_file(optarg, true);
            break;

        case '?':
            exit(EXIT_FAILURE);

        default:
            abort();
        }
    }
    free(short_options);
}

static void
usage(void)
{
    printf("%s: JSON-RPC test utility\n"
           "usage: %s [OPTIONS] COMMAND [ARG...]\n"
           "  listen LOCAL             listen for connections on LOCAL\n"
           "  request REMOTE METHOD PARAMS   send request, print reply\n"
           "  notify REMOTE METHOD PARAMS  send notification and exit\n",
           program_name, program_name);
    stream_usage("JSON-RPC", true, true, true);
    daemon_usage();
    vlog_usage();
    printf("\nOther options:\n"
           "  -h, --help                  display this help message\n");
    exit(EXIT_SUCCESS);
}
int
main (int argc, char *argv[])
{
  gl_oset_t set1, set2;

  set_program_name (argv[0]);

  /* Allow the user to provide a non-default random seed on the command line.  */
  if (argc > 1)
    srand (atoi (argv[1]));

  {
    size_t initial_size = RANDOM (20);
    size_t i;
    unsigned int repeat;

    /* Create set1.  */
    set1 = gl_oset_nx_create_empty (GL_ARRAY_OSET, (gl_setelement_compar_fn) strcmp, NULL);
    ASSERT (set1 != NULL);

    /* Create set2.  */
    set2 = gl_oset_nx_create_empty (GL_AVLTREE_OSET, (gl_setelement_compar_fn) strcmp, NULL);
    ASSERT (set2 != NULL);

    check_all (set1, set2);

    /* Initialize them.  */
    for (i = 0; i < initial_size; i++)
      {
        const char *obj = RANDOM_OBJECT ();
        ASSERT (gl_oset_nx_add (set1, obj) == gl_oset_nx_add (set2, obj));
        check_all (set1, set2);
      }

    for (repeat = 0; repeat < 100000; repeat++)
      {
        unsigned int operation = RANDOM (3);
        switch (operation)
          {
          case 0:
            {
              const char *obj = RANDOM_OBJECT ();
              ASSERT (gl_oset_search (set1, obj) == gl_oset_search (set2, obj));
            }
            break;
          case 1:
            {
              const char *obj = RANDOM_OBJECT ();
              ASSERT (gl_oset_nx_add (set1, obj) == gl_oset_nx_add (set2, obj));
            }
            break;
          case 2:
            {
              const char *obj = RANDOM_OBJECT ();
              ASSERT (gl_oset_remove (set1, obj) == gl_oset_remove (set2, obj));
            }
            break;
          }
        check_all (set1, set2);
      }

    gl_oset_free (set1);
    gl_oset_free (set2);
  }

  return 0;
}
Example #6
0
int
main (int argc, char *argv[])
{
  char *dev_map = DEFAULT_DEVICE_MAP;
  volatile int hold = 0;
  int opt;

  set_program_name (argv[0]);

  dir = xstrdup (DEFAULT_DIRECTORY);

  while ((opt = getopt_long (argc, argv, "r:d:m:vH:hV", options, 0)) != -1)
    switch (opt)
      {
      case 'r':
	free (root_dev);
        root_dev = xstrdup (optarg);
        break;
      case 'd':
	free (dir);
        dir = xstrdup (optarg);
        break;
      case 'm':
        dev_map = optarg;
        break;
      case 'v':
        verbosity++;
        break;
      case 'H':
        hold = (optarg ? atoi (optarg) : -1);
        break;
      case 'h':
        return usage (0);
      case 'V':
        printf ("%s (%s) %s\n", program_name, PACKAGE_NAME, PACKAGE_VERSION);
        return 0;
      default:
        return usage (1);
      }

  if (optind < argc)
    {
      fprintf (stderr, "Unknown extra argument `%s'.\n", argv[optind]);
      return usage (1);
    }

  /* Wait until the ARGS.HOLD variable is cleared by an attached debugger. */
  if (hold && verbosity > 0)
    printf ("Run \"gdb %s %d\", and set ARGS.HOLD to zero.\n",
            program_name, (int) getpid ());
  while (hold)
    {
      if (hold > 0)
        hold--;

      sleep (1);
    }

  signal (SIGINT, SIG_IGN);
  grub_emu_init ();
  grub_console_init ();
  grub_host_init ();

  /* XXX: This is a bit unportable.  */
  grub_util_biosdisk_init (dev_map);

  grub_init_all ();

  grub_hostfs_init ();

  grub_emu_post_init ();

  /* Make sure that there is a root device.  */
  if (! root_dev)
    root_dev = grub_strdup ("host");

  dir = xstrdup (dir);

  /* Start GRUB!  */
  if (setjmp (main_env) == 0)
    grub_main ();

  grub_fini_all ();
  grub_hostfs_fini ();
  grub_host_fini ();

  grub_machine_fini ();

  return 0;
}
Example #7
0
int
udatapath_cmd(int argc, char *argv[])
{
    int n_listeners;
    int error;
    int i;

    set_program_name(argv[0]);
    register_fault_handlers();
    time_init();
    vlog_init();

    dp = dp_new();

    parse_options(dp, argc, argv);
    signal(SIGPIPE, SIG_IGN);

    if (argc - optind < 1) {
        OFP_FATAL(0, "at least one listener argument is required; "
          "use --help for usage");
    }

    if (use_multiple_connections && (argc - optind) % 2 != 0)
        OFP_FATAL(0, "when using multiple connections, you must specify an even number of listeners");
        
    n_listeners = 0;
    for (i = optind; i < argc; i += 2) {
        const char *pvconn_name = argv[i];
        const char *pvconn_name_aux = NULL;
        if (use_multiple_connections)
            pvconn_name_aux = argv[i + 1];

        struct pvconn *pvconn, *pvconn_aux = NULL;
        int retval, retval_aux;

        retval = pvconn_open(pvconn_name, &pvconn);
        if (!retval || retval == EAGAIN) {
            // Get another listener if we are using auxiliary connections
            if (use_multiple_connections) {
                retval_aux = pvconn_open(pvconn_name_aux, &pvconn_aux);
                if (retval_aux && retval_aux != EAGAIN) {
                    ofp_error(retval_aux, "opening auxiliary %s", pvconn_name_aux);
                    pvconn_aux = NULL;
                }
            }
            dp_add_pvconn(dp, pvconn, pvconn_aux);
            n_listeners++;
        } else {
            ofp_error(retval, "opening %s", pvconn_name);
        }
    }
    if (n_listeners == 0) {
        OFP_FATAL(0, "could not listen for any connections");
    }

    if (port_list != NULL) {
        add_ports(dp, port_list);
    }
    if (local_port != NULL) {
        error = dp_ports_add_local(dp, local_port);
        if (error) {
            OFP_FATAL(error, "failed to add local port %s", local_port);
        }
    }

    error = vlog_server_listen(NULL, NULL);
    if (error) {
        OFP_FATAL(error, "could not listen for vlog connections");
    }

    die_if_already_running();
    daemonize();

    /* DMA must start first, then open the switch */
    ons_dma_start();

    for (;;) {
        dp_run(dp);
        dp_wait(dp);
        poll_block();
    }

    return 0;
}
Example #8
0
int
main (int argc, char *argv[])
{
  setlocale (LC_ALL, "");
  bindtextdomain (PACKAGE, LOCALEBASEDIR);
  textdomain (PACKAGE);

  parse_config ();

  enum { HELP_OPTION = CHAR_MAX + 1 };

  /* The command line arguments are broadly compatible with (a subset
   * of) guestfish.  Thus we have to deal mainly with -a, -m and --ro.
   */
  static const char *options = "a:c:d:im:no:rv?Vwx";
  static const struct option long_options[] = {
    { "add", 1, 0, 'a' },
    { "connect", 1, 0, 'c' },
    { "dir-cache-timeout", 1, 0, 0 },
    { "domain", 1, 0, 'd' },
    { "echo-keys", 0, 0, 0 },
    { "format", 2, 0, 0 },
    { "fuse-help", 0, 0, 0 },
    { "help", 0, 0, HELP_OPTION },
    { "inspector", 0, 0, 'i' },
    { "keys-from-stdin", 0, 0, 0 },
    { "live", 0, 0, 0 },
    { "mount", 1, 0, 'm' },
    { "no-sync", 0, 0, 'n' },
    { "option", 1, 0, 'o' },
    { "pid-file", 1, 0, 0 },
    { "ro", 0, 0, 'r' },
    { "rw", 0, 0, 'w' },
    { "selinux", 0, 0, 0 },
    { "trace", 0, 0, 'x' },
    { "verbose", 0, 0, 'v' },
    { "version", 0, 0, 'V' },
    { 0, 0, 0, 0 }
  };

  struct drv *drvs = NULL;
  struct drv *drv;
  struct mp *mps = NULL;
  struct mp *mp;
  char *p;
  const char *format = NULL;
  int c, r;
  int option_index;
  struct sigaction sa;

  int debug_calls = 0;
  int dir_cache_timeout = -1;
  int do_fork = 1;
  char *fuse_options = NULL;
  char *pid_file = NULL;

  struct guestfs_mount_local_argv optargs;

  /* LC_ALL=C is required so we can parse error messages. */
  setenv ("LC_ALL", "C", 1);

  /* Set global program name that is not polluted with libtool artifacts.  */
  set_program_name (argv[0]);

  memset (&sa, 0, sizeof sa);
  sa.sa_handler = SIG_IGN;
  sa.sa_flags = SA_RESTART;
  sigaction (SIGPIPE, &sa, NULL);

  g = guestfs_create ();
  if (g == NULL) {
    fprintf (stderr, _("guestfs_create: failed to create handle\n"));
    exit (EXIT_FAILURE);
  }

  for (;;) {
    c = getopt_long (argc, argv, options, long_options, &option_index);
    if (c == -1) break;

    switch (c) {
    case 0:			/* options which are long only */
      if (STREQ (long_options[option_index].name, "dir-cache-timeout"))
        dir_cache_timeout = atoi (optarg);
      else if (STREQ (long_options[option_index].name, "fuse-help"))
        fuse_help ();
      else if (STREQ (long_options[option_index].name, "selinux")) {
        if (guestfs_set_selinux (g, 1) == -1)
          exit (EXIT_FAILURE);
      } else if (STREQ (long_options[option_index].name, "format")) {
        if (!optarg || STREQ (optarg, ""))
          format = NULL;
        else
          format = optarg;
      } else if (STREQ (long_options[option_index].name, "keys-from-stdin")) {
        keys_from_stdin = 1;
      } else if (STREQ (long_options[option_index].name, "echo-keys")) {
        echo_keys = 1;
      } else if (STREQ (long_options[option_index].name, "live")) {
        live = 1;
      } else if (STREQ (long_options[option_index].name, "pid-file")) {
        pid_file = optarg;
      } else {
        fprintf (stderr, _("%s: unknown long option: %s (%d)\n"),
                 program_name, long_options[option_index].name, option_index);
        exit (EXIT_FAILURE);
      }
      break;

    case 'a':
      OPTION_a;
      break;

    case 'c':
      OPTION_c;
      break;

    case 'd':
      OPTION_d;
      break;

    case 'i':
      OPTION_i;
      break;

    case 'm':
      OPTION_m;
      break;

    case 'n':
      OPTION_n;
      break;

    case 'o':
      fuse_opt_add_opt_escaped (&fuse_options, optarg);
      break;

    case 'r':
      OPTION_r;
      break;

    case 'v':
      OPTION_v;
      break;

    case 'V':
      OPTION_V;
      break;

    case 'w':
      OPTION_w;
      break;

    case 'x':
      OPTION_x;
      debug_calls = 1;
      do_fork = 0;
      break;

    case HELP_OPTION:
      usage (EXIT_SUCCESS);

    default:
      usage (EXIT_FAILURE);
    }
  }

  /* Check we have the right options. */
  if (!live) {
    if (!drvs || !(mps || inspector)) {
      fprintf (stderr,
               _("%s: must have at least one -a/-d and at least one -m/-i option\n"),
               program_name);
      exit (EXIT_FAILURE);
    }
  } else {
    size_t count_d = 0, count_other = 0;
    struct drv *drv;

    if (read_only) {
      fprintf (stderr,
               _("%s: --live is not compatible with --ro option\n"),
               program_name);
      exit (EXIT_FAILURE);
    }

    if (inspector) {
      fprintf (stderr,
               _("%s: --live is not compatible with -i option\n"),
               program_name);
      exit (EXIT_FAILURE);
    }

    /* --live: make sure there was one -d option and no -a options */
    for (drv = drvs; drv; drv = drv->next) {
      if (drv->type == drv_d)
        count_d++;
      else
        count_other++;
    }

    if (count_d != 1) {
      fprintf (stderr,
               _("%s: with --live, you must use exactly one -d option\n"),
               program_name);
      exit (EXIT_FAILURE);
    }

    if (count_other != 0) {
      fprintf (stderr,
               _("%s: --live is not compatible with -a option\n"),
               program_name);
      exit (EXIT_FAILURE);
    }
  }

  /* We'd better have a mountpoint. */
  if (optind+1 != argc) {
    fprintf (stderr,
             _("%s: you must specify a mountpoint in the host filesystem\n"),
             program_name);
    exit (EXIT_FAILURE);
  }

  /* If we're forking, we can't use the recovery process. */
  if (guestfs_set_recovery_proc (g, !do_fork) == -1)
    exit (EXIT_FAILURE);

  /* Do the guest drives and mountpoints. */
  add_drives (drvs, 'a');
  if (guestfs_launch (g) == -1)
    exit (EXIT_FAILURE);
  if (inspector)
    inspect_mount ();
  mount_mps (mps);

  free_drives (drvs);
  free_mps (mps);

  /* FUSE example does this, not clear if it's necessary, but ... */
  if (guestfs_umask (g, 0) == -1)
    exit (EXIT_FAILURE);

  optargs.bitmask = 0;
  if (read_only) {
    optargs.bitmask |= GUESTFS_MOUNT_LOCAL_READONLY_BITMASK;
    optargs.readonly = 1;
  }
  if (debug_calls) {
    optargs.bitmask |= GUESTFS_MOUNT_LOCAL_DEBUGCALLS_BITMASK;
    optargs.debugcalls = 1;
  }
  if (dir_cache_timeout > 0) {
    optargs.bitmask |= GUESTFS_MOUNT_LOCAL_CACHETIMEOUT_BITMASK;
    optargs.cachetimeout = dir_cache_timeout;
  }
  if (fuse_options != NULL) {
    optargs.bitmask |= GUESTFS_MOUNT_LOCAL_OPTIONS_BITMASK;
    optargs.options = fuse_options;
  }

  if (guestfs_mount_local_argv (g, argv[optind], &optargs) == -1)
    exit (EXIT_FAILURE);

  /* Daemonize. */
  if (do_fork) {
    pid_t pid;
    int fd;

    pid = fork ();
    if (pid == -1) {
      perror ("fork");
      exit (EXIT_FAILURE);
    }

    if (pid != 0) {             /* parent */
      if (write_pid_file (pid_file, pid) == -1)
        _exit (EXIT_FAILURE);

      _exit (EXIT_SUCCESS);
    }

    /* Emulate what old fuse_daemonize used to do. */
    if (setsid () == -1) {
      perror ("setsid");
      exit (EXIT_FAILURE);
    }

    ignore_value (chdir ("/"));

    fd = open ("/dev/null", O_RDWR);
    if (fd >= 0) {
      dup2 (fd, 0);
      dup2 (fd, 1);
      dup2 (fd, 2);
      if (fd > 2)
        close (fd);
    }
  }
  else {
    /* not forking, write PID file anyway */
    if (write_pid_file (pid_file, getpid ()) == -1)
      exit (EXIT_FAILURE);
  }

  /* At the last minute, remove the libguestfs error handler.  In code
   * above this point, the default error handler has been used which
   * sends all errors to stderr.  From now on, the FUSE code will
   * convert errors into error codes (errnos) when appropriate.
   */
  guestfs_push_error_handler (g, NULL, NULL);

  /* Main loop. */
  r = guestfs_mount_local_run (g);

  guestfs_pop_error_handler (g);

  /* Cleanup. */
  if (guestfs_shutdown (g) == -1)
    r = -1;
  guestfs_close (g);

  /* Don't delete PID file until the cleanup has been completed. */
  if (pid_file)
    unlink (pid_file);

  exit (r == 0 ? EXIT_SUCCESS : EXIT_FAILURE);
}
Example #9
0
int
main(int argc, char *argv[])
{
    struct ovsdb_idl *idl;
    struct ctl_command *commands;
    struct shash local_options;
    unsigned int seqno;
    size_t n_commands;
    char *args;

    set_program_name(argv[0]);
    fatal_ignore_sigpipe();
    vlog_set_levels(NULL, VLF_CONSOLE, VLL_WARN);
    vlog_set_levels_from_string_assert("reconnect:warn");

    sbctl_cmd_init();

    /* Log our arguments.  This is often valuable for debugging systems. */
    args = process_escape_args(argv);
    VLOG(ctl_might_write_to_db(argv) ? VLL_INFO : VLL_DBG, "Called as %s", args);

    /* Parse command line. */
    shash_init(&local_options);
    parse_options(argc, argv, &local_options);
    commands = ctl_parse_commands(argc - optind, argv + optind, &local_options,
                                  &n_commands);

    if (timeout) {
        time_alarm(timeout);
    }

    /* Initialize IDL. */
    idl = the_idl = ovsdb_idl_create(db, &sbrec_idl_class, false, false);
    run_prerequisites(commands, n_commands, idl);

    /* Execute the commands.
     *
     * 'seqno' is the database sequence number for which we last tried to
     * execute our transaction.  There's no point in trying to commit more than
     * once for any given sequence number, because if the transaction fails
     * it's because the database changed and we need to obtain an up-to-date
     * view of the database before we try the transaction again. */
    seqno = ovsdb_idl_get_seqno(idl);
    for (;;) {
        ovsdb_idl_run(idl);
        if (!ovsdb_idl_is_alive(idl)) {
            int retval = ovsdb_idl_get_last_error(idl);
            ctl_fatal("%s: database connection failed (%s)",
                        db, ovs_retval_to_string(retval));
        }

        if (seqno != ovsdb_idl_get_seqno(idl)) {
            seqno = ovsdb_idl_get_seqno(idl);
            if (do_sbctl(args, commands, n_commands, idl)) {
                free(args);
                exit(EXIT_SUCCESS);
            }
        }

        if (seqno == ovsdb_idl_get_seqno(idl)) {
            ovsdb_idl_wait(idl);
            poll_block();
        }
    }
}
int
main (int argc, char **argv)
{
  int c, err;
  bool verbose = false;
  unsigned int tcp_flags = TCP_UNSET;
  char *critical = NULL, *warning = NULL;
  nagstatus status = STATE_OK;
  thresholds *my_threshold = NULL;

  struct proc_tcptable *tcptable = NULL;
  unsigned long tcp_established;
  unsigned long tcp_syn_sent;
  unsigned long tcp_syn_recv;
  unsigned long tcp_fin_wait1;
  unsigned long tcp_fin_wait2;
  unsigned long tcp_time_wait;
  unsigned long tcp_close;
  unsigned long tcp_close_wait;
  unsigned long tcp_last_ack;
  unsigned long tcp_listen;
  unsigned long tcp_closing;

  set_program_name (argv[0]);

  while ((c = getopt_long (argc, argv,
			   "t6c:w:v" GETOPT_HELP_VERSION_STRING,
			   longopts, NULL)) != -1)
    {
      switch (c)
	{
	default:
	  usage (stderr);
	case 't':
	  tcp_flags |= TCP_v4;
	  break;
	case '6':
	  tcp_flags |= TCP_v6;
	  break;
	case 'c':
	  critical = optarg;
	  break;
	case 'w':
	  warning = optarg;
	  break;
	case 'v':
	  verbose = true;
	  break;

	case_GETOPT_HELP_CHAR
	case_GETOPT_VERSION_CHAR

	}
    }

  if (tcp_flags == TCP_UNSET)
    tcp_flags = TCP_v4;

  if (verbose)
    tcp_flags |= TCP_VERBOSE;

  status = set_thresholds (&my_threshold, warning, critical);
  if (status == NP_RANGE_UNPARSEABLE)
    usage (stderr);

  err = proc_tcptable_new (&tcptable);
  if (err < 0)
    plugin_error (STATE_UNKNOWN, err, "memory exhausted");

  proc_tcptable_read (tcptable, tcp_flags);

  tcp_established = proc_tcp_get_tcp_established (tcptable);
  tcp_syn_sent    = proc_tcp_get_tcp_syn_sent (tcptable);
  tcp_syn_recv    = proc_tcp_get_tcp_syn_recv (tcptable);
  tcp_fin_wait1   = proc_tcp_get_tcp_fin_wait1 (tcptable);
  tcp_fin_wait2   = proc_tcp_get_tcp_fin_wait2 (tcptable);
  tcp_time_wait   = proc_tcp_get_tcp_time_wait (tcptable);
  tcp_close       = proc_tcp_get_tcp_close (tcptable);
  tcp_close_wait  = proc_tcp_get_tcp_close_wait (tcptable);
  tcp_last_ack    = proc_tcp_get_tcp_last_ack (tcptable);
  tcp_listen      = proc_tcp_get_tcp_listen (tcptable);
  tcp_closing     = proc_tcp_get_tcp_closing (tcptable);

  proc_tcptable_unref (tcptable);

  status = get_status (tcp_established, my_threshold);
  free (my_threshold);

  printf ("%s %s - %lu tcp established | "
	  "tcp_established=%lu tcp_syn_sent=%lu tcp_syn_recv=%lu "
	  "tcp_fin_wait1=%lu tcp_fin_wait2=%lu tcp_time_wait=%lu "
	  "tcp_close=%lu tcp_close_wait=%lu tcp_last_ack=%lu "
	  "tcp_listen=%lu tcp_closing=%lu\n",
	  program_name_short, state_text (status), tcp_established,
	  tcp_established, tcp_syn_sent, tcp_syn_recv,
	  tcp_fin_wait1, tcp_fin_wait2, tcp_time_wait,
	  tcp_close, tcp_close_wait, tcp_last_ack,
	  tcp_listen, tcp_closing);

  return status;
}
Example #11
0
File: rsh.c Project: 274914765/C
int main (int argc, char **argv)
{
    int index;

    struct passwd *pw;

    struct servent *sp;

    sigset_t sigs, osigs;

    int asrsh, rem;

    pid_t pid = 0;

    uid_t uid;

    char *args, *host;

    set_program_name (argv[0]);

    asrsh = 0;
    host = user = NULL;

    /* If called as something other than "rsh", use it as the host name */
    {
        char *p = strrchr (argv[0], '/');

        if (p)
            ++p;
        else
            p = argv[0];
        if (strcmp (p, "rsh"))
            host = p;
        else
            asrsh = 1;
    }

    /* Parse command line */
    iu_argp_init ("rsh", default_program_authors);
    argp_parse (&argp, argc, argv, ARGP_IN_ORDER, &index, NULL);

    if (index < argc)
        host = argv[index++];

    /* To few args.  */
    if (!host)
        error (1, 0, "host not specified");

    /* If no further arguments, must have been called as rlogin. */
    if (!argv[index])
    {
        if (asrsh)
            *argv = (char *) "rlogin";
        seteuid (getuid ());
        setuid (getuid ());
        execv (PATH_RLOGIN, argv);
        error (1, errno, "cannot execute %s", PATH_RLOGIN);
    }

    argc -= index;
    argv += index;

    /* We must be setuid root.  */
    if (geteuid ())
        error (1, 0, "must be setuid root.\n");

    if (!(pw = getpwuid (uid = getuid ())))
        error (1, 0, "unknown user id");

    /* Accept user1@host format, though "-l user2" overrides user1 */
    {
        char *p = strchr (host, '@');

        if (p)
        {
            *p = '\0';
            if (!user && p > host)
                user = host;
            host = p + 1;
            if (*host == '\0')
                error (1, 0, "empty host name");
        }
    }

#if defined(KERBEROS) || defined(SHISHI)
# ifdef ENCRYPTION
    /* -x turns off -n */
    if (doencrypt)
        null_input_option = 0;
# endif
#endif

    args = copyargs (argv);

    sp = NULL;
#ifdef KERBEROS
    if (use_kerberos)
    {
        sp = getservbyname ((doencrypt ? "ekshell" : "kshell"), "tcp");
        if (sp == NULL)
        {
            use_kerberos = 0;
            warning ("can't get entry for %s/tcp service", doencrypt ? "ekshell" : "kshell");
        }
    }
#elif defined(SHISHI)
    if (use_kerberos)
    {
        sp = getservbyname ("kshell", "tcp");
        if (sp == NULL)
        {
            use_kerberos = 0;
            warning ("can't get entry for %s/tcp service", "kshell");
        }
    }
#endif
    if (sp == NULL)
        sp = getservbyname ("shell", "tcp");
    if (sp == NULL)
        error (1, 0, "shell/tcp: unknown service");


#if defined (KERBEROS) || defined(SHISHI)
  try_connect:
    if (use_kerberos)
    {
        struct hostent *hp;

        /* fully qualify hostname (needed for krb_realmofhost) */
        hp = gethostbyname (host);
        if (hp != NULL && !(host = strdup (hp->h_name)))
            error (1, errno, "strdup");

# if defined (KERBEROS)
        rem = KSUCCESS;
        errno = 0;
        if (dest_realm == NULL)
            dest_realm = krb_realmofhost (host);
# elif defined (SHISHI)
        rem = SHISHI_OK;
        errno = 0;
# endif

# ifdef ENCRYPTION
        if (doencrypt)
#  if defined(SHISHI)
        {
            int i;

            char *term;

            term = xmalloc (strlen (args) + 4);
            strcpy (term, "-x ");
            strcat (term, args);

            rem = krcmd_mutual (&h, &host, sp->s_port, &user, term, &rfd2, dest_realm, &enckey);
            if (rem > 0)
            {
                keytype = shishi_key_type (enckey);
                keylen = shishi_cipher_blocksize (keytype);

                ivtab[0] = &iv1;
                ivtab[1] = &iv2;
                ivtab[2] = &iv3;
                ivtab[3] = &iv4;

                for (i = 0; i < 4; i++)
                {
                    ivtab[i]->ivlen = keylen;

                    switch (keytype)
                    {
                        case SHISHI_DES_CBC_CRC:
                        case SHISHI_DES_CBC_MD4:
                        case SHISHI_DES_CBC_MD5:
                        case SHISHI_DES_CBC_NONE:
                        case SHISHI_DES3_CBC_HMAC_SHA1_KD:
                            ivtab[i]->keyusage = SHISHI_KEYUSAGE_KCMD_DES;
                            ivtab[i]->iv = malloc (ivtab[i]->ivlen);
                            memset (ivtab[i]->iv, 2 * i + 1 * (i < 2) - 4 * (i >= 2), ivtab[i]->ivlen);
                            ivtab[i]->ctx =
                                shishi_crypto (h, enckey, ivtab[i]->keyusage,
                                               shishi_key_type (enckey), ivtab[i]->iv, ivtab[i]->ivlen);
                            break;
                        case SHISHI_ARCFOUR_HMAC:
                        case SHISHI_ARCFOUR_HMAC_EXP:
                            ivtab[i]->keyusage = SHISHI_KEYUSAGE_KCMD_DES + 2 + 4 * i;
                            ivtab[i]->ctx =
                                shishi_crypto (h, enckey, ivtab[i]->keyusage, shishi_key_type (enckey), NULL, 0);
                            break;
                        default:
                            ivtab[i]->keyusage = SHISHI_KEYUSAGE_KCMD_DES + 2 + 4 * i;
                            ivtab[i]->iv = malloc (ivtab[i]->ivlen);
                            memset (ivtab[i]->iv, 0, ivtab[i]->ivlen);
                            ivtab[i]->ctx =
                                shishi_crypto (h, enckey, ivtab[i]->keyusage,
                                               shishi_key_type (enckey), ivtab[i]->iv, ivtab[i]->ivlen);
                    }
                }
            }
            free (term);
        }
        else
#  else
            rem = krcmd_mutual (&host, sp->s_port, user, args, &rfd2, dest_realm, &cred, schedule);
        else
#  endif
# endif
            rem = krcmd (
# if defined (SHISHI)
                            &h, &host, sp->s_port, &user, args, &rfd2, dest_realm);
# else
                            &host, sp->s_port, user, args, &rfd2, dest_realm);
# endif
        if (rem < 0)
        {
            use_kerberos = 0;
            sp = getservbyname ("shell", "tcp");
            if (sp == NULL)
                error (1, 0, "shell/tcp: unknown service");
            if (errno == ECONNREFUSED)
                warning ("remote host doesn't support Kerberos");
            if (errno == ENOENT)
                warning ("can't provide Kerberos auth data");
            goto try_connect;
        }
    }
Example #12
0
File: tftpd.c Project: 274914765/C
int main (int argc, char *argv[])
{
    int index;

    register struct tftphdr *tp;

    int on, n;

    struct sockaddr_in sin;

    set_program_name (argv[0]);
    iu_argp_init ("tftpd", default_program_authors);
    argp_parse (&argp, argc, argv, 0, &index, NULL);

    openlog ("tftpd", LOG_PID, LOG_FTP);

    if (index < argc)
    {
        struct dirlist *dirp;

        /* Get list of directory prefixes. Skip relative pathnames. */
        for (dirp = dirs; index < argc && dirp < &dirs[MAXDIRS]; index++)
        {
            if (argv[index][0] == '/')
            {
                dirp->name = argv[index];
                dirp->len = strlen (dirp->name);
                dirp++;
            }
        }
    }

    on = 1;
    if (ioctl (0, FIONBIO, &on) < 0)
    {
        syslog (LOG_ERR, "ioctl(FIONBIO): %m\n");
        exit (1);
    }
    fromlen = sizeof (from);
    n = recvfrom (0, buf, sizeof (buf), 0, (struct sockaddr *) &from, &fromlen);
    if (n < 0)
    {
        syslog (LOG_ERR, "recvfrom: %m\n");
        exit (1);
    }
    /*
     * Now that we have read the message out of the UDP
     * socket, we fork and exit.  Thus, inetd will go back
     * to listening to the tftp port, and the next request
     * to come in will start up a new instance of tftpd.
     *
     * We do this so that inetd can run tftpd in "wait" mode.
     * The problem with tftpd running in "nowait" mode is that
     * inetd may get one or more successful "selects" on the
     * tftp port before we do our receive, so more than one
     * instance of tftpd may be started up.  Worse, if tftpd
     * break before doing the above "recvfrom", inetd would
     * spawn endless instances, clogging the system.
     */
    {
        int pid;

        int i;

        socklen_t j;

        for (i = 1; i < 20; i++)
        {
            pid = fork ();
            if (pid < 0)
            {
                sleep (i);
                /*
                 * flush out to most recently sent request.
                 *
                 * This may drop some request, but those
                 * will be resent by the clients when
                 * they timeout.  The positive effect of
                 * this flush is to (try to) prevent more
                 * than one tftpd being started up to service
                 * a single request from a single client.
                 */
                j = sizeof from;
                i = recvfrom (0, buf, sizeof (buf), 0, (struct sockaddr *) &from, &j);
                if (i > 0)
                {
                    n = i;
                    fromlen = j;
                }
            }
            else
            {
                break;
            }
        }
        if (pid < 0)
        {
            syslog (LOG_ERR, "fork: %m\n");
            exit (1);
        }
        else if (pid != 0)
        {
            exit (0);
        }
    }
    from.sin_family = AF_INET;
    alarm (0);
    close (0);
    close (1);
    peer = socket (AF_INET, SOCK_DGRAM, 0);
    if (peer < 0)
    {
        syslog (LOG_ERR, "socket: %m\n");
        exit (1);
    }
    memset (&sin, 0, sizeof (sin));
    sin.sin_family = AF_INET;
    if (bind (peer, (struct sockaddr *) &sin, sizeof (sin)) < 0)
    {
        syslog (LOG_ERR, "bind: %m\n");
        exit (1);
    }
    if (connect (peer, (struct sockaddr *) &from, sizeof (from)) < 0)
    {
        syslog (LOG_ERR, "connect: %m\n");
        exit (1);
    }
    tp = (struct tftphdr *) buf;
    tp->th_opcode = ntohs (tp->th_opcode);
    if (tp->th_opcode == RRQ || tp->th_opcode == WRQ)
        tftp (tp, n);
    exit (1);
}
Example #13
0
int
main (int argc, char *argv[])
{
  set_program_name (argv[0]);
  setlocale (LC_ALL, "");
  (void) bindtextdomain (PACKAGE, LOCALEDIR);
  (void) bindtextdomain ("bison-runtime", LOCALEDIR);
  (void) textdomain (PACKAGE);

  {
    char const *cp = getenv ("LC_CTYPE");
    if (cp && STREQ (cp, "C"))
      set_custom_quoting (&quote_quoting_options, "'", "'");
    else
      set_quoting_style (&quote_quoting_options, locale_quoting_style);
  }

  atexit (close_stdout);

  uniqstrs_new ();
  muscle_init ();
  complain_init ();

  getargs (argc, argv);

  timevar_report = trace_flag & trace_time;
  init_timevar ();
  timevar_start (TV_TOTAL);

  if (trace_flag & trace_bitsets)
    bitset_stats_enable ();

  /* Read the input.  Copy some parts of it to FGUARD, FACTION, FTABLE
     and FATTRS.  In file reader.c.  The other parts are recorded in
     the grammar; see gram.h.  */

  timevar_push (TV_READER);
  reader ();
  timevar_pop (TV_READER);

  if (complaint_status == status_complaint)
    goto finish;

  /* Find useless nonterminals and productions and reduce the grammar. */
  timevar_push (TV_REDUCE);
  reduce_grammar ();
  timevar_pop (TV_REDUCE);

  /* Record other info about the grammar.  In files derives and
     nullable.  */
  timevar_push (TV_SETS);
  derives_compute ();
  nullable_compute ();
  timevar_pop (TV_SETS);

  /* Compute LR(0) parser states.  See state.h for more info.  */
  timevar_push (TV_LR0);
  generate_states ();
  timevar_pop (TV_LR0);

  /* Add lookahead sets to parser states.  Except when LALR(1) is
     requested, split states to eliminate LR(1)-relative
     inadequacies.  */
  ielr ();

  /* Find and record any conflicts: places where one token of
     lookahead is not enough to disambiguate the parsing.  In file
     conflicts.  Also resolve s/r conflicts based on precedence
     declarations.  */
  timevar_push (TV_CONFLICTS);
  conflicts_solve ();
  if (!muscle_percent_define_flag_if ("lr.keep-unreachable-state"))
    {
      state_number *old_to_new = xnmalloc (nstates, sizeof *old_to_new);
      state_number nstates_old = nstates;
      state_remove_unreachable_states (old_to_new);
      lalr_update_state_numbers (old_to_new, nstates_old);
      conflicts_update_state_numbers (old_to_new, nstates_old);
      free (old_to_new);
    }
  conflicts_print ();
  timevar_pop (TV_CONFLICTS);

  /* Compute the parser tables.  */
  timevar_push (TV_ACTIONS);
  tables_generate ();
  timevar_pop (TV_ACTIONS);

  grammar_rules_useless_report (_("rule useless in parser due to conflicts"));

  print_precedence_warnings ();

  /* Output file names. */
  compute_output_file_names ();

  /* Output the detailed report on the grammar.  */
  if (report_flag)
    {
      timevar_push (TV_REPORT);
      print_results ();
      timevar_pop (TV_REPORT);
    }

  /* Output the graph.  */
  if (graph_flag)
    {
      timevar_push (TV_GRAPH);
      print_graph ();
      timevar_pop (TV_GRAPH);
    }

  /* Output xml.  */
  if (xml_flag)
    {
      timevar_push (TV_XML);
      print_xml ();
      timevar_pop (TV_XML);
    }
    
  if (xml_tables_flag)
    {
      output_xmltables ();
    }

  /* Stop if there were errors, to avoid trashing previous output
     files.  */
  if (complaint_status == status_complaint)
    goto finish;

  /* Lookahead tokens are no longer needed. */
  timevar_push (TV_FREE);
  lalr_free ();
  timevar_pop (TV_FREE);

  /* Output the tables and the parser to ftable.  In file output.  */
  timevar_push (TV_PARSER);
  output ();
  timevar_pop (TV_PARSER);

  timevar_push (TV_FREE);
  nullable_free ();
  derives_free ();
  tables_free ();
  states_free ();
  reduce_free ();
  conflicts_free ();
  grammar_free ();
  output_file_names_free ();

  /* The scanner memory cannot be released right after parsing, as it
     contains things such as user actions, prologue, epilogue etc.  */
  gram_scanner_free ();
  muscle_free ();
  uniqstrs_free ();
  code_scanner_free ();
  skel_scanner_free ();
  quotearg_free ();
  timevar_pop (TV_FREE);

  if (trace_flag & trace_bitsets)
    bitset_stats_dump (stderr);

 finish:

  /* Stop timing and print the times.  */
  timevar_stop (TV_TOTAL);
  timevar_print (stderr);

  cleanup_caret ();

  return complaint_status ? EXIT_FAILURE : EXIT_SUCCESS;
}
Example #14
0
File: cli.c Project: nobled/gnutls
int
main (int argc, char **argv)
{
  int ret;
  int ii, i, inp;
  char buffer[MAX_BUF + 1];
  char *session_data = NULL;
  char *session_id = NULL;
  size_t session_data_size;
  size_t session_id_size = 0;
  int user_term = 0, retval = 0;
  socket_st hd;
  ssize_t bytes;

  set_program_name (argv[0]);
  cmd_parser (argc, argv);

  gnutls_global_set_log_function (tls_log_func);
  gnutls_global_set_log_level (OPT_VALUE_DEBUG);

  if ((ret = gnutls_global_init ()) < 0)
    {
      fprintf (stderr, "global_init: %s\n", gnutls_strerror (ret));
      exit (1);
    }

#ifdef ENABLE_PKCS11
//  pkcs11_common ();
#endif

  if (hostname == NULL)
    {
      fprintf (stderr, "No hostname given\n");
      exit (1);
    }

  sockets_init ();

  init_global_tls_stuff ();

  socket_open (&hd, hostname, service, udp);

  hd.session = init_tls_session (hostname);
  if (starttls)
    goto after_handshake;

  for (i = 0; i < 2; i++)
    {


      if (i == 1)
        {
          hd.session = init_tls_session (hostname);
          gnutls_session_set_data (hd.session, session_data,
                                   session_data_size);
          free (session_data);
        }

      ret = do_handshake (&hd);

      if (ret < 0)
        {
          fprintf (stderr, "*** Handshake has failed\n");
          gnutls_perror (ret);
          gnutls_deinit (hd.session);
          return 1;
        }
      else
        {
          printf ("- Handshake was completed\n");
          if (gnutls_session_is_resumed (hd.session) != 0)
            printf ("*** This is a resumed session\n");
        }

      if (resume != 0 && i == 0)
        {

          gnutls_session_get_data (hd.session, NULL, &session_data_size);
          session_data = malloc (session_data_size);

          gnutls_session_get_data (hd.session, session_data,
                                   &session_data_size);

          gnutls_session_get_id (hd.session, NULL, &session_id_size);

          session_id = malloc (session_id_size);
          gnutls_session_get_id (hd.session, session_id, &session_id_size);

          printf ("- Disconnecting\n");
          socket_bye (&hd);

          printf
            ("\n\n- Connecting again- trying to resume previous session\n");
          socket_open (&hd, hostname, service, udp);
        }
      else
        {
          break;
        }
    }

after_handshake:

  /* Warning!  Do not touch this text string, it is used by external
     programs to search for when gnutls-cli has reached this point. */
  printf ("\n- Simple Client Mode:\n\n");

  if (rehandshake)
    {
      ret = do_handshake (&hd);

      if (ret < 0)
        {
          fprintf (stderr, "*** ReHandshake has failed\n");
          gnutls_perror (ret);
          gnutls_deinit (hd.session);
          return 1;
        }
      else
        {
          printf ("- ReHandshake was completed\n");
        }
    }

#ifndef _WIN32
  signal (SIGALRM, &starttls_alarm);
#endif

  fflush (stdout);
  fflush (stderr);

  /* do not buffer */
#ifndef _WIN32
  setbuf (stdin, NULL);
#endif
  setbuf (stdout, NULL);
  setbuf (stderr, NULL);

  for (;;)
    {
      if (starttls_alarmed && !hd.secure)
        {
          /* Warning!  Do not touch this text string, it is used by
             external programs to search for when gnutls-cli has
             reached this point. */
          fprintf (stderr, "*** Starting TLS handshake\n");
          ret = do_handshake (&hd);
          if (ret < 0)
            {
              fprintf (stderr, "*** Handshake has failed\n");
              user_term = 1;
              retval = 1;
              break;
            }
        }

      inp = check_net_or_keyboard_input(&hd);

      if (inp == IN_NET)
        {
          memset (buffer, 0, MAX_BUF + 1);
          ret = socket_recv (&hd, buffer, MAX_BUF);

          if (ret == 0)
            {
              printf ("- Peer has closed the GnuTLS connection\n");
              break;
            }
          else if (handle_error (&hd, ret) < 0 && user_term == 0)
            {
              fprintf (stderr,
                       "*** Server has terminated the connection abnormally.\n");
              retval = 1;
              break;
            }
          else if (ret > 0)
            {
              if (verbose != 0)
                printf ("- Received[%d]: ", ret);
              for (ii = 0; ii < ret; ii++)
                {
                  fputc (buffer[ii], stdout);
                }
              fflush (stdout);
            }

          if (user_term != 0)
            break;
        }

      if (inp == IN_KEYBOARD)
      {
          if ((bytes = read (fileno (stdin), buffer, MAX_BUF - 1)) <= 0)
            {
              if (hd.secure == 0)
                {
                  /* Warning!  Do not touch this text string, it is
                     used by external programs to search for when
                     gnutls-cli has reached this point. */
                  fprintf (stderr, "*** Starting TLS handshake\n");
                  ret = do_handshake (&hd);
                  clearerr (stdin);
                  if (ret < 0)
                    {
                      fprintf (stderr, "*** Handshake has failed\n");
                      user_term = 1;
                      retval = 1;
                      break;
                    }
                }
              else
                {
                  user_term = 1;
                  break;
                }
              continue;
            }

          buffer[bytes] = 0;
          if (crlf != 0)
            {
              char *b = strchr (buffer, '\n');
              if (b != NULL)
                {
                  strcpy (b, "\r\n");
                  bytes++;
                }
            }

          ret = socket_send (&hd, buffer, bytes);

          if (ret > 0)
            {
              if (verbose != 0)
                printf ("- Sent: %d bytes\n", ret);
            }
          else
            handle_error (&hd, ret);

        }
    }

  if (user_term != 0)
    socket_bye (&hd);
  else
    gnutls_deinit (hd.session);

#ifdef ENABLE_SRP
  if (srp_cred)
    gnutls_srp_free_client_credentials (srp_cred);
#endif
#ifdef ENABLE_PSK
  if (psk_cred)
    gnutls_psk_free_client_credentials (psk_cred);
#endif

  gnutls_certificate_free_credentials (xcred);

#ifdef ENABLE_ANON
  gnutls_anon_free_client_credentials (anon_cred);
#endif

  gnutls_global_deinit ();

  return retval;
}
Example #15
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;
}
Example #16
0
File: test2.c Project: badi/guamps
int main(int argc, char *argv[]) {
  set_program_name(argv[0]);
  test0();
  return 0;
}
Example #17
0
int
main(int argc, char **argv)
{
     int index;
     int status = EX_OK;
     
     set_program_name(argv[0]);
     argp_version_setup("cflow", program_authors);
     
     setlocale(LC_ALL, "");
     bindtextdomain(PACKAGE, LOCALEDIR);
     textdomain(PACKAGE);
     
     register_output("gnu", gnu_output_handler, NULL);
     register_output("posix", posix_output_handler, NULL);

     symbol_map = SM_FUNCTIONS|SM_STATIC|SM_UNDEFINED;

     if (getenv("POSIXLY_CORRECT")) {
	  if (select_output_driver("posix")) {
	       error(0, 0, _("INTERNAL ERROR: %s: No such output driver"),
		     "posix");
	       abort();
	  }
	  output_init();
     }
     
     sourcerc(&argc, &argv);
     if (argp_parse(&argp, argc, argv, ARGP_IN_ORDER, &index, NULL))
	  exit(EX_USAGE);

     if (print_option == 0)
	  print_option = PRINT_TREE;

     init();

     if (arglist) {
	  struct linked_list_entry *p;

	  for (p = arglist->head; p; p = p->next) {
	       char *s = (char*)p->data;
	       if (s[0] == '-')
		    pp_option(s);
	       else if (source(s) == 0)
		    yyparse();
	  }
     }
     
     argc -= index;
     argv += index;

     while (argc--) {
	  if (source(*argv++) == 0)
	       yyparse();
	  else
	       status = EX_SOFT;
     }

     if (input_file_count == 0)
	     error(EX_USAGE, 0, _("no input files"));

     output();
     return status;
}
int
main (int argc, char **argv)
{
  bool show_swapping = false;
  bool swapping_only = false;
  int c, status;
  char *critical = NULL, *warning = NULL;
  char *status_msg;
  char *perfdata_paging_msg = NULL, *perfdata_swapping_msg = NULL;
  set_program_name (argv[0]);
  thresholds *my_threshold = NULL;
  paging_data_t paging;

  while ((c = getopt_long (argc, argv, "psSc:w:" GETOPT_HELP_VERSION_STRING,
			   longopts, NULL)) != -1)
    {
      switch (c)
	{
	default:
	  usage (stderr);
	case 'p':
	  /* show_paging = true; left for backward compatibility */
	  break;
	case 's':
	  show_swapping = true;
	  break;
	case 'S':
	  swapping_only = true;
	  break;
	case 'c':
	  critical = optarg;
	  break;
	case 'w':
	  warning = optarg;
	  break;

	case_GETOPT_HELP_CHAR
	case_GETOPT_VERSION_CHAR

	}
    }

  status = set_thresholds (&my_threshold, warning, critical);
  if (status == NP_RANGE_UNPARSEABLE)
    usage (stderr);

  get_paging_status (show_swapping, swapping_only, &paging);

  status = get_status (paging.summary, my_threshold);
  free (my_threshold);

  status_msg =
    xasprintf ("%s: %lu %s/s", state_text (status), paging.summary,
	       swapping_only ? "pswp" : "majfault");
  if (!swapping_only)
    perfdata_paging_msg =
      xasprintf ("vmem_pgpgin/s=%lu vmem_pgpgout/s=%lu vmem_pgfault/s=%lu "
		 "vmem_pgmajfault/s=%lu vmem_pgfree/s=%lu vmem_pgsteal/s=%lu "
		 "vmem_pgscand/s=%lu vmem_pgscank/s=%lu ",
		 paging.dpgpgin, paging.dpgpgout, paging.dpgfault,
		 paging.dpgmajfault, paging.dpgfree, paging.dpgsteal,
		 paging.dpgscand, paging.dpgscank);
  if (show_swapping || swapping_only)
    perfdata_swapping_msg =
      xasprintf ("vmem_pswpin/s=%lu vmem_pswpout/s=%lu",
		 paging.dpswpin, paging.dpswpout);

  printf ("%s %s | %s%s\n", program_name_short, status_msg,
	  perfdata_paging_msg ? perfdata_paging_msg : "",
	  perfdata_swapping_msg ? perfdata_swapping_msg : "");

  return status;
}
Example #19
0
File: groups.c Project: 4solo/cs35
int
main (int argc, char **argv)
{
  int optc;
  bool ok = true;
  gid_t rgid, egid;
  uid_t ruid;

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

  atexit (close_stdout);

  /* Processing the arguments this way makes groups.c behave differently to
   * groups.sh if one of the arguments is "--".
   */
  while ((optc = getopt_long (argc, argv, "", longopts, NULL)) != -1)
    {
      switch (optc)
        {
        case_GETOPT_HELP_CHAR;
        case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS);
        default:
          usage (EXIT_FAILURE);
        }
    }

  if (optind == argc)
    {
      /* No arguments.  Divulge the details of the current process. */
      ruid = getuid ();
      egid = getegid ();
      rgid = getgid ();

      if (!print_group_list (NULL, ruid, rgid, egid, true))
        ok = false;
      putchar ('\n');
    }
  else
    {
      /* At least one argument.  Divulge the details of the specified users. */
      while (optind < argc)
        {
          struct passwd *pwd = getpwnam (argv[optind]);
          if (pwd == NULL)
            error (EXIT_FAILURE, 0, _("%s: No such user"), argv[optind]);
          ruid = pwd->pw_uid;
          rgid = egid = pwd->pw_gid;

          printf ("%s : ", argv[optind]);
          if (!print_group_list (argv[optind++], ruid, rgid, egid, true))
            ok = false;
          putchar ('\n');
        }
    }

  exit (ok ? EXIT_SUCCESS : EXIT_FAILURE);
}
Example #20
0
int
main (int argc, char *argv[])
{
  gl_list_t list1, list2;

  set_program_name (argv[0]);

  /* Allow the user to provide a non-default random seed on the command line.  */
  if (argc > 1)
    srand (atoi (argv[1]));

  {
    size_t initial_size = RANDOM (50);
    const void **contents =
      (const void **) malloc (initial_size * sizeof (const void *));
    size_t i;
    unsigned int repeat;

    for (i = 0; i < initial_size; i++)
      contents[i] = RANDOM_OBJECT ();

    /* Create list1.  */
    list1 = gl_list_nx_create (GL_ARRAY_LIST, NULL, NULL, NULL, true,
                               initial_size, contents);
    ASSERT (list1 != NULL);
    /* Create list2.  */
    list2 = gl_list_nx_create_empty (GL_ARRAY_LIST, NULL, NULL, NULL, true);
    ASSERT (list2 != NULL);
    for (i = 0; i < initial_size; i++)
      ASSERT (gl_list_nx_add_last (list2, contents[i]) != NULL);

    check_equals (list1, list2);

    for (repeat = 0; repeat < 10000; repeat++)
      {
        unsigned int operation = RANDOM (16);
        switch (operation)
          {
          case 0:
            if (gl_list_size (list1) > 0)
              {
                size_t index = RANDOM (gl_list_size (list1));
                const char *obj = RANDOM_OBJECT ();
                gl_list_node_t node1, node2;

                node1 = gl_list_nx_set_at (list1, index, obj);
                ASSERT (node1 != NULL);
                ASSERT (gl_list_get_at (list1, index) == obj);
                ASSERT (gl_list_node_value (list1, node1) == obj);

                node2 = gl_list_nx_set_at (list2, index, obj);
                ASSERT (node2 != NULL);
                ASSERT (gl_list_get_at (list2, index) == obj);
                ASSERT (gl_list_node_value (list2, node2) == obj);

                if (index > 0)
                  {
                    ASSERT (gl_list_node_value (list1, gl_list_previous_node (list1, node1))
                            == gl_list_get_at (list1, index - 1));
                  }
                if (index + 1 < gl_list_size (list1))
                  {
                    ASSERT (gl_list_node_value (list1, gl_list_next_node (list1, node1))
                            == gl_list_get_at (list1, index + 1));
                  }
              }
            break;
          case 1:
            {
              const char *obj = RANDOM_OBJECT ();
              gl_list_node_t node1, node2;
              node1 = gl_list_search (list1, obj);
              node2 = gl_list_search (list2, obj);
              if (node1 == NULL)
                {
                  ASSERT (node2 == NULL);
                }
              else
                {
                  ASSERT (node2 != NULL);
                  ASSERT (gl_list_node_value (list1, node1) == obj);
                  ASSERT (gl_list_node_value (list2, node2) == obj);
                }
            }
            break;
          case 2:
            {
              const char *obj = RANDOM_OBJECT ();
              size_t index1, index2;
              index1 = gl_list_indexof (list1, obj);
              index2 = gl_list_indexof (list2, obj);
              if (index1 == (size_t)(-1))
                {
                  ASSERT (index2 == (size_t)(-1));
                }
              else
                {
                  ASSERT (index2 != (size_t)(-1));
                  ASSERT (gl_list_get_at (list1, index1) == obj);
                  ASSERT (gl_list_get_at (list2, index2) == obj);
                  ASSERT (index2 == index1);
                }
            }
            break;
          case 3: /* add 1 element */
            {
              const char *obj = RANDOM_OBJECT ();
              gl_list_node_t node1, node2;
              node1 = gl_list_nx_add_first (list1, obj);
              ASSERT (node1 != NULL);
              node2 = gl_list_nx_add_first (list2, obj);
              ASSERT (node2 != NULL);
              ASSERT (gl_list_node_value (list1, node1) == obj);
              ASSERT (gl_list_node_value (list2, node2) == obj);
              ASSERT (gl_list_get_at (list1, 0) == obj);
              ASSERT (gl_list_get_at (list2, 0) == obj);
            }
            break;
          case 4: /* add 1 element */
            {
              const char *obj = RANDOM_OBJECT ();
              gl_list_node_t node1, node2;
              node1 = gl_list_nx_add_last (list1, obj);
              ASSERT (node1 != NULL);
              node2 = gl_list_nx_add_last (list2, obj);
              ASSERT (node2 != NULL);
              ASSERT (gl_list_node_value (list1, node1) == obj);
              ASSERT (gl_list_node_value (list2, node2) == obj);
              ASSERT (gl_list_get_at (list1, gl_list_size (list1) - 1) == obj);
              ASSERT (gl_list_get_at (list2, gl_list_size (list2) - 1) == obj);
            }
            break;
          case 5: /* add 3 elements */
            {
              const char *obj0 = RANDOM_OBJECT ();
              const char *obj1 = RANDOM_OBJECT ();
              const char *obj2 = RANDOM_OBJECT ();
              gl_list_node_t node1, node2;
              node1 = gl_list_nx_add_first (list1, obj2);
              ASSERT (node1 != NULL);
              node1 = gl_list_nx_add_before (list1, node1, obj0);
              ASSERT (node1 != NULL);
              node1 = gl_list_nx_add_after (list1, node1, obj1);
              ASSERT (node1 != NULL);
              node2 = gl_list_nx_add_first (list2, obj2);
              ASSERT (node2 != NULL);
              node2 = gl_list_nx_add_before (list2, node2, obj0);
              ASSERT (node2 != NULL);
              node2 = gl_list_nx_add_after (list2, node2, obj1);
              ASSERT (node2 != NULL);
              ASSERT (gl_list_node_value (list1, node1) == obj1);
              ASSERT (gl_list_node_value (list2, node2) == obj1);
              ASSERT (gl_list_get_at (list1, 0) == obj0);
              ASSERT (gl_list_get_at (list1, 1) == obj1);
              ASSERT (gl_list_get_at (list1, 2) == obj2);
              ASSERT (gl_list_get_at (list2, 0) == obj0);
              ASSERT (gl_list_get_at (list2, 1) == obj1);
              ASSERT (gl_list_get_at (list2, 2) == obj2);
            }
            break;
          case 6: /* add 1 element */
            {
              size_t index = RANDOM (gl_list_size (list1) + 1);
              const char *obj = RANDOM_OBJECT ();
              gl_list_node_t node1, node2;
              node1 = gl_list_nx_add_at (list1, index, obj);
              ASSERT (node1 != NULL);
              node2 = gl_list_nx_add_at (list2, index, obj);
              ASSERT (node2 != NULL);
              ASSERT (gl_list_get_at (list1, index) == obj);
              ASSERT (gl_list_node_value (list1, node1) == obj);
              ASSERT (gl_list_get_at (list2, index) == obj);
              ASSERT (gl_list_node_value (list2, node2) == obj);
              if (index > 0)
                {
                  ASSERT (gl_list_node_value (list1, gl_list_previous_node (list1, node1))
                          == gl_list_get_at (list1, index - 1));
                }
              if (index + 1 < gl_list_size (list1))
                {
                  ASSERT (gl_list_node_value (list1, gl_list_next_node (list1, node1))
                          == gl_list_get_at (list1, index + 1));
                }
            }
            break;
          case 7: case 8: /* remove 1 element */
            if (gl_list_size (list1) > 0)
              {
                size_t n = gl_list_size (list1);
                const char *obj = gl_list_get_at (list1, RANDOM (n));
                gl_list_node_t node1, node2;
                node1 = gl_list_search (list1, obj);
                node2 = gl_list_search (list2, obj);
                ASSERT (node1 != NULL);
                ASSERT (node2 != NULL);
                ASSERT (gl_list_remove_node (list1, node1));
                ASSERT (gl_list_remove_node (list2, node2));
                ASSERT (gl_list_size (list1) == n - 1);
              }
            break;
          case 9: case 10: /* remove 1 element */
            if (gl_list_size (list1) > 0)
              {
                size_t n = gl_list_size (list1);
                size_t index = RANDOM (n);
                ASSERT (gl_list_remove_at (list1, index));
                ASSERT (gl_list_remove_at (list2, index));
                ASSERT (gl_list_size (list1) == n - 1);
              }
            break;
          case 11: case 12: /* remove 1 element */
            if (gl_list_size (list1) > 0)
              {
                size_t n = gl_list_size (list1);
                const char *obj = gl_list_get_at (list1, RANDOM (n));
                ASSERT (gl_list_remove (list1, obj));
                ASSERT (gl_list_remove (list2, obj));
                ASSERT (gl_list_size (list1) == n - 1);
              }
            break;
          case 13:
            if (gl_list_size (list1) > 0)
              {
                size_t n = gl_list_size (list1);
                const char *obj = "xyzzy";
                ASSERT (!gl_list_remove (list1, obj));
                ASSERT (!gl_list_remove (list2, obj));
                ASSERT (gl_list_size (list1) == n);
              }
            break;
          case 14:
            {
              size_t n = gl_list_size (list1);
              gl_list_iterator_t iter1, iter2;
              const void *elt;
              iter1 = gl_list_iterator (list1);
              iter2 = gl_list_iterator (list2);
              for (i = 0; i < n; i++)
                {
                  ASSERT (gl_list_iterator_next (&iter1, &elt, NULL));
                  ASSERT (gl_list_get_at (list1, i) == elt);
                  ASSERT (gl_list_iterator_next (&iter2, &elt, NULL));
                  ASSERT (gl_list_get_at (list2, i) == elt);
                }
              ASSERT (!gl_list_iterator_next (&iter1, &elt, NULL));
              ASSERT (!gl_list_iterator_next (&iter2, &elt, NULL));
              gl_list_iterator_free (&iter1);
              gl_list_iterator_free (&iter2);
            }
            break;
          case 15:
            {
              size_t end = RANDOM (gl_list_size (list1) + 1);
              size_t start = RANDOM (end + 1);
              gl_list_iterator_t iter1, iter2;
              const void *elt;
              iter1 = gl_list_iterator_from_to (list1, start, end);
              iter2 = gl_list_iterator_from_to (list2, start, end);
              for (i = start; i < end; i++)
                {
                  ASSERT (gl_list_iterator_next (&iter1, &elt, NULL));
                  ASSERT (gl_list_get_at (list1, i) == elt);
                  ASSERT (gl_list_iterator_next (&iter2, &elt, NULL));
                  ASSERT (gl_list_get_at (list2, i) == elt);
                }
              ASSERT (!gl_list_iterator_next (&iter1, &elt, NULL));
              ASSERT (!gl_list_iterator_next (&iter2, &elt, NULL));
              gl_list_iterator_free (&iter1);
              gl_list_iterator_free (&iter2);
            }
            break;
          }
        check_equals (list1, list2);
      }

    gl_list_free (list1);
    gl_list_free (list2);
    free (contents);
  }

  return 0;
}