Пример #1
0
int main (int argc, char *argv[]) {
    // Child's CMD line
    int m = sysconf(_SC_ARG_MAX);           // Maximum CMD line length
    char *cmd;                              // Store child's CMD line
    cmd = (char *) calloc(m, sizeof(char));

    // Child's parameters
    int *child_delay = mmap(NULL, sizeof(int), PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANONYMOUS, -1, 0);
    *child_delay = 0;                       // Delay before starting (shared between parent and child)
    int child_pid = -1;                     // PID after the fork()
    int child_status = -1;                  // Used during waitpid()
    char *child_file = NULL;                // Binary file

    // Telnet server
    int ts_port = -1;                       // TCP (console) and UDP (serial converter) port
    int ts_socket = -1;                     // Telnet server socket
    char child_output = '\0';               // Store single char from child
    char client_input = '\0';               // Store single char from client
    char *xtitle = "Terminal Server";       // Title for telnet clients

    // Select parameters
    int *infd = calloc(2, sizeof(int));     // Array of integers [0] is for reading, [1] is for writing
    int *outfd = calloc(2, sizeof(int));    // Array of integers [0] is for reading, [1] is for writing
    int active_fd = -1;                     // Contains current active FD
    fd_set active_fd_set;                   // Contains active FD using in select()
    FD_ZERO(&active_fd_set);
    fd_set read_fd_set;                     // Contains FD selected in current loop
    FD_ZERO(&read_fd_set);

    // Wrapper parameters
    int child_afsocket = -1;                // Store AF_UNIX child socket
    int *eth_socket = calloc(64, sizeof(int));  // Store FD of ethernet intefaces
    int *ser_remoteid = calloc(64, sizeof(int));// Store Remote Device ID (used for UDP communication)
    int *ser_remoteif = calloc(64, sizeof(int));// Store Remote Interface ID (used for UDP communication)
    int *ser_socket = calloc(64, sizeof(int));  // Store FD of serial intefaces
    int udpserver_socket = -1;              // UDP socket for serial communications
    int wrapper_afsocket = -1;              // Store AF_UNIX wrapper socket

    // Other parameters
    int af_ready = 0;                       // 1 = AF_UNIX files are configured (needed if IOL is delayed)
    int i = -1;                             // Counter
    int j = -1;                             // Counter
    int opt = NULL;                         // Store CMD options
    int rc = -1;                            // Generic return code
    char *tmp = NULL;                       // Generic char string
    struct sigaction sa;                    // Manage signals (SIGHUP, SIGTERM...)

    setpgrp();

    // Check for iourc file
    tmp = (char *) malloc(m * sizeof(char));
    sprintf(tmp, "iourc");
    if (is_file(tmp) != 0) {
        printf("ERR: file '%s' does not exist.\n", tmp);
        exit(1);
    }
    free(tmp);

    // Adding options to child's CMD line
    while ((opt = getopt(argc, argv, ":vT:D:d:t:F:e:s:l:")) != -1) {
        switch (opt) {
            default:
                usage(argv[0]);
                exit(1);
            // Begin standard parameters
            case 'v':
                version();
                exit(0);
            case 'T':
                // Mandatory: Tenant ID
                tenant_id = atoi(optarg);
                if (tenant_id < 0) {
                    printf("ERR: tenant_id must be integer.\n");
                    exit(1);
                }
                break;
            case 'D':
                // Mandatory: Device ID
                device_id = atoi(optarg);
                if (tenant_id < 0) {
                    printf("ERR: device_id must be integer.\n");
                    exit(1);
                }
                break;
            case 'F':
                child_file = optarg;
                if (is_file(child_file) != 0) {
                    printf("ERR: file '%s' does not exist.\n", child_file);
                    exit(1);
                }
                break;
            case 'd':
                // Optional: child's startup delay (default 0)
                *child_delay = atoi(optarg);
                if (*child_delay < 0) {
                    printf("ERR: delay must be integer.\n");
                    exit(1);
                }
                break;
            case 't':
                // Optional: telnet window title (default "Terminal Server")
                xtitle = optarg;
                break;
            // End standard parameters
            // Optional: number of Ethernet progroups (default: 2)
            case 'e':
                child_eth = atoi(optarg);
                if (child_eth < 0) {
                    printf("ERR: Ethernet portgroup must be integer.\n");
                    exit(1);
                }
                break;
            // Optional: number of Serial progroups (default: 2)
            case 's':
                child_ser = atoi(optarg);
                if (child_ser < 0) {
                    printf("ERR: Serial portgroup must be numeric.\n");
                    exit(1);
                }
                break;
            // Optional: Serial link end-point (no default)
            case 'l':
                if (udpserver_socket == -1 && tenant_id != -1 && device_id != -1) {
                    // First Serial2UDP definition, must listen()
                    if ((rc = serial2udp_listen(32768 + 128 * tenant_id + device_id, &udpserver_socket)) != 0) {
                        printf("%u:%u ERR: failed to open UDP socket (%i).\n", tenant_id, device_id, rc);
                        exit(1);
                    }
                    // Now add serial end-point
                    if ((rc = serial2udp_add(ser_socket, ser_remoteid, ser_remoteif, optarg)) != 0) {
                        printf("%u:%u ERR: failed to add serial end-point (%i).\n", tenant_id, device_id, rc);
                        exit(1);
                    }
                } else if (udpserver_socket > 0) {
                    // Serial2UDP wrapper already started, add serial end-point
                    if ((rc = serial2udp_add(ser_socket, ser_remoteid, ser_remoteif, optarg)) != 0) {
                        printf("%u:%u ERR: failed to add serial end-point (%i).\n", tenant_id, device_id, rc);
                        exit(1);
                    }
                } else {
                    printf("ERR: flag '-l' must be after '-T' and '-D'.\n");
                    exit(1);
                }
                break;
        }
    }

    // Checking if tenant_id is set
    if (tenant_id < 0) {
        printf("ERR: tenant ID not set.\n");
        exit(1);
    }

    // Checking if device_id is set
    if (device_id < 0) {
        printf("ERR: device ID not set.\n");
        exit(1);
    }

    // Checking if child_file is set
    if (child_file == NULL) {
        printf("%u:%u ERR: subprocess executable not set.\n", tenant_id, device_id);
        exit(1);
    }

    // Checking total interfaces
    if (child_eth + child_ser > 16) {
        printf("%u:%u ERR: Ethernet + Serial portgroups must lower equal than 16.\n", tenant_id, device_id);
        exit(1);
    }

    // Building the CMD line
    cmd_add(&cmd, "LD_LIBRARY_PATH=/opt/unetlab/addons/iol/lib ");
    cmd_add(&cmd, child_file);

    // Adding interfaces
    tmp = (char *) malloc(m * sizeof(char));
    sprintf(tmp, " -e %i -s %i", child_eth, child_ser);
    cmd_add(&cmd, tmp);
    free(tmp);

    // Adding parameters after "--"
    j = 0;
    for (i = 1; i < argc; i++) {
        if (j == 1) {
            // Adding parameter given after "--"
            cmd_add(&cmd, " ");
            cmd_add(&cmd, argv[i]);
        }
        if (strcmp(argv[i], "--") == 0) {
            // Found "--"
            j = 1;
        }
    }

    // Adding device_id as last
    tmp = (char *) malloc(m * sizeof(char));
    sprintf(tmp, "%i", device_id);
    cmd_add(&cmd, " ");
    cmd_add(&cmd, tmp);
    free(tmp);

    // Creating NETMAP
    if ((rc = mk_netmap()) != 0) {
        printf("%u:%u ERR: failed to create NETMAP file (%i).\n", tenant_id, device_id, rc);
        exit(1);
    }

    // Creating PIPEs for select()
    if ((pipe(infd)) < 0 || pipe(outfd) < 0) {
         printf("%u:%u ERR: failed to create PIPEs (%s).\n", tenant_id, device_id, strerror(errno));
         exit(1);
    }

    // Telnet listen
    ts_port = 32768 + 128 * tenant_id + device_id;
    tsclients_socket[0] = 0;
    if ((rc = ts_listen(ts_port, &ts_socket)) != 0) {
        printf("%u:%u ERR: failed to open TCP socket (%i).\n", tenant_id, device_id, rc);
        exit(1);
    }

    // Creating TAP interfaces
    if ((rc = mk_tap(child_eth, eth_socket)) != 0) {
        printf("%u:%u ERR: failed to create TAP interfaces (%i).\n", tenant_id, device_id, rc);
        kill(0, SIGTERM);
        exit(1);
    }

    // Forking
    if ((rc = fork()) == 0) {
        // Child: starting subprocess
        if (DEBUG > 0) printf("DEBUG: starting child (%s).\n", cmd);
        if (*child_delay > 0) {
            // Delay is set, waiting
            for (; *child_delay > 0;) {
                rc = write(outfd[1], ".", 1);
                *child_delay = *child_delay - 1;
                sleep(1);
            }
            rc = write(outfd[1], "\n", 1);
        }
        close(STDIN_FILENO);            // Closing child's stdin
        close(STDOUT_FILENO);           // Closing child's stdout
        dup2(infd[0], STDIN_FILENO);    // Linking stdin to PIPE
        dup2(outfd[1], STDOUT_FILENO);  // Linking stdout to PIPE
        dup2(outfd[1], STDERR_FILENO);  // Redirect child's stderr to child's stdout
        close(infd[0]);
        close(infd[1]);
        close(outfd[0]);
        close(outfd[1]);
        // Start process
        rc = cmd_start(cmd);
        // Subprocess terminated, killing the parent
        printf("%u:%u ERR: child terminated (%i).\n", tenant_id, device_id, rc);
    } else if (rc > 0) {
        // Parent
        close(infd[0]);                     // Used by the child
        close(outfd[1]);                    // Used by the child

        // Handling Signals
        signal(SIGPIPE,SIG_IGN);            // Ignoring SIGPIPE when a client terminates
        sa.sa_handler = &signal_handler;    // Setup the sighub handler
        sa.sa_flags = SA_RESTART;           // Restart the system call, if at all possible
        sigemptyset(&sa.sa_mask);           // Signals blocked during the execution of the handler
        sigaddset(&sa.sa_mask, SIGHUP);     // Signal 1
        sigaddset(&sa.sa_mask, SIGINT);     // Signal 2
        sigaddset(&sa.sa_mask, SIGTERM);    // Signal 15
        sigfillset(&sa.sa_mask);

        // Intercept SIGHUP, SIGINT, SIGUSR1 and SIGTERM
        if (sigaction(SIGHUP, &sa, NULL) == -1) {
            printf("%u:%u ERR: cannot handle SIGHUP (%s).\n", tenant_id, device_id, strerror(errno));
        }
        if (sigaction(SIGINT, &sa, NULL) == -1) {
            printf("%u:%u ERR: cannot handle SIGINT (%s).\n", tenant_id, device_id, strerror(errno));
        }
        if (sigaction(SIGTERM, &sa, NULL) == -1) {
            printf("%u:%u ERR: cannot handle SIGTERM (%s).\n", tenant_id, device_id, strerror(errno));
        }

        // Preparing select()
        FD_ZERO(&active_fd_set);
        FD_ZERO(&read_fd_set);
        if (DEBUG > 0) printf("DEBUG: adding subprocess stdout descriptor (%i).\n", outfd[0]);
        FD_SET(outfd[0], &active_fd_set);         // Adding subprocess stdout
        if (DEBUG > 0) printf("DEBUG: adding telnet socket descriptor (%i).\n", ts_socket);
        FD_SET(ts_socket, &active_fd_set);        // Adding telnet socket
        if (udpserver_socket > 0) {
            if (DEBUG > 0) printf("DEBUG: adding UDP socket descriptor (%i).\n", udpserver_socket);
            FD_SET(udpserver_socket, &active_fd_set); // Adding UDP socket
        }

        // Adding TAP interfaces for select()
        for (i = 0; i <= 63; i++) {
            if (eth_socket[i] > 0) {
                if (DEBUG > 0) printf("DEBUG: adding TAP interface descriptor (%i).\n", eth_socket[i]);
                FD_SET(eth_socket[i], &active_fd_set);
            }
        }

        // While subprocess is running, check IO from subprocess, telnet clients, socket and network
        while (waitpid(child_pid, &child_status, WNOHANG|WUNTRACED) == 0) {
            // Creating AF communication from child
            if (af_ready == 0 && *child_delay == 0) {
                // wait 3 seconds for AF_UNIX
                sleep(3);
                if ((rc = mk_afsocket(&wrapper_afsocket, &child_afsocket)) != 0) {;
                    printf("%u:%u ERR: failed to create AF_UNIX socket file (%i).\n", tenant_id, device_id, rc);
                    kill(0, SIGTERM);
                    break;
                }
                af_ready = 1;
                if (DEBUG > 0) printf("DEBUG: adding wrapper socket descriptor (%i).\n", wrapper_afsocket);
                FD_SET(wrapper_afsocket, &active_fd_set);   // Adding subprocess AF_UNIX socket
            }

            // Check if select() is valid
            read_fd_set = active_fd_set;
            if ((active_fd = select(FD_SETSIZE, &read_fd_set, NULL, NULL, NULL)) <= 0) {
                printf("%u:%u ERR: failed to select().\n", tenant_id, device_id);
                kill(0, SIGTERM);
                break;
            }
            if (DEBUG > 2) printf("DEBUG: data from select descriptor (%i).\n", active_fd);

            // Check if output from child
            if (FD_ISSET(outfd[0], &read_fd_set)) {
                if (read(outfd[0], &child_output, 1) <= 0) {
                    printf("%u:%u ERR: error while reading data from the subprocess, killing it.\n", tenant_id, device_id);
                    kill(0, SIGTERM);
                    break;
                }
                // Writing to all telnet clients
                ts_broadcast(child_output, &active_fd_set, tsclients_socket);
            }

            // Check if new client is coming
            if (FD_ISSET(ts_socket, &read_fd_set)) {
                if ((rc = ts_accept(&active_fd_set, ts_socket, xtitle, tsclients_socket,1)) != 0) {
                    printf("%u:%u ERR: failed to accept a new client (%i).\n", tenant_id, device_id, rc);
                }
            }

            // Check for output from all telnet clients
            if (ts_receive(&client_input, &read_fd_set, &active_fd_set, tsclients_socket) == 0) {
                // Write to child
                rc = write(infd[1], &client_input, 1);
                if (rc < 0) {
                    printf("%u:%u ERR: error writing to the subprocess, closing.\n", tenant_id, device_id);
                    kill(0, SIGTERM);
                    break;
                }
            }

            // If AF, UDP and TAP sockets are configured, check for packets
            if (af_ready == 1) {
                // Check for packets from subprocess
                if (FD_ISSET(wrapper_afsocket, &read_fd_set)) {
                    if ((rc = packet_af(wrapper_afsocket, eth_socket, ser_socket, ser_remoteid, ser_remoteif)) != 0) {
                        printf("%u:%u ERR: error forwarding packet from AF_UNIX socket to TAP/UDP (%i).\n", tenant_id, device_id, rc);
                        kill(0, SIGTERM);
                        break;
                    }
                }

                // Check for packets from TAP interfaces
                for (i = 0; i <= 63; i++) {
                    if (eth_socket[i] > 0 && FD_ISSET(eth_socket[i], &read_fd_set)) {
                        if ((rc = packet_tap(eth_socket[i], child_afsocket, i)) != 0) {
                            if (rc == 3) {
                              af_ready = 0;
                              printf("Failed to forward TAP => AF_UNIX. Will try to recreate it later...\n");
                            } else {
                              printf("%u:%u ERR: error forwarding packet from TAP to AF_UNIX socket (%i).\n", tenant_id, device_id, rc);
                              kill(0, SIGTERM);
                              break;
                            }
                        }
                    }
                }

                // Check for incoming serial (UDP) packets
                if (udpserver_socket > 0) {
                    if (FD_ISSET(udpserver_socket, &read_fd_set)) {
                        if ((rc = packet_udp(udpserver_socket, child_afsocket)) != 0) {
                            if (rc == 3) {
                                af_ready = 0;
                                printf("Failed to forward UDP => AF_UNIX. Will try to recreate it later...\n");
                            } else {
                                printf("%u:%u ERR: error forwarding packet from UDP to AF_UNIX (%i).\n", tenant_id, device_id, rc);
                                kill(0, SIGTERM);
                                break;
                            }
                        }
                    }
                }
            }

            // We should not have other active dscriptor
        }

        // Child is no more running
        printf("%u:%u ERR: child is no more running.\n", tenant_id, device_id);
    } else {
        printf("%u:%u ERR: failed to fork.\n", tenant_id, device_id);
        exit(1);
    }
    close(ts_socket);
    close(wrapper_afsocket);
    exit(0);
}
Пример #2
0
int main(int argc, char **argv)
{
    BlockDriverState *bs;
    off_t dev_offset = 0;
    off_t offset = 0;
    uint32_t nbdflags = 0;
    bool disconnect = false;
    const char *bindto = "0.0.0.0";
    int port = NBD_DEFAULT_PORT;
    struct sockaddr_in addr;
    socklen_t addr_len = sizeof(addr);
    off_t fd_size;
    const char *sopt = "hVb:o:p:rsnP:c:dvk:e:t";
    struct option lopt[] = {
        { "help", 0, NULL, 'h' },
        { "version", 0, NULL, 'V' },
        { "bind", 1, NULL, 'b' },
        { "port", 1, NULL, 'p' },
        { "socket", 1, NULL, 'k' },
        { "offset", 1, NULL, 'o' },
        { "read-only", 0, NULL, 'r' },
        { "partition", 1, NULL, 'P' },
        { "connect", 1, NULL, 'c' },
        { "disconnect", 0, NULL, 'd' },
        { "snapshot", 0, NULL, 's' },
        { "nocache", 0, NULL, 'n' },
        { "shared", 1, NULL, 'e' },
        { "persistent", 0, NULL, 't' },
        { "verbose", 0, NULL, 'v' },
        { NULL, 0, NULL, 0 }
    };
    int ch;
    int opt_ind = 0;
    int li;
    char *end;
    int flags = BDRV_O_RDWR;
    int partition = -1;
    int ret;
    int shared = 1;
    uint8_t *data;
    fd_set fds;
    int *sharing_fds;
    int fd;
    int i;
    int nb_fds = 0;
    int max_fd;
    int persistent = 0;
    pthread_t client_thread;

    /* The client thread uses SIGTERM to interrupt the server.  A signal
     * handler ensures that "qemu-nbd -v -c" exits with a nice status code.
     */
    struct sigaction sa_sigterm;
    int sigterm_fd[2];
    if (qemu_pipe(sigterm_fd) == -1) {
        err(EXIT_FAILURE, "Error setting up communication pipe");
    }

    sigterm_wfd = sigterm_fd[1];
    memset(&sa_sigterm, 0, sizeof(sa_sigterm));
    sa_sigterm.sa_handler = termsig_handler;
    sigaction(SIGTERM, &sa_sigterm, NULL);

    while ((ch = getopt_long(argc, argv, sopt, lopt, &opt_ind)) != -1) {
        switch (ch) {
        case 's':
            flags |= BDRV_O_SNAPSHOT;
            break;
        case 'n':
            flags |= BDRV_O_NOCACHE | BDRV_O_CACHE_WB;
            break;
        case 'b':
            bindto = optarg;
            break;
        case 'p':
            li = strtol(optarg, &end, 0);
            if (*end) {
                errx(EXIT_FAILURE, "Invalid port `%s'", optarg);
            }
            if (li < 1 || li > 65535) {
                errx(EXIT_FAILURE, "Port out of range `%s'", optarg);
            }
            port = (uint16_t)li;
            break;
        case 'o':
                dev_offset = strtoll (optarg, &end, 0);
            if (*end) {
                errx(EXIT_FAILURE, "Invalid offset `%s'", optarg);
            }
            if (dev_offset < 0) {
                errx(EXIT_FAILURE, "Offset must be positive `%s'", optarg);
            }
            break;
        case 'r':
            nbdflags |= NBD_FLAG_READ_ONLY;
            flags &= ~BDRV_O_RDWR;
            break;
        case 'P':
            partition = strtol(optarg, &end, 0);
            if (*end)
                errx(EXIT_FAILURE, "Invalid partition `%s'", optarg);
            if (partition < 1 || partition > 8)
                errx(EXIT_FAILURE, "Invalid partition %d", partition);
            break;
        case 'k':
            sockpath = optarg;
            if (sockpath[0] != '/')
                errx(EXIT_FAILURE, "socket path must be absolute\n");
            break;
        case 'd':
            disconnect = true;
            break;
        case 'c':
            device = optarg;
            break;
        case 'e':
            shared = strtol(optarg, &end, 0);
            if (*end) {
                errx(EXIT_FAILURE, "Invalid shared device number '%s'", optarg);
            }
            if (shared < 1) {
                errx(EXIT_FAILURE, "Shared device number must be greater than 0\n");
            }
            break;
	case 't':
	    persistent = 1;
	    break;
        case 'v':
            verbose = 1;
            break;
        case 'V':
            version(argv[0]);
            exit(0);
            break;
        case 'h':
            usage(argv[0]);
            exit(0);
            break;
        case '?':
            errx(EXIT_FAILURE, "Try `%s --help' for more information.",
                 argv[0]);
        }
    }

    if ((argc - optind) != 1) {
        errx(EXIT_FAILURE, "Invalid number of argument.\n"
             "Try `%s --help' for more information.",
             argv[0]);
    }

    if (disconnect) {
        fd = open(argv[optind], O_RDWR);
        if (fd == -1)
            err(EXIT_FAILURE, "Cannot open %s", argv[optind]);

        nbd_disconnect(fd);

        close(fd);

        printf("%s disconnected\n", argv[optind]);

	return 0;
    }

    if (device && !verbose) {
        int stderr_fd[2];
        pid_t pid;
        int ret;

        if (qemu_pipe(stderr_fd) == -1) {
            err(EXIT_FAILURE, "Error setting up communication pipe");
        }

        /* Now daemonize, but keep a communication channel open to
         * print errors and exit with the proper status code.
         */
        pid = fork();
        if (pid == 0) {
            close(stderr_fd[0]);
            ret = qemu_daemon(0, 0);

            /* Temporarily redirect stderr to the parent's pipe...  */
            dup2(stderr_fd[1], STDERR_FILENO);
            if (ret == -1) {
                err(EXIT_FAILURE, "Failed to daemonize");
            }

            /* ... close the descriptor we inherited and go on.  */
            close(stderr_fd[1]);
        } else {
            bool errors = false;
            char *buf;

            /* In the parent.  Print error messages from the child until
             * it closes the pipe.
             */
            close(stderr_fd[1]);
            buf = g_malloc(1024);
            while ((ret = read(stderr_fd[0], buf, 1024)) > 0) {
                errors = true;
                ret = qemu_write_full(STDERR_FILENO, buf, ret);
                if (ret == -1) {
                    exit(EXIT_FAILURE);
                }
            }
            if (ret == -1) {
                err(EXIT_FAILURE, "Cannot read from daemon");
            }

            /* Usually the daemon should not print any message.
             * Exit with zero status in that case.
             */
            exit(errors);
        }
    }

    if (device) {
        /* Open before spawning new threads.  In the future, we may
         * drop privileges after opening.
         */
        fd = open(device, O_RDWR);
        if (fd == -1) {
            err(EXIT_FAILURE, "Failed to open %s", device);
        }

        if (sockpath == NULL) {
            sockpath = g_malloc(128);
            snprintf(sockpath, 128, SOCKET_PATH, basename(device));
        }
    }

    bdrv_init();
    atexit(bdrv_close_all);

    bs = bdrv_new("hda");
    srcpath = argv[optind];
    if ((ret = bdrv_open(bs, srcpath, flags, NULL)) < 0) {
        errno = -ret;
        err(EXIT_FAILURE, "Failed to bdrv_open '%s'", argv[optind]);
    }

    fd_size = bs->total_sectors * 512;

    if (partition != -1 &&
        find_partition(bs, partition, &dev_offset, &fd_size)) {
        err(EXIT_FAILURE, "Could not find partition %d", partition);
    }

    sharing_fds = g_malloc((shared + 1) * sizeof(int));

    if (sockpath) {
        sharing_fds[0] = unix_socket_incoming(sockpath);
    } else {
        sharing_fds[0] = tcp_socket_incoming(bindto, port);
    }

    if (sharing_fds[0] == -1)
        return 1;

    if (device) {
        int ret;

        ret = pthread_create(&client_thread, NULL, nbd_client_thread, &fd);
        if (ret != 0) {
            errx(EXIT_FAILURE, "Failed to create client thread: %s",
                 strerror(ret));
        }
    } else {
        /* Shut up GCC warnings.  */
        memset(&client_thread, 0, sizeof(client_thread));
    }

    max_fd = sharing_fds[0];
    nb_fds++;

    data = qemu_blockalign(bs, NBD_BUFFER_SIZE);
    if (data == NULL) {
        errx(EXIT_FAILURE, "Cannot allocate data buffer");
    }

    do {
        FD_ZERO(&fds);
        FD_SET(sigterm_fd[0], &fds);
        for (i = 0; i < nb_fds; i++)
            FD_SET(sharing_fds[i], &fds);

        do {
            ret = select(max_fd + 1, &fds, NULL, NULL, NULL);
        } while (ret == -1 && errno == EINTR);
        if (ret == -1 || FD_ISSET(sigterm_fd[0], &fds)) {
            break;
        }

        if (FD_ISSET(sharing_fds[0], &fds))
            ret--;
        for (i = 1; i < nb_fds && ret; i++) {
            if (FD_ISSET(sharing_fds[i], &fds)) {
                if (nbd_trip(bs, sharing_fds[i], fd_size, dev_offset,
                    &offset, nbdflags, data, NBD_BUFFER_SIZE) != 0) {
                    close(sharing_fds[i]);
                    nb_fds--;
                    sharing_fds[i] = sharing_fds[nb_fds];
                    i--;
                }
                ret--;
            }
        }
        /* new connection ? */
        if (FD_ISSET(sharing_fds[0], &fds)) {
            if (nb_fds < shared + 1) {
                sharing_fds[nb_fds] = accept(sharing_fds[0],
                                             (struct sockaddr *)&addr,
                                             &addr_len);
                if (sharing_fds[nb_fds] != -1 &&
                    nbd_negotiate(sharing_fds[nb_fds], fd_size, nbdflags) != -1) {
                        if (sharing_fds[nb_fds] > max_fd)
                            max_fd = sharing_fds[nb_fds];
                        nb_fds++;
                }
            }
        }
    } while (persistent || nb_fds > 1);
    qemu_vfree(data);

    close(sharing_fds[0]);
    g_free(sharing_fds);
    if (sockpath) {
        unlink(sockpath);
    }

    if (device) {
        void *ret;
        pthread_join(client_thread, &ret);
        exit(ret != NULL);
    } else {
        exit(EXIT_SUCCESS);
    }
}
Пример #3
0
nsresult
GfxInfo::GetFeatureStatusImpl(PRInt32 aFeature, 
                              PRInt32 *aStatus, 
                              nsAString & aSuggestedDriverVersion, 
                              GfxDriverInfo* aDriverInfo /* = nsnull */, 
                              OperatingSystem* aOS /* = nsnull */)

{
    GetData();
    *aStatus = nsIGfxInfo::FEATURE_NO_INFO;
    aSuggestedDriverVersion.SetIsVoid(true);

#ifdef MOZ_PLATFORM_MAEMO
    // on Maemo, the glxtest probe doesn't build, and we don't really need GfxInfo anyway
    return NS_OK;
#endif

    OperatingSystem os = DRIVER_OS_LINUX;

    // Disable OpenGL layers when we don't have texture_from_pixmap because it regresses performance. 
    if (aFeature == nsIGfxInfo::FEATURE_OPENGL_LAYERS && !mHasTextureFromPixmap) {
        *aStatus = nsIGfxInfo::FEATURE_BLOCKED_DRIVER_VERSION;
        aSuggestedDriverVersion.AssignLiteral("<Anything with EXT_texture_from_pixmap support>");
        return NS_OK;
    }

    // whitelist the linux test slaves' current configuration.
    // this is necessary as they're still using the slightly outdated 190.42 driver.
    // this isn't a huge risk, as at least this is the exact setting in which we do continuous testing,
    // and this only affects GeForce 9400 cards on linux on this precise driver version, which is very few users.
    // We do the same thing on Windows XP, see in widget/src/windows/GfxInfo.cpp
    if (mIsNVIDIA &&
        !strcmp(mRenderer.get(), "GeForce 9400/PCI/SSE2") &&
        !strcmp(mVersion.get(), "3.2.0 NVIDIA 190.42"))
    {
        return NS_OK;
    }

    if (mIsMesa) {
        if (version(mMajorVersion, mMinorVersion, mRevisionVersion) < version(7,10,3)) {
            *aStatus = nsIGfxInfo::FEATURE_BLOCKED_DRIVER_VERSION;
            aSuggestedDriverVersion.AssignLiteral("Mesa 7.10.3");
        }
    } else if (mIsNVIDIA) {
        if (version(mMajorVersion, mMinorVersion, mRevisionVersion) < version(257,21)) {
            *aStatus = nsIGfxInfo::FEATURE_BLOCKED_DRIVER_VERSION;
            aSuggestedDriverVersion.AssignLiteral("NVIDIA 257.21");
        }
    } else if (mIsFGLRX) {
        // FGLRX does not report a driver version number, so we have the OpenGL version instead.
        // by requiring OpenGL 3, we effectively require recent drivers.
        if (version(mMajorVersion, mMinorVersion, mRevisionVersion) < version(3, 0)) {
            *aStatus = nsIGfxInfo::FEATURE_BLOCKED_DRIVER_VERSION;
        }
    } else {
        // like on windows, let's block unknown vendors. Think of virtual machines.
        // Also, this case is hit whenever the GLXtest probe failed to get driver info or crashed.
        *aStatus = nsIGfxInfo::FEATURE_BLOCKED_DEVICE;
    }

  if (aOS)
    *aOS = os;

  return GfxInfoBase::GetFeatureStatusImpl(aFeature, aStatus, aSuggestedDriverVersion, aDriverInfo, &os);
}
Пример #4
0
int
main(int argc, char **argv)
{
	struct bsdtar		*bsdtar, bsdtar_storage;
	int			 opt, t;
	char			 option_o;
	char			 possible_help_request;
	char			 buff[16];
	time_t			 now;

	/*
	 * Use a pointer for consistency, but stack-allocated storage
	 * for ease of cleanup.
	 */
	_bsdtar = bsdtar = &bsdtar_storage;
	memset(bsdtar, 0, sizeof(*bsdtar));
	bsdtar->fd = -1; /* Mark as "unused" */
	bsdtar->gid = -1;
	bsdtar->uid = -1;
	option_o = 0;

#if defined(HAVE_SIGACTION) && (defined(SIGINFO) || defined(SIGUSR1))
	{ /* Catch SIGINFO and SIGUSR1, if they exist. */
		struct sigaction sa;
		sa.sa_handler = siginfo_handler;
		sigemptyset(&sa.sa_mask);
		sa.sa_flags = 0;
#ifdef SIGINFO
		if (sigaction(SIGINFO, &sa, NULL))
			lafe_errc(1, errno, "sigaction(SIGINFO) failed");
#endif
#ifdef SIGUSR1
		/* ... and treat SIGUSR1 the same way as SIGINFO. */
		if (sigaction(SIGUSR1, &sa, NULL))
			lafe_errc(1, errno, "sigaction(SIGUSR1) failed");
#endif
	}
#endif

	/* Need lafe_progname before calling lafe_warnc. */
	if (*argv == NULL)
		lafe_progname = "bsdtar";
	else {
#if defined(_WIN32) && !defined(__CYGWIN__)
		lafe_progname = strrchr(*argv, '\\');
#else
		lafe_progname = strrchr(*argv, '/');
#endif
		if (lafe_progname != NULL)
			lafe_progname++;
		else
			lafe_progname = *argv;
	}

	time(&now);

#if HAVE_SETLOCALE
	if (setlocale(LC_ALL, "") == NULL)
		lafe_warnc(0, "Failed to set default locale");
#endif
#if defined(HAVE_NL_LANGINFO) && defined(HAVE_D_MD_ORDER)
	bsdtar->day_first = (*nl_langinfo(D_MD_ORDER) == 'd');
#endif
	possible_help_request = 0;

	/* Look up uid of current user for future reference */
	bsdtar->user_uid = geteuid();

	/* Default: open tape drive. */
	bsdtar->filename = getenv("TAPE");
	if (bsdtar->filename == NULL)
		bsdtar->filename = _PATH_DEFTAPE;

	/* Default: preserve mod time on extract */
	bsdtar->extract_flags = ARCHIVE_EXTRACT_TIME;

	/* Default: Perform basic security checks. */
	bsdtar->extract_flags |= SECURITY;

#ifndef _WIN32
	/* On POSIX systems, assume --same-owner and -p when run by
	 * the root user.  This doesn't make any sense on Windows. */
	if (bsdtar->user_uid == 0) {
		/* --same-owner */
		bsdtar->extract_flags |= ARCHIVE_EXTRACT_OWNER;
		/* -p */
		bsdtar->extract_flags |= ARCHIVE_EXTRACT_PERM;
		bsdtar->extract_flags |= ARCHIVE_EXTRACT_ACL;
		bsdtar->extract_flags |= ARCHIVE_EXTRACT_XATTR;
		bsdtar->extract_flags |= ARCHIVE_EXTRACT_FFLAGS;
	}
#endif

	bsdtar->argv = argv;
	bsdtar->argc = argc;

	/*
	 * Comments following each option indicate where that option
	 * originated:  SUSv2, POSIX, GNU tar, star, etc.  If there's
	 * no such comment, then I don't know of anyone else who
	 * implements that option.
	 */
	while ((opt = bsdtar_getopt(bsdtar)) != -1) {
		switch (opt) {
		case 'B': /* GNU tar */
			/* libarchive doesn't need this; just ignore it. */
			break;
		case 'b': /* SUSv2 */
			t = atoi(bsdtar->optarg);
			if (t <= 0 || t > 8192)
				lafe_errc(1, 0,
				    "Argument to -b is out of range (1..8192)");
			bsdtar->bytes_per_block = 512 * t;
			break;
		case 'C': /* GNU tar */
			set_chdir(bsdtar, bsdtar->optarg);
			break;
		case 'c': /* SUSv2 */
			set_mode(bsdtar, opt);
			break;
		case OPTION_CHECK_LINKS: /* GNU tar */
			bsdtar->option_warn_links = 1;
			break;
		case OPTION_CHROOT: /* NetBSD */
			bsdtar->option_chroot = 1;
			break;
		case OPTION_EXCLUDE: /* GNU tar */
			if (lafe_exclude(&bsdtar->matching, bsdtar->optarg))
				lafe_errc(1, 0,
				    "Couldn't exclude %s\n", bsdtar->optarg);
			break;
		case OPTION_FORMAT: /* GNU tar, others */
			bsdtar->create_format = bsdtar->optarg;
			break;
		case 'f': /* SUSv2 */
			bsdtar->filename = bsdtar->optarg;
			if (strcmp(bsdtar->filename, "-") == 0)
				bsdtar->filename = NULL;
			break;
		case OPTION_GID: /* cpio */
			t = atoi(bsdtar->optarg);
			if (t < 0)
				lafe_errc(1, 0,
				    "Argument to --gid must be positive");
			bsdtar->gid = t;
			break;
		case OPTION_GNAME: /* cpio */
			bsdtar->gname = bsdtar->optarg;
			break;
		case 'H': /* BSD convention */
			bsdtar->symlink_mode = 'H';
			break;
		case 'h': /* Linux Standards Base, gtar; synonym for -L */
			bsdtar->symlink_mode = 'L';
			/* Hack: -h by itself is the "help" command. */
			possible_help_request = 1;
			break;
		case OPTION_HELP: /* GNU tar, others */
			long_help();
			exit(0);
			break;
		case 'I': /* GNU tar */
			/*
			 * TODO: Allow 'names' to come from an archive,
			 * not just a text file.  Design a good UI for
			 * allowing names and mode/owner to be read
			 * from an archive, with contents coming from
			 * disk.  This can be used to "refresh" an
			 * archive or to design archives with special
			 * permissions without having to create those
			 * permissions on disk.
			 */
			bsdtar->names_from_file = bsdtar->optarg;
			break;
		case OPTION_INCLUDE:
			/*
			 * Noone else has the @archive extension, so
			 * noone else needs this to filter entries
			 * when transforming archives.
			 */
			if (lafe_include(&bsdtar->matching, bsdtar->optarg))
				lafe_errc(1, 0,
				    "Failed to add %s to inclusion list",
				    bsdtar->optarg);
			break;
		case 'j': /* GNU tar */
			if (bsdtar->create_compression != '\0')
				lafe_errc(1, 0,
				    "Can't specify both -%c and -%c", opt,
				    bsdtar->create_compression);
			bsdtar->create_compression = opt;
			break;
		case 'J': /* GNU tar 1.21 and later */
			if (bsdtar->create_compression != '\0')
				lafe_errc(1, 0,
				    "Can't specify both -%c and -%c", opt,
				    bsdtar->create_compression);
			bsdtar->create_compression = opt;
			break;
		case 'k': /* GNU tar */
			bsdtar->extract_flags |= ARCHIVE_EXTRACT_NO_OVERWRITE;
			break;
		case OPTION_KEEP_NEWER_FILES: /* GNU tar */
			bsdtar->extract_flags |= ARCHIVE_EXTRACT_NO_OVERWRITE_NEWER;
			break;
		case 'L': /* BSD convention */
			bsdtar->symlink_mode = 'L';
			break;
	        case 'l': /* SUSv2 and GNU tar beginning with 1.16 */
			/* GNU tar 1.13  used -l for --one-file-system */
			bsdtar->option_warn_links = 1;
			break;
		case OPTION_LZMA:
			if (bsdtar->create_compression != '\0')
				lafe_errc(1, 0,
				    "Can't specify both -%c and -%c", opt,
				    bsdtar->create_compression);
			bsdtar->create_compression = opt;
			break;
		case 'm': /* SUSv2 */
			bsdtar->extract_flags &= ~ARCHIVE_EXTRACT_TIME;
			break;
		case 'n': /* GNU tar */
			bsdtar->option_no_subdirs = 1;
			break;
	        /*
		 * Selecting files by time:
		 *    --newer-?time='date' Only files newer than 'date'
		 *    --newer-?time-than='file' Only files newer than time
		 *         on specified file (useful for incremental backups)
		 * TODO: Add corresponding "older" options to reverse these.
		 */
		case OPTION_NEWER_CTIME: /* GNU tar */
			bsdtar->newer_ctime_sec = get_date(now, bsdtar->optarg);
			break;
		case OPTION_NEWER_CTIME_THAN:
			{
				struct stat st;
				if (stat(bsdtar->optarg, &st) != 0)
					lafe_errc(1, 0,
					    "Can't open file %s", bsdtar->optarg);
				bsdtar->newer_ctime_sec = st.st_ctime;
				bsdtar->newer_ctime_nsec =
				    ARCHIVE_STAT_CTIME_NANOS(&st);
			}
			break;
		case OPTION_NEWER_MTIME: /* GNU tar */
			bsdtar->newer_mtime_sec = get_date(now, bsdtar->optarg);
			break;
		case OPTION_NEWER_MTIME_THAN:
			{
				struct stat st;
				if (stat(bsdtar->optarg, &st) != 0)
					lafe_errc(1, 0,
					    "Can't open file %s", bsdtar->optarg);
				bsdtar->newer_mtime_sec = st.st_mtime;
				bsdtar->newer_mtime_nsec =
				    ARCHIVE_STAT_MTIME_NANOS(&st);
			}
			break;
		case OPTION_NODUMP: /* star */
			bsdtar->option_honor_nodump = 1;
			break;
		case OPTION_NO_SAME_OWNER: /* GNU tar */
			bsdtar->extract_flags &= ~ARCHIVE_EXTRACT_OWNER;
			break;
		case OPTION_NO_SAME_PERMISSIONS: /* GNU tar */
			bsdtar->extract_flags &= ~ARCHIVE_EXTRACT_PERM;
			bsdtar->extract_flags &= ~ARCHIVE_EXTRACT_ACL;
			bsdtar->extract_flags &= ~ARCHIVE_EXTRACT_XATTR;
			bsdtar->extract_flags &= ~ARCHIVE_EXTRACT_FFLAGS;
			break;
		case OPTION_NULL: /* GNU tar */
			bsdtar->option_null++;
			break;
		case OPTION_NUMERIC_OWNER: /* GNU tar */
			bsdtar->uname = "";
			bsdtar->gname = "";
			break;
		case 'O': /* GNU tar */
			bsdtar->option_stdout = 1;
			break;
		case 'o': /* SUSv2 and GNU conflict here, but not fatally */
			option_o = 1; /* Record it and resolve it later. */
			break;
		case OPTION_ONE_FILE_SYSTEM: /* GNU tar */
			bsdtar->option_dont_traverse_mounts = 1;
			break;
		case OPTION_OPTIONS:
			bsdtar->option_options = bsdtar->optarg;
			break;
#if 0
		/*
		 * The common BSD -P option is not necessary, since
		 * our default is to archive symlinks, not follow
		 * them.  This is convenient, as -P conflicts with GNU
		 * tar anyway.
		 */
		case 'P': /* BSD convention */
			/* Default behavior, no option necessary. */
			break;
#endif
		case 'P': /* GNU tar */
			bsdtar->extract_flags &= ~SECURITY;
			bsdtar->option_absolute_paths = 1;
			break;
		case 'p': /* GNU tar, star */
			bsdtar->extract_flags |= ARCHIVE_EXTRACT_PERM;
			bsdtar->extract_flags |= ARCHIVE_EXTRACT_ACL;
			bsdtar->extract_flags |= ARCHIVE_EXTRACT_XATTR;
			bsdtar->extract_flags |= ARCHIVE_EXTRACT_FFLAGS;
			break;
		case OPTION_POSIX: /* GNU tar */
			bsdtar->create_format = "pax";
			break;
		case 'q': /* FreeBSD GNU tar --fast-read, NetBSD -q */
			bsdtar->option_fast_read = 1;
			break;
		case 'r': /* SUSv2 */
			set_mode(bsdtar, opt);
			break;
		case 'S': /* NetBSD pax-as-tar */
			bsdtar->extract_flags |= ARCHIVE_EXTRACT_SPARSE;
			break;
		case 's': /* NetBSD pax-as-tar */
#if HAVE_REGEX_H
			add_substitution(bsdtar, bsdtar->optarg);
#else
			lafe_warnc(0,
			    "-s is not supported by this version of bsdtar");
			usage();
#endif
			break;
		case OPTION_SAME_OWNER: /* GNU tar */
			bsdtar->extract_flags |= ARCHIVE_EXTRACT_OWNER;
			break;
		case OPTION_STRIP_COMPONENTS: /* GNU tar 1.15 */
			bsdtar->strip_components = atoi(bsdtar->optarg);
			break;
		case 'T': /* GNU tar */
			bsdtar->names_from_file = bsdtar->optarg;
			break;
		case 't': /* SUSv2 */
			set_mode(bsdtar, opt);
			bsdtar->verbose++;
			break;
		case OPTION_TOTALS: /* GNU tar */
			bsdtar->option_totals++;
			break;
		case 'U': /* GNU tar */
			bsdtar->extract_flags |= ARCHIVE_EXTRACT_UNLINK;
			bsdtar->option_unlink_first = 1;
			break;
		case 'u': /* SUSv2 */
			set_mode(bsdtar, opt);
			break;
		case OPTION_UID: /* cpio */
			t = atoi(bsdtar->optarg);
			if (t < 0)
				lafe_errc(1, 0,
				    "Argument to --uid must be positive");
			bsdtar->uid = t;
			break;
		case OPTION_UNAME: /* cpio */
			bsdtar->uname = bsdtar->optarg;
			break;
		case 'v': /* SUSv2 */
			bsdtar->verbose++;
			break;
		case OPTION_VERSION: /* GNU convention */
			version();
			break;
#if 0
		/*
		 * The -W longopt feature is handled inside of
		 * bsdtar_getopt(), so -W is not available here.
		 */
		case 'W': /* Obscure GNU convention. */
			break;
#endif
		case 'w': /* SUSv2 */
			bsdtar->option_interactive = 1;
			break;
		case 'X': /* GNU tar */
			if (lafe_exclude_from_file(&bsdtar->matching, bsdtar->optarg))
				lafe_errc(1, 0,
				    "failed to process exclusions from file %s",
				    bsdtar->optarg);
			break;
		case 'x': /* SUSv2 */
			set_mode(bsdtar, opt);
			break;
		case 'y': /* FreeBSD version of GNU tar */
			if (bsdtar->create_compression != '\0')
				lafe_errc(1, 0,
				    "Can't specify both -%c and -%c", opt,
				    bsdtar->create_compression);
			bsdtar->create_compression = opt;
			break;
		case 'Z': /* GNU tar */
			if (bsdtar->create_compression != '\0')
				lafe_errc(1, 0,
				    "Can't specify both -%c and -%c", opt,
				    bsdtar->create_compression);
			bsdtar->create_compression = opt;
			break;
		case 'z': /* GNU tar, star, many others */
			if (bsdtar->create_compression != '\0')
				lafe_errc(1, 0,
				    "Can't specify both -%c and -%c", opt,
				    bsdtar->create_compression);
			bsdtar->create_compression = opt;
			break;
		case OPTION_USE_COMPRESS_PROGRAM:
			bsdtar->compress_program = bsdtar->optarg;
			break;
		default:
			usage();
		}
	}

	/*
	 * Sanity-check options.
	 */

	/* If no "real" mode was specified, treat -h as --help. */
	if ((bsdtar->mode == '\0') && possible_help_request) {
		long_help();
		exit(0);
	}

	/* Otherwise, a mode is required. */
	if (bsdtar->mode == '\0')
		lafe_errc(1, 0,
		    "Must specify one of -c, -r, -t, -u, -x");

	/* Check boolean options only permitted in certain modes. */
	if (bsdtar->option_dont_traverse_mounts)
		only_mode(bsdtar, "--one-file-system", "cru");
	if (bsdtar->option_fast_read)
		only_mode(bsdtar, "--fast-read", "xt");
	if (bsdtar->option_honor_nodump)
		only_mode(bsdtar, "--nodump", "cru");
	if (option_o > 0) {
		switch (bsdtar->mode) {
		case 'c':
			/*
			 * In GNU tar, -o means "old format."  The
			 * "ustar" format is the closest thing
			 * supported by libarchive.
			 */
			bsdtar->create_format = "ustar";
			/* TODO: bsdtar->create_format = "v7"; */
			break;
		case 'x':
			/* POSIX-compatible behavior. */
			bsdtar->option_no_owner = 1;
			bsdtar->extract_flags &= ~ARCHIVE_EXTRACT_OWNER;
			break;
		default:
			only_mode(bsdtar, "-o", "xc");
			break;
		}
	}
	if (bsdtar->option_no_subdirs)
		only_mode(bsdtar, "-n", "cru");
	if (bsdtar->option_stdout)
		only_mode(bsdtar, "-O", "xt");
	if (bsdtar->option_unlink_first)
		only_mode(bsdtar, "-U", "x");
	if (bsdtar->option_warn_links)
		only_mode(bsdtar, "--check-links", "cr");

	/* Check other parameters only permitted in certain modes. */
	if (bsdtar->create_compression != '\0') {
		strcpy(buff, "-?");
		buff[1] = bsdtar->create_compression;
		only_mode(bsdtar, buff, "cxt");
	}
	if (bsdtar->create_format != NULL)
		only_mode(bsdtar, "--format", "cru");
	if (bsdtar->symlink_mode != '\0') {
		strcpy(buff, "-?");
		buff[1] = bsdtar->symlink_mode;
		only_mode(bsdtar, buff, "cru");
	}
	if (bsdtar->strip_components != 0)
		only_mode(bsdtar, "--strip-components", "xt");

	switch(bsdtar->mode) {
	case 'c':
		tar_mode_c(bsdtar);
		break;
	case 'r':
		tar_mode_r(bsdtar);
		break;
	case 't':
		tar_mode_t(bsdtar);
		break;
	case 'u':
		tar_mode_u(bsdtar);
		break;
	case 'x':
		tar_mode_x(bsdtar);
		break;
	}

	lafe_cleanup_exclusions(&bsdtar->matching);
#if HAVE_REGEX_H
	cleanup_substitution(bsdtar);
#endif

	if (bsdtar->return_value != 0)
		lafe_warnc(0,
		    "Error exit delayed from previous errors.");
	return (bsdtar->return_value);
}
Пример #5
0
void main()
{
	int len, fileSize, flag, comm;

	char string[50];
	char command[10];
	char name[40];
	char *s, *s1;

	version();

	initial();


	flag = 1;
	while (flag){
		cout << endl << " 模拟文件管理模拟系统" << endl;
		cout << endl << "CD 改变目录 CREATE 创建文件 DEL 删除文件 " << endl << "LSALL 显示目录 MD 创建目录 RD 删除目录" << endl << "exit 退出" << endl;
		cout << endl << "-----------------------------------------------" << endl;
		printf("%s:>#", path);

		gets(string);
		len = strlen(string);

		if (len == 0){
			strcpy(command, "errer");
		}
		else{
			//获得命令 
			s = NULL;
			s = strchr(string, ' ');
			if (s != NULL){
				*s = '\0';
			}
			strcpy(command, string);

			//测试命令类型 
			if ((!strcmp(command, "CD")) || !strcmp(command, "cd")){
				comm = 1;
			}
			else{
				if ((!strcmp(command, "CREATE")) || !strcmp(command, "create")){
					comm = 2;
				}
				else{
					if ((!strcmp(command, "DEL")) || !strcmp(command, "del")){
						comm = 3;
					}
					else{
						if ((!strcmp(command, "LSALL")) || !strcmp(command, "lsall")){
							comm = 4;
						}
						else{
							if ((!strcmp(command, "MD")) || !strcmp(command, "md")){
								comm = 5;
							}
							else{
								if ((!strcmp(command, "RD")) || !strcmp(command, "rd")){
									comm = 6;
								}
								else{
									if ((!strcmp(command, "EXIT")) || !strcmp(command, "exit")){
										comm = 0;
									}
									else{
										comm = 100;
									}
								}
							}
						}
					}
				}
			}
			switch (comm){
			case 1:
				//1 改变目录 
				strcpy(name, s + 1);
				CD(name);
				break;
			case 2:
				//2 创建文件 
				s1 = strchr(s + 1, ' ');
				*s1 = '\0';
				strcpy(name, s + 1);
				fileSize = atoi(s1 + 1);
				CREATE(name, fileSize);
				break;
			case 3:
				//3 删除文件 
				strcpy(name, s + 1);
				DEL(name);
				break;
			case 4:
				//4 显示目录 
				LSALL();
				break;
			case 5:
				//5 创建目录 
				strcpy(name, s + 1);
				MD(name);
				break;
			case 6:
				//6 删除目录 
				strcpy(name, s + 1);
				RD(name);
				break;
			case 0:
				//0 退出系统 
				flag = 0;
				break;
			default:
				cout << "命令错误" << endl;
			}
		}
	}
}
Пример #6
0
int majorVersion()
      {
      version();
      return _majorVersion;
      }
Пример #7
0
int updateVersion()
      {
      version();
      return _updateVersion;
      }
Пример #8
0
int process_commandline(int argc, char **argv, SMSD_Parameters * params)
{
	int opt;

#ifdef HAVE_GETOPT_LONG
	struct option long_options[] = {
		{"help", 0, 0, 'h'},
		{"version", 0, 0, 'v'},
		{"config", 1, 0, 'c'},
		{"use-log", 0, 0, 'l'},
		{"no-use-log", 0, 0, 'L'},
		{0, 0, 0, 0}
	};
	int option_index;

	while ((opt =
		getopt_long(argc, argv, "+hvc:lL", long_options,
			    &option_index)) != -1) {
#elif defined(HAVE_GETOPT)
	while ((opt = getopt(argc, argv, "+hvc:lL")) != -1) {
#else
	/* Poor mans getopt replacement */
	int i, optind = -1;

#define optarg argv[++i]

	for (i = 1; i < argc; i++) {
		if (strlen(argv[i]) != 2 || argv[i][0] != '-') {
			wrong_params();
		}
		opt = argv[i][1];
#endif
		switch (opt) {
			case 'c':
				params->config_file = optarg;
				break;
			case 'v':
				version();
				break;
			case 'l':
				params->use_log = TRUE;
				break;
			case 'L':
				params->use_log = FALSE;
				break;
			case '?':
				wrong_params();
			case 'h':
				help();
				exit(0);
			default:
#if defined(HAVE_GETOPT) || defined(HAVE_GETOPT_LONG)
				wrong_params();
#else
				optind = 1;
#endif
				break;
		}
#if !defined(HAVE_GETOPT) && !defined(HAVE_GETOPT_LONG)
		if (optind != -1)
			break;
#endif
	}

	return optind;

}

#ifndef WIN32
#endif

int main(int argc, char **argv)
{
	GSM_Error error;
	int startarg;
	GSM_MultiSMSMessage sms;
	GSM_Message_Type type = SMS_SMSD;
	GSM_SMSDConfig *config;
	const char program_name[] = "gammu-smsd-inject";
	char newid[200] = { 0 };

	SMSD_Parameters params = {
		NULL,
		NULL,
		-1,
		-1,
		NULL,
		NULL,
		FALSE,
		FALSE,
		FALSE,
		FALSE,
		FALSE,
		FALSE,
		FALSE,
		FALSE,
		FALSE,
		0
	};

	/*
	 * We don't need gettext, but need to set locales so that
	 * charset conversion works.
	 */
	GSM_InitLocales(NULL);

	startarg = process_commandline(argc, argv, &params);

	if (params.config_file == NULL) {
#ifdef HAVE_DEFAULT_CONFIG
		params.config_file = default_config;
#else
		fprintf(stderr, "No config file specified!\n");
		help();
		exit(1);
#endif
	}

	error = CreateMessage(&type, &sms, argc, startarg, argv, NULL);
	if (error != ERR_NONE) {
		printf("Failed to create message: %s\n",
		       GSM_ErrorString(error));
		return 1;
	}

	config = SMSD_NewConfig(program_name);
	assert(config != NULL);

	error = SMSD_ReadConfig(params.config_file, config, params.use_log);
	if (error != ERR_NONE) {
		printf("Failed to read config: %s\n", GSM_ErrorString(error));
		SMSD_FreeConfig(config);
		return 2;
	}

	error = SMSD_InjectSMS(config, &sms, newid);
	if (error != ERR_NONE) {
		printf("Failed to inject message: %s\n",
		       GSM_ErrorString(error));
		SMSD_FreeConfig(config);
		return 3;
	}
	if (strlen(newid) == 0) {
		printf("Written message without ID\n");
	} else {
		printf("Written message with ID %s\n", newid);
	}

	SMSD_FreeConfig(config);

	return 0;
}
Пример #9
0
int main(int argc, char **argv) {
	FILE *source;
	FILE *dest;

	if (argc < 2)
		usage(argv[0]);

	bool isDoingArgs = true;

	for (char **arg = argv+1; *arg; arg++) {
		if (strncmp(*arg, "--", 2) != 0)
			isDoingArgs = false;

		if (isDoingArgs) {
			if (strcmp(*arg, "--version") == 0) {
				version();
			} else if (strcmp(*arg, "--verbose") == 0) {
				isVerbose = true;
			} else if (strncmp(*arg, "--from=", 7) == 0) {
				fromFile = (*arg)+7;
			} else if (strncmp(*arg, "--to=", 5) == 0) {
				toFile = (*arg)+5;
			} else {
				usage(argv[0]);
			}
		} else {
			if (fromFile) {
				if (toFile) {
					usage(argv[0]);
				}
				toFile = *arg;
			} else {
				fromFile = *arg;
			}
		}
	}

	if (!fromFile || !toFile)
		usage(argv[0]);

	source = fopen(fromFile, "rb");
	if (!source) {
		perror(fromFile);
		exit(1);
	}
	dest = fopen(toFile, "wb");
	if (!dest) {
		perror(toFile);
		exit(1);
	}

	char buf[16384];
	size_t len,total;
	total = 0;
	len = fread(buf, sizeof(buf[0]), sizeof(buf), source);
	while (len > 0) {
		fwrite(buf, sizeof(buf[0]), len, dest);
		total += len;
		len = fread(buf, sizeof(buf[0]), sizeof(buf), source);
	}

	fclose(dest);
	fclose(source);

	if (isVerbose)
		fprintf(stderr, "%d bytes transfered from %s to %s\n", total, fromFile, toFile);
	return 0;
}
Пример #10
0
int main(int argc, char **argv)
{
	const char *sopts = "hVvit:o:";
	struct option lopts[] = {
		{ "help", 0, 0, 'h' },
		{ "version", 0, 0, 'V' },
		{ "verbose", 0, 0, 'v' },
		{ "interactive", 0, 0, 'i' },
		{ "log", 1, 0, 'l' },
		{ "log-dir", 1, 0, 'r' },
		{ "pid-file", 1, 0, 'p' },
		{ "timestamp", 1, 0, 't' },
		{ "overflow-data", 1, 0, 'o'},
		{ 0 },
	};
	bool is_interactive = false;
	int ch;
	int syslog_option = LOG_CONS;
	int syslog_mask = LOG_MASK(LOG_WARNING)|LOG_MASK(LOG_ERR)|LOG_MASK(LOG_CRIT)|\
		          LOG_MASK(LOG_ALERT)|LOG_MASK(LOG_EMERG);
	int opt_ind = 0;
	char *pidfile = NULL;

	while ((ch = getopt_long(argc, argv, sopts, lopts, &opt_ind)) != -1) {
		switch (ch) {
		case 'h':
			usage(argv[0]);
			exit(0);
		case 'V':
			version(argv[0]);
			exit(0);
		case 'v':
#ifndef __sun__
			syslog_option |= LOG_PERROR;
#endif
			syslog_mask |= LOG_MASK(LOG_NOTICE)|LOG_MASK(LOG_INFO)| \
				      LOG_MASK(LOG_DEBUG);
			break;
		case 'i':
			is_interactive = true;
			break;
		case 'l':
		        if (!strcmp(optarg, "all")) {
			      log_hv = 1;
			      log_guest = 1;
			} else if (!strcmp(optarg, "hv")) {
			      log_hv = 1;
			} else if (!strcmp(optarg, "guest")) {
			      log_guest = 1;
			}
			break;
		case 'r':
		        log_dir = strdup(optarg);
			break;
		case 'p':
		        pidfile = strdup(optarg);
			break;
		case 't':
			if (!strcmp(optarg, "all")) {
				log_time_hv = 1;
				log_time_guest = 1;
			} else if (!strcmp(optarg, "hv")) {
				log_time_hv = 1;
			} else if (!strcmp(optarg, "guest")) {
				log_time_guest = 1;
			} else if (!strcmp(optarg, "none")) {
				log_time_guest = 0;
				log_time_hv = 0;
			}
			break;
		case 'o':
			if (!strcmp(optarg, "keep")) {
				discard_overflowed_data = 0;
			} else if (!strcmp(optarg, "discard")) {
				discard_overflowed_data = 1;
			}
			break;
		case '?':
			fprintf(stderr,
				"Try `%s --help' for more information\n",
				argv[0]);
			exit(EINVAL);
		}
	}

	if (!log_dir) {
		log_dir = strdup("/var/log/xen/console");
	}

	if (geteuid() != 0) {
		fprintf(stderr, "%s requires root to run.\n", argv[0]);
		exit(EPERM);
	}

	signal(SIGHUP, handle_hup);

	openlog("xenconsoled", syslog_option, LOG_DAEMON);
	setlogmask(syslog_mask);

	if (!is_interactive) {
		daemonize(pidfile ? pidfile : "/var/run/xenconsoled.pid");
	}

	if (!xen_setup())
		exit(1);

	handle_io();

	closelog();
	free(log_dir);
	free(pidfile);

	return 0;
}
Пример #11
0
Файл: main.c Проект: lbmeng/ufsp
int main(int argc, char **argv)
{
	const char *file = NULL;
	struct cpuid_state_t state;
	int c, ret = 0;
	int cpu_start = -2, cpu_end = -2;

	while (TRUE) {
		static struct option long_options[] = {
			{"version", no_argument, 0, 'v'},
			{"help", no_argument, 0, 'h'},
			{"sanity", no_argument, &do_sanity, 1},
			{"dump", no_argument, &do_dump, 1},
			{"cpu", required_argument, 0, 'c'},
			{"kernel", no_argument, &do_kernel, 'k'},
			{"ignore-vendor", no_argument, &ignore_vendor, 1},
			{"parse", required_argument, 0, 'f'},
			{"format", required_argument, 0, 'o'},
			{"scan-to", required_argument, 0, 2},
			{0, 0, 0, 0}
		};
		int option_index = 0;

		c = getopt_long(argc, argv, "c:hdvo:f:", long_options, &option_index);
		if (c == -1)
			break;
		switch (c) {
		case 0:
			break;
		case 2:
			assert(optarg);
			if (sscanf(optarg, "0x%x", &scan_to) != 1)
				if (sscanf(optarg, "%u", &scan_to) != 1)
					if (sscanf(optarg, "%x", &scan_to) != 1)
						scan_to = 0;
			break;
		case 'c':
			assert(optarg);
			if (sscanf(optarg, "%d", &cpu_start) != 1) {
				printf("Option --cpu= requires an integer parameter.\n");
				exit(1);
			}
			if (cpu_start < -1) {
				printf("Option --cpu= requires a value >= -1.\n");
				exit(1);
			}
			break;
		case 'd':
			do_dump = 1;
			if (cpu_start == -2 && cpu_end == -2)
				cpu_start = -1;
			break;
		case 'f':
			file = optarg;
			break;
		case 'o':
			assert(optarg);
			for (c = 0; formats[c].name != NULL; c++) {
				if (0 == strcmp(optarg, formats[c].name)) {
					do_dump = 1;
					dump_format = formats[c].value;
					break;
				}
			}
			if (!formats[c].name) {
				printf("Unrecognized format: '%s'\n", optarg);
				exit(1);
			}
			break;
		case 'v':
			version();
		case 'h':
		case '?':
		default:
			usage(argv[0]);
		}
	}

	INIT_CPUID_STATE(&state);

	if (cpu_start == -2)
		cpu_start = cpu_end = 0;

	switch(dump_format) {
	case DUMP_FORMAT_DEFAULT:
		state.cpuid_print = cpuid_dump_normal;
		break;
	case DUMP_FORMAT_VMWARE:
		cpu_start = 0;
		state.cpuid_print = cpuid_dump_vmware;
		break;
	case DUMP_FORMAT_XEN:
		cpu_start = 0;
		state.cpuid_print = cpuid_dump_xen;
		printf("cpuid = [\n");
		break;
	case DUMP_FORMAT_XEN_SXP:
		cpu_start = 0;
		state.cpuid_print = cpuid_dump_xen_sxp;
		printf("(\n");
		break;
	case DUMP_FORMAT_ETALLEN:
		state.cpuid_print = cpuid_dump_etallen;
		break;
	}

	if (file) {
		cpuid_load_from_file(file, &state);
		state.cpuid_call = cpuid_stub;
		state.thread_bind = thread_bind_stub;
		state.thread_count = thread_count_stub;
#ifdef __linux__
	} else if (do_kernel) {
		state.cpuid_call = cpuid_kernel;
#endif
	}

	if (cpu_start == -1) {
#ifdef TARGET_OS_MACOSX
		/* Because thread_bind() doesn't work on Mac. Stupidest
		 * operating system design ever.
		 */
		cpu_start = 0;
		cpu_end = 0;
#else
		cpu_start = 0;
		cpu_end = state.thread_count(&state) - 1;
#endif
	} else {
		cpu_end = cpu_start;
	}

	if ((uint32_t)cpu_start >= state.thread_count(&state)) {
		printf("CPU %d doesn't seem to exist.\n", cpu_start);
		exit(1);
	}

	for (c = cpu_start; c <= cpu_end; c++) {
		state.thread_bind(&state, c);

		switch(dump_format) {
		case DUMP_FORMAT_DEFAULT:
		case DUMP_FORMAT_ETALLEN:
			printf("CPU %d:\n", c);
			break;
		}
		run_cpuid(&state, do_dump);
	}

	switch (dump_format) {
	case DUMP_FORMAT_XEN:
		printf("]\n");
		break;
	case DUMP_FORMAT_XEN_SXP:
		printf(")\n");
		break;
	}

	if (do_sanity && !file) {
		ret = sanity_run(&state);
	}

	FREE_CPUID_STATE(&state);

	return ret;
}
Пример #12
0
bool CServerList::SaveServermetToFile()
{
	if (thePrefs.GetLogFileSaving())
		AddDebugLogLine(false, _T("Saving servers list file \"%s\""), SERVER_MET_FILENAME);
	m_nLastSaved = ::GetTickCount(); 
	CString newservermet(thePrefs.GetConfigDir());
	newservermet += SERVER_MET_FILENAME _T(".new");
	CSafeBufferedFile servermet;
	CFileException fexp;
	if (!servermet.Open(newservermet, CFile::modeWrite|CFile::modeCreate|CFile::typeBinary|CFile::shareDenyWrite, &fexp)){
		CString strError(GetResString(IDS_ERR_SAVESERVERMET));
		TCHAR szError[MAX_CFEXP_ERRORMSG];
		if (fexp.GetErrorMessage(szError, ARRSIZE(szError))){
			strError += _T(" - ");
			strError += szError;
		}
		LogError(LOG_STATUSBAR, _T("%s"), strError);
		return false;
	}
	setvbuf(servermet.m_pStream, NULL, _IOFBF, 16384);
	
	try{
		servermet.WriteUInt8(0xE0);
		
		UINT fservercount = list.GetCount();
		servermet.WriteUInt32(fservercount);
		
		for (UINT j = 0; j < fservercount; j++)
		{
			const CServer* nextserver = GetServerAt(j);

			servermet.WriteUInt32(nextserver->GetIP());
			servermet.WriteUInt16(nextserver->GetPort());
			
			uint32 uTagCount = 0;
			ULONG uTagCountFilePos = (ULONG)servermet.GetPosition();
			servermet.WriteUInt32(uTagCount);

			if (!nextserver->GetListName().IsEmpty()){
				if (WriteOptED2KUTF8Tag(&servermet, nextserver->GetListName(), ST_SERVERNAME))
					uTagCount++;
				CTag servername(ST_SERVERNAME, nextserver->GetListName());
				servername.WriteTagToFile(&servermet);
				uTagCount++;
			}
			
			if (!nextserver->GetDynIP().IsEmpty()){
				if (WriteOptED2KUTF8Tag(&servermet, nextserver->GetDynIP(), ST_DYNIP))
					uTagCount++;
				CTag serverdynip(ST_DYNIP, nextserver->GetDynIP());
				serverdynip.WriteTagToFile(&servermet);
				uTagCount++;
			}
			
			if (!nextserver->GetDescription().IsEmpty()){
				if (WriteOptED2KUTF8Tag(&servermet, nextserver->GetDescription(), ST_DESCRIPTION))
					uTagCount++;
				CTag serverdesc(ST_DESCRIPTION, nextserver->GetDescription());
				serverdesc.WriteTagToFile(&servermet);
				uTagCount++;
			}
			
			if (nextserver->GetFailedCount()){
				CTag serverfail(ST_FAIL, nextserver->GetFailedCount());
				serverfail.WriteTagToFile(&servermet);
				uTagCount++;
			}
			
			if (nextserver->GetPreferences() != SRV_PR_NORMAL){
				CTag serverpref(ST_PREFERENCE, nextserver->GetPreferences());
				serverpref.WriteTagToFile(&servermet);
				uTagCount++;
			}
			
			if (nextserver->GetUsers()){
				CTag serveruser("users", nextserver->GetUsers());
				serveruser.WriteTagToFile(&servermet);
				uTagCount++;
			}
			
			if (nextserver->GetFiles()){
				CTag serverfiles("files", nextserver->GetFiles());
				serverfiles.WriteTagToFile(&servermet);
				uTagCount++;
			}
			
			if (nextserver->GetPing()){
				CTag serverping(ST_PING, nextserver->GetPing());
				serverping.WriteTagToFile(&servermet);
				uTagCount++;
			}
			
			if (nextserver->GetLastPingedTime()){
				CTag serverlastp(ST_LASTPING, nextserver->GetLastPingedTime());
				serverlastp.WriteTagToFile(&servermet);
				uTagCount++;
			}
			
			if (nextserver->GetMaxUsers()){
				CTag servermaxusers(ST_MAXUSERS, nextserver->GetMaxUsers());
				servermaxusers.WriteTagToFile(&servermet);
				uTagCount++;
			}
			
			if (nextserver->GetSoftFiles()){
				CTag softfiles(ST_SOFTFILES, nextserver->GetSoftFiles());
				softfiles.WriteTagToFile(&servermet);
				uTagCount++;
			}
			
			if (nextserver->GetHardFiles()){
				CTag hardfiles(ST_HARDFILES, nextserver->GetHardFiles());
				hardfiles.WriteTagToFile(&servermet);
				uTagCount++;
			}
			
			if (!nextserver->GetVersion().IsEmpty()){
				// as long as we don't receive an integer version tag from the local server (TCP) we store it as string
				CTag version(ST_VERSION, nextserver->GetVersion());
				version.WriteTagToFile(&servermet);
				uTagCount++;
			}
			
			if (nextserver->GetUDPFlags()){
				CTag tagUDPFlags(ST_UDPFLAGS, nextserver->GetUDPFlags());
				tagUDPFlags.WriteTagToFile(&servermet);
				uTagCount++;
			}
			
			if (nextserver->GetLowIDUsers()){
				CTag tagLowIDUsers(ST_LOWIDUSERS, nextserver->GetLowIDUsers());
				tagLowIDUsers.WriteTagToFile(&servermet);
				uTagCount++;
			}

			servermet.Seek(uTagCountFilePos, CFile::begin);
			servermet.WriteUInt32(uTagCount);
			servermet.SeekToEnd();
		}

		if (thePrefs.GetCommitFiles() >= 2 || (thePrefs.GetCommitFiles() >= 1 && !theApp.emuledlg->IsRunning())){
			servermet.Flush(); // flush file stream buffers to disk buffers
			if (_commit(_fileno(servermet.m_pStream)) != 0) // commit disk buffers to disk
				AfxThrowFileException(CFileException::hardIO, GetLastError(), servermet.GetFileName());
		}
		servermet.Close();

		CString curservermet(thePrefs.GetConfigDir());
		CString oldservermet(thePrefs.GetConfigDir());
		curservermet += SERVER_MET_FILENAME;
		oldservermet += _T("server_met.old");
		
		if (_taccess(oldservermet, 0) == 0)
			CFile::Remove(oldservermet);
		if (_taccess(curservermet, 0) == 0)
			CFile::Rename(curservermet,oldservermet);
		CFile::Rename(newservermet,curservermet);
	}
	catch(CFileException* error) {
		CString strError(GetResString(IDS_ERR_SAVESERVERMET2));
		TCHAR szError[MAX_CFEXP_ERRORMSG];
		if (error->GetErrorMessage(szError, ARRSIZE(szError))){
			strError += _T(" - ");
			strError += szError;
		}
		LogError(LOG_STATUSBAR, _T("%s"), strError);
		error->Delete();
		return false;
	}
	return true;
}
int main(int argc, char* argv[])
{
    po::options_description options("Options");
    // Don't use default values because the help print it ugly and too wide
    options.add_options()
        ("move,m", "move files rather than copy")
        ("symlink,s", "symlink files rather than copy (posix only)")
        ("order,o", po::value<std::string>(), 
            "order and types of metadata to read\ne=exif, i=iptc, f=file (default: eif)")
        ("unsorted,u", po::value<std::string>(), 
            "special directory to store unsorted files (default: unsorted)")
        ("dups,d", po::value<std::string>(), 
            "special directory to store files with duplicate names (default: duplicates)")
        ("force,f", "overwrite duplicate files instead of using special directory")
        ("rename,r", "rename duplicate files instead of using special directory")
        ("ignore,i", "ignore both unsorted and duplicate files instead of using special directories")
        ("ignore-unsorted", "ignore unsorted files instead of using special directory")
        ("ignore-dups", "ignore duplicate files instead of using special directory")
        ("verify", "verify copied or moved files and exit if incorrect")
        ("exclude,x", po::value< std::vector<std::string> >(), 
            "exclude directories and files that contain arg (case sensitive on all platforms)")
        ("limit-depth,l", po::value<long>(), 
            "limit recursion to specified depth (0 disables recursion)")
        ("verbose,v", "prints operations as they happen")
        ("dry-run,n", "do not make actual changes (implies verbose)")
        ("help,h", "show this help message then exit")
        ("version,V", "show program version then exit")
        ;

    po::options_description hidden("Hidden Options");
    hidden.add_options()
        ("source-dir", po::value< std::string >(), "directory of files to organize, may end in file wildcard")
        ("dest-dir", po::value< std::string >(), "desination directory for files, may not be within source-dir")
        ("pattern", po::value< std::string >(), "subdirectory pattern for grouping files within dest-dir")
        ;

    po::options_description cmdline;
    cmdline.add(options).add(hidden);

    po::positional_options_description positional;
    positional.add("source-dir", 1);
    positional.add("dest-dir", 1);
    positional.add("pattern", 1);

    try {
        po::variables_map vm;
        po::store(po::command_line_parser(argc, argv).
        options(cmdline).positional(positional).run(), vm);
        po::notify(vm);

        if (vm.count("help")) {
            usage_full(options, argv[0]);
            return 0;
        }
    
        if (vm.count("version")) {
            version();
            return 0;
        }
    
        conflicting(vm, "verify", "symlink");
        conflicting(vm, "move", "symlink");
        conflicting(vm, "unsorted", "ignore");
        conflicting(vm, "unsorted", "ignore-unsorted");
        conflicting(vm, "dups", "ignore");
        conflicting(vm, "dups", "ignore-dups");
        conflicting(vm, "force", "ignore");
        conflicting(vm, "force", "ignore-dups");
        conflicting(vm, "force", "rename");
        conflicting(vm, "rename", "ignore");
        conflicting(vm, "rename", "ignore-dups");
        required(vm, "source-dir");
        required(vm, "dest-dir");
        required(vm, "pattern");
    
        const bool dry_run = vm.count("dry-run") != 0;
        g_verbose = (vm.count("verbose") != 0 || dry_run);
    
        std::string order = "eif";
        if(vm.count("order")) {
            order = vm["order"].as<std::string>();
    
            boost::to_lower(order);
            if(order.length() > 3) {
                throw std::logic_error(std::string("order is longer than 4 characters"));
            }
        }
    
        unsigned i = 0;
        std::string::iterator end = order.end();
        for(std::string::iterator iter = order.begin(); iter != end && i < 4; ++iter, ++i) {
            switch(*iter) {
                case 'e': 
                    g_run_order[i] = EXIF_SLOT;
                    break;
                case 'i': 
                    g_run_order[i] = IPTC_SLOT;
                    break;
                case 'x': 
                    throw std::logic_error(std::string("xmp not implemented yet '") + 
                        *iter + "'");
                    break;
                case 'f': 
                    g_run_order[i] = FILE_SLOT;
                    break;
                default:
                    throw std::logic_error(std::string("unknown order character '") + 
                        *iter + "'");
            }
        }
    
        const fs::path source_dir( vm["source-dir"].as<std::string>() );
        if( !exists(source_dir) || !is_directory(source_dir) ) {
            throw std::logic_error(std::string("source '") + 
                source_dir.string() + "' must exist and be a directory");
        }
    
        const fs::path dest_dir( vm["dest-dir"].as<std::string>() );
        if( exists(dest_dir) && !is_directory(dest_dir) ) {
            throw std::logic_error(std::string("destination '") + 
                dest_dir.string() + "' must be a directory");
        }
    
        // Boost doesn't seem to have a way to get a canonical path, so this
        // simple test is easy to confuse with some ../../'s in the paths. Oh
        // well, this is good enough for now.
        fs::path test_dest(dest_dir);
        for(; !test_dest.empty(); test_dest = test_dest.parent_path()) {
            if(fs::equivalent(source_dir, test_dest)) {
                throw std::logic_error(std::string("dest-dir must not be within source-dir"));
            }
        }
    
        // Disect the pattern
        std::string pattern = vm["pattern"].as<std::string>();
        boost::regex regex( "([^@]*)(@[[:alpha:]]+)([^@]*)");
        boost::sregex_iterator m_iter = make_regex_iterator(pattern, regex);
        boost::sregex_iterator m_end;
        for( ; m_iter != m_end; ++m_iter) {
            const boost::smatch &match = *m_iter;
            const std::string &pre = match[1];
            const std::string &pat = match[2];
            const std::string &post = match[3];
    
            // Should put this in a map, but there aren't that many options now
            bool found = false;
            for( const Pattern *pattern = g_patterns; pattern->pat.length(); ++pattern) {
                if(pattern->pat == pat) {
                    PathPart part(pre, pattern, post);
                    g_path_parts.push_back(part);
                    found = true;
                    break;
                }
            }
        
            if(!found) {
                throw std::logic_error(std::string("unknown pattern '") + pat + "'");
            }
        }
    
        // Assign defaults to params that need them
        const bool ignore = vm.count("ignore") != 0;
        std::vector<std::string> excludes;
        if(vm.count("exclude"))
            excludes = vm["exclude"].as< std::vector<std::string> >();
        long limit_depth = LONG_MAX;
        if(vm.count("limit-depth")) {
            limit_depth = vm["limit-depth"].as<long>();
            // Boost program_options doesn't work with unsigned, so do it manually
            if( limit_depth < 0 )
                throw std::logic_error(std::string("recursion depth limit must be positive"));
        }
        std::string dups = "duplicates";
        if(vm.count("dups"))
            dups = vm["dups"].as<std::string>();
        const fs::path dups_dir = dest_dir / dups;
    
        std::string unsorted = "unsorted";
        if(vm.count("unsorted"))
            unsorted = vm["unsorted"].as<std::string>();
        const fs::path unsorted_dir = dest_dir / unsorted;
    
        ProcessParams params = {
            dest_dir, 
            dry_run,
            (vm.count("ignore-dups") != 0 || ignore), 
            (vm.count("ignore-unsorted") != 0 || ignore), 
            vm.count("force") != 0,
            vm.count("rename") != 0,
            vm.count("symlink") != 0, 
            vm.count("verify") != 0, 
            vm.count("move") != 0, 
            limit_depth, 
            dups_dir, 
            unsorted_dir, 
            excludes,
            0, 0, 0, 0, 0, 0, 0, 0, 0
        };
    
        process_directory(source_dir, 0, params);
    
        std::string op = "copied";
        if(params.symlink)
            op = "linked";
        else if(params.move)
            op = "moved";
    
        if(dry_run)
            op = std::string("would be ") + op;
    
        if(g_neednewline)
            std::cout << "\n";
    
        std::cout << "\n" << params.ok_count << " files " << op << "\n";
        std::cout << "   " << params.dups_count << " duplicates\n";
        std::cout << "   " << params.unsorted_count << " unsorted\n";
        if(params.dups_ignored_count)
            std::cout << params.dups_ignored_count << " duplicates ignored\n";
        if(params.unsorted_ignored_count)
            std::cout << params.unsorted_ignored_count << " unsorted ignored\n";
        if(params.dir_ex_count)
            std::cout << params.dir_ex_count << " directories excluded\n";
        if(params.file_ex_count)
            std::cout << params.file_ex_count << " files excluded\n";
        if(params.dir_err_count)
            std::cout << params.dir_err_count << " directory errors\n";
        if(params.file_err_count)
            std::cout << params.file_err_count << " file errors\n";
    
        return 0;
    }
    catch (Exiv2::AnyError& e) {
        error(e, std::string("Aborting"));
        return -1;
    }
    catch(std::logic_error& e) {
        error(e, "");
        usage_header(argv[0]);
        std::cout << argv[0] << " -h    for more help" << std::endl;
        return -2;
    }
    catch(std::exception& e) {
        error(e, "Aborting");
        return -3;
    }
}
Пример #14
0
int main(int argc, char **argv)
{
	int ret = 0, c, opt_index, udp = 0, ipv4 = -1, daemon = 1, log = 1;
	char *port = NULL, *stun = NULL, *dev = NULL, *home = NULL, *alias = NULL;
	enum working_mode wmode = MODE_UNKNOW;

	setfsuid(getuid());
	setfsgid(getgid());

	home = fetch_home_dir();

	while ((c = getopt_long(argc, argv, short_options, long_options,
	       &opt_index)) != EOF) {
		switch (c) {
		case 'h':
			help();
			break;
		case 'v':
			version();
			break;
		case 'D':
			daemon = 0;
			break;
		case 'N':
			log = 0;
			break;
		case 'C':
			wmode = MODE_DUMPC;
			break;
		case 'S':
			wmode = MODE_DUMPS;
			break;
		case 'c':
			wmode = MODE_CLIENT;
			if (optarg) {
				if (*optarg == '=')
					optarg++;
				alias = xstrdup(optarg);
			}
			break;
		case 'd':
			dev = xstrdup(optarg);
			break;
		case 'k':
			wmode = MODE_KEYGEN;
			break;
		case '4':
			ipv4 = 1;
			break;
		case '6':
			ipv4 = 0;
			break;
		case 'x':
			wmode = MODE_EXPORT;
			break;
		case 's':
			wmode = MODE_SERVER;
			break;
		case 'u':
			udp = 1;
			break;
		case 't':
			stun = xstrdup(optarg);
			break;
		case 'p':
			port = xstrdup(optarg);
			break;
		case '?':
			switch (optopt) {
			case 't':
			case 'd':
			case 'u':
			case 'p':
				panic("Option -%c requires an argument!\n",
				      optopt);
			default:
				if (isprint(optopt))
					printf("Unknown option character `0x%X\'!\n", optopt);
				die();
			}
		default:
			break;
		}
	}

	if (argc < 2)
		help();

	register_signal(SIGINT, signal_handler);
	register_signal(SIGHUP, signal_handler);
	register_signal(SIGTERM, signal_handler);
	register_signal(SIGPIPE, signal_handler);

	curve25519_selftest();

	switch (wmode) {
	case MODE_KEYGEN:
		ret = main_keygen(home);
		break;
	case MODE_EXPORT:
		ret = main_export(home);
		break;
	case MODE_DUMPC:
		ret = main_dumpc(home);
		break;
	case MODE_DUMPS:
		ret = main_dumps(home);
		break;
	case MODE_CLIENT:
		ret = main_client(home, dev, alias, daemon);
		break;
	case MODE_SERVER:
		if (!port)
			panic("No port specified!\n");
		if (stun)
			print_stun_probe(stun, 3478, strtoul(port, NULL, 10));
		ret = main_server(home, dev, port, udp, ipv4, daemon, log);
		break;
	default:
		die();
	}

	free(dev);
	free(stun);
	free(port);
	free(alias);

	return ret;
}
Пример #15
0
int main (int argc, char **argv) {
    int c, j;
    int reel_count=0;
    int height = 0;
    int width  = 0;
    char buffer[80];
    opendcp_t *opendcp;
    reel_list_t reel_list[MAX_REELS];

    if ( argc <= 1 ) {
        dcp_usage();
    }

    opendcp = opendcp_create();

    /* parse options */
    while (1)
    {
        static struct option long_options[] =
        {
            {"annotation",     required_argument, 0, 'a'},
            {"base",           required_argument, 0, 'b'},
            {"digest",         no_argument,       0, 'd'},
            {"duration",       required_argument, 0, 'n'},
            {"entry",          required_argument, 0, 'e'},
            {"help",           no_argument,       0, 'h'},
            {"issuer",         required_argument, 0, 'i'},
            {"kind",           required_argument, 0, 'k'},
            {"log_level",      required_argument, 0, 'l'},
            {"rating",         required_argument, 0, 'm'},
            {"reel",           required_argument, 0, 'r'},
            {"title",          required_argument, 0, 't'},
            {"root",           required_argument, 0, '1'},
            {"ca",             required_argument, 0, '2'},
            {"signer",         required_argument, 0, '3'},
            {"privatekey",     required_argument, 0, 'p'},
            {"sign",           no_argument,       0, 's'},
            {"height",         required_argument, 0, 'y'},
            {"width",          required_argument, 0, 'x'},
            {"version",        no_argument,       0, 'v'},
            {0, 0, 0, 0}
        };

        /* getopt_long stores the option index here. */
        int option_index = 0;

        c = getopt_long (argc, argv, "a:b:e:svdhi:k:r:l:m:n:t:x:y:p:1:2:3:",
                         long_options, &option_index);

        /* Detect the end of the options. */
        if (c == -1)
            break;

        switch (c)
        {
            case 0:
                /* If this option set a flag, do nothing else now. */
                if (long_options[option_index].flag != 0)
                   break;
            break;

            case 'a':
               sprintf(opendcp->dcp.annotation,"%.128s",optarg);
            break;

            case 'b':
               sprintf(opendcp->dcp.basename,"%.80s",optarg);
            break;

            case 'd':
               opendcp->dcp.digest_flag = 1;
            break;

            case 'e':
               opendcp->entry_point = atoi(optarg);
            break;

            case 'h':
               dcp_usage();
            break;

            case 'i':
               sprintf(opendcp->dcp.issuer,"%.80s",optarg);
            break;

            case 'k':
               sprintf(opendcp->dcp.kind,"%.15s",optarg);
            break;

            case 'l':
               opendcp->log_level = atoi(optarg);
            break;

            case 'm':
               if ( !strcmp(optarg,"G")
                    || !strcmp(optarg,"PG")
                    || !strcmp(optarg,"PG-13")
                    || !strcmp(optarg,"R")
                    || !strcmp(optarg,"NC-17") ) {
                   sprintf(opendcp->dcp.rating,"%.5s",optarg);
               } else {
                   sprintf(buffer,"Invalid rating %s\n",optarg);
                   dcp_fatal(opendcp,buffer);
               }
            break;

            case 'n':
               opendcp->duration = atoi(optarg);
            break;

            case 'r':
               j = 0;
               optind--;
               while ( optind<argc && strncmp("-",argv[optind],1) != 0) {
                   sprintf(reel_list[reel_count].asset_list[j++].filename,"%s",argv[optind++]);
               }
               reel_list[reel_count++].asset_count = j--;
            break;

#ifdef XMLSEC
            case 's':
                opendcp->xml_signature.sign = 1;
            break;
#endif

            case 't':
               sprintf(opendcp->dcp.title,"%.80s",optarg);
            break;

            case 'x':
               width = atoi(optarg);
            break;

            case 'y':
               height = atoi(optarg);
            break;

            case '1':
               opendcp->xml_signature.root = optarg;
               opendcp->xml_signature.use_external = 1;
            break;

            case '2':
               opendcp->xml_signature.ca = optarg;
               opendcp->xml_signature.use_external = 1;
            break;

            case '3':
               opendcp->xml_signature.signer = optarg;
               opendcp->xml_signature.use_external = 1;
            break;

            case 'p':
               opendcp->xml_signature.private_key = optarg;
               opendcp->xml_signature.use_external = 1;
            break;

            case 'v':
               version();
            break;

            default:
               dcp_usage();
        }
    }

    /* set log level */
    dcp_set_log_level(opendcp->log_level);

    if (opendcp->log_level > 0) {
        printf("\nOpenDCP XML %s %s\n",OPENDCP_VERSION,OPENDCP_COPYRIGHT);
    }

    if (reel_count < 1) {
        dcp_fatal(opendcp,"No reels supplied");
    }

    /* check cert files */
    if (opendcp->xml_signature.sign && opendcp->xml_signature.use_external == 1) {
        FILE *tp;
        if (opendcp->xml_signature.root) {
            tp = fopen(opendcp->xml_signature.root,"rb");
            if (tp) {
                fclose(tp);
            } else {
                dcp_fatal(opendcp,"Could not read root certificate");
            }
        } else {
            dcp_fatal(opendcp,"XML digital signature certifcates enabled, but root certificate file not specified");
        }
        if (opendcp->xml_signature.ca) {
            tp = fopen(opendcp->xml_signature.ca,"rb");
            if (tp) {
                fclose(tp);
            } else {
                dcp_fatal(opendcp,"Could not read ca certificate");
            }
        } else {
            dcp_fatal(opendcp,"XML digital signature certifcates enabled, but ca certificate file not specified");
        }
        if (opendcp->xml_signature.signer) {
            tp = fopen(opendcp->xml_signature.signer,"rb");
            if (tp) {
                fclose(tp);
            } else {
                dcp_fatal(opendcp,"Could not read signer certificate");
            }
        } else {
            dcp_fatal(opendcp,"XML digital signature certifcates enabled, but signer certificate file not specified");
        }
        if (opendcp->xml_signature.private_key) {
            tp = fopen(opendcp->xml_signature.private_key,"rb");
            if (tp) {
                fclose(tp);
            } else {
                dcp_fatal(opendcp,"Could not read private key file");
            }
        } else {
            dcp_fatal(opendcp,"XML digital signature certifcates enabled, but private key file not specified");
        }
    }

    /* set aspect ratio override */
    if (width || height) {
        if (!height) {
            dcp_fatal(opendcp,"You must specify height, if you specify width");
        }

        if (!width) {
            dcp_fatal(opendcp,"You must specify widht, if you specify height");
        }

        sprintf(opendcp->dcp.aspect_ratio,"%d %d",width,height);
    }

    /* add pkl to the DCP (only one PKL currently support) */
    pkl_t pkl;
    create_pkl(opendcp->dcp, &pkl);
    add_pkl_to_dcp(&opendcp->dcp, pkl);

    /* add cpl to the DCP/PKL (only one CPL currently support) */
    cpl_t cpl;
    create_cpl(opendcp->dcp, &cpl);
    add_cpl_to_pkl(&opendcp->dcp.pkl[0], cpl);

    /* set the callbacks (optional) for the digest generator */
    if (opendcp->log_level>0 && opendcp->log_level<3) {
        opendcp->dcp.sha1_update.callback = sha1_update_done_cb;
    }

    /* Add and validate reels */
    for (c = 0; c<reel_count; c++) {
        int a;
        reel_t reel;
        create_reel(opendcp->dcp, &reel);

        for (a = 0; a < reel_list[c].asset_count; a++) {
            val   = 0;
            asset_t asset;
            add_asset(opendcp, &asset, reel_list[c].asset_list[a].filename);
            sprintf(progress_string, "%-.25s %.25s", asset.filename, "Digest Calculation");
            total = atoi(asset.size) / read_size;
            if (opendcp->log_level>0 && opendcp->log_level<3) {
                printf("\n");
                progress_bar();
            }
            calculate_digest(opendcp, asset.filename, asset.digest);
            add_asset_to_reel(opendcp, &reel, asset);
        }

        if (validate_reel(opendcp, &reel, c) == OPENDCP_NO_ERROR) {
            add_reel_to_cpl(&opendcp->dcp.pkl[0].cpl[0], reel);
        } else {
            sprintf(buffer,"Could not validate reel %d\n",c+1);
            dcp_fatal(opendcp,buffer);
        }
    }

    /* set ASSETMAP/VOLINDEX path */
    if (opendcp->ns == XML_NS_SMPTE) {
        sprintf(opendcp->dcp.assetmap.filename,"%s","ASSETMAP.xml");
        sprintf(opendcp->dcp.volindex.filename,"%s","VOLINDEX.xml");
    } else {
        sprintf(opendcp->dcp.assetmap.filename,"%s","ASSETMAP");
        sprintf(opendcp->dcp.volindex.filename,"%s","VOLINDEX");
    }

    /* Write CPL File */
    if (opendcp->log_level>0 && opendcp->log_level<3) {
        printf("\n");
        sprintf(progress_string, "%-.50s", opendcp->dcp.pkl[0].cpl[0].filename);
        progress_bar();
    }
    if (write_cpl(opendcp, &opendcp->dcp.pkl[0].cpl[0]) != OPENDCP_NO_ERROR)
        dcp_fatal(opendcp,"Writing composition playlist failed");

    /* Write PKL File */
    if (opendcp->log_level>0 && opendcp->log_level<3) {
        printf("\n");
        sprintf(progress_string, "%-.50s", opendcp->dcp.pkl[0].filename);
        progress_bar();
    }
    if (write_pkl(opendcp, &opendcp->dcp.pkl[0]) != OPENDCP_NO_ERROR)
        dcp_fatal(opendcp,"Writing packing list failed");

    if (opendcp->log_level>0 && opendcp->log_level<3) {
        printf("\n");
        sprintf(progress_string, "%-.50s", opendcp->dcp.assetmap.filename);
        progress_bar();
    }
    if (write_volumeindex(opendcp) != OPENDCP_NO_ERROR)
        dcp_fatal(opendcp,"Writing volume index failed");

    if (opendcp->log_level>0 && opendcp->log_level<3) {
        printf("\n");
        sprintf(progress_string, "%-.50s", opendcp->dcp.volindex.filename);
        progress_bar();
    }
    if (write_assetmap(opendcp) != OPENDCP_NO_ERROR)
        dcp_fatal(opendcp,"Writing asset map failed");

    dcp_log(LOG_INFO,"DCP Complete");

    if (opendcp->log_level > 0) {
        printf("\nDCP Creation Done\n");
    }

    opendcp_delete(opendcp);

    exit(0);
}
Пример #16
0
/******************************************************************************
 *                                                                            *
 * Function: main                                                             *
 *                                                                            *
 * Purpose: executes server processes                                         *
 *                                                                            *
 * Author: Eugene Grigorjev                                                   *
 *                                                                            *
 ******************************************************************************/
int	main(int argc, char **argv)
{
	zbx_task_t	task = ZBX_TASK_START;
	char		ch = '\0';
	int		nodeid = 0;

#if defined(PS_OVERWRITE_ARGV) || defined(PS_PSTAT_ARGV)
	argv = setproctitle_save_env(argc, argv);
#endif
	progname = get_program_name(argv[0]);

	/* parse the command-line */
	while ((char)EOF != (ch = (char)zbx_getopt_long(argc, argv, shortopts, longopts, NULL)))
	{
		switch (ch)
		{
			case 'c':
				CONFIG_FILE = zbx_strdup(CONFIG_FILE, zbx_optarg);
				break;
			case 'R':
				if (0 == strcmp(zbx_optarg, ZBX_CONFIG_CACHE_RELOAD))
					task = ZBX_TASK_CONFIG_CACHE_RELOAD;
				else
				{
					printf("invalid runtime control option: %s\n", zbx_optarg);
					exit(EXIT_FAILURE);
				}
				break;
			case 'h':
				help();
				exit(-1);
				break;
			case 'n':
				nodeid = (NULL == zbx_optarg ? 0 : atoi(zbx_optarg));
				task = ZBX_TASK_CHANGE_NODEID;
				break;
			case 'V':
				version();
				exit(-1);
				break;
			default:
				usage();
				exit(-1);
				break;
		}
	}

	if (NULL == CONFIG_FILE)
		CONFIG_FILE = zbx_strdup(CONFIG_FILE, SYSCONFDIR "/zabbix_server.conf");

	/* required for simple checks */
	init_metrics();

	zbx_load_config();

	if (ZBX_TASK_CONFIG_CACHE_RELOAD == task)
		exit(SUCCEED == zbx_sigusr_send(ZBX_TASK_CONFIG_CACHE_RELOAD) ? EXIT_SUCCESS : EXIT_FAILURE);

#ifdef HAVE_OPENIPMI
	init_ipmi_handler();
#endif

	switch (task)
	{
		case ZBX_TASK_CHANGE_NODEID:
			exit(SUCCEED == change_nodeid(nodeid) ? EXIT_SUCCESS : EXIT_FAILURE);
			break;
		default:
			break;
	}

	return daemon_start(CONFIG_ALLOW_ROOT);
}
Пример #17
0
int main(int argc, char *argv[]) {
    int i, j = 0;
    char **newargv = (char**) calloc(argc + 2, sizeof(char*));
    ATsetWarningHandler(WarningHandler);
    ATsetErrorHandler(ErrorHandler);
    if (!newargv) ATerror("Cannot allocate array argv");  
    newargv[j++] = argv[0]; newargv[j++] = "-no-extra-rules";
    ATinit(argc, argv, (ATerm*) &argc);
    ATprotect((ATerm*) &smds);
    ATprotect((ATerm*) &pars);
    ATprotect((ATerm*) &inits);
    ATprotect((ATerm*) &vars);
    ATprotect((ATerm*) &actnames);
    ATprotect((ATerm*) &actargs);
    vars = actnames = actargs = ATempty;
    for (i=1;i<argc;i++) {
    if (!strcmp(argv[i],"-help")) {
	help();
	exit(0);
	}
    if (!strcmp(argv[i],"-version")) {
	version();
	exit(0);
	}
   if (!strcmp(argv[i],"-pars")) {
	pars = ATempty;
        continue;
	}
   if (!strcmp(argv[i],"-npars")) {
	npars = ATtrue;
        continue;
	}
   if (!strcmp(argv[i],"-extra")) {
	extra = ATtrue;
        continue;
	}
    newargv[j++] = argv[i];
    }
    if (extra) {
         if (!MCRLinitRW(j, newargv)) exit(EXIT_FAILURE);
         RWdeclareVariables(MCRLgetListOfPars());
         }
    else
    {if (!MCRLinitSU(j, newargv)) exit(EXIT_FAILURE);}
    if (npars) {
        fprintf(stdout,"%d", MCRLgetNumberOfPars());
        exit(EXIT_SUCCESS);
        }
    smds = MCRLgetListOfSummands();
    if (pars) {
         pars = MCRLgetListOfPars();
         inits = MCRLgetListOfInitValues();
         }
    ATfprintf(stdout, "Number of process parameters: %d\n", 
          MCRLgetNumberOfPars());
    ATfprintf(stdout, "Number of summands: %d\n",ATgetLength(smds));
    for (;!ATisEmpty(smds);smds=ATgetNext(smds)) {
         ATerm smd = ATgetFirst(smds);
         ATerm actname = ATgetArgument((ATermAppl) smd, 1),
               actarg = ATgetArgument((ATermAppl) smd, 2);
         vars = ATconcat(vars, (ATermList) ATgetArgument((ATermAppl) smd, 0));
         if (ATindexOf(actnames , actname, 0) < 0 || 
               ATindexOf(actargs , actarg, 0)<0) {
                actnames = ATinsert(actnames, actname); 
                actargs = ATinsert(actargs, actarg);
                }
         if (extra) {
                if (!ATisEmpty(vars)) ATerror(
                "Flag -extra cannot be used, there are sum variables present");
                DisabledEdges(
                   (ATermList) ATgetArgument(
                      (ATermAppl)ATgetArgument((ATermAppl) smd, 3), 0));
                }
         }
    ATfprintf(stdout, "Number of sum variables: %d\n", ATgetLength(vars));
    ATfprintf(stdout, "Number of different action names: %d\n", 
               ATgetLength(actnames));
    if (pars) {
        ATfprintf(stdout, "Process parameters\n");
        for (i=1;!ATisEmpty(pars)&&!ATisEmpty(inits);
             pars=ATgetNext(pars), inits=ATgetNext(inits),i++) {
             ATerm par = ATgetFirst(pars);
             ATfprintf(stdout, "%t:\t%t\tinit[%d]=%t\n", MCRLprint(
                   ATgetArgument((ATermAppl)par, 0)),
                   MCRLprint(ATgetArgument((ATermAppl)par, 1)),
                   i, MCRLprint(ATgetFirst(inits))); 
             }
       }
    exit(EXIT_SUCCESS); 
    }
Пример #18
0
/*
 *	The main guy.
 */
int main(int argc, char *argv[])
{
    int rcode = EXIT_SUCCESS;
    int status;
    int argval;
    bool spawn_flag = true;
    bool write_pid = false;
    bool display_version = false;
    int flag = 0;
    int from_child[2] = {-1, -1};

    /*
     *	We probably don't want to free the talloc autofree context
     *	directly, so we'll allocate a new context beneath it, and
     *	free that before any leak reports.
     */
    TALLOC_CTX *autofree = talloc_init("main");

    /*
     *	If the server was built with debugging enabled always install
     *	the basic fatal signal handlers.
     */
#ifndef NDEBUG
    if (fr_fault_setup(getenv("PANIC_ACTION"), argv[0]) < 0) {
        fr_perror("radiusd");
        exit(EXIT_FAILURE);
    }
#endif

#ifdef OSFC2
    set_auth_parameters(argc,argv);
#endif

    if ((progname = strrchr(argv[0], FR_DIR_SEP)) == NULL)
        progname = argv[0];
    else
        progname++;

#ifdef WIN32
    {
        WSADATA wsaData;
        if (WSAStartup(MAKEWORD(2, 0), &wsaData)) {
            fprintf(stderr, "%s: Unable to initialize socket library.\n", progname);
            exit(EXIT_FAILURE);
        }
    }
#endif

    debug_flag = 0;
    set_radius_dir(autofree, RADIUS_DIR);

    /*
     *	Ensure that the configuration is initialized.
     */
    memset(&main_config, 0, sizeof(main_config));
    main_config.myip.af = AF_UNSPEC;
    main_config.port = 0;
    main_config.name = "radiusd";
    main_config.daemonize = true;

    /*
     *	Don't put output anywhere until we get told a little
     *	more.
     */
    default_log.dst = L_DST_NULL;
    default_log.fd = -1;
    main_config.log_file = NULL;

    /*  Process the options.  */
    while ((argval = getopt(argc, argv, "Cd:D:fhi:l:mMn:p:PstvxX")) != EOF) {

        switch(argval) {
        case 'C':
            check_config = true;
            spawn_flag = false;
            main_config.daemonize = false;
            break;

        case 'd':
            set_radius_dir(autofree, optarg);
            break;

        case 'D':
            main_config.dictionary_dir = talloc_typed_strdup(NULL, optarg);
            break;

        case 'f':
            main_config.daemonize = false;
            break;

        case 'h':
            usage(0);
            break;

        case 'l':
            if (strcmp(optarg, "stdout") == 0) {
                goto do_stdout;
            }
            main_config.log_file = strdup(optarg);
            default_log.dst = L_DST_FILES;
            default_log.fd = open(main_config.log_file,
                                  O_WRONLY | O_APPEND | O_CREAT, 0640);
            if (default_log.fd < 0) {
                fprintf(stderr, "radiusd: Failed to open log file %s: %s\n", main_config.log_file, fr_syserror(errno));
                exit(EXIT_FAILURE);
            }
            fr_log_fp = fdopen(default_log.fd, "a");
            break;

        case 'i':
            if (ip_hton(optarg, AF_UNSPEC, &main_config.myip) < 0) {
                fprintf(stderr, "radiusd: Invalid IP Address or hostname \"%s\"\n", optarg);
                exit(EXIT_FAILURE);
            }
            flag |= 1;
            break;

        case 'n':
            main_config.name = optarg;
            break;

        case 'm':
            main_config.debug_memory = true;
            break;

        case 'M':
            main_config.memory_report = true;
            main_config.debug_memory = true;
            break;

        case 'p':
        {
            unsigned long port;

            port = strtoul(optarg, 0, 10);
            if ((port == 0) || (port > UINT16_MAX)) {
                fprintf(stderr, "radiusd: Invalid port number \"%s\"\n", optarg);
                exit(EXIT_FAILURE);
            }

            main_config.port = (uint16_t) port;
            flag |= 2;
        }
        break;

        case 'P':
            /* Force the PID to be written, even in -f mode */
            write_pid = true;
            break;

        case 's':	/* Single process mode */
            spawn_flag = false;
            main_config.daemonize = false;
            break;

        case 't':	/* no child threads */
            spawn_flag = false;
            break;

        case 'v':
            display_version = true;
            break;

        case 'X':
            spawn_flag = false;
            main_config.daemonize = false;
            debug_flag += 2;
            main_config.log_auth = true;
            main_config.log_auth_badpass = true;
            main_config.log_auth_goodpass = true;
do_stdout:
            fr_log_fp = stdout;
            default_log.dst = L_DST_STDOUT;
            default_log.fd = STDOUT_FILENO;
            break;

        case 'x':
            debug_flag++;
            break;

        default:
            usage(1);
            break;
        }
    }

    /*
     *	Mismatch between the binary and the libraries it depends on
     */
    if (fr_check_lib_magic(RADIUSD_MAGIC_NUMBER) < 0) {
        fr_perror("radiusd");
        exit(EXIT_FAILURE);
    }

    if (rad_check_lib_magic(RADIUSD_MAGIC_NUMBER) < 0) {
        exit(EXIT_FAILURE);
    }

    /*
     *	Mismatch between build time OpenSSL and linked SSL,
     *	better to die here than segfault later.
     */
#ifdef HAVE_OPENSSL_CRYPTO_H
    if (ssl_check_consistency() < 0) {
        exit(EXIT_FAILURE);
    }
#endif

    if (flag && (flag != 0x03)) {
        fprintf(stderr, "radiusd: The options -i and -p cannot be used individually.\n");
        exit(EXIT_FAILURE);
    }

    /*
     *	Better here, so it doesn't matter whether we get passed
     *	-xv or -vx.
     */
    if (display_version) {
        /* Don't print timestamps */
        debug_flag += 2;
        fr_log_fp = stdout;
        default_log.dst = L_DST_STDOUT;
        default_log.fd = STDOUT_FILENO;

        version();
        exit(EXIT_SUCCESS);
    }

    if (debug_flag) {
        version();
    }

    /*
     *  Initialising OpenSSL once, here, is safer than having individual
     *  modules do it.
     */
#ifdef HAVE_OPENSSL_CRYPTO_H
    tls_global_init();
#endif

    /*
     *  Initialize any event loops just enough so module instantiations
     *  can add fd/event to them, but do not start them yet.
     */
    if (!radius_event_init(autofree)) {
        exit(EXIT_FAILURE);
    }

    /*  Read the configuration files, BEFORE doing anything else.  */
    if (main_config_init() < 0) {
        exit(EXIT_FAILURE);
    }

    /*  Check for vulnerabilities in the version of libssl were linked against */
#ifdef HAVE_OPENSSL_CRYPTO_H
    if (tls_global_version_check(main_config.allow_vulnerable_openssl) < 0) {
        exit(EXIT_FAILURE);
    }
#endif

    /*
     *  Load the modules
     */
    if (modules_init(main_config.config) < 0) {
        exit(EXIT_FAILURE);
    }

    /* Set the panic action (if required) */
    if (main_config.panic_action &&
#ifndef NDEBUG
            !getenv("PANIC_ACTION") &&
#endif
            (fr_fault_setup(main_config.panic_action, argv[0]) < 0)) {
        fr_perror("radiusd");
        exit(EXIT_FAILURE);
    }

#ifndef __MINGW32__


    /*
     *  Disconnect from session
     */
    if (main_config.daemonize) {
        pid_t pid;
        int devnull;

        /*
         *  Really weird things happen if we leave stdin open and call things like
         *  system() later.
         */
        devnull = open("/dev/null", O_RDWR);
        if (devnull < 0) {
            ERROR("Failed opening /dev/null: %s", fr_syserror(errno));
            exit(EXIT_FAILURE);
        }
        dup2(devnull, STDIN_FILENO);

        close(devnull);

        if (pipe(from_child) != 0) {
            ERROR("Couldn't open pipe for child status: %s", fr_syserror(errno));
            exit(EXIT_FAILURE);
        }

        pid = fork();
        if (pid < 0) {
            ERROR("Couldn't fork: %s", fr_syserror(errno));
            exit(EXIT_FAILURE);
        }

        /*
         *  The parent exits, so the child can run in the background.
         *
         *  As the child can still encounter an error during initialisation
         *  we do a blocking read on a pipe between it and the parent.
         *
         *  Just before entering the event loop the child will send a success
         *  or failure message to the parent, via the pipe.
         */
        if (pid > 0) {
            uint8_t ret = 0;
            int stat_loc;

            /* So the pipe is correctly widowed if the child exits */
            close(from_child[1]);

            /*
             *	The child writes a 0x01 byte on
             *	success, and closes the pipe on error.
             */
            if ((read(from_child[0], &ret, 1) < 0)) {
                ret = 0;
            }

            /* For cleanliness... */
            close(from_child[0]);

            /* Don't turn children into zombies */
            if (!ret) {
                waitpid(pid, &stat_loc, WNOHANG);
                exit(EXIT_FAILURE);
            }

            exit(EXIT_SUCCESS);
        }

        /* so the pipe is correctly widowed if the parent exits?! */
        close(from_child[0]);
#  ifdef HAVE_SETSID
        setsid();
#  endif
    }
#endif

    /*
     *	Ensure that we're using the CORRECT pid after forking,
     *	NOT the one we started with.
     */
    radius_pid = getpid();

    /*
     *	Redirect stderr/stdout as appropriate.
     */
    if (radlog_init(&default_log, main_config.daemonize) < 0) {
        ERROR("%s", fr_strerror());
        exit(EXIT_FAILURE);
    }

    /*
     *	Start the event loop(s) and threads.
     */
    radius_event_start(main_config.config, spawn_flag);

    /*
     *	Now that we've set everything up, we can install the signal
     *	handlers.  Before this, if we get any signal, we don't know
     *	what to do, so we might as well do the default, and die.
     */
#ifdef SIGPIPE
    signal(SIGPIPE, SIG_IGN);
#endif

    if ((fr_set_signal(SIGHUP, sig_hup) < 0) ||
            (fr_set_signal(SIGTERM, sig_fatal) < 0)) {
        ERROR("%s", fr_strerror());
        exit(EXIT_FAILURE);
    }

    /*
     *	If we're debugging, then a CTRL-C will cause the
     *	server to die immediately.  Use SIGTERM to shut down
     *	the server cleanly in that case.
     */
    if (main_config.debug_memory || (debug_flag == 0)) {
        if ((fr_set_signal(SIGINT, sig_fatal) < 0)
#ifdef SIGQUIT
                || (fr_set_signal(SIGQUIT, sig_fatal) < 0)
#endif
           ) {
            ERROR("%s", fr_strerror());
            exit(EXIT_FAILURE);
        }
    }

    /*
     *	Everything seems to have loaded OK, exit gracefully.
     */
    if (check_config) {
        DEBUG("Configuration appears to be OK");

        /* for -C -m|-M */
        if (main_config.debug_memory) {
            goto cleanup;
        }

        exit(EXIT_SUCCESS);
    }

#ifdef WITH_STATS
    radius_stats_init(0);
#endif

    /*
     *	Write the PID always if we're running as a daemon.
     */
    if (main_config.daemonize) write_pid = true;

    /*
     *	Write the PID after we've forked, so that we write the
     *	correct one.
     */
    if (write_pid) {
        FILE *fp;

        fp = fopen(main_config.pid_file, "w");
        if (fp != NULL) {
            /*
             *	FIXME: What about following symlinks,
             *	and having it over-write a normal file?
             */
            fprintf(fp, "%d\n", (int) radius_pid);
            fclose(fp);
        } else {
            ERROR("Failed creating PID file %s: %s\n",
                  main_config.pid_file, fr_syserror(errno));
            exit(EXIT_FAILURE);
        }
    }

    exec_trigger(NULL, NULL, "server.start", false);

    /*
     *	Inform the parent (who should still be waiting) that
     *	the rest of initialisation went OK, and that it should
     *	exit with a 0 status.  If we don't get this far, then
     *	we just close the pipe on exit, and the parent gets a
     *	read failure.
     */
    if (main_config.daemonize) {
        if (write(from_child[1], "\001", 1) < 0) {
            WARN("Failed informing parent of successful start: %s",
                 fr_syserror(errno));
        }
        close(from_child[1]);
    }

    /*
     *	Clear the libfreeradius error buffer
     */
    fr_strerror();

    /*
     *	Process requests until HUP or exit.
     */
    while ((status = radius_event_process()) == 0x80) {
#ifdef WITH_STATS
        radius_stats_init(1);
#endif
        main_config_hup();
    }
    if (status < 0) {
        ERROR("Exiting due to internal error: %s", fr_strerror());
        rcode = EXIT_FAILURE;
    } else {
        INFO("Exiting normally");
    }

    exec_trigger(NULL, NULL, "server.stop", false);

    /*
     *	Ignore the TERM signal: we're
     *	about to die.
     */
    signal(SIGTERM, SIG_IGN);

    /*
     *	Send a TERM signal to all
     *	associated processes
     *	(including us, which gets
     *	ignored.)
     */
#ifndef __MINGW32__
    if (spawn_flag) kill(-radius_pid, SIGTERM);
#endif

    /*
     *	We're exiting, so we can delete the PID
     *	file.  (If it doesn't exist, we can ignore
     *	the error returned by unlink)
     */
    if (main_config.daemonize) {
        unlink(main_config.pid_file);
    }

    radius_event_free();

cleanup:
    /*
     *	Detach any modules.
     */
    modules_free();

    xlat_free();		/* modules may have xlat's */

    /*
     *	Free the configuration items.
     */
    main_config_free();

#ifdef WIN32
    WSACleanup();
#endif

#ifdef HAVE_OPENSSL_CRYPTO_H
    tls_global_cleanup();
#endif
    /*
     *	So we don't see autofreed memory in the talloc report
     */
    talloc_free(autofree);

    if (main_config.memory_report) {
        INFO("Allocated memory at time of report:");
        fr_log_talloc_report(NULL);
    }

    return rcode;
}
Пример #19
0
int minorVersion()
      {
      version();
      return _minorVersion;
      }
Пример #20
0
    StatusWith<ChunkType> ChunkType::fromBSON(const BSONObj& source) {
        ChunkType chunk;

        {
            std::string chunkName;
            Status status = bsonExtractStringField(source, name.name(), &chunkName);
            if (!status.isOK()) return status;
            chunk._name = chunkName;
        }

        {
            std::string chunkNS;
            Status status = bsonExtractStringField(source, ns.name(), &chunkNS);
            if (!status.isOK()) return status;
            chunk._ns = chunkNS;
        }

        {
            BSONElement chunkMinElement;
            Status status = bsonExtractTypedField(source, min.name(), Object, &chunkMinElement);
            if (!status.isOK()) return status;
            chunk._min = chunkMinElement.Obj().getOwned();
        }

        {
            BSONElement chunkMaxElement;
            Status status = bsonExtractTypedField(source, max.name(), Object, &chunkMaxElement);
            if (!status.isOK()) return status;
            chunk._max = chunkMaxElement.Obj().getOwned();
        }

        {
            std::string chunkShard;
            Status status = bsonExtractStringField(source, shard.name(), &chunkShard);
            if (!status.isOK()) return status;
            chunk._shard = chunkShard;
        }

        {
            bool chunkJumbo;
            Status status = bsonExtractBooleanField(source, jumbo.name(), &chunkJumbo);
            if (status.isOK()) {
                chunk._jumbo = chunkJumbo;
            }
            else if (status == ErrorCodes::NoSuchKey) {
                // Jumbo status is missing, so it will be presumed false
            }
            else {
                return status;
            }
        }

        //
        // ChunkVersion backward compatibility logic contained in ChunkVersion
        //

        // ChunkVersion is currently encoded as { 'version': [<TS>,<OID>] }

        if (ChunkVersion::canParseBSON(source, version())) {
            chunk._version = ChunkVersion::fromBSON(source, version());
        }
        else if (ChunkVersion::canParseBSON(source, DEPRECATED_lastmod())) {
            chunk._version = ChunkVersion::fromBSON(source, DEPRECATED_lastmod());
        }

        return chunk;
    }
Пример #21
0
int main(int argc, char **argv)
{
   int nb_samples, total_samples=0, nb_encoded;
   int c;
   int option_index = 0;
   char *inFile, *outFile;
   FILE *fin, *fout;
   short input[MAX_FRAME_SIZE];
   int frame_size;
   int quiet=0;
   int vbr_enabled=0;
   int abr_enabled=0;
   int vad_enabled=0;
   int dtx_enabled=0;
   int nbBytes;
   const SpeexMode *mode=NULL;
   int modeID = -1;
   void *st;
   SpeexBits bits;
   char cbits[MAX_FRAME_BYTES];
   struct option long_options[] =
   {
      {"wideband", no_argument, NULL, 0},
      {"ultra-wideband", no_argument, NULL, 0},
      {"narrowband", no_argument, NULL, 0},
      {"vbr", no_argument, NULL, 0},
      {"abr", required_argument, NULL, 0},
      {"vad", no_argument, NULL, 0},
      {"dtx", no_argument, NULL, 0},
      {"quality", required_argument, NULL, 0},
      {"bitrate", required_argument, NULL, 0},
      {"nframes", required_argument, NULL, 0},
      {"comp", required_argument, NULL, 0},
      {"denoise", no_argument, NULL, 0},
      {"agc", no_argument, NULL, 0},
      {"help", no_argument, NULL, 0},
      {"quiet", no_argument, NULL, 0},
      {"le", no_argument, NULL, 0},
      {"be", no_argument, NULL, 0},
      {"8bit", no_argument, NULL, 0},
      {"16bit", no_argument, NULL, 0},
      {"stereo", no_argument, NULL, 0},
      {"rate", required_argument, NULL, 0},
      {"version", no_argument, NULL, 0},
      {"version-short", no_argument, NULL, 0},
      {"comment", required_argument, NULL, 0},
      {"author", required_argument, NULL, 0},
      {"title", required_argument, NULL, 0},
      {0, 0, 0, 0}
   };
   int print_bitrate=0;
   int rate=0, size;
   int chan=1;
   int fmt=16;
   int quality=-1;
   float vbr_quality=-1;
   int lsb=1;
   ogg_stream_state os;
   ogg_page 		 og;
   ogg_packet 		 op;
   int bytes_written=0, ret, result;
   int id=-1;
   SpeexHeader header;
   int nframes=1;
   int complexity=3;
   char *vendor_string = "Encoded with Speex " SPEEX_VERSION;
   char *comments;
   int comments_length;
   int close_in=0, close_out=0;
   int eos=0;
   int bitrate=0;
   double cumul_bits=0, enc_frames=0;
   char first_bytes[12];
   int wave_input=0;
   int tmp;
   SpeexPreprocessState *preprocess = NULL;
   int denoise_enabled=0, agc_enabled=0;
   int lookahead = 0;
   
   comment_init(&comments, &comments_length, vendor_string);

   /*Process command-line options*/
   while(1)
   {
      c = getopt_long (argc, argv, "nwuhvV",
                       long_options, &option_index);
      if (c==-1)
         break;
      
      switch(c)
      {
      case 0:
         if (strcmp(long_options[option_index].name,"narrowband")==0)
         {
            modeID = SPEEX_MODEID_NB;
         } else if (strcmp(long_options[option_index].name,"wideband")==0)
         {
            modeID = SPEEX_MODEID_WB;
         } else if (strcmp(long_options[option_index].name,"ultra-wideband")==0)
         {
            modeID = SPEEX_MODEID_UWB;
         } else if (strcmp(long_options[option_index].name,"vbr")==0)
         {
            vbr_enabled=1;
         } else if (strcmp(long_options[option_index].name,"abr")==0)
         {
            abr_enabled=atoi(optarg);
            if (!abr_enabled)
            {
               fprintf (stderr, "Invalid ABR value: %d\n", abr_enabled);
               exit(1);
            }
         } else if (strcmp(long_options[option_index].name,"vad")==0)
         {
            vad_enabled=1;
         } else if (strcmp(long_options[option_index].name,"dtx")==0)
         {
            dtx_enabled=1;
         } else if (strcmp(long_options[option_index].name,"quality")==0)
         {
            quality = atoi (optarg);
            vbr_quality=atof(optarg);
         } else if (strcmp(long_options[option_index].name,"bitrate")==0)
         {
            bitrate = atoi (optarg);
         } else if (strcmp(long_options[option_index].name,"nframes")==0)
         {
            nframes = atoi (optarg);
            if (nframes<1)
               nframes=1;
            if (nframes>10)
               nframes=10;
         } else if (strcmp(long_options[option_index].name,"comp")==0)
         {
            complexity = atoi (optarg);
         } else if (strcmp(long_options[option_index].name,"denoise")==0)
         {
            denoise_enabled=1;
         } else if (strcmp(long_options[option_index].name,"agc")==0)
         {
            agc_enabled=1;
         } else if (strcmp(long_options[option_index].name,"help")==0)
         {
            usage();
            exit(0);
         } else if (strcmp(long_options[option_index].name,"quiet")==0)
         {
            quiet = 1;
         } else if (strcmp(long_options[option_index].name,"version")==0)
         {
            version();
            exit(0);
         } else if (strcmp(long_options[option_index].name,"version-short")==0)
         {
            version_short();
            exit(0);
         } else if (strcmp(long_options[option_index].name,"le")==0)
         {
            lsb=1;
         } else if (strcmp(long_options[option_index].name,"be")==0)
         {
            lsb=0;
         } else if (strcmp(long_options[option_index].name,"8bit")==0)
         {
            fmt=8;
         } else if (strcmp(long_options[option_index].name,"16bit")==0)
         {
            fmt=16;
         } else if (strcmp(long_options[option_index].name,"stereo")==0)
         {
            chan=2;
         } else if (strcmp(long_options[option_index].name,"rate")==0)
         {
            rate=atoi (optarg);
         } else if (strcmp(long_options[option_index].name,"comment")==0)
         {
	   if (!strchr(optarg, '='))
	   {
	     fprintf (stderr, "Invalid comment: %s\n", optarg);
	     fprintf (stderr, "Comments must be of the form name=value\n");
	     exit(1);
	   }
           comment_add(&comments, &comments_length, NULL, optarg); 
         } else if (strcmp(long_options[option_index].name,"author")==0)
         {
           comment_add(&comments, &comments_length, "author=", optarg); 
         } else if (strcmp(long_options[option_index].name,"title")==0)
         {
           comment_add(&comments, &comments_length, "title=", optarg); 
         }

         break;
      case 'n':
         modeID = SPEEX_MODEID_NB;
         break;
      case 'h':
         usage();
         exit(0);
         break;
      case 'v':
         version();
         exit(0);
         break;
      case 'V':
         print_bitrate=1;
         break;
      case 'w':
         modeID = SPEEX_MODEID_WB;
         break;
      case 'u':
         modeID = SPEEX_MODEID_UWB;
         break;
      case '?':
         usage();
         exit(1);
         break;
      }
   }
   if (argc-optind!=2)
   {
      usage();
      exit(1);
   }
   inFile=argv[optind];
   outFile=argv[optind+1];

   /*Initialize Ogg stream struct*/
   srand(time(NULL));
   if (ogg_stream_init(&os, rand())==-1)
   {
      fprintf(stderr,"Error: stream init failed\n");
      exit(1);
   }

   if (strcmp(inFile, "-")==0)
   {
#if defined WIN32 || defined _WIN32
         _setmode(_fileno(stdin), _O_BINARY);
#endif
      fin=stdin;
   }
   else 
   {
      fin = fopen(inFile, "rb");
      if (!fin)
      {
         perror(inFile);
         exit(1);
      }
      close_in=1;
   }

   {
      fread(first_bytes, 1, 12, fin);
      if (strncmp(first_bytes,"RIFF",4)==0 && strncmp(first_bytes,"RIFF",4)==0)
      {
         if (read_wav_header(fin, &rate, &chan, &fmt, &size)==-1)
            exit(1);
         wave_input=1;
         lsb=1; /* CHECK: exists big-endian .wav ?? */
      }
   }

   if (modeID==-1 && !rate)
   {
      /* By default, use narrowband/8 kHz */
      modeID = SPEEX_MODEID_NB;
      rate=8000;
   } else if (modeID!=-1 && rate)
   {
      if (rate>48000)
      {
         fprintf (stderr, "Error: sampling rate too high: %d Hz, try down-sampling\n", rate);
         exit(1);
      } else if (rate>25000)
      {
         if (modeID != SPEEX_MODEID_UWB)
         {
            fprintf (stderr, "Warning: Trying to encode in %s at %d Hz. I'll do it but I suggest you try ultra-wideband instead\n", mode->modeName , rate);
         }
      } else if (rate>12500)
      {
         if (modeID != SPEEX_MODEID_WB)
         {
            fprintf (stderr, "Warning: Trying to encode in %s at %d Hz. I'll do it but I suggest you try wideband instead\n", mode->modeName , rate);
         }
      } else if (rate>=6000)
      {
         if (modeID != SPEEX_MODEID_NB)
         {
            fprintf (stderr, "Warning: Trying to encode in %s at %d Hz. I'll do it but I suggest you try narrowband instead\n", mode->modeName , rate);
         }
      } else {
         fprintf (stderr, "Error: sampling rate too low: %d Hz\n", rate);
         exit(1);
      }
   } else if (modeID==-1)
   {
      if (rate>48000)
      {
         fprintf (stderr, "Error: sampling rate too high: %d Hz, try down-sampling\n", rate);
         exit(1);
      } else if (rate>25000)
      {
         modeID = SPEEX_MODEID_UWB;
      } else if (rate>12500)
      {
         modeID = SPEEX_MODEID_WB;
      } else if (rate>=6000)
      {
         modeID = SPEEX_MODEID_NB;
      } else {
         fprintf (stderr, "Error: Sampling rate too low: %d Hz\n", rate);
         exit(1);
      }
   } else if (!rate)
   {
      if (modeID == SPEEX_MODEID_NB)
         rate=8000;
      else if (modeID == SPEEX_MODEID_WB)
         rate=16000;
      else if (modeID == SPEEX_MODEID_UWB)
         rate=32000;
   }

   if (!quiet)
      if (rate!=8000 && rate!=16000 && rate!=32000)
         fprintf (stderr, "Warning: Speex is only optimized for 8, 16 and 32 kHz. It will still work at %d Hz but your mileage may vary\n", rate); 

   mode = speex_lib_get_mode (modeID);

   speex_init_header(&header, rate, 1, mode);
   header.frames_per_packet=nframes;
   header.vbr=vbr_enabled;
   header.nb_channels = chan;

   {
      char *st_string="mono";
      if (chan==2)
         st_string="stereo";
      if (!quiet)
         fprintf (stderr, "Encoding %d Hz audio using %s mode (%s)\n", 
               header.rate, mode->modeName, st_string);
   }
   /*fprintf (stderr, "Encoding %d Hz audio at %d bps using %s mode\n", 
     header.rate, mode->bitrate, mode->modeName);*/

   /*Initialize Speex encoder*/
   st = speex_encoder_init(mode);

   if (strcmp(outFile,"-")==0)
   {
#if defined WIN32 || defined _WIN32
      _setmode(_fileno(stdout), _O_BINARY);
#endif
      fout=stdout;
   }
   else 
   {
      fout = fopen(outFile, "wb");
      if (!fout)
      {
         perror(outFile);
         exit(1);
      }
      close_out=1;
   }

   speex_encoder_ctl(st, SPEEX_GET_FRAME_SIZE, &frame_size);
   speex_encoder_ctl(st, SPEEX_SET_COMPLEXITY, &complexity);
   speex_encoder_ctl(st, SPEEX_SET_SAMPLING_RATE, &rate);

   if (quality >= 0)
   {
      if (vbr_enabled)
         speex_encoder_ctl(st, SPEEX_SET_VBR_QUALITY, &vbr_quality);
      else
         speex_encoder_ctl(st, SPEEX_SET_QUALITY, &quality);
   }
   if (bitrate)
   {
      if (quality >= 0 && vbr_enabled)
         fprintf (stderr, "Warning: --bitrate option is overriding --quality\n");
      speex_encoder_ctl(st, SPEEX_SET_BITRATE, &bitrate);
   }
   if (vbr_enabled)
   {
      tmp=1;
      speex_encoder_ctl(st, SPEEX_SET_VBR, &tmp);
   } else if (vad_enabled)
   {
      tmp=1;
      speex_encoder_ctl(st, SPEEX_SET_VAD, &tmp);
   }
   if (dtx_enabled)
      speex_encoder_ctl(st, SPEEX_SET_DTX, &tmp);
   if (dtx_enabled && !(vbr_enabled || abr_enabled || vad_enabled))
   {
      fprintf (stderr, "Warning: --dtx is useless without --vad, --vbr or --abr\n");
   } else if ((vbr_enabled || abr_enabled) && (vad_enabled))
   {
      fprintf (stderr, "Warning: --vad is already implied by --vbr or --abr\n");
   }

   if (abr_enabled)
   {
      speex_encoder_ctl(st, SPEEX_SET_ABR, &abr_enabled);
   }

   speex_encoder_ctl(st, SPEEX_GET_LOOKAHEAD, &lookahead);
   
   if (denoise_enabled || agc_enabled)
   {
      preprocess = speex_preprocess_state_init(frame_size, rate);
      speex_preprocess_ctl(preprocess, SPEEX_PREPROCESS_SET_DENOISE, &denoise_enabled);
      speex_preprocess_ctl(preprocess, SPEEX_PREPROCESS_SET_AGC, &agc_enabled);
      lookahead += frame_size;
   }

   /*Write header*/
   {

      op.packet = (unsigned char *)speex_header_to_packet(&header, (int*)&(op.bytes));
      op.b_o_s = 1;
      op.e_o_s = 0;
      op.granulepos = 0;
      op.packetno = 0;
      ogg_stream_packetin(&os, &op);
      free(op.packet);

      op.packet = (unsigned char *)comments;
      op.bytes = comments_length;
      op.b_o_s = 0;
      op.e_o_s = 0;
      op.granulepos = 0;
      op.packetno = 1;
      ogg_stream_packetin(&os, &op);
      
      while((result = ogg_stream_flush(&os, &og)))
      {
         if(!result) break;
         ret = oe_write_page(&og, fout);
         if(ret != og.header_len + og.body_len)
         {
            fprintf (stderr,"Error: failed writing header to output stream\n");
            exit(1);
         }
         else
            bytes_written += ret;
      }
   }

   free(comments);

   speex_bits_init(&bits);

   if (!wave_input)
   {
      nb_samples = read_samples(fin,frame_size,fmt,chan,lsb,input, first_bytes, NULL);
   } else {
      nb_samples = read_samples(fin,frame_size,fmt,chan,lsb,input, NULL, &size);
   }
   if (nb_samples==0)
      eos=1;
   total_samples += nb_samples;
   nb_encoded = -lookahead;
   /*Main encoding loop (one frame per iteration)*/
   while (!eos || total_samples>nb_encoded)
   {
      id++;
      /*Encode current frame*/
      if (chan==2)
         speex_encode_stereo_int(input, frame_size, &bits);

      if (preprocess)
         speex_preprocess(preprocess, input, NULL);

      speex_encode_int(st, input, &bits);
      
      nb_encoded += frame_size;
      if (print_bitrate) {
         int tmp;
         char ch=13;
         speex_encoder_ctl(st, SPEEX_GET_BITRATE, &tmp);
         fputc (ch, stderr);
         cumul_bits += tmp;
         enc_frames += 1;
         if (!quiet)
         {
            if (vad_enabled || vbr_enabled || abr_enabled)
               fprintf (stderr, "Bitrate is use: %d bps  (average %d bps)   ", tmp, (int)(cumul_bits/enc_frames));
            else
               fprintf (stderr, "Bitrate is use: %d bps     ", tmp);
         }
         
      }

      if (wave_input)
      {
         nb_samples = read_samples(fin,frame_size,fmt,chan,lsb,input, NULL, &size);
      } else {
         nb_samples = read_samples(fin,frame_size,fmt,chan,lsb,input, NULL, NULL);
      }
      if (nb_samples==0)
      {
         eos=1;
      }
      if (eos && total_samples<=nb_encoded)
         op.e_o_s = 1;
      else
         op.e_o_s = 0;
      total_samples += nb_samples;

      if ((id+1)%nframes!=0)
         continue;
      speex_bits_insert_terminator(&bits);
      nbBytes = speex_bits_write(&bits, cbits, MAX_FRAME_BYTES);
      speex_bits_reset(&bits);
      op.packet = (unsigned char *)cbits;
      op.bytes = nbBytes;
      op.b_o_s = 0;
      /*Is this redundent?*/
      if (eos && total_samples<=nb_encoded)
         op.e_o_s = 1;
      else
         op.e_o_s = 0;
      op.granulepos = (id+1)*frame_size-lookahead;
      if (op.granulepos>total_samples)
         op.granulepos = total_samples;
      /*printf ("granulepos: %d %d %d %d %d %d\n", (int)op.granulepos, id, nframes, lookahead, 5, 6);*/
      op.packetno = 2+id/nframes;
      ogg_stream_packetin(&os, &op);

      /*Write all new pages (most likely 0 or 1)*/
      while (ogg_stream_pageout(&os,&og))
      {
         ret = oe_write_page(&og, fout);
         if(ret != og.header_len + og.body_len)
         {
            fprintf (stderr,"Error: failed writing header to output stream\n");
            exit(1);
         }
         else
            bytes_written += ret;
      }
   }
   if ((id+1)%nframes!=0)
   {
      while ((id+1)%nframes!=0)
      {
         id++;
         speex_bits_pack(&bits, 15, 5);
      }
      nbBytes = speex_bits_write(&bits, cbits, MAX_FRAME_BYTES);
      op.packet = (unsigned char *)cbits;
      op.bytes = nbBytes;
      op.b_o_s = 0;
      op.e_o_s = 1;
      op.granulepos = (id+1)*frame_size-lookahead;
      if (op.granulepos>total_samples)
         op.granulepos = total_samples;

      op.packetno = 2+id/nframes;
      ogg_stream_packetin(&os, &op);
   }
   /*Flush all pages left to be written*/
   while (ogg_stream_flush(&os, &og))
   {
      ret = oe_write_page(&og, fout);
      if(ret != og.header_len + og.body_len)
      {
         fprintf (stderr,"Error: failed writing header to output stream\n");
         exit(1);
      }
      else
         bytes_written += ret;
   }

   speex_encoder_destroy(st);
   speex_bits_destroy(&bits);
   ogg_stream_clear(&os);

   if (close_in)
      fclose(fin);
   if (close_out)
      fclose(fout);
   return 0;
}
Пример #22
0
int main(int argc, char **argv)
{
	bool slow = false, invoke_cpp = false, reseed = true, cpustats = true;
	bool prio_high = false, set_irq_aff = true;
	int c, opt_index, vals[4] = {0}, irq;
	uint64_t gap = 0;
	unsigned int i, j;
	char *confname = NULL, *ptr;
	unsigned long cpus_tmp, orig_num = 0;
	unsigned long long tx_packets, tx_bytes;
	struct ctx ctx;

	fmemset(&ctx, 0, sizeof(ctx));
	ctx.cpus = get_number_cpus_online();
	ctx.uid = getuid();
	ctx.gid = getgid();
	ctx.qdisc_path = false;

	while ((c = getopt_long(argc, argv, short_options, long_options,
				&opt_index)) != EOF) {
		switch (c) {
		case 'h':
			help();
			break;
		case 'v':
			version();
			break;
		case 'C':
			cpustats = false;
			break;
		case 'e':
			example();
			break;
		case 'p':
			invoke_cpp = true;
			break;
		case 'V':
			ctx.verbose = true;
			break;
		case 'P':
			cpus_tmp = strtoul(optarg, NULL, 0);
			if (cpus_tmp > 0 && cpus_tmp < ctx.cpus)
				ctx.cpus = cpus_tmp;
			break;
		case 'd':
		case 'o':
			ctx.device = xstrndup(optarg, IFNAMSIZ);
			break;
		case 'H':
			prio_high = true;
			break;
		case 'Q':
			set_irq_aff = false;
			break;
		case 'q':
			ctx.qdisc_path = true;
			break;
		case 'r':
			ctx.rand = true;
			break;
		case 's':
			slow = true;
			ctx.cpus = 1;
			ctx.smoke_test = true;
			ctx.rhost = xstrdup(optarg);
			break;
		case 'R':
			ctx.rfraw = true;
			break;
		case 'J':
			ctx.jumbo_support = true;
			break;
		case 'c':
		case 'i':
			confname = xstrdup(optarg);
			if (!strncmp("-", confname, strlen("-")))
				ctx.cpus = 1;
			break;
		case 'u':
			ctx.uid = strtoul(optarg, NULL, 0);
			ctx.enforce = true;
			break;
		case 'g':
			ctx.gid = strtoul(optarg, NULL, 0);
			ctx.enforce = true;
			break;
		case 'k':
			ctx.kpull = strtoul(optarg, NULL, 0);
			break;
		case 'E':
			seed = strtoul(optarg, NULL, 0);
			reseed = false;
			break;
		case 'n':
			orig_num = strtoul(optarg, NULL, 0);
			ctx.num = orig_num;
			break;
		case 't':
			slow = true;
			ptr = optarg;
			gap = strtoul(optarg, NULL, 0);

			for (j = i = strlen(optarg); i > 0; --i) {
				if (!isdigit(optarg[j - i]))
					break;
				ptr++;
			}

			if (!strncmp(ptr, "ns", strlen("ns"))) {
				ctx.gap.tv_sec = gap / 1000000000;
				ctx.gap.tv_nsec = gap % 1000000000;
			} else if (*ptr == '\0' || !strncmp(ptr, "us", strlen("us"))) {
				/*  Default to microseconds for backwards
				 *  compatibility if no postfix is given.
				 */
				ctx.gap.tv_sec = gap / 1000000;
				ctx.gap.tv_nsec = (gap % 1000000) * 1000;
			} else if (!strncmp(ptr, "ms", strlen("ms"))) {
				ctx.gap.tv_sec = gap / 1000;
				ctx.gap.tv_nsec = (gap % 1000) * 1000000;
			} else if (!strncmp(ptr, "s", strlen("s"))) {
				ctx.gap.tv_sec = gap;
				ctx.gap.tv_nsec = 0;
			} else
				panic("Syntax error in time param!\n");

			if (gap > 0)
				/* Fall back to single core to not mess up
				 * correct timing. We are slow anyway!
				 */
				ctx.cpus = 1;
			break;
		case 'S':
			ptr = optarg;
			ctx.reserve_size = 0;

			for (j = i = strlen(optarg); i > 0; --i) {
				if (!isdigit(optarg[j - i]))
					break;
				ptr++;
			}

			if (!strncmp(ptr, "KiB", strlen("KiB")))
				ctx.reserve_size = 1 << 10;
			else if (!strncmp(ptr, "MiB", strlen("MiB")))
				ctx.reserve_size = 1 << 20;
			else if (!strncmp(ptr, "GiB", strlen("GiB")))
				ctx.reserve_size = 1 << 30;
			else
				panic("Syntax error in ring size param!\n");

			ctx.reserve_size *= strtol(optarg, NULL, 0);
			break;
		case '?':
			switch (optopt) {
			case 'd':
			case 'c':
			case 'n':
			case 'S':
			case 's':
			case 'P':
			case 'o':
			case 'E':
			case 'i':
			case 'k':
			case 'u':
			case 'g':
			case 't':
				panic("Option -%c requires an argument!\n",
				      optopt);
			default:
				if (isprint(optopt))
					printf("Unknown option character `0x%X\'!\n", optopt);
				die();
			}
		default:
			break;
		}
	}

	if (argc < 5)
		help();
	if (ctx.device == NULL)
		panic("No networking device given!\n");
	if (confname == NULL)
		panic("No configuration file given!\n");
	if (device_mtu(ctx.device) == 0)
		panic("This is no networking device!\n");

	register_signal(SIGINT, signal_handler);
	register_signal(SIGQUIT, signal_handler);
	register_signal(SIGTERM, signal_handler);
	register_signal(SIGHUP, signal_handler);
	register_signal_f(SIGALRM, timer_elapsed, SA_SIGINFO);

	if (prio_high) {
		set_proc_prio(-20);
		set_sched_status(SCHED_FIFO, sched_get_priority_max(SCHED_FIFO));
	}

	set_system_socket_memory(vals, array_size(vals));
	xlockme();

	if (ctx.rfraw) {
		ctx.device_trans = xstrdup(ctx.device);
		xfree(ctx.device);

		enter_rfmon_mac80211(ctx.device_trans, &ctx.device);
		sleep(0);
	}

	irq = device_irq_number(ctx.device);
	if (set_irq_aff)
		device_set_irq_affinity_list(irq, 0, ctx.cpus - 1);

	stats = setup_shared_var(ctx.cpus);

	for (i = 0; i < ctx.cpus; i++) {
		pid_t pid = fork();

		switch (pid) {
		case 0:
			if (reseed)
				seed = generate_srand_seed();
			srand(seed);

			cpu_affinity(i);
			main_loop(&ctx, confname, slow, i, invoke_cpp, orig_num);

			goto thread_out;
		case -1:
			panic("Cannot fork processes!\n");
		}
	}

	for (i = 0; i < ctx.cpus; i++) {
		int status;

		wait(&status);
		if (WEXITSTATUS(status) == EXIT_FAILURE)
			die();
	}

	if (ctx.rfraw)
		leave_rfmon_mac80211(ctx.device);

	reset_system_socket_memory(vals, array_size(vals));

	for (i = 0, tx_packets = tx_bytes = 0; i < ctx.cpus; i++) {
		while ((__get_state(i) & CPU_STATS_STATE_RES) == 0)
			sched_yield();

		tx_packets += stats[i].tx_packets;
		tx_bytes   += stats[i].tx_bytes;
	}

	fflush(stdout);
	printf("\n");
	printf("\r%12llu packets outgoing\n", tx_packets);
	printf("\r%12llu bytes outgoing\n", tx_bytes);
	for (i = 0; cpustats && i < ctx.cpus; i++) {
		printf("\r%12lu sec, %lu usec on CPU%d (%llu packets)\n",
		       stats[i].tv_sec, stats[i].tv_usec, i,
		       stats[i].tx_packets);
	}

thread_out:
	xunlockme();
	destroy_shared_var(stats, ctx.cpus);
	if (set_irq_aff)
		device_restore_irq_affinity_list();

	free(ctx.device);
	free(ctx.device_trans);
	free(ctx.rhost);
	free(confname);

	return 0;
}
Пример #23
0
/*
 * IMAPFilter: an IMAP mail filtering utility.
 */
int
main(int argc, char *argv[])
{
	int c;

	setlocale(LC_CTYPE, "");

	opts.verbose = 0;
	opts.interactive = 0;
	opts.log = NULL;
	opts.config = NULL;
	opts.oneline = NULL;
	opts.debug = NULL;

	env.home = NULL;
	env.pathmax = -1;

	while ((c = getopt(argc, argv, "Vc:d:e:il:v?")) != -1) {
		switch (c) {
		case 'V':
			version();
			/* NOTREACHED */
			break;
		case 'c':
			opts.config = optarg;
			break;
		case 'd':
			opts.debug = optarg;
			break;
		case 'e':
			opts.oneline = optarg;
			break;
		case 'i':
			opts.interactive = 1;
			break;
		case 'l':
			opts.log = optarg;
			break;
		case 'v':
			opts.verbose = 1;
			break;
		case '?':
		default:
			usage();
			/* NOTREACHED */
			break;
		}
	}

	get_pathmax();
	open_debug();
	create_homedir();
	catch_signals();
	open_log();
	if (opts.config == NULL)
		opts.config = get_filepath("config.lua");

	buffer_init(&ibuf, INPUT_BUF);
	buffer_init(&obuf, OUTPUT_BUF);
	buffer_init(&nbuf, NAMESPACE_BUF);
	buffer_init(&cbuf, CONVERSION_BUF);

	regexp_compile(responses);

	SSL_library_init();
	SSL_load_error_strings();

	start_lua();
#if LUA_VERSION_NUM < 502
	{
		list *l;
		session *s;

		l = sessions;
		while (l != NULL) {
			s = l->data;
			l = l->next;

			request_logout(s);
		}
	}
#endif
	stop_lua();

	ERR_free_strings();

	regexp_free(responses);

	buffer_free(&ibuf);
	buffer_free(&obuf);
	buffer_free(&nbuf);
	buffer_free(&cbuf);

	xfree(env.home);

	close_log();
	close_debug();

	exit(0);
}
Пример #24
0
int
main(int argc, char *argv[])
{
    struct login_ctx ctx[1];
    struct passwd *pw;
    pid_t pid;
    int c, stat;
    
    memset(ctx, 0, sizeof(ctx));
    
    while ((c = getopt(argc, argv, "vc:df:h:?")) != -1) {
        switch (c) {
        case 'v':
            version();
            break;
        case 'c':
            ctx->config = optarg;
            break;
        case 'd':
            duo_debug = 1;
            break;
        case 'f':
            ctx->duouser = optarg;
            break;
        case 'h':
            ctx->host = optarg;
            break;
        default:
            usage();
        }
    }
    argc -= optind;
    argv += optind;

        ctx->uid = getuid();
        
    if (geteuid() != ctx->uid) {
        /* Setuid-root operation protecting private config. */
        if (ctx->config != NULL || ctx->duouser != NULL) {
            die("Only root may specify -c or -f");
        }
        if ((pw = getpwnam(DUO_PRIVSEP_USER)) == NULL) {
            die("User '%s' not found", DUO_PRIVSEP_USER);
        }
        if ((pid = fork()) == 0) {
            /* Unprivileged auth child. */
            if (drop_privs(pw->pw_uid, pw->pw_gid) != 0) {
                die("couldn't drop privileges: %s",
                    strerror(errno));
            }
            exit(do_auth(ctx, get_command(argc, argv)));
        } else {
            /* Parent continues as user. */
            if (drop_privs(getuid(), getgid()) != 0) {
                die("couldn't drop privileges: %s",
                    strerror(errno));
            }
            /* Check auth child status. */
            if (waitpid(pid, &stat, 0) != pid) {
                die("waitpid: %s", strerror(errno));
            }
            if (WEXITSTATUS(stat) == 0) {
                do_exec(ctx, get_command(argc, argv));
            }
        }
    } else {
                char *cmd = get_command(argc, argv);
                
        /* Non-setuid root operation or running as root. */
        if (do_auth(ctx, cmd) == EXIT_SUCCESS) {
            do_exec(ctx, cmd);
        }
    }
    exit(EXIT_FAILURE);
}
Пример #25
0
int
main(int argc, char *argv[])
{
    const char     *allowed_args = "hl:x:p:o:sv:i:r:V";
    char           *node = NULL;
    int             retval;
    int             async = 1;
    val_log_t      *logp;
    char           *label_str = NULL;
    struct val_daneparams daneparams;
    struct val_danestatus *danestatus = NULL;
    struct val_ssl_data *ssl_dane_data = NULL;
    int port = 443;
    int proto = DANE_PARAM_PROTO_TCP;
    val_context_t *context = NULL;
    val_status_t val_status;
    struct addrinfo *val_ainfo = NULL;
    struct addrinfo hints;
    int ret = 0;
    int dane_retval = VAL_DANE_INTERNAL_ERROR;
    int ai_retval = 0;
    int err;

    /* Parse the command line */
    while (1) {
        int             c;
#ifdef HAVE_GETOPT_LONG
        int             opt_index = 0;
#ifdef HAVE_GETOPT_LONG_ONLY
        c = getopt_long_only(argc, argv, allowed_args,
                             prog_options, &opt_index);
#else
        c = getopt_long(argc, argv, allowed_args, prog_options, &opt_index);
#endif
#else                           /* only have getopt */
        c = getopt(argc, argv, allowed_args);
#endif

        if (c == -1) {
            break;
        }

        switch (c) {
        case 'h':
            usage(argv[0]);
            return -1;
        case 'l':
            label_str = optarg;
            break;
        case 'o':
            logp = val_log_add_optarg(optarg, 1);
            if (NULL == logp) { /* err msg already logged */
                usage(argv[0]);
                return -1;
            }
            break;

        case 's':
            async = 0;
            break;

        case 'p':
            port = atoi(optarg);
            break;

        case 'x':
            if(strncmp(optarg, DANE_PARAM_PROTO_STR_TCP,
                       strlen(DANE_PARAM_PROTO_STR_TCP)))
                proto = DANE_PARAM_PROTO_TCP;
            else if (strncmp(optarg, DANE_PARAM_PROTO_STR_UDP,
                        strlen(DANE_PARAM_PROTO_STR_UDP)))
                proto = DANE_PARAM_PROTO_UDP;
            else if (strncmp(optarg, DANE_PARAM_PROTO_STR_SCTP, 
                        strlen(DANE_PARAM_PROTO_STR_SCTP)))
                proto = DANE_PARAM_PROTO_SCTP;
            else {
                usage(argv[0]);
                return -1;
            }
            break;

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

        case 'i':
            root_hints_set(optarg);
            break;

        case 'r':
            resolv_conf_set(optarg);
            break;

        case 'V':
            version();
            return 0;
        default:
            fprintf(stderr, "Invalid option %s\n", argv[optind - 1]);
            usage(argv[0]);
            return -1;
        }
    }

    if (optind < argc) {
        node = argv[optind++];
    } else {
        fprintf(stderr, "Error: node name not specified\n");
        usage(argv[0]);
        return -1;
    }

    if (VAL_NO_ERROR != (retval = 
                val_create_context(label_str, &context))) {
        fprintf(stderr, "Cannot create context %s(%d)\n", 
                p_val_error(retval), retval);
        return -1;
    }

    daneparams.port = port;
    daneparams.proto = proto;
    memset(&hints, 0, sizeof(struct addrinfo));
#ifdef AI_ADDRCONFIG
    hints.ai_flags = AI_ADDRCONFIG;
#endif

    if (!async) {
        /* synchronous lookup and validation */
        ai_retval = val_getaddrinfo(context, node, NULL, &hints,
                                    &val_ainfo, &val_status);
        dane_retval = val_getdaneinfo(context, node, &daneparams, &danestatus); 
    }
    else {
#ifdef VAL_NO_ASYNC
        fprintf(stderr, "async support not available\n");
#else
        struct dane_cb cb_data_dane = { &dane_retval, &danestatus, 0 };
        val_dane_callback my_dane_cb = &_danecallback;
        struct timeval tv;
        val_async_status *das = NULL; /* helps us cancel the lookup if we need to */

        struct getaddr_s cb_data_ai = { &ai_retval, &val_ainfo, &val_status, 0 };
        val_gai_callback my_ai_cb = &_aicallback;
        val_gai_status *status = NULL;

        /*
         * submit requests
         */
        if (VAL_NO_ERROR != val_dane_submit(context, node, &daneparams,
                                 my_dane_cb, &cb_data_dane, &das) ||
            VAL_NO_ERROR != val_getaddrinfo_submit(context, node, NULL,
                                &hints, my_ai_cb, &cb_data_ai, 0, &status)) {
            dane_retval = VAL_DANE_INTERNAL_ERROR; 
            goto done;
        }

        /*
         * wait for it to complete
         */
#if 0
        while(0 == cb_data_dane.done ||
              0 == cb_data_ai.done) {
            tv.tv_sec = 10;
            tv.tv_usec = 0;
            val_async_check_wait(context, NULL, NULL, &tv, 0);
        }
#endif

#if 1
        while(0 == cb_data_dane.done || 
              0 == cb_data_ai.done) {
            fd_set  activefds;
            int nfds = 0;
            int ready;

            FD_ZERO(&activefds);

            tv.tv_sec = 10; /* 10 sec */
            tv.tv_usec = 0;

            val_async_select_info(context, &activefds, &nfds, &tv);
            ready = select(nfds+1, &activefds, NULL, NULL, &tv);
            if (ready < 0) {
                continue;
            } 
            val_async_check(context, &activefds, &nfds, 0);
        }
#endif

#endif
    }

done:
    if (ai_retval != 0) {
        fprintf(stderr, "Error in val_getaddrinfo(): %d\n", ai_retval);
        return -1;
    }

    if (!val_istrusted(val_status)) {
        fprintf(stderr, 
                "Address lookup information could not be validated: %s\n", 
                p_val_status(val_status));

    } else if(dane_retval == VAL_DANE_NOERROR && 
              proto == DANE_PARAM_PROTO_TCP) {

        /* Set up the SSL connection */
        SSL_library_init();
        SSL_load_error_strings();

        const SSL_METHOD *meth = SSLv23_client_method();
        SSL_CTX *sslctx = SSL_CTX_new(meth);

        struct addrinfo *ai = NULL;
        int presetup_okay;

        /*
         * OpenSSL only does protocol negotiation on SSLv23_client_method;
         * we need to set SNI to get the correct certificate from many
         * modern browsers, so we disable both SSLv2 and SSLv3 if we can.
         * That leaves (currently) TLSv1.0 TLSv1.1 TLSv1.2
         */
        long ssl_options = 0
#ifdef SSL_OP_NO_SSLv2
            | SSL_OP_NO_SSLv2
#endif
#ifdef SSL_OP_NO_SSLv3
            | SSL_OP_NO_SSLv3
#endif
            ;

        if (!SSL_CTX_set_options(sslctx, ssl_options)) {
            fprintf(stderr, "Failed to set SSL context options (%ld): %s\n",
              ssl_options, ssl_error());
            presetup_okay = 0;
        } else {
            presetup_okay = 1;
        }

        if (VAL_NO_ERROR != (err = val_enable_dane_ssl(context, sslctx, node,
                                        danestatus, &ssl_dane_data))) {
            fprintf(stderr,
                    "Could not set danestatus for SSL connection %s\n",
                    p_val_error(err));
        }

        ai = val_ainfo;
        while(presetup_okay && ai && (ai->ai_protocol == IPPROTO_TCP) && 
             (ai->ai_family == AF_INET || ai->ai_family == AF_INET6)) {

            int sock;
            char buf[INET6_ADDRSTRLEN];
            size_t buflen = sizeof(buf);
            const char *addr = NULL;

            if (ai->ai_family == AF_INET) {
                sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
                ((struct sockaddr_in *)(ai)->ai_addr)->sin_port = htons(port);
            } else {
                sock = socket(AF_INET6, SOCK_STREAM, IPPROTO_TCP);
                ((struct sockaddr_in6 *)(ai)->ai_addr)->sin6_port = htons(port);
            }

            INET_NTOP(ai->ai_family, ai->ai_addr, sizeof(ai->ai_addr), buf, buflen, addr);
            fprintf(stderr, "Connecting to %s\n", addr);

            if (0 == connect(sock, ai->ai_addr, ai->ai_addrlen)) {
                SSL *ssl = SSL_new(sslctx);
                BIO * sbio = BIO_new_socket(sock,BIO_NOCLOSE);


#if OPENSSL_VERSION_NUMBER >= 0x0090806fL && !defined(OPENSSL_NO_TLSEXT)
                SSL_set_tlsext_host_name(ssl, node);
#endif

                SSL_set_bio(ssl,sbio,sbio);

                if ((err = SSL_connect(ssl)) != 1) {
                    fprintf(stderr, "SSL Connect to %s failed: %d\n", node, err);
                } 
                SSL_shutdown(ssl);
                SSL_free(ssl);
            } else {
                fprintf(stderr, "TCP Connect to %s failed\n", node);
            }

            ai = (struct addrinfo *) (ai->ai_next);
        }

    } else if (dane_retval == VAL_DANE_IGNORE_TLSA) {
        fprintf(stderr, "TLSA is either provably non-existant or provably insecure. It will be ignored.\n");
    } else {
        fprintf(stderr, "TLSA record could not be validated.\n");
        ret = 1;
    }

    if (danestatus != NULL)
        val_free_dane(danestatus);

    if (val_ainfo != NULL)
        val_freeaddrinfo(val_ainfo);    

    val_free_dane_ssl(ssl_dane_data);/* MUST happen before we free the context*/
    val_free_context(context);
    val_free_validator_state();

    return ret;
}
Пример #26
0
/**
 * @brief main of scepclient
 *
 * @param argc number of arguments
 * @param argv pointer to the argument values
 */
int main(int argc, char **argv)
{
	/* external values */
	extern char * optarg;
	extern int optind;

	/* type of input and output files */
	typedef enum {
		PKCS1      =  0x01,
		PKCS10     =  0x02,
		PKCS7      =  0x04,
		CERT_SELF  =  0x08,
		CERT       =  0x10,
		CACERT_ENC =  0x20,
		CACERT_SIG =  0x40
	} scep_filetype_t;

	/* filetype to read from, defaults to "generate a key" */
	scep_filetype_t filetype_in = 0;

	/* filetype to write to, no default here */
	scep_filetype_t filetype_out = 0;

	/* input files */
	char *file_in_pkcs1      = DEFAULT_FILENAME_PKCS1;
	char *file_in_cacert_enc = DEFAULT_FILENAME_CACERT_ENC;
	char *file_in_cacert_sig = DEFAULT_FILENAME_CACERT_SIG;

	/* output files */
	char *file_out_pkcs1     = DEFAULT_FILENAME_PKCS1;
	char *file_out_pkcs10    = DEFAULT_FILENAME_PKCS10;
	char *file_out_pkcs7     = DEFAULT_FILENAME_PKCS7;
	char *file_out_cert_self = DEFAULT_FILENAME_CERT_SELF;
	char *file_out_cert      = DEFAULT_FILENAME_CERT;
	char *file_out_prefix_cacert = DEFAULT_FILENAME_PREFIX_CACERT;

	/* by default user certificate is requested */
	bool request_ca_certificate = FALSE;

	/* by default existing files are not overwritten */
	bool force = FALSE;

	/* length of RSA key in bits */
	u_int rsa_keylength = DEFAULT_RSA_KEY_LENGTH;

	/* validity of self-signed certificate */
	time_t validity  = DEFAULT_CERT_VALIDITY;
	time_t notBefore = 0;
	time_t notAfter  = 0;

	/* distinguished name for requested certificate, ASCII format */
	char *distinguishedName = NULL;

	/* challenge password */
	char challenge_password_buffer[MAX_PASSWORD_LENGTH];

	/* symmetric encryption algorithm used by pkcs7, default is 3DES */
	int pkcs7_symmetric_cipher = OID_3DES_EDE_CBC;

	/* digest algorithm used by pkcs7, default is SHA-1 */
	int pkcs7_digest_alg = OID_SHA1;

	/* signature algorithm used by pkcs10, default is SHA-1 */
	hash_algorithm_t pkcs10_signature_alg = HASH_SHA1;

	/* URL of the SCEP-Server */
	char *scep_url = NULL;

	/* http request method, default is GET */
	bool http_get_request = TRUE;

	/* poll interval time in manual mode in seconds */
	u_int poll_interval = DEFAULT_POLL_INTERVAL;

	/* maximum poll time */
	u_int max_poll_time = 0;

	err_t ugh = NULL;

	/* initialize library */
	if (!library_init(NULL))
	{
		library_deinit();
		exit(SS_RC_LIBSTRONGSWAN_INTEGRITY);
	}
	if (lib->integrity &&
		!lib->integrity->check_file(lib->integrity, "scepclient", argv[0]))
	{
		fprintf(stderr, "integrity check of scepclient failed\n");
		library_deinit();
		exit(SS_RC_DAEMON_INTEGRITY);
	}

	/* initialize global variables */
	pkcs1             = chunk_empty;
	pkcs7             = chunk_empty;
	serialNumber      = chunk_empty;
	transID           = chunk_empty;
	fingerprint       = chunk_empty;
	encoding          = chunk_empty;
	pkcs10_encoding   = chunk_empty;
	issuerAndSubject  = chunk_empty;
	challengePassword = chunk_empty;
	getCertInitial    = chunk_empty;
	scep_response     = chunk_empty;
	subjectAltNames   = linked_list_create();
	options           = options_create();
	log_to_stderr     = TRUE;

	for (;;)
	{
		static const struct option long_opts[] = {
			/* name, has_arg, flag, val */
			{ "help", no_argument, NULL, 'h' },
			{ "version", no_argument, NULL, 'v' },
			{ "optionsfrom", required_argument, NULL, '+' },
			{ "quiet", no_argument, NULL, 'q' },
			{ "in", required_argument, NULL, 'i' },
			{ "out", required_argument, NULL, 'o' },
			{ "force", no_argument, NULL, 'f' },
			{ "keylength", required_argument, NULL, 'k' },
			{ "dn", required_argument, NULL, 'd' },
			{ "days", required_argument, NULL, 'D' },
			{ "startdate", required_argument, NULL, 'S' },
			{ "enddate", required_argument, NULL, 'E' },
			{ "subjectAltName", required_argument, NULL, 's' },
			{ "password", required_argument, NULL, 'p' },
			{ "algorithm", required_argument, NULL, 'a' },
			{ "url", required_argument, NULL, 'u' },
			{ "method", required_argument, NULL, 'm' },
			{ "interval", required_argument, NULL, 't' },
			{ "maxpolltime", required_argument, NULL, 'x' },
#ifdef DEBUG
			{ "debug-all", no_argument, NULL, 'A' },
			{ "debug-parsing", no_argument, NULL, 'P'},
			{ "debug-raw", no_argument, NULL, 'R'},
			{ "debug-control", no_argument, NULL, 'C'},
			{ "debug-controlmore", no_argument, NULL, 'M'},
			{ "debug-private", no_argument, NULL, 'X'},
#endif
			{ 0,0,0,0 }
		};

		/* parse next option */
		int c = getopt_long(argc, argv, "hv+:qi:o:fk:d:s:p:a:u:m:t:x:APRCMS", long_opts, NULL);

		switch (c)
		{
		case EOF:       /* end of flags */
			break;

		case 'h':       /* --help */
			usage(NULL);

		case 'v':       /* --version */
			version();

		case 'q':       /* --quiet */
			log_to_stderr = FALSE;
			continue;

		case 'i':       /* --in <type> [= <filename>] */
			{
				char *filename = strstr(optarg, "=");

				if (filename)
				{
					/* replace '=' by '\0' */
					*filename = '\0';
					/* set pointer to start of filename */
					filename++;
				}
				if (strcaseeq("pkcs1", optarg))
				{
					filetype_in |= PKCS1;
					if (filename)
						file_in_pkcs1 = filename;
				}
				else if (strcaseeq("cacert-enc", optarg))
				{
					filetype_in |= CACERT_ENC;
					if (filename)
						file_in_cacert_enc = filename;
				}
				else if (strcaseeq("cacert-sig", optarg))
				{
					filetype_in |= CACERT_SIG;
					if (filename)
						 file_in_cacert_sig = filename;
				}
				else
				{
					usage("invalid --in file type");
				}
				continue;
			}

		case 'o':       /* --out <type> [= <filename>] */
			{
				char *filename = strstr(optarg, "=");

				if (filename)
				{
					/* replace '=' by '\0' */
					*filename = '\0';
					/* set pointer to start of filename */
					filename++;
				}
				if (strcaseeq("pkcs1", optarg))
				{
					filetype_out |= PKCS1;
					if (filename)
						file_out_pkcs1 = filename;
				}
				else if (strcaseeq("pkcs10", optarg))
				{
					filetype_out |= PKCS10;
					if (filename)
						file_out_pkcs10 = filename;
				}
				else if (strcaseeq("pkcs7", optarg))
				{
					filetype_out |= PKCS7;
					if (filename)
						file_out_pkcs7 = filename;
				}
				else if (strcaseeq("cert-self", optarg))
				{
					filetype_out |= CERT_SELF;
					if (filename)
						file_out_cert_self = filename;
				}
				else if (strcaseeq("cert", optarg))
				{
					filetype_out |= CERT;
					if (filename)
						file_out_cert = filename;
				}
				else if (strcaseeq("cacert", optarg))
				{
					request_ca_certificate = TRUE;
					if (filename)
						file_out_prefix_cacert = filename;
				}
				else
				{
					usage("invalid --out file type");
				}
				continue;
			}

		case 'f':       /* --force */
			force = TRUE;
			continue;

		case '+':       /* --optionsfrom <filename> */
			if (!options->from(options, optarg, &argc, &argv, optind))
			{
				exit_scepclient("optionsfrom failed");
			}
			continue;

		case 'k':        /* --keylength <length> */
			{
				div_t q;

				rsa_keylength = atoi(optarg);
				if (rsa_keylength == 0)
					usage("invalid keylength");

				/* check if key length is a multiple of 8 bits */
				q = div(rsa_keylength, 2*BITS_PER_BYTE);
				if (q.rem != 0)
				{
					exit_scepclient("keylength is not a multiple of %d bits!"
						, 2*BITS_PER_BYTE);
				}
				continue;
			}

		case 'D':       /* --days */
			if (optarg == NULL || !isdigit(optarg[0]))
				usage("missing number of days");
			{
				char *endptr;
				long days = strtol(optarg, &endptr, 0);

				if (*endptr != '\0' || endptr == optarg
				|| days <= 0)
					usage("<days> must be a positive number");
				validity = 24*3600*days;
			}
			continue;

		case 'S':       /* --startdate */
			if (optarg == NULL || strlen(optarg) != 13 || optarg[12] != 'Z')
				usage("date format must be YYMMDDHHMMSSZ");
			{
				chunk_t date = { optarg, 13 };
				notBefore = asn1_to_time(&date, ASN1_UTCTIME);
			}
			continue;

		case 'E':       /* --enddate */
			if (optarg == NULL || strlen(optarg) != 13 || optarg[12] != 'Z')
				usage("date format must be YYMMDDHHMMSSZ");
			{
				chunk_t date = { optarg, 13 };
				notAfter = asn1_to_time(&date, ASN1_UTCTIME);
			}
			continue;

		case 'd':       /* --dn */
			if (distinguishedName)
				usage("only one distinguished name allowed");
			distinguishedName = optarg;
			continue;

		case 's':       /* --subjectAltName */
			{
				char *value = strstr(optarg, "=");

				if (value)
				{
					/* replace '=' by '\0' */
					*value = '\0';
					/* set pointer to start of value */
					value++;
				}

				if (strcaseeq("email", optarg) ||
					strcaseeq("dns", optarg)   ||
					strcaseeq("ip", optarg))
				{
					subjectAltNames->insert_last(subjectAltNames,
								 identification_create_from_string(value));
					continue;
				}
				else
				{
					usage("invalid --subjectAltName type");
					continue;
				}
			}

		case 'p':       /* --password */
			if (challengePassword.len > 0)
			{
				usage("only one challenge password allowed");
			}
			if (strcaseeq("%prompt", optarg))
			{
				printf("Challenge password: "******"challenge password could not be read");
				}
			}
			else
			{
				challengePassword.ptr = optarg;
				challengePassword.len = strlen(optarg);
			}
			continue;

		case 'u':       /* -- url */
			if (scep_url)
			{
				usage("only one URL argument allowed");
			}
			scep_url = optarg;
			continue;

		case 'm':       /* --method */
			if (strcaseeq("get", optarg))
			{
				http_get_request = TRUE;
			}
			else if (strcaseeq("post", optarg))
			{
				http_get_request = FALSE;
			}
			else
			{
				usage("invalid http request method specified");
			}
			continue;

		case 't':       /* --interval */
			poll_interval = atoi(optarg);
			if (poll_interval <= 0)
			{
				usage("invalid interval specified");
			}
			continue;

		case 'x':       /* --maxpolltime */
			max_poll_time = atoi(optarg);
			if (max_poll_time < 0)
			{
				usage("invalid maxpolltime specified");
			}
			continue;

		case 'a':       /*--algorithm */
		{
			const proposal_token_t *token;

			token = proposal_get_token(optarg, strlen(optarg));
			if (token == NULL || token->type != ENCRYPTION_ALGORITHM)
			{
				usage("invalid algorithm specified");
			}
			pkcs7_symmetric_cipher = encryption_algorithm_to_oid(
										token->algorithm, token->keysize);
			if (pkcs7_symmetric_cipher == OID_UNKNOWN)
			{
				usage("unsupported encryption algorithm specified");
			}
			continue;
		}
#ifdef DEBUG
		case 'A':       /* --debug-all */
			base_debugging |= DBG_ALL;
			continue;
		case 'P':       /* debug parsing */
			base_debugging |= DBG_PARSING;
			continue;
		case 'R':       /* debug raw */
			base_debugging |= DBG_RAW;
			continue;
		case 'C':       /* debug control */
			base_debugging |= DBG_CONTROL;
			continue;
		case 'M':       /* debug control more */
			base_debugging |= DBG_CONTROLMORE;
			continue;
		case 'X':       /* debug private */
			base_debugging |= DBG_PRIVATE;
			continue;
#endif
		default:
			usage("unknown option");
		}
		/* break from loop */
		break;
	}
	cur_debugging = base_debugging;

	init_log("scepclient");

	/* load plugins, further infrastructure may need it */
	if (!lib->plugins->load(lib->plugins, NULL,
			lib->settings->get_str(lib->settings, "scepclient.load", PLUGINS)))
	{
		exit_scepclient("plugin loading failed");
	}
	print_plugins();

	if ((filetype_out == 0) && (!request_ca_certificate))
	{
		usage ("--out filetype required");
	}
	if (request_ca_certificate && (filetype_out > 0 || filetype_in > 0))
	{
		usage("in CA certificate request, no other --in or --out option allowed");
	}

	/* check if url is given, if cert output defined */
	if (((filetype_out & CERT) || request_ca_certificate) && !scep_url)
	{
		usage("URL of SCEP server required");
	}

	/* check for sanity of --in/--out */
	if (!filetype_in && (filetype_in > filetype_out))
	{
		usage("cannot generate --out of given --in!");
	}

	/*
	 * input of PKCS#1 file
	 */
	if (filetype_in & PKCS1)    /* load an RSA key pair from file */
	{
		char *path = concatenate_paths(PRIVATE_KEY_PATH, file_in_pkcs1);

		private_key = lib->creds->create(lib->creds, CRED_PRIVATE_KEY, KEY_RSA,
										 BUILD_FROM_FILE, path, BUILD_END);
	}
	else                                /* generate an RSA key pair */
	{
		private_key = lib->creds->create(lib->creds, CRED_PRIVATE_KEY, KEY_RSA,
										 BUILD_KEY_SIZE, rsa_keylength,
										 BUILD_END);
	}
	if (private_key == NULL)
	{
		exit_scepclient("no RSA private key available");
	}
	public_key = private_key->get_public_key(private_key);

	/* check for minimum key length */
	if (private_key->get_keysize(private_key) < RSA_MIN_OCTETS / BITS_PER_BYTE)
	{
		exit_scepclient("length of RSA key has to be at least %d bits"
			,RSA_MIN_OCTETS * BITS_PER_BYTE);
	}

	/*
	 * input of PKCS#10 file
	 */
	if (filetype_in & PKCS10)
	{
		/* user wants to load a pkcs10 request
		 * operation is not yet supported
		 * would require a PKCS#10 parsing function

		pkcs10 = pkcs10_read_from_file(file_in_pkcs10);

		 */
	}
	else
	{
		if (distinguishedName == NULL)
		{
			char buf[BUF_LEN];
			int n = sprintf(buf, DEFAULT_DN);

			/* set the common name to the hostname */
			if (gethostname(buf + n, BUF_LEN - n) || strlen(buf) == n)
			{
				exit_scepclient("no hostname defined, use "
								"--dn <distinguished name> option");
			}
			distinguishedName = buf;
		}

		DBG(DBG_CONTROL,
			DBG_log("dn: '%s'", distinguishedName);
		)
		subject = identification_create_from_string(distinguishedName);
		if (subject->get_type(subject) != ID_DER_ASN1_DN)
		{
			exit_scepclient("parsing of distinguished name failed");
		}

		DBG(DBG_CONTROL,
			DBG_log("building pkcs10 object:")
		)
		pkcs10_req = lib->creds->create(lib->creds, CRED_CERTIFICATE,
						CERT_PKCS10_REQUEST,
						BUILD_SIGNING_KEY, private_key,
						BUILD_SUBJECT, subject,
						BUILD_SUBJECT_ALTNAMES, subjectAltNames,
						BUILD_CHALLENGE_PWD, challengePassword,
						BUILD_DIGEST_ALG, pkcs10_signature_alg,
						BUILD_END);
		if (!pkcs10_req)
		{
			exit_scepclient("generating pkcs10 request failed");
		}
		pkcs10_req->get_encoding(pkcs10_req, CERT_ASN1_DER, &pkcs10_encoding);
		fingerprint = scep_generate_pkcs10_fingerprint(pkcs10_encoding);
		plog("  fingerprint:    %s", fingerprint.ptr);
	}
Пример #27
0
        void run() {

            int numShards = 10;
            int numInitialChunks = 5;
            int maxChunks = 100000; // Needed to not overflow the BSONArray's max bytes
            int keySize = 2;

            BSONArrayBuilder chunksB;

            BSONObj lastSplitPt;
            ShardChunkVersion version( 1, 0, OID() );

            //
            // Generate numChunks with a given key size over numShards
            // All chunks have double key values, so we can split them a bunch
            //

            for( int i = -1; i < numInitialChunks; i++ ){

                BSONObjBuilder splitPtB;
                for( int k = 0; k < keySize; k++ ){
                    string field = string( "k" ) + string( 1, (char)('0' + k) );
                    if( i < 0 )
                        splitPtB.appendMinKey( field );
                    else if( i < numInitialChunks - 1 )
                        splitPtB.append( field, (double)i );
                    else
                        splitPtB.appendMaxKey( field );
                }
                BSONObj splitPt = splitPtB.obj();

                if( i >= 0 ){
                    BSONObjBuilder chunkB;

                    chunkB.append( "min", lastSplitPt );
                    chunkB.append( "max", splitPt );

                    int shardNum = rand( numShards );
                    chunkB.append( "shard", "shard" + string( 1, (char)('A' + shardNum) ) );

                    rand( 2 ) ? version.incMajor() : version.incMinor();
                    version.addToBSON( chunkB, "lastmod" );

                    chunksB.append( chunkB.obj() );
                }

                lastSplitPt = splitPt;
            }

            BSONArray chunks = chunksB.arr();

            // log() << "Chunks generated : " << chunks << endl;

            DBClientMockCursor chunksCursor( chunks );

            // Setup the empty ranges and versions first
            RangeMap ranges;
            ShardChunkVersion maxVersion = ShardChunkVersion( 0, 0, OID() );
            VersionMap maxShardVersions;

            // Create a differ which will track our progress
            boost::shared_ptr< DefaultDiffAdapter > differ( _inverse ? new InverseDiffAdapter() : new DefaultDiffAdapter() );
            differ->attach( "test", ranges, maxVersion, maxShardVersions );

            // Validate initial load
            differ->calculateConfigDiff( chunksCursor );
            validate( chunks, ranges, maxVersion, maxShardVersions );

            // Generate a lot of diffs, and keep validating that updating from the diffs always
            // gives us the right ranges and versions

            int numDiffs = 135; // Makes about 100000 chunks overall
            int numChunks = numInitialChunks;
            for( int i = 0; i < numDiffs; i++ ){

                // log() << "Generating new diff... " << i << endl;

                BSONArrayBuilder diffsB;
                BSONArrayBuilder newChunksB;
                BSONObjIterator chunksIt( chunks );

                while( chunksIt.more() ){

                    BSONObj chunk = chunksIt.next().Obj();

                    int randChoice = rand( 10 );

                    if( randChoice < 2 && numChunks < maxChunks ){
                        // Simulate a split

                        // log() << " ...starting a split with chunk " << chunk << endl;

                        BSONObjBuilder leftB;
                        BSONObjBuilder rightB;
                        BSONObjBuilder midB;

                        for( int k = 0; k < keySize; k++ ){
                            string field = string( "k" ) + string( 1, (char)('0' + k) );

                            BSONType maxType = chunk["max"].Obj()[field].type();
                            double max = maxType == NumberDouble ? chunk["max"].Obj()[field].Number() : 0.0;
                            BSONType minType = chunk["min"].Obj()[field].type();
                            double min = minType == NumberDouble ? chunk["min"].Obj()[field].Number() : 0.0;

                            if( minType == MinKey ){
                                midB.append( field, max - 1.0 );
                            }
                            else if( maxType == MaxKey ){
                                midB.append( field, min + 1.0 );
                            }
                            else {
                                midB.append( field, ( max + min ) / 2.0 );
                            }
                        }

                        BSONObj midPt = midB.obj();
                        // Only happens if we can't split the min chunk
                        if( midPt.isEmpty() ) continue;

                        leftB.append( chunk["min"] );
                        leftB.append( "max", midPt );
                        rightB.append( "min", midPt );
                        rightB.append( chunk["max"] );

                        leftB.append( chunk["shard"] );
                        rightB.append( chunk["shard"] );

                        version.incMajor();
                        version._minor = 0;
                        version.addToBSON( leftB, "lastmod" );
                        version.incMinor();
                        version.addToBSON( rightB, "lastmod" );

                        BSONObj left = leftB.obj();
                        BSONObj right = rightB.obj();

                        // log() << " ... split into " << left << " and " << right << endl;

                        newChunksB.append( left );
                        newChunksB.append( right );

                        diffsB.append( right );
                        diffsB.append( left );

                        numChunks++;
                    }
                    else if( randChoice < 4 && chunksIt.more() ){
                        // Simulate a migrate

                        // log() << " ...starting a migrate with chunk " << chunk << endl;

                        BSONObj prevShardChunk;
                        while( chunksIt.more() ){
                            prevShardChunk = chunksIt.next().Obj();
                            if( prevShardChunk["shard"].String() == chunk["shard"].String() ) break;

                            // log() << "... appending chunk from diff shard: " << prevShardChunk << endl;
                            newChunksB.append( prevShardChunk );

                            prevShardChunk = BSONObj();
                        }

                        // We need to move between different shards, hence the weirdness in logic here
                        if( ! prevShardChunk.isEmpty() ){

                            BSONObjBuilder newShardB;
                            BSONObjBuilder prevShardB;

                            newShardB.append( chunk["min"] );
                            newShardB.append( chunk["max"] );
                            prevShardB.append( prevShardChunk["min"] );
                            prevShardB.append( prevShardChunk["max"] );

                            int shardNum = rand( numShards );
                            newShardB.append( "shard", "shard" + string( 1, (char)('A' + shardNum) ) );
                            prevShardB.append( prevShardChunk["shard"] );

                            version.incMajor();
                            version._minor = 0;
                            version.addToBSON( newShardB, "lastmod" );
                            version.incMinor();
                            version.addToBSON( prevShardB, "lastmod" );

                            BSONObj newShard = newShardB.obj();
                            BSONObj prevShard = prevShardB.obj();

                            // log() << " ... migrated to " << newShard << " and updated " << prevShard << endl;

                            newChunksB.append( newShard );
                            newChunksB.append( prevShard );

                            diffsB.append( newShard );
                            diffsB.append( prevShard );

                        }
                        else{
                            // log() << "... appending chunk, no more left: " << chunk << endl;
                            newChunksB.append( chunk );
                        }
                    }
                    else{
                        // log() << "Appending chunk : " << chunk << endl;
                        newChunksB.append( chunk );
                    }

                }

                BSONArray diffs = diffsB.arr();
                chunks = newChunksB.arr();

                // log() << "Diffs generated : " << diffs << endl;
                // log() << "All chunks : " << chunks << endl;

                // Rarely entirely clear out our data
                if( rand( 10 ) < 1 ){
                    diffs = chunks;
                    ranges.clear();
                    maxVersion = ShardChunkVersion( 0, 0, OID() );
                    maxShardVersions.clear();
                }

                // log() << "Total number of chunks : " << numChunks << " iteration " << i << endl;

                DBClientMockCursor diffCursor( diffs );

                differ->calculateConfigDiff( diffCursor );

                validate( chunks, ranges, maxVersion, maxShardVersions );

            }

        }
Пример #28
0
Файл: main.c Проект: zayac/eq
int
main (int argc, char *argv[])
{
  int c, ret = 0;
  char *subopts;
  char *value;
  char *src_name = NULL;
  extern char *optarg;
  extern int optind;

  struct eq_lexer *lex = (struct eq_lexer *) malloc (sizeof (struct eq_lexer));
  struct eq_parser *parser = (struct eq_parser *) malloc (sizeof (struct eq_parser));

  init_global ();
  init_global_tree ();
  init_options ();

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

  while (-1 != (c = getopt (argc, argv, "B:P:V")))
    switch (c)
      {
      case 'P':
	subopts = optarg;
	while (*subopts != '\0')
	  switch (getsubopt (&subopts, p_opts, &value))
	    {
	    case OPT_PRINT_PROGRAM:
	      options.print_program = true;
	      break;
	    case OPT_PRINT_MATCHES:
	      options.print_matches = true;
	      break;
	    case OPT_PRINT_TYPES:
	      options.print_types = true;
	      break;
	    default:
	      fprintf (stderr, "unknown -P suboption `%s'\n", value);
	      goto cleanup;
	      break;
	    }
	break;
      case 'B':
	subopts = optarg;
	while (*subopts != '\0')
	  switch (getsubopt (&subopts, b_opts, &value))
	    {
	    case OPT_BREAK_PARSER:
	      options.break_option = break_parser;
	      break;
	    case OPT_BREAK_TYPECHECK:
	      options.break_option = break_typecheck;
	      break;
	    case OPT_BREAK_CONTROLFLOW:
	      options.break_option = break_controlflow;
	    case OPT_BREAK_DATAFLOW:
	      options.break_option = break_dataflow;
	      break;
	    default:
	      fprintf (stderr, "unknown -B suboption `%s'\n", value);
	      goto cleanup;
	      break;
	    }
	break;
      case 'V':
	version ();
	goto cleanup;
      default:
	usage ();
	goto cleanup;
      }

  if (options.print_types
      && !(options.print_program || options.print_matches))
    fprintf (stderr, "warning: 'types' flag is useless without either "
	     "'program' flag or 'matches' flag\n");

  argv += optind;

  /* FIXME: What if we have multiple files?  */
  if (NULL == *argv)
    {
      fprintf (stderr, "%s:error: filename argument required\n", progname);
      usage ();
      ret = -1;
      goto cleanup;
    }

  /* Initialize the lexer.  */
  if (!eq_lexer_init (lex, *argv))
    {
      fprintf (stderr, "%s cannot create a lexer for file `%s'\n", progname,
	       *argv);
      ret = -2;
      goto cleanup;
    }
  else
    {
      /* Discard extension from file to compile.  */
      char* start = strrchr (*argv, '/');
      char* ext = strrchr (*argv, '.');
      int size = 0;
      
      if (start == NULL)
	start = *argv;
      else
	start += 1;
      if (ext == NULL)
	size = strlen(start);
      else
	size = ext - start;
      src_name = strndup (start, size);
    }


  /* Initialize the parser.  */
  eq_parser_init (parser, lex);

  if ((ret += eq_parse (parser)) == 0 && options.break_option != break_parser)
    ret += typecheck ();

  /* printing debug routine.  */
  if (options.print_program)
    {
      xfile *  xf = xfile_init_file_stdout ();

      printf ("\n######### Output ########\n");

      print_program (xf);

      xfile_finalize (xf);
    }

  if (options.print_matches)
    {
      printf ("\n####### Transforms ########\n");
      print_matches ();
    }
 
  if (options.break_option != break_typecheck
   && options.break_option != break_parser && !ret)
    controlflow ();

  if (options.break_option != break_controlflow
   && options.break_option != break_typecheck
   && options.break_option != break_parser && !ret)
    dataflow ();

  if (options.break_option != break_dataflow
   && options.break_option != break_controlflow
   && options.break_option != break_typecheck
   && options.break_option != break_parser && !ret)
    codegen (src_name);
  printf ("note: finished compiling.\n");

  free (src_name);
cleanup:
  eq_parser_finalize (parser);
  finalize_global_tree ();
  finalize_global ();

  /* That should be called at the very end.  */
  free_atomic_trees ();

  if (parser)
    free (parser);
  if (lex)
    free (lex);

  return ret == 0 ? EXIT_SUCCESS : EXIT_FAILURE;
}
Пример #29
0
int main(int argc, char *argv[])	{
	int ret=0;
	argc--;
	argv0 = *argv++;
	int done=0;

	while(argc>0) {
		if (argc > 0 && strcmp(*argv, "--chip_awake") == 0) {
			/* WLAN enable */
			chip_awake(2);
			return ASI_SUCCESS;
		}
		else if (argc > 0 && strcmp(*argv, "--on") == 0) {
			/* WLAN enable */
			chip_awake(1);
			return ASI_SUCCESS;
		}
		else if (argc > 0 && strcmp(*argv, "--off") == 0) {
			/* WLAN enable */
			chip_awake(0);
			return ASI_SUCCESS;
		}
		else if (argc > 0 && strcmp(*argv, "--log") == 0) {
			argc--;
			argv++;
			ret=LOG_FILE_FAIL;
			if(argc>0) {
				ret=log_init(LOG_TO_FILE, *argv);
				argc--;
				argv++;
			}
			if (ret!=LOG_FILE_SUCCESS) {
				usage();
				return ASI_FAIL;
			}
		}
		else if (argc > 0 && strcmp(*argv, "--debug") == 0) {
			argc--;
			argv++;
			ret=log_init(LOG_PRNT_SCR, NULL);
			if (ret!=LOG_FILE_SUCCESS) {
				usage();
				return ASI_FAIL;
			}
		}
		else if (argc > 0 && ((strcmp(*argv, "--version") == 0) ||
				 (strcmp(*argv, "-v") == 0))) {
			version();
			return ASI_SUCCESS;
		}
		else if(argc==1){
			if (set_debugfs_sdio(*argv) !=ASI_SUCCESS) {
				usage();
				return ASI_FAIL;
			}
			argc--;
			argv++;
		}
		else {
			usage();
			return ASI_FAIL;
		}
	}


	if ( argc > 0 || get_debugfs_sdio_file_status() != ASI_SUCCESS) {
		usage();
		return ASI_FAIL;
	}

	start_adb_socket();
    return ASI_SUCCESS;
}
Пример #30
0
int main(int argc, char* argv[])
{
	char*	config_path	= NULL;
	char*	pid_path	= NULL;
	int 	daemon		= 1;
	int 	c		= 0;
	int 	pid_path_set	= 0;
	int 	daemon_set	= 0;
	pid_t 	pid		= 0;
	eemo_rv	rv		= ERV_OK;
	
	while ((c = getopt(argc, argv, "fc:p:Ghv")) != -1)
	{
		switch(c)
		{
		case 'f':
			daemon = 0;
			daemon_set = 1;
			break;
		case 'c':
			config_path = strdup(optarg);

			if (config_path == NULL)
			{
				fprintf(stderr, "Error allocating memory, exiting\n");
				return ERV_MEMORY;
			}

			break;
		case 'p':
			pid_path = strdup(optarg);

			if (pid_path == NULL)
			{
				fprintf(stderr, "Error allocating memory, exiting\n");
				return ERV_MEMORY;
			}
			
			pid_path_set = 1;
			break;
		case 'G':
			generate_guid();

			return 0;
			break;
		case 'h':
			usage();
			return 0;
		case 'v':
			version();
			return 0;
		}
	}

	if (config_path == NULL)
	{
		config_path = strdup(DEFAULT_EEMO_SENSOR_CONF);

		if (config_path == NULL)
		{
			fprintf(stderr, "Error allocating memory, exiting\n");
			return ERV_MEMORY;
		}
	}

	if (pid_path == NULL)
	{
		pid_path = strdup(DEFAULT_EEMO_SENSOR_PIDFILE);

		if (pid_path == NULL)
		{
			fprintf(stderr, "Error allocating memory, exiting\n");
			return ERV_MEMORY;
		}
	}

	/* Load the configuration */
	if (eemo_init_config_handling(config_path) != ERV_OK)
	{
		fprintf(stderr, "Failed to load the configuration, exiting\n");

		return ERV_CONFIG_ERROR;
	}

	/* Initialise logging */
	if (eemo_init_log() != ERV_OK)
	{
		fprintf(stderr, "Failed to initialise logging, exiting\n");

		return ERV_LOG_INIT_FAIL;
	}

	/* Determine configuration settings that were not specified on the command line */
	if (!pid_path_set)
	{
		char* conf_pid_path = NULL;

		if (eemo_conf_get_string("daemon", "pidfile", &conf_pid_path, NULL) != ERV_OK)
		{
			ERROR_MSG("Failed to retrieve pidfile information from the configuration");
		}
		else
		{
			if (conf_pid_path != NULL)
			{
				free(pid_path);
				pid_path = conf_pid_path;
			}
		}
	}

	if (!daemon_set)
	{
		if (eemo_conf_get_bool("daemon", "fork", &daemon, 1) != ERV_OK)
		{
			ERROR_MSG("Failed to retrieve daemon information from the configuration");
		}
	}

	/* Now fork if that was requested */
	if (daemon)
	{
		pid = fork();

		if (pid != 0)
		{
			/* This is the parent process; write the PID file and exit */
			write_pid(pid_path, pid);

			/* Unload the configuration */
			if (eemo_uninit_config_handling() != ERV_OK)
			{
				ERROR_MSG("Failed to uninitialise configuration handling");
			}
		
			/* Uninitialise logging */
			if (eemo_uninit_log() != ERV_OK)
			{
				fprintf(stderr, "Failed to uninitialise logging\n");
			}
		
			free(pid_path);
			free(config_path);
			
			return ERV_OK;
		}
	}

	/* If we forked, this is the child */
	INFO_MSG("Starting the Extensible Ethernet Monitor Sensor (eemo_sensor) version %s", VERSION);
	INFO_MSG("eemo_sensor %sprocess ID is %d", daemon ? "daemon " : "", getpid());

	/* Install signal handlers */
	signal(SIGABRT, signal_handler);
	signal(SIGBUS, signal_handler);
	signal(SIGFPE, signal_handler);
	signal(SIGILL, signal_handler);
	signal(SIGPIPE, signal_handler);
	signal(SIGQUIT, signal_handler);
	signal(SIGSEGV, signal_handler);
	signal(SIGSYS, signal_handler);
	signal(SIGXCPU, signal_handler);
	signal(SIGXFSZ, signal_handler);
	
	/* Initialise OpenSSL */
	SSL_library_init();
	SSL_load_error_strings();
	
	DEBUG_MSG("Initialised OpenSSL");

	if (eemo_mt_openssl_init() != ERV_OK)
	{
		ERROR_MSG("Failed to initialise multi-thread use of OpenSSL");

		return ERV_GENERAL_ERROR;
	}

	/* Initialise the sensor */
	if (eemo_sensor_init() == ERV_OK)
	{
		/* Run the multiplexer until it is stopped */
		eemo_sensor_run();

		/* Uninitialise the sensor */
		eemo_sensor_finalize();
	}
	else
	{
		ERROR_MSG("Failed to initialise the sensor");

		rv = ERV_GENERAL_ERROR;
	}

	/* Remove signal handlers */
	signal(SIGABRT, SIG_DFL);
	signal(SIGBUS, SIG_DFL);
	signal(SIGFPE, SIG_DFL);
	signal(SIGILL, SIG_DFL);
	signal(SIGPIPE, SIG_DFL);
	signal(SIGQUIT, SIG_DFL);
	signal(SIGSEGV, SIG_DFL);
	signal(SIGSYS, SIG_DFL);
	signal(SIGXCPU, SIG_DFL);
	signal(SIGXFSZ, SIG_DFL);
	
	INFO_MSG("Extensible Ethernet Monitor Sensor exiting");

	eemo_mt_openssl_finalize();
	
	/* Uninitialise logging */
	if (eemo_uninit_log() != ERV_OK)
	{
		fprintf(stderr, "Failed to uninitialise logging\n");
	}

	free(pid_path);
	free(config_path);

	return rv;
}