Exemple #1
0
int main(int argc, const char **argv)
{
	const char *config_file = get_dyn_CONFIGFILE();
	int ret = 0;
	poptContext pc;
	char *count_str = NULL;
	int i, count = 1;

	struct poptOption long_options[] = {
		POPT_AUTOHELP
		{"count", 'c', POPT_ARG_STRING, &count_str, 1,
		 "Load config <count> number of times"},
		POPT_COMMON_DEBUGLEVEL
		POPT_TABLEEND
	};

	TALLOC_CTX *frame = talloc_stackframe();

	load_case_tables();
	DEBUGLEVEL_CLASS[DBGC_ALL] = 0;

	pc = poptGetContext(NULL, argc, argv, long_options,
			    POPT_CONTEXT_KEEP_FIRST);
	poptSetOtherOptionHelp(pc, "[OPTION...] <config-file>");

	while(poptGetNextOpt(pc) != -1);

	setup_logging(poptGetArg(pc), True);

	if (poptPeekArg(pc)) {
		config_file = poptGetArg(pc);
	}

	poptFreeContext(pc);

	if (count_str != NULL) {
		count = atoi(count_str);
	}

	dbf = x_stderr;
	/* Don't let the debuglevel be changed by smb.conf. */
	AllowDebugChange = False;

	for (i=0; i < count; i++) {
		printf("call lp_load() #%d: ", i+1);
		if (!lp_load_with_registry_shares(config_file,
						  False, /* global only */
						  True,  /* save defaults */
						  False, /*add_ipc */
						  True)) /*init globals */
		{
			printf("ERROR.\n");
			ret = 1;
			goto done;
		}
		printf("ok.\n");
	}


done:
	gfree_loadparm();
	TALLOC_FREE(frame);
	return ret;
}
Exemple #2
0
int main(const int argc, const char **argv) {
    int width = -1;
    int height = -1;
    float start = 0.0;
    float end = 1.0;
    char *output_file = NULL;
    char *styles_string = NULL;
    nordlicht_strategy strategy;
    int free_output_file = 0;

    int quiet = 0;
    int help = 0;
    int version = 0;

    const struct poptOption optionsTable[] = {
        {"width", 'w', POPT_ARG_INT, &width, 0, "set the barcode's width; by default it's \"height*10\", or 1920 pixels, if both are undefined", NULL},
        {"height", 'h', POPT_ARG_INT, &height, 0, "set the barcode's height; by default it's \"width/10\"", NULL},
        {"output", 'o', POPT_ARG_STRING, &output_file, 0, "set output filename, the default is VIDEOFILE.png; when you specify an *.bgra file, you'll get a raw 32-bit BGRA file that is updated as the barcode is generated", "FILENAME"},
        {"style", 's', POPT_ARG_STRING, &styles_string, 0, "default is 'horizontal', see \"Styles\" section below. You can specify more than one style, separated by '+', to get multiple tracks", "STYLE"},
        {"start", '\0', POPT_ARG_FLOAT, &start, 0, "specify where to start the barcode (ratio between 0 and 1)", NULL},
        {"end", '\0', POPT_ARG_FLOAT, &end, 0, "specify where to end the barcode (ratio between 0 and 1)", NULL},
        {"quiet", 'q', 0, &quiet, 0, "don't show progress indicator", NULL},
        {"help", '\0', 0, &help, 0, "display this help and exit", NULL},
        {"version", '\0', 0, &version, 0, "output version information and exit", NULL},
        POPT_TABLEEND
    };

    const poptContext popt = poptGetContext(NULL, argc, argv, optionsTable, 0);
    poptSetOtherOptionHelp(popt, "[OPTION]... VIDEOFILE\n\nOptions:");

    if (argc == 1) {
        print_help(popt, 1);
    }

    int option;

    // The next line leaks 2 bytes, blame popt!
    while ((option = poptGetNextOpt(popt)) >= 0) { }

    if (option < -1) {
        fprintf(stderr, "nordlicht: %s: %s\n", poptBadOption(popt, POPT_BADOPTION_NOALIAS), poptStrerror(option));
        return 1;
    }

    if (version) {
      printf("nordlicht %s\n\nWritten by Sebastian Morr and contributors.\n", NORDLICHT_VERSION);
      return 0;
    }

    if (help) {
        print_help(popt, 0);
    }

    const char *filename = (char*)poptGetArg(popt);

    if (filename == NULL) {
        print_error("Please specify an input file.");
        exit(1);
    }

    if (poptGetArg(popt) != NULL) {
        print_error("Please specify only one input file.");
        exit(1);
    }

    if (output_file == NULL) {
        size_t len = snprintf(NULL, 0, "%s.nordlicht.png", filename) + 1;
        output_file = (char *) malloc(len);
        snprintf(output_file, len, "%s.nordlicht.png", filename);
        free_output_file = 1;
    }

    if (width == -1 && height != -1) {
        width = height*10;
    }
    if (height == -1 && width != -1) {
        height = width/10;
        if (height < 1) {
            height = 1;
        }
    }
    if (height == -1 && width == -1) {
        width = 1920;
        height = 192;
    }

    if (styles_string == NULL) {
        styles_string = "horizontal";
    }

    // count the occurrences of "+" in the styles_string
    const char *s = styles_string;
    int num_tracks;
    for (num_tracks=0; s[num_tracks]; s[num_tracks]=='+' ? num_tracks++ : *s++);
    num_tracks++;

    nordlicht_style *styles;
    styles = (nordlicht_style *) malloc(num_tracks * sizeof(nordlicht_style));

    const char *style_string;
    num_tracks = 0;
    while ((style_string = strsep(&styles_string, "+"))) {
        int i;
        for (i = 0; style_table[i].name; i++) {
            if (strcmp(style_string, style_table[i].name) == 0) {
                styles[num_tracks] = style_table[i].style;
                break;
            }
        }

        if (!style_table[i].name) {
            print_error("Unknown style '%s'. Use '--help' to display available styles.", style_string);
            exit(1);
        }
        num_tracks++;
    }

    const char *ext = filename_ext(output_file);
    if (strcmp(ext, "bgra") == 0) {
        strategy = NORDLICHT_STRATEGY_LIVE;
    } else if (strcmp(ext, "png") == 0) {
        strategy = NORDLICHT_STRATEGY_FAST;
    } else {
        strategy = NORDLICHT_STRATEGY_FAST;
        fprintf(stderr, "nordlicht: Unsupported file extension '%s', will write a PNG.\n", ext);
    }

    // Interesting stuff begins here!

    nordlicht *n = nordlicht_init(filename, width, height);
    unsigned char *data = NULL;

    if (n == NULL) {
        print_error(nordlicht_error());
        exit(1);
    }

    nordlicht_set_start(n, start);
    nordlicht_set_end(n, end);
    nordlicht_set_styles(n, styles, num_tracks);
    nordlicht_set_strategy(n, strategy);

    if (nordlicht_error() != NULL) {
        print_error(nordlicht_error());
        exit(1);
    }

    if (strategy == NORDLICHT_STRATEGY_LIVE) {
        int fd = open(output_file, O_CREAT | O_TRUNC | O_RDWR, 0666);
        if (fd == -1) {
            print_error("Could not open '%s'.", output_file);
            exit(1);
        }
        if (ftruncate(fd, nordlicht_buffer_size(n)) == -1) {
            print_error("Could not truncate '%s'.", output_file);
            exit(1);
        }
        data = (unsigned char *) mmap(NULL, nordlicht_buffer_size(n), PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
        if (data == (void *) -1) {
            print_error("Could not mmap %d bytes.", nordlicht_buffer_size(n));
            exit(1);
        }
        nordlicht_set_buffer(n, data);
        close(fd);
    } else {
        // Try to write the empty buffer to fail early if this does not work
        if (nordlicht_write(n, output_file) != 0) {
            print_error(nordlicht_error());
            exit(1);
        }
    }

    int phase = -1;
    while(!nordlicht_done(n)) {
        if (nordlicht_generate_step(n) == 0) {
            if (! quiet) {
                float progress = nordlicht_progress(n);
                if (progress == 0) {
                    if (phase == -1) {
                        phase = 0;
                        printf("nordlicht: Building keyframe index... ");
                        fflush(stdout);
                    }
                } else {
                    if (phase == 0) {
                        phase = 1;
                        printf("done.\n");
                    }
                    printf("\rnordlicht: %02.0f%%", progress*100);
                    fflush(stdout);
                }
            }
        } else {
            print_error(nordlicht_error());
            exit(1);
        }
    }

    if (strategy != NORDLICHT_STRATEGY_LIVE) {
        if (nordlicht_write(n, output_file) != 0) {
            print_error(nordlicht_error());
            exit(1);
        }
    }

    free(styles);

    if (strategy == NORDLICHT_STRATEGY_LIVE) {
        munmap(data, nordlicht_buffer_size(n));
    }

    nordlicht_free(n);

    if (! quiet) {
        printf(" -> '%s'\n", output_file);
    }

    if (free_output_file) {
        free(output_file);
    }

    poptFreeContext(popt);
    return 0;
}
int main(int argc, const char **argv)
{
    int ret = EXIT_SUCCESS;
    struct tools_ctx *tctx = NULL;
    const char *pc_username = NULL;

    int pc_debug = SSSDBG_DEFAULT;
    int pc_remove = 0;
    int pc_force = 0;
    int pc_kick = 0;
    poptContext pc = NULL;
    struct poptOption long_options[] = {
        POPT_AUTOHELP
        { "debug", '\0', POPT_ARG_INT | POPT_ARGFLAG_DOC_HIDDEN, &pc_debug,
                    0, _("The debug level to run with"), NULL },
        { "remove", 'r', POPT_ARG_NONE, NULL, 'r',
                    _("Remove home directory and mail spool"), NULL },
        { "no-remove", 'R', POPT_ARG_NONE, NULL, 'R',
                    _("Do not remove home directory and mail spool"), NULL },
        { "force", 'f', POPT_ARG_NONE, NULL, 'f',
                    _("Force removal of files not owned by the user"), NULL },
        { "kick", 'k', POPT_ARG_NONE, NULL, 'k',
                    _("Kill users' processes before removing him"), NULL },
        POPT_TABLEEND
    };

    debug_prg_name = argv[0];

    ret = set_locale();
    if (ret != EOK) {
        DEBUG(1, ("set_locale failed (%d): %s\n", ret, strerror(ret)));
        ERROR("Error setting the locale\n");
        ret = EXIT_FAILURE;
        goto fini;
    }

    /* parse parameters */
    pc = poptGetContext(NULL, argc, argv, long_options, 0);
    poptSetOtherOptionHelp(pc, "USERNAME");
    while ((ret = poptGetNextOpt(pc)) > 0) {
        switch (ret) {
            case 'r':
                pc_remove = DO_REMOVE_HOME;
                break;

            case 'R':
                pc_remove = DO_NOT_REMOVE_HOME;
                break;

            case 'f':
                pc_force = DO_FORCE_REMOVAL;
                break;

            case 'k':
                pc_kick = 1;
                break;
        }
    }

    DEBUG_INIT(pc_debug);

    if (ret != -1) {
        BAD_POPT_PARAMS(pc, poptStrerror(ret), ret, fini);
    }

    pc_username = poptGetArg(pc);
    if (pc_username == NULL) {
        BAD_POPT_PARAMS(pc, _("Specify user to delete\n"), ret, fini);
    }

    CHECK_ROOT(ret, debug_prg_name);

    ret = init_sss_tools(&tctx);
    if (ret != EOK) {
        DEBUG(1, ("init_sss_tools failed (%d): %s\n", ret, strerror(ret)));
        if (ret == ENOENT) {
            ERROR("Error initializing the tools - no local domain\n");
        } else {
            ERROR("Error initializing the tools\n");
        }
        ret = EXIT_FAILURE;
        goto fini;
    }

    /* if the domain was not given as part of FQDN, default to local domain */
    ret = parse_name_domain(tctx, pc_username);
    if (ret != EOK) {
        ERROR("Invalid domain specified in FQDN\n");
        ret = EXIT_FAILURE;
        goto fini;
    }

    /*
     * Fills in defaults for ops_ctx user did not specify.
     */
    ret = userdel_defaults(tctx, tctx->confdb, tctx->octx, pc_remove);
    if (ret != EOK) {
        ERROR("Cannot set default values\n");
        ret = EXIT_FAILURE;
        goto fini;
    }

    ret = sysdb_getpwnam_sync(tctx,
                              tctx->sysdb,
                              tctx->octx->name,
                              tctx->octx);
    if (ret != EOK) {
        /* Error message will be printed in the switch */
        goto done;
    }

    if ((tctx->octx->uid < tctx->local->id_min) ||
        (tctx->local->id_max && tctx->octx->uid > tctx->local->id_max)) {
        ERROR("User %1$s is outside the defined ID range for domain\n",
              tctx->octx->name);
        ret = EXIT_FAILURE;
        goto fini;
    }

    if (pc_kick) {
        ret = kick_user(tctx);
        if (ret != EOK) {
            tctx->error = ret;

            goto done;
        }
    }

    /* userdel */
    ret = userdel(tctx, tctx->sysdb, tctx->octx);
    if (ret != EOK) {
        goto done;
    }

    /* Set SELinux login context - must be done after transaction is done
     * b/c libselinux calls getpwnam */
    ret = del_seuser(tctx->octx->name);
    if (ret != EOK) {
        ERROR("Cannot reset SELinux login context\n");
        ret = EXIT_FAILURE;
        goto fini;
    }

    if (!pc_kick) {
        ret = is_logged_in(tctx, tctx->octx->uid);
        switch(ret) {
            case ENOENT:
                break;

            case EOK:
                ERROR("WARNING: The user (uid %1$lu) was still logged in when "
                      "deleted.\n", (unsigned long) tctx->octx->uid);
                break;

            case ENOSYS:
                ERROR("Cannot determine if the user was logged in on this "
                      "platform");
                break;

            default:
                ERROR("Error while checking if the user was logged in\n");
                break;
        }
    }

    ret = run_userdel_cmd(tctx);
    if (ret != EOK) {
        ERROR("The post-delete command failed: %1$s\n", strerror(ret));
        goto fini;
    }

    /* Delete user from memory cache */
    ret = sss_mc_refresh_user(pc_username);
    if (ret != EOK) {
        ERROR("NSS request failed (%1$d). Entry might remain in memory "
              "cache.\n", ret);
        /* Nothing we can do about it */
    }

    if (tctx->octx->remove_homedir) {
        ret = remove_homedir(tctx,
                             tctx->octx->home,
                             tctx->octx->maildir,
                             tctx->octx->name,
                             tctx->octx->uid,
                             pc_force);
        if (ret == EPERM) {
            ERROR("Not removing home dir - not owned by user\n");
        } else if (ret != EOK) {
            ERROR("Cannot remove homedir: %1$s\n", strerror(ret));
            ret = EXIT_FAILURE;
            goto fini;
        }
    }

    ret = EOK;

done:
    if (ret) {
        DEBUG(1, ("sysdb operation failed (%d)[%s]\n", ret, strerror(ret)));
        switch (ret) {
            case ENOENT:
                ERROR("No such user in local domain. "
                      "Removing users only allowed in local domain.\n");
                break;

            default:
                ERROR("Internal error. Could not remove user.\n");
                break;
        }
        ret = EXIT_FAILURE;
        goto fini;
    }

    ret = EXIT_SUCCESS;

fini:
    talloc_free(tctx);
    poptFreeContext(pc);
    exit(ret);
}
Exemple #4
0
int main(int argc, const char *argv[])
{
    int rv;
    poptContext pc;
    int opt;
    struct poptOption long_options[] = {
        POPT_AUTOHELP
        SSSD_DEBUG_OPTS
        POPT_TABLEEND
    };

    const struct CMUnitTest tests[] = {
        /* user */
        cmocka_unit_test_setup_teardown(test_ncache_nocache_user,
                                        test_ncache_setup,
                                        test_ncache_teardown),
        cmocka_unit_test_setup_teardown(test_ncache_local_user,
                                        test_ncache_setup,
                                        test_ncache_teardown),
        cmocka_unit_test_setup_teardown(test_ncache_domain_user,
                                        test_ncache_setup,
                                        test_ncache_teardown),
        cmocka_unit_test_setup_teardown(test_ncache_both_user,
                                        test_ncache_setup,
                                        test_ncache_teardown),
        /* uid */
        cmocka_unit_test_setup_teardown(test_ncache_nocache_uid,
                                        test_ncache_setup,
                                        test_ncache_teardown),
        cmocka_unit_test_setup_teardown(test_ncache_local_uid,
                                        test_ncache_setup,
                                        test_ncache_teardown),
        cmocka_unit_test_setup_teardown(test_ncache_domain_uid,
                                        test_ncache_setup,
                                        test_ncache_teardown),
        cmocka_unit_test_setup_teardown(test_ncache_both_uid,
                                        test_ncache_setup,
                                        test_ncache_teardown),
        /* group */
        cmocka_unit_test_setup_teardown(test_ncache_nocache_group,
                                        test_ncache_setup,
                                        test_ncache_teardown),
        cmocka_unit_test_setup_teardown(test_ncache_local_group,
                                        test_ncache_setup,
                                        test_ncache_teardown),
        cmocka_unit_test_setup_teardown(test_ncache_domain_group,
                                        test_ncache_setup,
                                        test_ncache_teardown),
        cmocka_unit_test_setup_teardown(test_ncache_both_group,
                                        test_ncache_setup,
                                        test_ncache_teardown),
        /* gid */
        cmocka_unit_test_setup_teardown(test_ncache_nocache_gid,
                                        test_ncache_setup,
                                        test_ncache_teardown),
        cmocka_unit_test_setup_teardown(test_ncache_local_gid,
                                        test_ncache_setup,
                                        test_ncache_teardown),
        cmocka_unit_test_setup_teardown(test_ncache_domain_gid,
                                        test_ncache_setup,
                                        test_ncache_teardown),
        cmocka_unit_test_setup_teardown(test_ncache_both_gid,
                                        test_ncache_setup,
                                        test_ncache_teardown),
    };

    /* Set debug level to invalid value so we can decide if -d 0 was used. */
    debug_level = SSSDBG_INVALID;

    pc = poptGetContext(argv[0], argc, argv, long_options, 0);
    while ((opt = poptGetNextOpt(pc)) != -1) {
        switch (opt) {
        default:
            fprintf(stderr, "\nInvalid option %s: %s\n\n",
                    poptBadOption(pc, 0), poptStrerror(opt));
            poptPrintUsage(pc, stderr, 0);
            return 1;
        }
    }
    poptFreeContext(pc);

    DEBUG_CLI_INIT(debug_level);

    tests_set_cwd();
    test_dom_suite_cleanup(TESTS_PATH, TEST_CONF_DB, TEST_DOM_NAME);
    rv = cmocka_run_group_tests(tests, NULL, NULL);

    return rv;
}
Exemple #5
0
int main(int argc, const char** argv)
{
	poptContext optCon;
	exword_t *device;
	int rsp;
	optCon = poptGetContext(NULL, argc, argv, options, 0);

	setlocale(LC_ALL, "");

	if (poptGetNextOpt(optCon) < -1)
		usage(optCon, 1, NULL);

	if (command & CMD_INTERACTIVE) {
		interactive();
		exit(0);
	}

	if ((command & CMD_MASK) == 0)
		usage(optCon, 1, NULL);

	if (sd_path && mem_path)
		usage(optCon, 1, "--sd and --internal options mutually exclusive");

	device = exword_open();
	if (device == NULL) {
		fprintf(stderr, "Failed to open device or no device found\n");
	} else {
		exword_set_debug(debug_level);
		rsp = connect(device);
		if (rsp == 0x20) {
			if (sd_path)
				rsp = set_path(device, SD_CARD, sd_path);
			else if (mem_path)
				rsp = set_path(device, INTERNAL_MEM, mem_path);
			else
				rsp = set_path(device, INTERNAL_MEM, "\\");
		}
		if (rsp == 0x20) {
			switch(command & CMD_MASK) {
			case CMD_LIST:
				rsp = list_files(device);
				break;
			case CMD_MODEL:
				rsp = display_model(device);
				break;
			case CMD_CAPACITY:
				rsp = display_capacity(device);
				break;
			case CMD_SEND:
				rsp = send_file(device, filename);
				break;
			case CMD_GET:
				rsp = get_file(device, filename);
				break;
			case CMD_DELETE:
				rsp = delete_file(device, filename);
				break;
			case CMD_FORMAT:
				rsp = sd_format(device);
				break;
			default:
				usage(optCon, 1, "No such command");
			}
		}
		disconnect(device);
		printf("%s\n", exword_response_to_string(rsp));
		exword_close(device);
	}
	poptFreeContext(optCon);
	return 0;
}
Exemple #6
0
int main(int argc, char **argv)
{
	int opt;
	const char *file = NULL;
	poptContext pc;
	const char *remote = NULL;
	struct regshell_context *ctx;
	struct tevent_context *ev_ctx;
	bool ret = true;
	struct poptOption long_options[] = {
		POPT_AUTOHELP
		{"file", 'F', POPT_ARG_STRING, &file, 0, "open hive file", NULL },
		{"remote", 'R', POPT_ARG_STRING, &remote, 0, "connect to specified remote server", NULL},
		POPT_COMMON_SAMBA
		POPT_COMMON_CREDENTIALS
		POPT_COMMON_VERSION
		{ NULL }
	};

	pc = poptGetContext(argv[0], argc, (const char **) argv, long_options,0);

	while((opt = poptGetNextOpt(pc)) != -1) {
	}

	ctx = talloc_zero(NULL, struct regshell_context);

	ev_ctx = s4_event_context_init(ctx);

	if (remote != NULL) {
		ctx->registry = reg_common_open_remote(remote, ev_ctx,
					 cmdline_lp_ctx, cmdline_credentials);
	} else if (file != NULL) {
		ctx->current = reg_common_open_file(file, ev_ctx, cmdline_lp_ctx, cmdline_credentials);
		if (ctx->current == NULL)
			return 1;
		ctx->registry = ctx->current->context;
		ctx->path = talloc_strdup(ctx, "");
		ctx->predef = NULL;
		ctx->root = ctx->current;
	} else {
		ctx->registry = reg_common_open_local(cmdline_credentials, ev_ctx, cmdline_lp_ctx);
	}

	if (ctx->registry == NULL)
		return 1;

	if (ctx->current == NULL) {
		unsigned int i;

		for (i = 0; (reg_predefined_keys[i].handle != 0) &&
			(ctx->current == NULL); i++) {
			WERROR err;
			err = reg_get_predefined_key(ctx->registry,
						     reg_predefined_keys[i].handle,
						     &ctx->current);
			if (W_ERROR_IS_OK(err)) {
				ctx->predef = talloc_strdup(ctx,
							  reg_predefined_keys[i].name);
				ctx->path = talloc_strdup(ctx, "");
				ctx->root = ctx->current;
				break;
			} else {
				ctx->current = NULL;
				ctx->root = NULL;
			}
		}
	}

	if (ctx->current == NULL) {
		fprintf(stderr, "Unable to access any of the predefined keys\n");
		return 1;
	}

	poptFreeContext(pc);

	while (true) {
		char *line, *prompt;

		if (asprintf(&prompt, "%s\\%s> ", ctx->predef?ctx->predef:"",
			     ctx->path) < 0) {
			ret = false;
			break;
		}

		current_key = ctx->current; 		/* No way to pass a void * pointer
							   via readline :-( */
		line = smb_readline(prompt, NULL, reg_completion);

		if (line == NULL) {
			free(prompt);
			break;
		}

		if (line[0] != '\n') {
			ret = W_ERROR_IS_OK(process_cmd(ctx, line));
		}
		free(line);
		free(prompt);
	}
	talloc_free(ctx);

	return (ret?0:1);
}
Exemple #7
0
int main(int argc, const char *argv[])
{
    int ret;
    int kerr;
    int opt;
    int debug_fd = -1;
    poptContext pc;
    TALLOC_CTX *main_ctx = NULL;
    uint8_t *buf = NULL;
    ssize_t len = 0;
    const char *ccname = NULL;
    time_t expire_time = 0;
    struct input_buffer *ibuf = NULL;
    struct response *resp = NULL;
    size_t written;

    struct poptOption long_options[] = {
        POPT_AUTOHELP
        {"debug-level", 'd', POPT_ARG_INT, &debug_level, 0,
         _("Debug level"), NULL},
        {"debug-timestamps", 0, POPT_ARG_INT, &debug_timestamps, 0,
         _("Add debug timestamps"), NULL},
        {"debug-microseconds", 0, POPT_ARG_INT, &debug_microseconds, 0,
         _("Show timestamps with microseconds"), NULL},
        {"debug-fd", 0, POPT_ARG_INT, &debug_fd, 0,
         _("An open file descriptor for the debug logs"), NULL},
        POPT_TABLEEND
    };

    /* Set debug level to invalid value so we can decide if -d 0 was used. */
    debug_level = SSSDBG_INVALID;

    pc = poptGetContext(argv[0], argc, argv, long_options, 0);
    while((opt = poptGetNextOpt(pc)) != -1) {
        switch(opt) {
        default:
        fprintf(stderr, "\nInvalid option %s: %s\n\n",
                  poptBadOption(pc, 0), poptStrerror(opt));
            poptPrintUsage(pc, stderr, 0);
            _exit(-1);
        }
    }

    poptFreeContext(pc);

    CONVERT_AND_SET_DEBUG_LEVEL(debug_level);

    debug_prg_name = talloc_asprintf(NULL, "[sssd[ldap_child[%d]]]", getpid());
    if (!debug_prg_name) {
        DEBUG(SSSDBG_CRIT_FAILURE, ("talloc_asprintf failed.\n"));
        goto fail;
    }

    if (debug_fd != -1) {
        ret = set_debug_file_from_fd(debug_fd);
        if (ret != EOK) {
            DEBUG(SSSDBG_CRIT_FAILURE, ("set_debug_file_from_fd failed.\n"));
        }
    }

    DEBUG(SSSDBG_TRACE_FUNC, ("ldap_child started.\n"));

    main_ctx = talloc_new(NULL);
    if (main_ctx == NULL) {
        DEBUG(SSSDBG_CRIT_FAILURE, ("talloc_new failed.\n"));
        talloc_free(discard_const(debug_prg_name));
        goto fail;
    }
    talloc_steal(main_ctx, debug_prg_name);

    buf = talloc_size(main_ctx, sizeof(uint8_t)*IN_BUF_SIZE);
    if (buf == NULL) {
        DEBUG(1, ("talloc_size failed.\n"));
        goto fail;
    }

    ibuf = talloc_zero(main_ctx, struct input_buffer);
    if (ibuf == NULL) {
        DEBUG(1, ("talloc_size failed.\n"));
        goto fail;
    }

    errno = 0;
    len = sss_atomic_read_s(STDIN_FILENO, buf, IN_BUF_SIZE);
    if (len == -1) {
        ret = errno;
        DEBUG(SSSDBG_CRIT_FAILURE, ("read failed [%d][%s].\n", ret, strerror(ret)));
        goto fail;
    }

    close(STDIN_FILENO);

    ret = unpack_buffer(buf, len, ibuf);
    if (ret != EOK) {
        DEBUG(1, ("unpack_buffer failed.[%d][%s].\n", ret, strerror(ret)));
        goto fail;
    }

    kerr = ldap_child_get_tgt_sync(main_ctx,
                                   ibuf->realm_str, ibuf->princ_str,
                                   ibuf->keytab_name, ibuf->lifetime,
                                   &ccname, &expire_time);
    if (kerr != EOK) {
        DEBUG(1, ("ldap_child_get_tgt_sync failed.\n"));
        /* Do not return, must report failure */
    }

    ret = prepare_response(main_ctx, ccname, expire_time, kerr, &resp);
    if (ret != EOK) {
        DEBUG(SSSDBG_CRIT_FAILURE, ("prepare_response failed. [%d][%s].\n", ret, strerror(ret)));
        goto fail;
    }

    errno = 0;
    written = sss_atomic_write_s(STDOUT_FILENO, resp->buf, resp->size);
    if (written == -1) {
        ret = errno;
        DEBUG(SSSDBG_CRIT_FAILURE, ("write failed [%d][%s].\n", ret, strerror(ret)));
        goto fail;
    }

    if (written != resp->size) {
        DEBUG(SSSDBG_CRIT_FAILURE, ("Expected to write %d bytes, wrote %d\n",
              resp->size, written));
        goto fail;
    }

    DEBUG(SSSDBG_TRACE_FUNC, ("ldap_child completed successfully\n"));
    close(STDOUT_FILENO);
    talloc_free(main_ctx);
    _exit(0);

fail:
    DEBUG(SSSDBG_CRIT_FAILURE, ("ldap_child failed!\n"));
    close(STDOUT_FILENO);
    talloc_free(main_ctx);
    _exit(-1);
}
Exemple #8
0
/*
 main server.
*/
static int binary_smbd_main(const char *binary_name, int argc, const char *argv[])
{
	bool opt_daemon = false;
	bool opt_interactive = false;
	int opt;
	poptContext pc;
#define _MODULE_PROTO(init) extern NTSTATUS init(void);
	STATIC_service_MODULES_PROTO;
	init_module_fn static_init[] = { STATIC_service_MODULES };
	init_module_fn *shared_init;
	struct tevent_context *event_ctx;
	uint16_t stdin_event_flags;
	NTSTATUS status;
	const char *model = "standard";
	int max_runtime = 0;
	enum {
		OPT_DAEMON = 1000,
		OPT_INTERACTIVE,
		OPT_PROCESS_MODEL,
		OPT_SHOW_BUILD
	};
	struct poptOption long_options[] = {
		POPT_AUTOHELP
		{"daemon", 'D', POPT_ARG_NONE, NULL, OPT_DAEMON,
		 "Become a daemon (default)", NULL },
		{"interactive",	'i', POPT_ARG_NONE, NULL, OPT_INTERACTIVE,
		 "Run interactive (not a daemon)", NULL},
		{"model", 'M', POPT_ARG_STRING,	NULL, OPT_PROCESS_MODEL, 
		 "Select process model", "MODEL"},
		{"maximum-runtime",0, POPT_ARG_INT, &max_runtime, 0, 
		 "set maximum runtime of the server process, till autotermination", "seconds"},
		{"show-build", 'b', POPT_ARG_NONE, NULL, OPT_SHOW_BUILD, "show build info", NULL },
		POPT_COMMON_SAMBA
		POPT_COMMON_VERSION
		{ NULL }
	};

	pc = poptGetContext(binary_name, argc, argv, long_options, 0);
	while((opt = poptGetNextOpt(pc)) != -1) {
		switch(opt) {
		case OPT_DAEMON:
			opt_daemon = true;
			break;
		case OPT_INTERACTIVE:
			opt_interactive = true;
			break;
		case OPT_PROCESS_MODEL:
			model = poptGetOptArg(pc);
			break;
		case OPT_SHOW_BUILD:
			show_build();
			break;
		default:
			fprintf(stderr, "\nInvalid option %s: %s\n\n",
				  poptBadOption(pc, 0), poptStrerror(opt));
			poptPrintUsage(pc, stderr, 0);
			return 1;
		}
	}

	if (opt_daemon && opt_interactive) {
		fprintf(stderr,"\nERROR: "
			  "Option -i|--interactive is not allowed together with -D|--daemon\n\n");
		poptPrintUsage(pc, stderr, 0);
		return 1;
	} else if (!opt_interactive) {
		/* default is --daemon */
		opt_daemon = true;
	}

	poptFreeContext(pc);

	setup_logging(binary_name, opt_interactive?DEBUG_STDOUT:DEBUG_FILE);
	setup_signals();

	/* we want total control over the permissions on created files,
	   so set our umask to 0 */
	umask(0);

	DEBUG(0,("%s version %s started.\n", binary_name, SAMBA_VERSION_STRING));
	DEBUGADD(0,("Copyright Andrew Tridgell and the Samba Team 1992-2011\n"));

	if (sizeof(uint16_t) < 2 || sizeof(uint32_t) < 4 || sizeof(uint64_t) < 8) {
		DEBUG(0,("ERROR: Samba is not configured correctly for the word size on your machine\n"));
		DEBUGADD(0,("sizeof(uint16_t) = %u, sizeof(uint32_t) %u, sizeof(uint64_t) = %u\n",
			    (unsigned int)sizeof(uint16_t), (unsigned int)sizeof(uint32_t), (unsigned int)sizeof(uint64_t)));
		return 1;
	}

	if (opt_daemon) {
		DEBUG(3,("Becoming a daemon.\n"));
		become_daemon(true, false, false);
	}

	cleanup_tmp_files(cmdline_lp_ctx);

	if (!directory_exist(lpcfg_lockdir(cmdline_lp_ctx))) {
		mkdir(lpcfg_lockdir(cmdline_lp_ctx), 0755);
	}

	pidfile_create(lpcfg_piddir(cmdline_lp_ctx), binary_name);

	/* Set up a database to hold a random seed, in case we don't
	 * have /dev/urandom */
	if (!randseed_init(talloc_autofree_context(), cmdline_lp_ctx)) {
		return 1;
	}

	if (lpcfg_server_role(cmdline_lp_ctx) == ROLE_DOMAIN_CONTROLLER) {
		if (!open_schannel_session_store(talloc_autofree_context(), lpcfg_private_dir(cmdline_lp_ctx))) {
			DEBUG(0,("ERROR: Samba cannot open schannel store for secured NETLOGON operations.\n"));
			exit(1);
		}
	}

	gensec_init(); /* FIXME: */

	ntptr_init();	/* FIXME: maybe run this in the initialization function 
						of the spoolss RPC server instead? */

	ntvfs_init(cmdline_lp_ctx); 	/* FIXME: maybe run this in the initialization functions 
						of the SMB[,2] server instead? */

	process_model_init(cmdline_lp_ctx); 

	shared_init = load_samba_modules(NULL, "service");

	run_init_functions(static_init);
	run_init_functions(shared_init);

	talloc_free(shared_init);
	
	/* the event context is the top level structure in smbd. Everything else
	   should hang off that */
	event_ctx = s4_event_context_init(talloc_autofree_context());

	if (event_ctx == NULL) {
		DEBUG(0,("Initializing event context failed\n"));
		return 1;
	}

	if (opt_interactive) {
		/* terminate when stdin goes away */
		stdin_event_flags = TEVENT_FD_READ;
	} else {
		/* stay alive forever */
		stdin_event_flags = 0;
	}

	/* catch EOF on stdin */
#ifdef SIGTTIN
	signal(SIGTTIN, SIG_IGN);
#endif
	tevent_add_fd(event_ctx, event_ctx, 0, stdin_event_flags,
		      server_stdin_handler,
		      discard_const(binary_name));

	if (max_runtime) {
		DEBUG(0,("Called with maxruntime %d - current ts %llu\n",
		      max_runtime, (unsigned long long) time(NULL)));
		tevent_add_timer(event_ctx, event_ctx,
				 timeval_current_ofs(max_runtime, 0),
				 max_runtime_handler,
				 discard_const(binary_name));
	}

	prime_ldb_databases(event_ctx);

	status = setup_parent_messaging(event_ctx, cmdline_lp_ctx);
	if (!NT_STATUS_IS_OK(status)) {
		DEBUG(0,("Failed to setup parent messaging - %s\n", nt_errstr(status)));
		return 1;
	}

	DEBUG(0,("%s: using '%s' process model\n", binary_name, model));

	status = server_service_startup(event_ctx, cmdline_lp_ctx, model, 
					lpcfg_server_services(cmdline_lp_ctx));
	if (!NT_STATUS_IS_OK(status)) {
		DEBUG(0,("Starting Services failed - %s\n", nt_errstr(status)));
		return 1;
	}

	/* wait for events - this is where smbd sits for most of its
	   life */
	tevent_loop_wait(event_ctx);

	/* as everything hangs off this event context, freeing it
	   should initiate a clean shutdown of all services */
	talloc_free(event_ctx);

	return 0;
}
Exemple #9
0
void
grg_parse_argv (gint argc, gchar * argv[], gchar ** filename,
		gboolean * rootCheck)
{
	poptContext optCon;
	gchar *wipe, *etit;
	gint passes, ennum;
	gboolean dump, help, strongRnd;

	struct poptOption optionsTable[] = {
		{"help", 'h', POPT_ARG_NONE, &help, 1, _("shows the help"),
		 NULL},
		{"input-file", 'f', POPT_ARG_STRING, filename, 0,
		 _("specify the input file to open"), _("FILE")},
#ifndef ROOT_FILTER
		{"allow-root", 's', POPT_ARG_NONE, rootCheck, 1,
		 _("allow usage as root -- DANGEROUS"), NULL},
#endif
		{"strong-random", 'R', POPT_ARG_NONE, &strongRnd, 0,
		 _("force use of /dev/random -- slower"), NULL},
		{"dump", 'd', POPT_ARG_NONE, &dump, 0,
		 _("dump the content of a file"), NULL},
		{"entry-num", 0, POPT_ARG_INT, &ennum, 0,
		 _("index of the entry to dump"), _("NUM")},
		{"entry-title", 0, POPT_ARG_STRING, &etit, 0,
		 _("title of the entry to dump"), _("TXT")},
		{"wipe-file", 'w', POPT_ARG_STRING, &wipe, 0,
		 _("securely wipe a file"), _("FILE")},
		{"wipe-passes", 0, POPT_ARG_INT, &passes, 0,
		 _("passes in file wiping"), _("NUM")},
		{NULL, 0, 0, NULL, 0}
	};

	*filename = NULL;
	wipe = NULL;
	etit = NULL;
	passes = 0;
	ennum = -1;
	*rootCheck = FALSE;
	strongRnd = FALSE;
	dump = FALSE;
	help = FALSE;

	optCon = poptGetContext (NULL, argc, (const char **) argv,
				 optionsTable, 0);

	while (poptGetNextOpt (optCon) >= 0) ;

	if (help)
	{
		poptPrintHelp (optCon, stdout, 0);
		poptFreeContext (optCon);
		exit_freeing_ctx (1);
	}

	poptFreeContext (optCon);

	if (strongRnd)
		grg_ctx_set_security_lvl (gctx, GRG_SEC_PARANOIA);

/*quite cerebrotic, I know. The idea is: to ensure that stdin isn't exploitable,
  the best way is to close and reopen it, so that any "abnormal" setting is
  wasted. Since it isn't possible to do this atomically, I check that the former
  file descriptor hasn't been opened in the while by someone that could pretend
  to "be" stdin.*/
	if (!(wipe || dump))
	{
		int canary;

		close (STDIN);
		canary = open ("/dev/null", O_RDONLY);
		if (canary != STDIN)
			exit_freeing_ctx (1);
		return;
	}

/*wipe and dump operations are processed without returning to main() */

/*FIXME this should be in grg_safe.c */
#ifdef HAVE_ISATTY
	if (!isatty (STDIN))
	{
		g_critical ("%s",
			    _
			    ("It isn't possible to redirect data to stdin, as it is a potential security flaw."));
		exit_freeing_ctx (1);
	}
#endif

	if (!grg_security_filter (*rootCheck))
		exit_freeing_ctx (1);

	if (wipe)
	{
		gint res;
		gchar c;

		if (!g_file_test (wipe, G_FILE_TEST_IS_REGULAR))
			report_err (_("The file does not exist"), 0, 1, NULL);

		printf ("%s (y/n)",
			_("Are you sure you want to wipe this file?\n"
			  "Its content will be securely erased, so no\n"
			  "recover is possible."));

		if (passes < 0 || passes > 32)
			passes = 8;

		c = getchar ();

		if (c != 'y' && c != 'Y')
			exit_freeing_ctx (0);

		res = grg_file_shred (wipe, passes);

		if (res < 0)
			report_err (_("File wiping failed"), 0, 1, NULL);

		exit_freeing_ctx (0);
	}

	if (dump)
	{
		if (!*filename)
			report_err (_
				    ("You must specify a file to dump (with the -f switch)"),
				    0, 1, NULL);
		dump_content (*filename, ennum, etit);
		exit_freeing_ctx (0);
	}
}
/* Read project preferences and command line arguments */
static int parseParameters(int argc, const char** argv, SeparationFlags* sfOut)
{
    poptContext context;
    int argRead;
    static int version = FALSE;
    static int copyright = FALSE;
    static unsigned int numParams = 0;
    static int serverParams = 0;
    static const char** rest = NULL;
    static SeparationFlags sf;

    static const struct poptOption options[] =
        {
            {
                "astronomy-parameter-file", 'a',
                POPT_ARG_STRING, &sf.ap_file,
                0, "Astronomy parameter file", NULL
            },

            {
                "star-points-file", 's',
                POPT_ARG_STRING, &sf.star_points_file,
                0, "Star points files", NULL
            },

            {
                "output", 'o',
                POPT_ARG_STRING, &sf.separation_outfile,
                0, "Output file for separation (enables separation)", NULL
            },

            {
                "seed", 'e',
                POPT_ARG_INT, &sf.separationSeed,
                SEED_ARGUMENT, "Seed for random number generator", NULL
            },

            {
                "modfit", 'f',
                POPT_ARG_NONE, &sf.modfit,
                0, "Modified fit from Newby 2011", NULL
            },

            {
				"newbg", 'y',
				POPT_ARG_NONE, &sf.background,
				0, "Uses broken power law as background fit", NULL
			},

            {
                "ignore-checkpoint", 'i',
                POPT_ARG_NONE, &sf.ignoreCheckpoint,
                0, "Ignore the checkpoint file", NULL
            },

            {
                "cleanup-checkpoint", 'c',
                POPT_ARG_NONE, &sf.cleanupCheckpoint,
                0, "Delete checkpoint on successful", NULL
            },

            {
                "print-likelihood-text", 't',
                POPT_ARG_NONE, &sf.LikelihoodToText,
                0, "Create text file with likelihood for use in local MLE", NULL
            },

            {
                "debug-boinc", 'g',
                POPT_ARG_NONE, &sf.debugBOINC,
                0, "Init BOINC with debugging. No effect if not built with BOINC_APPLICATION", NULL
            },

            {
                "process-priority", 'b',
                POPT_ARG_INT, &sf.processPriority,
                0, "Set process priority. Set priority 0 (lowest) to 4 (highest)", NULL
            },

            {
                "device", 'd',
                POPT_ARG_INT, &sf.useDevNumber,
                0, "Device number passed by BOINC to use", NULL
            },

            {
                "non-responsive", 'r',
                POPT_ARG_NONE, &sf.nonResponsive,
                0, "Do not care about display responsiveness (use with caution)", NULL
            },

            {
                "gpu-target-frequency", 'q',
                POPT_ARG_DOUBLE, &sf.targetFrequency,
                0, "Target frequency for GPU tasks" , NULL
            },

            {
                "gpu-wait-factor", 'w',
                POPT_ARG_DOUBLE, &sf.waitFactor,
                0, "Wait correction factor when using high CPU workarounds" , NULL
            },

            {
                "gpu-polling-mode", 'm',
                POPT_ARG_INT, &sf.pollingMode,
                0, "Interval for polling GPU: (-2 (default): Use mode -1 unless working around high CPU driver issue.  -1: use clWaitForEvents(). 0: Use clWaitForEvents() with initial wait, >= 1: sets manual interval polling in ms)" , NULL
            },

            {
                "gpu-disable-checkpointing", 'k',
                POPT_ARG_NONE, &sf.disableGPUCheckpointing,
                0, "Disable checkpointing with GPUs" , NULL
            },

            {
                "platform", 'l',
                POPT_ARG_INT, &sf.usePlatform,
                0, "CL platform index to use", NULL
            },

            {
                "platform-vendor", '\0',
                POPT_ARG_STRING, &sf.preferredPlatformVendor,
                0, "CL Platform vendor name to try to use", NULL
            },

            {
                "verbose", '\0',
                POPT_ARG_NONE, &sf.verbose,
                0, "Print some extra debugging information", NULL
            },

            {
                "force-no-opencl", '\0',
                POPT_ARG_NONE, &sf.forceNoOpenCL,
                0, "Use regular CPU path instead of OpenCL if available", NULL
            },

            {
                "force-no-il-kernel", '\0',
                POPT_ARG_NONE, &sf.forceNoILKernel,
                0, "Do not use AMD IL replacement kernels if available", NULL
            },

            {
                "force-no-intrinsics", '\0',
                POPT_ARG_NONE, &sf.forceNoIntrinsics,
                0, "Use old default path", NULL
            },

            {
                "force-x87", '\0',
                POPT_ARG_NONE, &sf.forceX87,
                0, "Force to use x87 path (ignored if x86_64)", NULL
            },

            {
                "force-sse2", '\0',
                POPT_ARG_NONE, &sf.forceSSE2,
                0, "Force to use SSE2 path", NULL
            },

            {
                "force-sse3", '\0',
                POPT_ARG_NONE, &sf.forceSSE3,
                0, "Force to use SSE3 path", NULL
            },

            {
                "force-sse4.1", '\0',
                POPT_ARG_NONE, &sf.forceSSE41,
                0, "Force to use SSE4.1 path", NULL
            },

            {
                "force-avx", '\0',
                POPT_ARG_NONE, &sf.forceAVX,
                0, "Force to use AVX path", NULL
            },

            {
                "p", 'p',
                POPT_ARG_NONE, &serverParams,
                0, "Unused dummy argument to satisfy primitive arguments the server sends", NULL
            },

            {
                "np", '\0',
                POPT_ARG_INT | POPT_ARGFLAG_ONEDASH, &numParams,
                0, "Unused dummy argument to satisfy primitive arguments the server sends", NULL
            },

            {
                "version", 'v',
                POPT_ARG_NONE, &version,
                0, "Print version information", NULL
            },

            {
                "copyright", '\0',
                POPT_ARG_NONE, &copyright,
                0, "Print copyright information and exit", NULL
            },

            POPT_AUTOHELP
            POPT_TABLEEND
        };

    setInitialFlags(&sf);

    context = poptGetContext(argv[0], argc, argv, options, POPT_CONTEXT_POSIXMEHARDER);
    if (!context)
    {
        mw_printf("Failed to get popt context\n");
        exit(EXIT_FAILURE);
    }

    if (argc < 2)
    {
        poptPrintUsage(context, stderr, 0);
        poptFreeContext(context);
        exit(EXIT_FAILURE);
    }

    argRead = mwReadArguments(context);
    if (argRead < 0)
    {
        poptFreeContext(context);
        freeSeparationFlags(&sf);
        exit(EXIT_FAILURE);
    }

    if (version)
    {
        printVersion(FALSE, sf.verbose);
    }

    if (copyright)
    {
        printCopyright();
    }

    if (version || copyright)
    {
        exit(EXIT_SUCCESS);
    }

    sf.setSeed = !!(argRead & SEED_ARGUMENT); /* Check if these flags were used */

    sf.do_separation = (sf.separation_outfile && strcmp(sf.separation_outfile, ""));
    if (sf.do_separation)
        prob_ok_init(sf.separationSeed, sf.setSeed);

    rest = poptGetArgs(context);
    sf.forwardedArgs = mwGetForwardedArguments(rest, &sf.nForwardedArgs);
    sf.numArgs = mwReadRestArgs(rest, sf.nForwardedArgs); /* Temporary */

    poptFreeContext(context);
    setDefaults(&sf);
    *sfOut = sf;

    return 0;
}
Exemple #11
0
int
main(int argc, const char **argv)
{
    poptContext opt_con;        /* context for parsing command-line options */
    int rc;
    uint16_t a_height, a_width, b_height, b_width;
    size_t a_no_anchors, b_no_anchors;
    vector2 *a_anchors, *b_anchors;
    float *a_results, *b_results, *results;

    opt_con = poptGetContext(NULL, argc, argv, cli_options, 0);
    poptSetOtherOptionHelp(opt_con, "[OPTIONS] <file1> <file2>");

    // Check for sufficient number of command line arguments
    if (argc < 3) {
        poptPrintUsage(opt_con, stderr, 0);
        poptFreeContext(opt_con);
        exit(EXIT_FAILURE);
    }

    // Parse the command line arguments.
    while ((rc = poptGetNextOpt(opt_con)) >= 0) {
        switch (rc) {
        default:
            break;
        }
    }

    if (rc < -1) {
        /* an error occurred during option processing */
        fprintf(stderr, "%s: %s\n",
                poptBadOption(opt_con, POPT_BADOPTION_NOALIAS),
                poptStrerror(rc));
        poptFreeContext(opt_con);
        exit(EXIT_FAILURE);
    }

    // Handle the left-over arguments.
    if (poptPeekArg(opt_con) != NULL) {
        file[0] = strdup(poptGetArg(opt_con));
    } else {
        fprintf(stderr, "error: missing input file name\n");
        fflush(stderr);
        poptPrintUsage(opt_con, stderr, 0);
        poptFreeContext(opt_con);
        exit(EXIT_FAILURE);
    }

    // Handle the left-over arguments.
    if (poptPeekArg(opt_con) != NULL) {
        file[1] = strdup(poptGetArg(opt_con));
    } else {
        fprintf(stderr, "error: missing input file name\n");
        fflush(stderr);
        poptPrintUsage(opt_con, stderr, 0);
        poptFreeContext(opt_con);
        exit(EXIT_FAILURE);
    }

    for (ls2_output_variant var = AVERAGE_ERROR; var < NUM_VARIANTS; var++) {
        if (compare[var] == NULL)
            continue;
        ls2_hdf5_read_locbased(file[0], var, &a_anchors, &a_no_anchors,
                               &a_results, &a_width, &a_height);

        ls2_hdf5_read_locbased(file[1], var, &b_anchors, &b_no_anchors,
                               &b_results, &b_width, &b_height);
        if (a_width != b_width || a_height != b_height) {
            fprintf(stderr, "Sizes differ. Cannot continue.\n");
            exit(EXIT_FAILURE);
        }

        /* Check whether both images are comparable. */
        if (a_no_anchors != b_no_anchors) {
            fprintf(stderr, "warning: number of anchors do not match\n");
        } else {
            for (size_t i = 0; i < a_no_anchors; i++) {
                if (a_anchors[i].x != b_anchors[i].x ||
                        a_anchors[i].y != b_anchors[i].y) {
                    fprintf(stderr, "warning: anchor positions differ\n");
                }
            }
        }

        /* Compute the difference between both images.
         * A positive number means that image one has the larger error.
         * A negative number means that image two has the larger error.
         */
        results = calloc((size_t)(a_width * a_height), sizeof(float));
        for (uint16_t y = 0; y < a_height; y++) {
            for (uint16_t x = 0; x < a_width; x++) {
                const int i = x + y * a_width;
                results[i] = a_results[i] - b_results[i];
            }
        }

        float mu, sigma, min, max;
        ls2_statistics(results, (size_t) a_width * a_height,
                       &mu, &sigma, &min, &max);
        fprintf(stdout, "Average difference = %f, sdev = %f, min = %f, "
                "max = %f\n", mu, sigma, min, max);

        ls2_cairo_write_png_diff(compare[var], a_anchors, a_no_anchors,
                                 results, a_width, a_height,
                                 similarity, dynamic);
    }
    exit(EXIT_SUCCESS);
}
Exemple #12
0
int main(int argc, const char *argv[])
{
    int opt;
    poptContext pc;
    struct main_context *main_ctx;
    int ret;
    uid_t uid;
    gid_t gid;

    struct poptOption long_options[] = {
        POPT_AUTOHELP
        SSSD_MAIN_OPTS
        SSSD_SERVER_OPTS(uid, gid)
        POPT_TABLEEND
    };

    /* Set debug level to invalid value so we can decide if -d 0 was used. */
    debug_level = SSSDBG_INVALID;

    umask(DFL_RSP_UMASK);

    pc = poptGetContext(argv[0], argc, argv, long_options, 0);
    while((opt = poptGetNextOpt(pc)) != -1) {
        switch(opt) {
        default:
            fprintf(stderr, "\nInvalid option %s: %s\n\n",
                  poptBadOption(pc, 0), poptStrerror(opt));
            poptPrintUsage(pc, stderr, 0);
            return 1;
        }
    }

    poptFreeContext(pc);

    DEBUG_INIT(debug_level);

    /* set up things like debug, signals, daemonization, etc... */
    debug_log_file = "sssd_autofs";

    ret = server_setup("sssd[autofs]", 0, uid, gid,
                       CONFDB_AUTOFS_CONF_ENTRY, &main_ctx);
    if (ret != EOK) {
        return 2;
    }

    ret = die_if_parent_died();
    if (ret != EOK) {
        /* This is not fatal, don't return */
        DEBUG(SSSDBG_OP_FAILURE, "Could not set up to exit "
                                  "when parent process does\n");
    }

    ret = autofs_process_init(main_ctx,
                              main_ctx->event_ctx,
                              main_ctx->confdb_ctx);
    if (ret != EOK) {
        return 3;
    }

    /* loop on main */
    server_loop(main_ctx);

    return 0;
}
Exemple #13
0
 int main(int argc, const char *argv[])
{
	static bool is_daemon;
	static bool opt_interactive;
	static bool Fork = true;
	static bool no_process_group;
	static bool log_stdout;
	poptContext pc;
	char *p_lmhosts = NULL;
	int opt;
	enum {
		OPT_DAEMON = 1000,
		OPT_INTERACTIVE,
		OPT_FORK,
		OPT_NO_PROCESS_GROUP,
		OPT_LOG_STDOUT
	};
	struct poptOption long_options[] = {
	POPT_AUTOHELP
	{"daemon", 'D', POPT_ARG_NONE, NULL, OPT_DAEMON, "Become a daemon(default)" },
	{"interactive", 'i', POPT_ARG_NONE, NULL, OPT_INTERACTIVE, "Run interactive (not a daemon)" },
	{"foreground", 'F', POPT_ARG_NONE, NULL, OPT_FORK, "Run daemon in foreground (for daemontools & etc)" },
	{"no-process-group", 0, POPT_ARG_NONE, NULL, OPT_NO_PROCESS_GROUP, "Don't create a new process group" },
	{"log-stdout", 'S', POPT_ARG_NONE, NULL, OPT_LOG_STDOUT, "Log to stdout" },
	{"hosts", 'H', POPT_ARG_STRING, &p_lmhosts, 0, "Load a netbios hosts file"},
	{"port", 'p', POPT_ARG_INT, &global_nmb_port, 0, "Listen on the specified port" },
	POPT_COMMON_SAMBA
	{ NULL }
	};
	TALLOC_CTX *frame;
	NTSTATUS status;

	/*
	 * Do this before any other talloc operation
	 */
	talloc_enable_null_tracking();
	frame = talloc_stackframe();

	load_case_tables();

	global_nmb_port = NMB_PORT;

	pc = poptGetContext("nmbd", argc, argv, long_options, 0);
	while ((opt = poptGetNextOpt(pc)) != -1) {
		switch (opt) {
		case OPT_DAEMON:
			is_daemon = true;
			break;
		case OPT_INTERACTIVE:
			opt_interactive = true;
			break;
		case OPT_FORK:
			Fork = false;
			break;
		case OPT_NO_PROCESS_GROUP:
			no_process_group = true;
			break;
		case OPT_LOG_STDOUT:
			log_stdout = true;
			break;
		default:
			d_fprintf(stderr, "\nInvalid option %s: %s\n\n",
				  poptBadOption(pc, 0), poptStrerror(opt));
			poptPrintUsage(pc, stderr, 0);
			exit(1);
		}
	};
	poptFreeContext(pc);

	global_in_nmbd = true;
	
	StartupTime = time(NULL);
	
	sys_srandom(time(NULL) ^ sys_getpid());
	
	if (!override_logfile) {
		char *lfile = NULL;
		if (asprintf(&lfile, "%s/log.nmbd", get_dyn_LOGFILEBASE()) < 0) {
			exit(1);
		}
		lp_set_logfile(lfile);
		SAFE_FREE(lfile);
	}
	
	fault_setup();
	dump_core_setup("nmbd", lp_logfile());
	
	/* POSIX demands that signals are inherited. If the invoking process has
	 * these signals masked, we will have problems, as we won't receive them. */
	BlockSignals(False, SIGHUP);
	BlockSignals(False, SIGUSR1);
	BlockSignals(False, SIGTERM);

#if defined(SIGFPE)
	/* we are never interested in SIGFPE */
	BlockSignals(True,SIGFPE);
#endif

	/* We no longer use USR2... */
#if defined(SIGUSR2)
	BlockSignals(True, SIGUSR2);
#endif

	if ( opt_interactive ) {
		Fork = False;
		log_stdout = True;
	}

	if ( log_stdout && Fork ) {
		DEBUG(0,("ERROR: Can't log to stdout (-S) unless daemon is in foreground (-F) or interactive (-i)\n"));
		exit(1);
	}
	if (log_stdout) {
		setup_logging( argv[0], DEBUG_STDOUT);
	} else {
		setup_logging( argv[0], DEBUG_FILE);
	}

	reopen_logs();

	DEBUG(0,("nmbd version %s started.\n", samba_version_string()));
	DEBUGADD(0,("%s\n", COPYRIGHT_STARTUP_MESSAGE));

	if (!lp_load_initial_only(get_dyn_CONFIGFILE())) {
		DEBUG(0, ("error opening config file '%s'\n", get_dyn_CONFIGFILE()));
		exit(1);
	}

	if (nmbd_messaging_context() == NULL) {
		return 1;
	}

	if ( !reload_nmbd_services(False) )
		return(-1);

	if(!init_names())
		return -1;

	reload_nmbd_services( True );

	if (strequal(lp_workgroup(),"*")) {
		DEBUG(0,("ERROR: a workgroup name of * is no longer supported\n"));
		exit(1);
	}

	set_samba_nb_type();

	if (!is_daemon && !is_a_socket(0)) {
		DEBUG(0,("standard input is not a socket, assuming -D option\n"));
		is_daemon = True;
	}
  
	if (is_daemon && !opt_interactive) {
		DEBUG( 2, ( "Becoming a daemon.\n" ) );
		become_daemon(Fork, no_process_group, log_stdout);
	}

#if HAVE_SETPGID
	/*
	 * If we're interactive we want to set our own process group for 
	 * signal management.
	 */
	if (opt_interactive && !no_process_group)
		setpgid( (pid_t)0, (pid_t)0 );
#endif

	if (nmbd_messaging_context() == NULL) {
		return 1;
	}

#ifndef SYNC_DNS
	/* Setup the async dns. We do it here so it doesn't have all the other
		stuff initialised and thus chewing memory and sockets */
	if(lp_we_are_a_wins_server() && lp_dns_proxy()) {
		start_async_dns();
	}
#endif

	if (!directory_exist(lp_lockdir())) {
		mkdir(lp_lockdir(), 0755);
	}

	pidfile_create("nmbd");

	status = reinit_after_fork(nmbd_messaging_context(),
				   nmbd_event_context(),
				   procid_self(), false);

	if (!NT_STATUS_IS_OK(status)) {
		DEBUG(0,("reinit_after_fork() failed\n"));
		exit(1);
	}

	if (!nmbd_setup_sig_term_handler())
		exit(1);
	if (!nmbd_setup_sig_hup_handler())
		exit(1);

	/* get broadcast messages */

	if (!serverid_register(procid_self(),
			       FLAG_MSG_GENERAL|FLAG_MSG_DBWRAP)) {
		DEBUG(1, ("Could not register myself in serverid.tdb\n"));
		exit(1);
	}

	messaging_register(nmbd_messaging_context(), NULL,
			   MSG_FORCE_ELECTION, nmbd_message_election);
#if 0
	/* Until winsrepl is done. */
	messaging_register(nmbd_messaging_context(), NULL,
			   MSG_WINS_NEW_ENTRY, nmbd_wins_new_entry);
#endif
	messaging_register(nmbd_messaging_context(), NULL,
			   MSG_SHUTDOWN, nmbd_terminate);
	messaging_register(nmbd_messaging_context(), NULL,
			   MSG_SMB_CONF_UPDATED, msg_reload_nmbd_services);
	messaging_register(nmbd_messaging_context(), NULL,
			   MSG_SEND_PACKET, msg_nmbd_send_packet);

	TimeInit();

	DEBUG( 3, ( "Opening sockets %d\n", global_nmb_port ) );

	if ( !open_sockets( is_daemon, global_nmb_port ) ) {
		kill_async_dns_child();
		return 1;
	}

	/* Determine all the IP addresses we have. */
	load_interfaces();

	/* Create an nmbd subnet record for each of the above. */
	if( False == create_subnets() ) {
		DEBUG(0,("ERROR: Failed when creating subnet lists. Exiting.\n"));
		kill_async_dns_child();
		exit(1);
	}

	/* Load in any static local names. */ 
	if (p_lmhosts) {
		set_dyn_LMHOSTSFILE(p_lmhosts);
	}
	load_lmhosts_file(get_dyn_LMHOSTSFILE());
	DEBUG(3,("Loaded hosts file %s\n", get_dyn_LMHOSTSFILE()));

	/* If we are acting as a WINS server, initialise data structures. */
	if( !initialise_wins() ) {
		DEBUG( 0, ( "nmbd: Failed when initialising WINS server.\n" ) );
		kill_async_dns_child();
		exit(1);
	}

	/* 
	 * Register nmbd primary workgroup and nmbd names on all
	 * the broadcast subnets, and on the WINS server (if specified).
	 * Also initiate the startup of our primary workgroup (start
	 * elections if we are setup as being able to be a local
	 * master browser.
	 */

	if( False == register_my_workgroup_and_names() ) {
		DEBUG(0,("ERROR: Failed when creating my my workgroup. Exiting.\n"));
		kill_async_dns_child();
		exit(1);
	}

	if (!initialize_nmbd_proxy_logon()) {
		DEBUG(0,("ERROR: Failed setup nmbd_proxy_logon.\n"));
		kill_async_dns_child();
		exit(1);
	}

	if (!nmbd_init_packet_server()) {
		kill_async_dns_child();
                exit(1);
        }

	TALLOC_FREE(frame);
	process();

	kill_async_dns_child();
	return(0);
}
Exemple #14
0
/*
 *  cmd_stop
 *
 *  The 'stop <options>' first level command
 */
int cmd_stop(int argc, const char **argv)
{
	int opt, ret = CMD_SUCCESS, command_ret = CMD_SUCCESS, success = 1;
	static poptContext pc;
	const char *leftover = NULL;

	pc = poptGetContext(NULL, argc, argv, long_options, 0);
	poptReadDefaultConfig(pc, 0);

	while ((opt = poptGetNextOpt(pc)) != -1) {
		switch (opt) {
		case OPT_HELP:
			SHOW_HELP();
			goto end;
		case OPT_LIST_OPTIONS:
			list_cmd_options(stdout, long_options);
			goto end;
		default:
			ret = CMD_UNDEFINED;
			goto end;
		}
	}

	/* Mi check */
	if (lttng_opt_mi) {
		writer = mi_lttng_writer_create(fileno(stdout), lttng_opt_mi);
		if (!writer) {
			ret = -LTTNG_ERR_NOMEM;
			goto end;
		}

		/* Open command element */
		ret = mi_lttng_writer_command_open(writer,
				mi_lttng_element_command_stop);
		if (ret) {
			ret = CMD_ERROR;
			goto end;
		}

		/* Open output element */
		ret = mi_lttng_writer_open_element(writer,
				mi_lttng_element_command_output);
		if (ret) {
			ret = CMD_ERROR;
			goto end;
		}

		/*
		 * Open sessions element
		 * For validation
		 */
		ret = mi_lttng_writer_open_element(writer,
				config_element_sessions);
		if (ret) {
			ret = CMD_ERROR;
			goto end;
		}
	}

	opt_session_name = (char*) poptGetArg(pc);

	leftover = poptGetArg(pc);
	if (leftover) {
		ERR("Unknown argument: %s", leftover);
		ret = CMD_ERROR;
		goto end;
	}

	command_ret = stop_tracing();
	if (command_ret) {
		success = 0;
	}

	/* Mi closing */
	if (lttng_opt_mi) {
		/* Close sessions and  output element */
		ret = mi_lttng_close_multi_element(writer, 2);
		if (ret) {
			ret = CMD_ERROR;
			goto end;
		}

		/* Success ? */
		ret = mi_lttng_writer_write_element_bool(writer,
				mi_lttng_element_command_success, success);
		if (ret) {
			ret = CMD_ERROR;
			goto end;
		}

		/* Command element close */
		ret = mi_lttng_writer_command_close(writer);
		if (ret) {
			ret = CMD_ERROR;
			goto end;
		}
	}

end:
	/* Mi clean-up */
	if (writer && mi_lttng_writer_destroy(writer)) {
		/* Preserve original error code */
		ret = ret ? ret : -LTTNG_ERR_MI_IO_FAIL;
	}

	/* Overwrite ret if an error occurred in stop_tracing() */
	ret = command_ret ? command_ret : ret;

	poptFreeContext(pc);
	return ret;
}
 int main(int argc, const char *argv[])
{
	const char *config_file = get_dyn_CONFIGFILE();
	int s;
	static int silent_mode = False;
	static int show_all_parameters = False;
	int ret = 0;
	poptContext pc;
	static char *parameter_name = NULL;
	static const char *section_name = NULL;
	const char *cname;
	const char *caddr;
	static int show_defaults;
	static int skip_logic_checks = 0;

	struct poptOption long_options[] = {
		POPT_AUTOHELP
		{"suppress-prompt", 's', POPT_ARG_VAL, &silent_mode, 1, "Suppress prompt for enter"},
		{"verbose", 'v', POPT_ARG_NONE, &show_defaults, 1, "Show default options too"},
		{"skip-logic-checks", 'l', POPT_ARG_NONE, &skip_logic_checks, 1, "Skip the global checks"},
		{"show-all-parameters", '\0', POPT_ARG_VAL, &show_all_parameters, True, "Show the parameters, type, possible values" },
		{"parameter-name", '\0', POPT_ARG_STRING, &parameter_name, 0, "Limit testparm to a named parameter" },
		{"section-name", '\0', POPT_ARG_STRING, &section_name, 0, "Limit testparm to a named section" },
		POPT_COMMON_VERSION
		POPT_COMMON_DEBUGLEVEL
		POPT_COMMON_OPTION
		POPT_TABLEEND
	};

	TALLOC_CTX *frame = talloc_stackframe();

	load_case_tables();
	/*
	 * Set the default debug level to 2.
	 * Allow it to be overridden by the command line,
	 * not by smb.conf.
	 */
	lp_set_cmdline("log level", "2");

	pc = poptGetContext(NULL, argc, argv, long_options, 
			    POPT_CONTEXT_KEEP_FIRST);
	poptSetOtherOptionHelp(pc, "[OPTION...] <config-file> [host-name] [host-ip]");

	while(poptGetNextOpt(pc) != -1);

	if (show_all_parameters) {
		show_parameter_list();
		exit(0);
	}

	setup_logging(poptGetArg(pc), DEBUG_STDERR);

	if (poptPeekArg(pc)) 
		config_file = poptGetArg(pc);

	cname = poptGetArg(pc);
	caddr = poptGetArg(pc);

	poptFreeContext(pc);

	if ( cname && ! caddr ) {
		printf ( "ERROR: You must specify both a machine name and an IP address.\n" );
		ret = 1;
		goto done;
	}

	fprintf(stderr,"Load smb config files from %s\n",config_file);

	if (!lp_load_with_registry_shares(config_file,False,True,False,True)) {
		fprintf(stderr,"Error loading services.\n");
		ret = 1;
		goto done;
	}

	fprintf(stderr,"Loaded services file OK.\n");

	if (skip_logic_checks == 0) {
		ret = do_global_checks();
	}

	for (s=0;s<1000;s++) {
		if (VALID_SNUM(s))
			if (strlen(lp_servicename(talloc_tos(), s)) > 12) {
				fprintf(stderr, "WARNING: You have some share names that are longer than 12 characters.\n" );
				fprintf(stderr, "These may not be accessible to some older clients.\n" );
				fprintf(stderr, "(Eg. Windows9x, WindowsMe, and smbclient prior to Samba 3.0.)\n" );
				break;
			}
	}

	for (s=0;s<1000;s++) {
		if (VALID_SNUM(s) && (skip_logic_checks == 0)) {
			do_per_share_checks(s);
		}
	}


	if (!section_name && !parameter_name) {
		fprintf(stderr,
			"Server role: %s\n\n",
			server_role_str(lp_server_role()));
	}

	if (!cname) {
		if (!silent_mode) {
			fprintf(stderr,"Press enter to see a dump of your service definitions\n");
			fflush(stdout);
			getc(stdin);
		}
		if (parameter_name || section_name) {
			bool isGlobal = False;
			s = GLOBAL_SECTION_SNUM;

			if (!section_name) {
				section_name = GLOBAL_NAME;
				isGlobal = True;
			} else if ((isGlobal=!strwicmp(section_name, GLOBAL_NAME)) == 0 &&
				 (s=lp_servicenumber(section_name)) == -1) {
					fprintf(stderr,"Unknown section %s\n",
						section_name);
					ret = 1;
					goto done;
			}
			if (parameter_name) {
				if (!dump_a_parameter( s, parameter_name, stdout, isGlobal)) {
					fprintf(stderr,"Parameter %s unknown for section %s\n",
						parameter_name, section_name);
					ret = 1;
					goto done;
				}
			} else {
				if (isGlobal == True)
					lp_dump(stdout, show_defaults, 0);
				else
					lp_dump_one(stdout, show_defaults, s);
			}
			goto done;
		}

		lp_dump(stdout, show_defaults, lp_numservices());
	}

	if(cname && caddr){
		/* this is totally ugly, a real `quick' hack */
		for (s=0;s<1000;s++) {
			if (VALID_SNUM(s)) {
				if (allow_access(lp_hosts_deny(-1), lp_hosts_allow(-1), cname, caddr)
				    && allow_access(lp_hosts_deny(s), lp_hosts_allow(s), cname, caddr)) {
					fprintf(stderr,"Allow connection from %s (%s) to %s\n",
						   cname,caddr,lp_servicename(talloc_tos(), s));
				} else {
					fprintf(stderr,"Deny connection from %s (%s) to %s\n",
						   cname,caddr,lp_servicename(talloc_tos(), s));
				}
			}
		}
	}

done:
	gfree_loadparm();
	TALLOC_FREE(frame);
	return ret;
}
Exemple #16
0
int main(int argc, const char **argv)
{
	NET_API_STATUS status;
	struct libnetapi_ctx *ctx = NULL;
	const char *hostname = NULL;
	const char *groupname = NULL;
	const char *username = NULL;

	poptContext pc;
	int opt;

	struct poptOption long_options[] = {
		POPT_AUTOHELP
		POPT_COMMON_LIBNETAPI_EXAMPLES
		POPT_TABLEEND
	};

	status = libnetapi_init(&ctx);
	if (status != 0) {
		return status;
	}

	pc = poptGetContext("group_deluser", argc, argv, long_options, 0);

	poptSetOtherOptionHelp(pc, "hostname groupname username");
	while((opt = poptGetNextOpt(pc)) != -1) {
	}

	if (!poptPeekArg(pc)) {
		poptPrintHelp(pc, stderr, 0);
		goto out;
	}
	hostname = poptGetArg(pc);

	if (!poptPeekArg(pc)) {
		poptPrintHelp(pc, stderr, 0);
		goto out;
	}
	groupname = poptGetArg(pc);

	if (!poptPeekArg(pc)) {
		poptPrintHelp(pc, stderr, 0);
		goto out;
	}
	username = poptGetArg(pc);

	/* NetGroupDelUser */

	status = NetGroupDelUser(hostname,
				 groupname,
				 username);
	if (status != 0) {
		printf("NetGroupDelUser failed with: %s\n",
			libnetapi_get_error_string(ctx, status));
	}

 out:
	libnetapi_free(ctx);
	poptFreeContext(pc);

	return status;
}
int
main (int argc, char **argv)
{
	gchar c;		/* used for argument parsing */
	const gchar *filename;
	gint width = 0;
	gint height = 0;
	poptContext optCon;	/* context for parsing command-line options */

	const struct poptOption optionsTable[] = {
		{"width", 'w', POPT_ARG_INT, &width, 0,
		 "Width of the output image (to be resized)", "Width"},
		{"height", 'h', POPT_ARG_INT, &height, 0,
		 "Height of the output image (to be resized)", "Height"},
		POPT_AUTOHELP {NULL, 0, 0, NULL, 0}
	};

	optCon =
	    poptGetContext (NULL, argc, (const char **) argv, optionsTable,
			    0);
	poptSetOtherOptionHelp (optCon, "[options] <filename>");

	if (argc < 2) {
		poptPrintUsage (optCon, stderr, 0);
		return 1;
	}

	while ((c = poptGetNextOpt (optCon)) >= 0) {
		switch (c) {
		case 'w':
			if (width <= 0) {
				width = 0;
			}
			break;
		case 'h':
			if (height <= 0) {
				height = 0;
			}
			break;
		}
	}
	filename = poptGetArg (optCon);
	if ((filename == NULL) || !(poptPeekArg (optCon) == NULL)) {
		poptPrintUsage (optCon, stderr, 0);
		g_printerr ("\n\tYou must to specify the output filename"
			    " such as screenshot.png\n");
		return -1;
	}

	if (c < -1) {
		/* an error occurred during option processing */
		g_printerr ("%s: %s\n",
			    poptBadOption (optCon, POPT_BADOPTION_NOALIAS),
			    poptStrerror (c));
		return 1;
	}

	gdk_init (&argc, &argv);

	take_screenshot (filename, width, height);

	poptFreeContext (optCon);

	return 0;
}
Exemple #18
0
/**
 * Program entry point
 *
 *	@param argc Number of argv elements
 *	@param argv Program name and arguments
 *	@param envp Program environment
 *	@return <i>0</i> Success
 *	@return <br><i>254</i> Initialization failed
 */
int
main(int argc, char **argv, char **envp)
{
    bk_s B = NULL;				/* Baka general structure */
    BK_ENTRY_MAIN(B, __FUNCTION__, __FILE__, "SIMPLE");
    int c;
    int getopterr = 0;
    int debug_level = 0;
    char i18n_localepath[_POSIX_PATH_MAX];
    char *i18n_locale;
    struct program_config Pconfig, *pc = NULL;
    poptContext optCon = NULL;
    struct poptOption optionsTable[] =
    {
        {"debug", 'd', POPT_ARG_NONE, NULL, 'd', N_("Turn on debugging"), NULL },
        {"verbose", 'v', POPT_ARG_NONE, NULL, 'v', N_("Turn on verbose message"), NULL },
        {"no-seatbelts", 0, POPT_ARG_NONE, NULL, 0x1000, N_("Sealtbelts off & speed up"), NULL },
        {"seatbelts", 0, POPT_ARG_NONE, NULL, 0x1001, N_("Enable function tracing"), NULL },
        {"route", 'r', POPT_ARG_STRING, NULL, 'r', N_("Get specific route instead of whole table"), N_("ip_destination") },
        {"profiling", 0, POPT_ARG_STRING, NULL, 0x1002, N_("Enable and write profiling data"), N_("filename") },
        {"long-arg-only", 0, POPT_ARG_NONE, NULL, 1, N_("An example of a long argument without a shortcut"), NULL },
        {NULL, 's', POPT_ARG_NONE, NULL, 2, N_("An example of a short argument without a longcut"), NULL },
        POPT_AUTOHELP
        POPT_TABLEEND
    };

    if (!(B=bk_general_init(argc, &argv, &envp, BK_ENV_GWD(NULL, "BK_ENV_CONF_APP", BK_APP_CONF), NULL, ERRORQUEUE_DEPTH, LOG_LOCAL0, 0)))
    {
        fprintf(stderr,"Could not perform basic initialization\n");
        exit(254);
    }
    bk_fun_reentry(B);

    // Enable error output
    bk_error_config(B, BK_GENERAL_ERROR(B), ERRORQUEUE_DEPTH, stderr, BK_ERR_ERR,
                    BK_ERR_ERR, BK_ERROR_CONFIG_FH |
                    BK_ERROR_CONFIG_SYSLOGTHRESHOLD | BK_ERROR_CONFIG_HILO_PIVOT);

    // i18n stuff
    setlocale(LC_ALL, "");
    if (!(i18n_locale = BK_GWD(B, STD_LOCALEDIR_KEY, NULL)))
    {
        i18n_locale = i18n_localepath;
        snprintf(i18n_localepath, sizeof(i18n_localepath), "%s/%s", BK_ENV_GWD(B, STD_LOCALEDIR_ENV,STD_LOCALEDIR_DEF), STD_LOCALEDIR_SUB);
    }
    bindtextdomain(BK_GENERAL_PROGRAM(B), i18n_locale);
    textdomain(BK_GENERAL_PROGRAM(B));
    for (c = 0; optionsTable[c].longName || optionsTable[c].shortName; c++)
    {
        if (optionsTable[c].descrip) (*((char **)&(optionsTable[c].descrip)))=_(optionsTable[c].descrip);
        if (optionsTable[c].argDescrip) (*((char **)&(optionsTable[c].argDescrip)))=_(optionsTable[c].argDescrip);
    }

    pc = &Pconfig;
    memset(pc, 0, sizeof(*pc));

    if (!(optCon = poptGetContext(NULL, argc, (const char **)argv, optionsTable, 0)))
    {
        bk_error_printf(B, BK_ERR_ERR, "Could not initialize options processing\n");
        bk_exit(B, 254);
    }
    poptSetOtherOptionHelp(optCon, _("[NON-FLAG ARGUMENTS]"));

    while ((c = poptGetNextOpt(optCon)) >= 0)
    {
        switch (c)
        {
        case 'd':					// debug
            if (!debug_level)
            {
                // Set up debugging, from config file
                bk_general_debug_config(B, stderr, BK_ERR_NONE, 0);
                bk_debug_printf(B, "Debugging on\n");
                debug_level++;
            }
            else if (debug_level == 1)
            {
                /*
                 * Enable output of error and higher error logs (this can be
                 * annoying so require -dd)
                 */
                bk_error_config(B, BK_GENERAL_ERROR(B), 0, stderr, BK_ERR_NONE, BK_ERR_ERR, BK_ERROR_CONFIG_FH | BK_ERROR_CONFIG_HILO_PIVOT | BK_ERROR_CONFIG_SYSLOGTHRESHOLD);
                bk_debug_printf(B, "Extra debugging on\n");
                debug_level++;
            }
            else if (debug_level == 2)
            {
                /*
                 * Enable output of all levels of bk_error logs (this can be
                 * very annoying so require -ddd)
                 */
                bk_error_config(B, BK_GENERAL_ERROR(B), 0, stderr, BK_ERR_NONE, BK_ERR_DEBUG, BK_ERROR_CONFIG_FH | BK_ERROR_CONFIG_HILO_PIVOT | BK_ERROR_CONFIG_SYSLOGTHRESHOLD);
                bk_debug_printf(B, "Super-extra debugging on\n");
                debug_level++;
            }
            break;
        case 'v':					// verbose
            BK_FLAG_SET(pc->pc_flags, PC_VERBOSE);
            bk_error_config(B, BK_GENERAL_ERROR(B), ERRORQUEUE_DEPTH, stderr, BK_ERR_NONE, BK_ERR_ERR, 0);
            break;

        case 'r':
            pc->pc_dst = (char *)poptGetOptArg(optCon);
            break;

        case 0x1000:				// no-seatbelts
            BK_FLAG_CLEAR(BK_GENERAL_FLAGS(B), BK_BGFLAGS_FUNON);
            break;
        case 0x1001:				// seatbelts
            BK_FLAG_SET(BK_GENERAL_FLAGS(B), BK_BGFLAGS_FUNON);
            break;
        case 0x1002:				// profiling
            bk_general_funstat_init(B, (char *)poptGetOptArg(optCon), 0);
            break;
        default:
            getopterr++;
            break;
        case 1:					// long-arg-only
            printf("You specificed the long-arg-only option\n");
            break;
        case 2:					// s
            printf("You specificed the short only option\n");
            break;
        }
    }

    /*
     * Reprocess so that argc and argv contain the remaining command
     * line arguments (note argv[0] is an argument, not the program
     * name).  argc remains the number of elements in the argv array.
     */
    argv = (char **)poptGetArgs(optCon);
    argc = 0;
    if (argv)
        for (; argv[argc]; argc++)
            ; // Void

    if (c < -1 || getopterr)
    {
        if (c < -1)
        {
            fprintf(stderr, "%s\n", poptStrerror(c));
        }
        poptPrintUsage(optCon, stderr, 0);
        bk_exit(B, 254);
    }

    if (proginit(B, pc) < 0)
    {
        bk_die(B, 254, stderr, _("Could not perform program initialization\n"), BK_FLAG_ISSET(pc->pc_flags, PC_VERBOSE)?BK_WARNDIE_WANTDETAILS:0);
    }

    progrun(B, pc);

    poptFreeContext(optCon);
    bk_exit(B, 0);
    return(255);					// Stupid INSIGHT stuff.
}
Exemple #19
0
int main(const int argc, const char **argv){
	initstdio();
#else
int _7ciso(const int argc, const char **argv){
#endif
	int cmode=0,mode=0;
	int zlib=0,sevenzip=0,zopfli=0,miniz=0,slz=0,libdeflate=0;
	int threshold=100;
	poptContext optCon;
	int optc;

	struct poptOption optionsTable[] = {
		//{ "longname", "shortname", argInfo,      *arg,       int val, description, argment description}
		{ "stdout", 'c',         POPT_ARG_NONE,            &cmode,      0,       "stdout (currently ignored)", NULL },
		{ "zlib",   'z',         POPT_ARG_INT|POPT_ARGFLAG_OPTIONAL, NULL,       'z',     "1-9 (default 6) zlib", "level" },
		{ "miniz",     'm',         POPT_ARG_INT|POPT_ARGFLAG_OPTIONAL, NULL,    'm',       "1-2 (default 1) miniz", "level" },
		{ "slz",     's',         POPT_ARG_INT|POPT_ARGFLAG_OPTIONAL, NULL,    's',       "1-1 (default 1) slz", "level" },
		{ "libdeflate",     'l',         POPT_ARG_INT|POPT_ARGFLAG_OPTIONAL, NULL,    'l',       "1-12 (default 6) libdeflate", "level" },
		{ "7zip",     'S',         POPT_ARG_INT|POPT_ARGFLAG_OPTIONAL, NULL,    'S',       "1-9 (default 2) 7zip", "level" },
		{ "zopfli",     'Z',         POPT_ARG_INT, &zopfli,    0,       "zopfli", "numiterations" },
		{ "threshold",  't',         POPT_ARG_INT, &threshold, 0,       "compression threshold (in %, 10-100)", "threshold" },
		{ "decompress", 'd',         POPT_ARG_NONE,            &mode,      0,       "decompress", NULL },
		POPT_AUTOHELP,
		POPT_TABLEEND,
	};
	optCon = poptGetContext(argv[0], argc, argv, optionsTable, 0);
	poptSetOtherOptionHelp(optCon, "{-z9 dec.iso enc.cso} or {-cd <enc.cso >dec.iso}");

	for(;(optc=poptGetNextOpt(optCon))>=0;){
		switch(optc){
			case 'z':{
				char *arg=poptGetOptArg(optCon);
				if(arg)zlib=strtol(arg,NULL,10),free(arg);
				else zlib=6;
				break;
			}
			case 'm':{
				char *arg=poptGetOptArg(optCon);
				if(arg)miniz=strtol(arg,NULL,10),free(arg);
				else miniz=1;
				break;
			}
			case 's':{
				char *arg=poptGetOptArg(optCon);
				if(arg)slz=strtol(arg,NULL,10),free(arg);
				else slz=1;
				break;
			}
			case 'l':{
				char *arg=poptGetOptArg(optCon);
				if(arg)libdeflate=strtol(arg,NULL,10),free(arg);
				else libdeflate=1;
				break;
			}
			case 'S':{
				char *arg=poptGetOptArg(optCon);
				if(arg)sevenzip=strtol(arg,NULL,10),free(arg);
				else sevenzip=2;
				break;
			}
		}
	}

	int level_sum=zlib+sevenzip+zopfli+miniz+slz+libdeflate;
	if(
		optc<-1 ||
		(!mode&&!zlib&&!sevenzip&&!zopfli&&!miniz&&!slz&&!libdeflate) ||
		(mode&&(zlib||sevenzip||zopfli||miniz||slz||libdeflate)) ||
		(!mode&&(level_sum==zlib)+(level_sum==sevenzip)+(level_sum==zopfli)+(level_sum==miniz)+(level_sum==slz)+(level_sum==libdeflate)!=1)
	){
		poptPrintHelp(optCon, stderr, 0);
		poptFreeContext(optCon);
		if(!lzmaOpen7z())fprintf(stderr,"\nNote: 7-zip is AVAILABLE.\n"),lzmaClose7z();
		else fprintf(stderr,"\nNote: 7-zip is NOT available.\n");
		return 1;
	}

	if(mode){
		if(isatty(fileno(stdin))||isatty(fileno(stdout)))
			{poptPrintHelp(optCon, stderr, 0);poptFreeContext(optCon);return -1;}
		poptFreeContext(optCon);
		//lzmaOpen7z();
		int ret=_decompress(stdin,stdout);
		//lzmaClose7z();
		return ret;
	}else{
		if(threshold<10)threshold=10;
		if(threshold>100)threshold=100;

		const char *fname=poptGetArg(optCon);
		if(!fname){poptPrintHelp(optCon, stderr, 0);poptFreeContext(optCon);return -1;}
		FILE *in=fopen(fname,"rb");
		if(!in){fprintf(stderr,"failed to open %s\n",fname);poptFreeContext(optCon);return 2;}
		fname=poptGetArg(optCon);
		if(!fname){poptPrintHelp(optCon, stderr, 0);poptFreeContext(optCon);return -1;}
		FILE *out=fopen(fname,"wb");
		if(!out){fclose(in);fprintf(stderr,"failed to open %s\n",fname);poptFreeContext(optCon);return 2;}
		poptFreeContext(optCon);

		fprintf(stderr,"compression level = %d ",level_sum);
		int ret=0;
		if(zlib){
			fprintf(stderr,"(zlib)\n");
			ret=_compress(in,out,zlib,DEFLATE_ZLIB,threshold);
		}else if(sevenzip){
			fprintf(stderr,"(7zip)\n");
			if(lzmaOpen7z()){
				fprintf(stderr,"7-zip is NOT available.\n");
				return -1;
			}
			ret=_compress(in,out,sevenzip,DEFLATE_7ZIP,threshold);
			lzmaClose7z();
		}else if(zopfli){
			fprintf(stderr,"(zopfli)\n");
			ret=_compress(in,out,zopfli,DEFLATE_ZOPFLI,threshold);
		}else if(miniz){
			fprintf(stderr,"(miniz)\n");
			ret=_compress(in,out,miniz,DEFLATE_MINIZ,threshold);
		}else if(slz){
			fprintf(stderr,"(slz)\n");
			ret=_compress(in,out,slz,DEFLATE_SLZ,threshold);
		}else if(libdeflate){
			fprintf(stderr,"(libdeflate)\n");
			ret=_compress(in,out,libdeflate,DEFLATE_LIBDEFLATE,threshold);
		}
		fclose(in),fclose(out);
		return ret;
	}
}
/*
 * Add/remove tracker to/from session.
 */
static
int cmd_track_untrack(enum cmd_type cmd_type, const char *cmd_str,
		int argc, const char **argv)
{
	int opt, ret = 0;
	enum cmd_error_code command_ret = CMD_SUCCESS;
	int success = 1;
	static poptContext pc;
	char *session_name = NULL;
	struct mi_writer *writer = NULL;

	if (argc < 1) {
		command_ret = CMD_ERROR;
		goto end;
	}

	pc = poptGetContext(NULL, argc, argv, long_options, 0);
	poptReadDefaultConfig(pc, 0);

	while ((opt = poptGetNextOpt(pc)) != -1) {
		switch (opt) {
		case OPT_HELP:
			SHOW_HELP();
			goto end;
		case OPT_LIST_OPTIONS:
			list_cmd_options(stdout, long_options);
			goto end;
		case OPT_SESSION:
		case OPT_PID:
			opt_pid = 1;
			break;
		default:
			command_ret = CMD_UNDEFINED;
			goto end;
		}
	}

	ret = print_missing_or_multiple_domains(opt_kernel + opt_userspace);
	if (ret) {
		ret = CMD_ERROR;
		goto end;
	}

	if (!opt_session_name) {
		session_name = get_session_name();
		if (session_name == NULL) {
			command_ret = CMD_ERROR;
			goto end;
		}
	} else {
		session_name = opt_session_name;
	}

	/* Currently only PID tracker is supported */
	if (!opt_pid) {
		ERR("Please specify at least one tracker with its expected arguments");
		command_ret = CMD_ERROR;
		goto end;
	}

	/* Mi check */
	if (lttng_opt_mi) {
		writer = mi_lttng_writer_create(fileno(stdout), lttng_opt_mi);
		if (!writer) {
			command_ret = CMD_ERROR;
			goto end;
		}
	}

	if (writer) {
		/* Open command element */
		ret = mi_lttng_writer_command_open(writer,
				get_mi_element_command(cmd_type));
		if (ret) {
			command_ret = CMD_ERROR;
			goto end;
		}

		/* Open output element */
		ret = mi_lttng_writer_open_element(writer,
				mi_lttng_element_command_output);
		if (ret) {
			command_ret = CMD_ERROR;
			goto end;
		}
	}

	command_ret = track_untrack_pid(cmd_type,
			cmd_str, session_name, opt_pid_string,
			opt_all, writer);
	if (command_ret != CMD_SUCCESS) {
		success = 0;
	}

	/* Mi closing */
	if (writer) {
		/* Close  output element */
		ret = mi_lttng_writer_close_element(writer);
		if (ret) {
			command_ret = CMD_ERROR;
			goto end;
		}

		/* Success ? */
		ret = mi_lttng_writer_write_element_bool(writer,
				mi_lttng_element_command_success, success);
		if (ret) {
			command_ret = CMD_ERROR;
			goto end;
		}

		/* Command element close */
		ret = mi_lttng_writer_command_close(writer);
		if (ret) {
			command_ret = CMD_ERROR;
			goto end;
		}
	}

end:
	if (!opt_session_name) {
		free(session_name);
	}

	/* Mi clean-up */
	if (writer && mi_lttng_writer_destroy(writer)) {
		/* Preserve original error code */
		command_ret = CMD_ERROR;
	}

	poptFreeContext(pc);
	return (int) command_ret;
}
Exemple #21
0
OptionParser::~OptionParser() {
  poptFreeContext(opt_con_);
}
Exemple #22
0
int main(const int ac, const char* av[])
{
  poptContext optCon=0;
  gint rc;
  gint status = 0;
  const gchar* arg;
  struct error* err;

#ifdef __DEBUG  
  g_mem_set_vtable(glib_mem_profiler_table);
#endif

  err = e_new();
  /* check if we have enough privileges */
#ifndef __WIN32__
  unsetenv("LD_LIBRARY_PATH");
#else
  putenv("LD_LIBRARY_PATH");
  putenv("LD_LIBRARY_PATH=");
#endif  

  /* load blacklists from SPKG_CONFDIR */
  gchar** bl_symopts = load_blacklist(SPKG_CONFDIR "/symopts_blacklist");
  if (bl_symopts)
    cmd_opts.bl_symopts = bl_symopts;

  /* preset ROOT */
  cmd_opts.root = getenv("ROOT");

  /* initialize popt context */
  optCon = poptGetContext("spkg", ac, av, opts, 0);
  poptSetOtherOptionHelp(optCon, "<command> [options] [packages...]");

  /* parse options */
  while ((rc = poptGetNextOpt(optCon)) != -1)
  {
    if (rc == 1)
      verbose++;
    else if (rc == 2)
      quiet++;
    if (rc < -1)
    {
      fprintf(stderr, "ERROR: Invalid argument: %s (%s)\n",
        poptStrerror(rc),
        poptBadOption(optCon, POPT_BADOPTION_NOALIAS));
      goto err_1;
    }
  }

  /* these are help handlers */
  if (help)
  {
    printf(
      PACKAGE_STRING "\n"
      "\n"
      "Written by Ondrej Jirman, 2005-2006.\n"
      "\n"
      "This is free software. Not like a beer or like in a \"freedom\",\n"
      "but like in \"I don't care what you are going to do with it.\"\n"
      "\n"
    );
    poptPrintHelp(optCon, stdout, 0);
    printf(
      "\n"
      "Examples:\n"
      "  spkg -i <packages>     [--install]\n"
      "  spkg -u <packages>     [--upgrade]\n"
      "  spkg -vd <packages>    [--verbose --remove]\n"
      "  spkg -l kde*           [--list]\n"
      "  spkg -vnu <packages>   [--upgrade --verbose --dry-run]\n"
      "\n"
      "Official website: http://spkg.megous.com\n"
      "Bug reports can be sent to <*****@*****.**>.\n"
    );
    goto out;
  }
  if (usage)
  {
    printf("Usage: spkg [-i|-u|-d|-l] [--root=ROOT] [-n] [-s] [-q] [-v] [packages...]\n");
    goto out;
  }
  if (version)
  {
    printf("%s\n", PACKAGE_STRING);
    goto out;
  }

  /* check verbosity options */
  if (verbose && quiet)
  {
    fprintf(stderr, "ERROR: Verbose or quiet?\n");
    goto err_1;
  }
  cmd_opts.verbosity += verbose;
  cmd_opts.verbosity -= quiet;

  /* check command options */
  switch (command)
  {
    case CMD_INSTALL:
      if (!cmd_opts.dryrun && !is_root())
        goto err_noroot;
      if (poptPeekArg(optCon) == 0)
        goto err_nopackages;
    break;
    case CMD_UPGRADE:
      if (!cmd_opts.dryrun && !is_root())
        goto err_noroot;
      if (poptPeekArg(optCon) == 0)
        goto err_nopackages;
    break;
    case CMD_REMOVE:
      if (!cmd_opts.dryrun && !is_root())
        goto err_noroot;
      if (poptPeekArg(optCon) == 0)
        goto err_nopackages;
    break;
    case CMD_LIST:
    break;
    case 0:
      if (poptPeekArg(optCon) == 0)
      {
        printf("Usage: spkg [-i|-u|-d|-l] [--root=ROOT] [-n] [-s] [-q] [-v] [packages...]\n");
        goto out;
      }
      if (!cmd_opts.dryrun && !is_root())
        goto err_noroot;
      command = CMD_UPGRADE;
      install_new = TRUE;
    break;
    default:
      fprintf(stderr, "ERROR: Schizofrenic command usage.\n");
      goto err_1;
  }

  /* init signal trap */
  if (sig_trap(err))
    goto err_2;

  /* open db */
  gboolean readonly = cmd_opts.dryrun || !is_root();
  if (db_open(cmd_opts.root, readonly, err))
    goto err_2;

  switch (command)
  {
    case CMD_INSTALL:
    {
      while ((arg = poptGetArg(optCon)) != 0 && !sig_break)
      {
        if (cmd_install(arg, &cmd_opts, err))
        {
          if (e_errno(err) & CMD_EXIST)
          {
            gchar* pkgname = parse_pkgname(arg, 5);
            _inform("Skipping package %s (package with same base name is already installed)...", pkgname ? pkgname : arg);
            g_free(pkgname);
            e_clean(err);
          }
          else
          {
            e_print(err);
            e_clean(err);
            status = 2;
          }
        }
      }
    }
    break;
    case CMD_UPGRADE:
    {
      while ((arg = poptGetArg(optCon)) != 0 && !sig_break)
      {
        if (cmd_upgrade(arg, &cmd_opts, err))
        {
          if (install_new && (e_errno(err) & CMD_NOTEX))
          {
            e_clean(err);
            if (cmd_install(arg, &cmd_opts, err))
            {
              e_print(err);
              e_clean(err);
              status = 2;
            }
          }
          else if (e_errno(err) & CMD_NOTEX)
          {
            gchar* pkgname = parse_pkgname(arg, 5);
            _inform("Skipping package %s (package with same base name is NOT installed)...", pkgname ? pkgname : arg);
            g_free(pkgname);
            e_clean(err);
          }
          else if (e_errno(err) & CMD_EXIST)
          {
            gchar* pkgname = parse_pkgname(arg, 5);
            _inform("Skipping package %s (already uptodate)...", pkgname ? pkgname : arg);
            g_free(pkgname);
            e_clean(err);
          }
          else
          {
            e_print(err);
            e_clean(err);
            status = 2;
          }
        }
      }
    }
    break;
    case CMD_REMOVE:
    {
      while ((arg = poptGetArg(optCon)) != 0 && !sig_break)
      {
        if (cmd_remove(arg, &cmd_opts, err))
        {
          e_print(err);
          e_clean(err);
          status = 2;
        }
      }
    }
    break;
    case CMD_LIST:
    {
      GSList* arglist = NULL;
      while ((arg = poptGetArg(optCon)) != 0)
        arglist = g_slist_append(arglist, g_strdup(arg));
      if (cmd_list(arglist, &cmd_opts, err))
      {
        e_print(err);
        e_clean(err);
        status = 2;
      }
      g_slist_foreach(arglist, (GFunc)g_free, 0);
      g_slist_free(arglist);
    }
    break;
  }

  db_close();

 out:
  poptFreeContext(optCon);
  e_free(err);

#ifdef __DEBUG  
  g_mem_profile();
#endif

  /* 0 = all ok
   * 1 = command line error
   * 2 = package manager error
   */
  return status;
 err_1:
  status = 1;
  goto out;
 err_2:
  status = 2;
  e_print(err);
  goto out;
 err_nopackages:
  fprintf(stderr, "ERROR: No packages specified.\n");
  goto err_1;
 err_noroot:
  fprintf(stderr, "ERROR: You need root privileges to run this command. Try using --dry-run.\n");
  goto err_1;
}
int main(int argc, const char **argv)
{
    gid_t pc_gid = 0;
    int pc_debug = SSSDBG_DEFAULT;
    struct poptOption long_options[] = {
        POPT_AUTOHELP
        { "debug", '\0', POPT_ARG_INT | POPT_ARGFLAG_DOC_HIDDEN, &pc_debug,
                            0, _("The debug level to run with"), NULL },
        { "append-group", 'a', POPT_ARG_STRING, NULL,
                            'a', _("Groups to add this group to"), NULL },
        { "remove-group", 'r', POPT_ARG_STRING, NULL,
                            'r', _("Groups to remove this group from"), NULL },
        { "gid",   'g', POPT_ARG_INT | POPT_ARGFLAG_DOC_HIDDEN, &pc_gid,
                            0, _("The GID of the group"), NULL },
        POPT_TABLEEND
    };
    poptContext pc = NULL;
    struct tools_ctx *tctx = NULL;
    char *addgroups = NULL, *rmgroups = NULL;
    int ret;
    errno_t sret;
    const char *pc_groupname = NULL;
    char *badgroup = NULL;
    bool in_transaction = false;

    debug_prg_name = argv[0];

    ret = set_locale();
    if (ret != EOK) {
        DEBUG(1, ("set_locale failed (%d): %s\n", ret, strerror(ret)));
        ERROR("Error setting the locale\n");
        ret = EXIT_FAILURE;
        goto fini;
    }

    /* parse parameters */
    pc = poptGetContext(NULL, argc, argv, long_options, 0);
    poptSetOtherOptionHelp(pc, "GROUPNAME");
    while ((ret = poptGetNextOpt(pc)) > 0) {
        switch (ret) {
            case 'a':
                addgroups = poptGetOptArg(pc);
                if (addgroups == NULL) {
                    BAD_POPT_PARAMS(pc, _("Specify group to add to\n"),
                                    ret, fini);
                }
                break;

            case 'r':
                rmgroups = poptGetOptArg(pc);
                if (rmgroups == NULL) {
                    BAD_POPT_PARAMS(pc, _("Specify group to remove from\n"),
                                    ret, fini);
                }
                break;
        }
    }

    if (ret != -1) {
        BAD_POPT_PARAMS(pc, poptStrerror(ret), ret, fini);
    }

    /* groupname is an argument without --option */
    pc_groupname = poptGetArg(pc);
    if (pc_groupname == NULL) {
        BAD_POPT_PARAMS(pc, _("Specify group to modify\n"), ret, fini);
    }

    DEBUG_INIT(pc_debug);

    CHECK_ROOT(ret, debug_prg_name);

    ret = init_sss_tools(&tctx);
    if (ret != EOK) {
        DEBUG(1, ("init_sss_tools failed (%d): %s\n", ret, strerror(ret)));
        if (ret == ENOENT) {
            ERROR("Error initializing the tools - no local domain\n");
        } else {
            ERROR("Error initializing the tools\n");
        }
        ret = EXIT_FAILURE;
        goto fini;
    }

    ret = parse_name_domain(tctx, pc_groupname);
    if (ret != EOK) {
        ERROR("Invalid domain specified in FQDN\n");
        ret = EXIT_FAILURE;
        goto fini;
    }
    /* check the username to be able to give sensible error message */
    ret = sysdb_getgrnam_sync(tctx, tctx->sysdb, tctx->octx->name, tctx->octx);
    if (ret != EOK) {
        ERROR("Cannot find group in local domain, "
              "modifying groups is allowed only in local domain\n");
        ret = EXIT_FAILURE;
        goto fini;
    }


    tctx->octx->gid = pc_gid;

    if (addgroups) {
        ret = parse_groups(tctx, addgroups, &tctx->octx->addgroups);
        if (ret != EOK) {
            DEBUG(1, ("Cannot parse groups to add the group to\n"));
            ERROR("Internal error while parsing parameters\n");
            ret = EXIT_FAILURE;
            goto fini;
        }

        ret = parse_group_name_domain(tctx, tctx->octx->addgroups);
        if (ret != EOK) {
            DEBUG(1, ("Cannot parse FQDN groups to add the group to\n"));
            ERROR("Member groups must be in the same domain as parent group\n");
            ret = EXIT_FAILURE;
            goto fini;
        }

        /* Check group names in the LOCAL domain */
        ret = check_group_names(tctx, tctx->octx->addgroups, &badgroup);
        if (ret != EOK) {
            ERROR("Cannot find group %1$s in local domain, "
                  "only groups in local domain are allowed\n", badgroup);
            ret = EXIT_FAILURE;
            goto fini;
        }
    }

    if (rmgroups) {
        ret = parse_groups(tctx, rmgroups, &tctx->octx->rmgroups);
        if (ret != EOK) {
            DEBUG(1, ("Cannot parse groups to remove the group from\n"));
            ERROR("Internal error while parsing parameters\n");
            ret = EXIT_FAILURE;
            goto fini;
        }

        ret = parse_group_name_domain(tctx, tctx->octx->rmgroups);
        if (ret != EOK) {
            DEBUG(1, ("Cannot parse FQDN groups to remove the group from\n"));
            ERROR("Member groups must be in the same domain as parent group\n");
            ret = EXIT_FAILURE;
            goto fini;
        }

        /* Check group names in the LOCAL domain */
        ret = check_group_names(tctx, tctx->octx->rmgroups, &badgroup);
        if (ret != EOK) {
            ERROR("Cannot find group %1$s in local domain, "
                  "only groups in local domain are allowed\n", badgroup);
            ret = EXIT_FAILURE;
            goto fini;
        }
    }

    if (id_in_range(tctx->octx->gid, tctx->octx->domain) != EOK) {
        ERROR("The selected GID is outside the allowed range\n");
        ret = EXIT_FAILURE;
        goto fini;
    }

    tctx->error = sysdb_transaction_start(tctx->sysdb);
    if (tctx->error != EOK) {
        DEBUG(SSSDBG_CRIT_FAILURE, ("Failed to start transaction\n"));
        goto done;
    }
    in_transaction = true;

    /* groupmod */
    tctx->error = groupmod(tctx, tctx->sysdb, tctx->octx);
    if (tctx->error) {
        goto done;
    }

    tctx->error = sysdb_transaction_commit(tctx->sysdb);
    if (tctx->error != EOK) {
        DEBUG(SSSDBG_CRIT_FAILURE, ("Failed to commit transaction\n"));
        goto done;
    }
    in_transaction = false;

    ret = sss_mc_refresh_group(pc_groupname);
    if (ret != EOK) {
        ERROR("NSS request failed (%1$d). Entry might remain in memory "
              "cache.\n", ret);
        /* Nothing we can do about it */
    }

    ret = sss_mc_refresh_grouplist(tctx, tctx->octx->addgroups);
    if (ret != EOK) {
        ERROR("NSS request failed (%1$d). Entry might remain in memory "
              "cache.\n", ret);
        /* Nothing we can do about it */
    }

    ret = sss_mc_refresh_grouplist(tctx, tctx->octx->rmgroups);
    if (ret != EOK) {
        ERROR("NSS request failed (%1$d). Entry might remain in memory "
              "cache.\n", ret);
        /* Nothing we can do about it */
    }

done:
    if (in_transaction) {
        sret = sysdb_transaction_cancel(tctx->sysdb);
        if (sret != EOK) {
            DEBUG(SSSDBG_CRIT_FAILURE, ("Failed to cancel transaction\n"));
        }
    }
    if (tctx->error) {
        ret = tctx->error;
        DEBUG(1, ("sysdb operation failed (%d)[%s]\n", ret, strerror(ret)));
        switch (ret) {
            case ENOENT:
                ERROR("Could not modify group - check if member group names are correct\n");
                break;

            case EFAULT:
                ERROR("Could not modify group - check if groupname is correct\n");
                break;

            default:
                ERROR("Transaction error. Could not modify group.\n");
                break;
        }

        ret = EXIT_FAILURE;
        goto fini;
    }

    ret = EXIT_SUCCESS;

fini:
    free(addgroups);
    free(rmgroups);
    poptFreeContext(pc);
    talloc_free(tctx);
    exit(ret);
}
Exemple #24
0
 int main(int argc,const char *argv[])
{
	/* shall I run as a daemon */
	bool is_daemon = false;
	bool interactive = false;
	bool Fork = true;
	bool no_process_group = false;
	bool log_stdout = false;
	char *ports = NULL;
	char *profile_level = NULL;
	int opt;
	poptContext pc;
	bool print_build_options = False;
        enum {
		OPT_DAEMON = 1000,
		OPT_INTERACTIVE,
		OPT_FORK,
		OPT_NO_PROCESS_GROUP,
		OPT_LOG_STDOUT
	};
	struct poptOption long_options[] = {
	POPT_AUTOHELP
	{"daemon", 'D', POPT_ARG_NONE, NULL, OPT_DAEMON, "Become a daemon (default)" },
	{"interactive", 'i', POPT_ARG_NONE, NULL, OPT_INTERACTIVE, "Run interactive (not a daemon)"},
	{"foreground", 'F', POPT_ARG_NONE, NULL, OPT_FORK, "Run daemon in foreground (for daemontools, etc.)" },
	{"no-process-group", '\0', POPT_ARG_NONE, NULL, OPT_NO_PROCESS_GROUP, "Don't create a new process group" },
	{"log-stdout", 'S', POPT_ARG_NONE, NULL, OPT_LOG_STDOUT, "Log to stdout" },
	{"build-options", 'b', POPT_ARG_NONE, NULL, 'b', "Print build options" },
	{"port", 'p', POPT_ARG_STRING, &ports, 0, "Listen on the specified ports"},
	{"profiling-level", 'P', POPT_ARG_STRING, &profile_level, 0, "Set profiling level","PROFILE_LEVEL"},
	POPT_COMMON_SAMBA
	POPT_TABLEEND
	};
	struct smbd_parent_context *parent = NULL;
	TALLOC_CTX *frame;
	NTSTATUS status;
	struct tevent_context *ev_ctx;
	struct messaging_context *msg_ctx;
	struct server_id server_id;
	struct tevent_signal *se;
	int profiling_level;
	char *np_dir = NULL;
	static const struct smbd_shim smbd_shim_fns =
	{
		.cancel_pending_lock_requests_by_fid = smbd_cancel_pending_lock_requests_by_fid,
		.send_stat_cache_delete_message = smbd_send_stat_cache_delete_message,
		.change_to_root_user = smbd_change_to_root_user,
		.become_authenticated_pipe_user = smbd_become_authenticated_pipe_user,
		.unbecome_authenticated_pipe_user = smbd_unbecome_authenticated_pipe_user,

		.contend_level2_oplocks_begin = smbd_contend_level2_oplocks_begin,
		.contend_level2_oplocks_end = smbd_contend_level2_oplocks_end,

		.become_root = smbd_become_root,
		.unbecome_root = smbd_unbecome_root,

		.exit_server = smbd_exit_server,
		.exit_server_cleanly = smbd_exit_server_cleanly,
	};

	/*
	 * Do this before any other talloc operation
	 */
	talloc_enable_null_tracking();
	frame = talloc_stackframe();

	setup_logging(argv[0], DEBUG_DEFAULT_STDOUT);

	smb_init_locale();

	set_smbd_shim(&smbd_shim_fns);

	smbd_init_globals();

	TimeInit();

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

	pc = poptGetContext("smbd", argc, argv, long_options, 0);
	while((opt = poptGetNextOpt(pc)) != -1) {
		switch (opt)  {
		case OPT_DAEMON:
			is_daemon = true;
			break;
		case OPT_INTERACTIVE:
			interactive = true;
			break;
		case OPT_FORK:
			Fork = false;
			break;
		case OPT_NO_PROCESS_GROUP:
			no_process_group = true;
			break;
		case OPT_LOG_STDOUT:
			log_stdout = true;
			break;
		case 'b':
			print_build_options = True;
			break;
		default:
			d_fprintf(stderr, "\nInvalid option %s: %s\n\n",
				  poptBadOption(pc, 0), poptStrerror(opt));
			poptPrintUsage(pc, stderr, 0);
			exit(1);
		}
	}
	poptFreeContext(pc);

	if (interactive) {
		Fork = False;
		log_stdout = True;
	}

	if (log_stdout) {
		setup_logging(argv[0], DEBUG_STDOUT);
	} else {
		setup_logging(argv[0], DEBUG_FILE);
	}

	if (print_build_options) {
		build_options(True); /* Display output to screen as well as debug */
		exit(0);
	}

#ifdef HAVE_SETLUID
	/* needed for SecureWare on SCO */
	setluid(0);
#endif

	set_remote_machine_name("smbd", False);

	if (interactive && (DEBUGLEVEL >= 9)) {
		talloc_enable_leak_report();
	}

	if (log_stdout && Fork) {
		DEBUG(0,("ERROR: Can't log to stdout (-S) unless daemon is in foreground (-F) or interactive (-i)\n"));
		exit(1);
	}

	/* we want to re-seed early to prevent time delays causing
           client problems at a later date. (tridge) */
	generate_random_buffer(NULL, 0);

	/* get initial effective uid and gid */
	sec_init();

	/* make absolutely sure we run as root - to handle cases where people
	   are crazy enough to have it setuid */
	gain_root_privilege();
	gain_root_group_privilege();

	fault_setup();
	dump_core_setup("smbd", lp_logfile(talloc_tos()));

	/* we are never interested in SIGPIPE */
	BlockSignals(True,SIGPIPE);

#if defined(SIGFPE)
	/* we are never interested in SIGFPE */
	BlockSignals(True,SIGFPE);
#endif

#if defined(SIGUSR2)
	/* We are no longer interested in USR2 */
	BlockSignals(True,SIGUSR2);
#endif

	/* POSIX demands that signals are inherited. If the invoking process has
	 * these signals masked, we will have problems, as we won't recieve them. */
	BlockSignals(False, SIGHUP);
	BlockSignals(False, SIGUSR1);
	BlockSignals(False, SIGTERM);

	/* Ensure we leave no zombies until we
	 * correctly set up child handling below. */

	CatchChild();

	/* we want total control over the permissions on created files,
	   so set our umask to 0 */
	umask(0);

	reopen_logs();

	DEBUG(0,("smbd version %s started.\n", samba_version_string()));
	DEBUGADD(0,("%s\n", COPYRIGHT_STARTUP_MESSAGE));

	DEBUG(2,("uid=%d gid=%d euid=%d egid=%d\n",
		 (int)getuid(),(int)getgid(),(int)geteuid(),(int)getegid()));

	/* Output the build options to the debug log */ 
	build_options(False);

	if (sizeof(uint16_t) < 2 || sizeof(uint32_t) < 4) {
		DEBUG(0,("ERROR: Samba is not configured correctly for the word size on your machine\n"));
		exit(1);
	}

	if (!lp_load_initial_only(get_dyn_CONFIGFILE())) {
		DEBUG(0, ("error opening config file '%s'\n", get_dyn_CONFIGFILE()));
		exit(1);
	}

	if (!cluster_probe_ok()) {
		exit(1);
	}

	/* Init the security context and global current_user */
	init_sec_ctx();

	/*
	 * Initialize the event context. The event context needs to be
	 * initialized before the messaging context, cause the messaging
	 * context holds an event context.
	 * FIXME: This should be s3_tevent_context_init()
	 */
	ev_ctx = server_event_context();
	if (ev_ctx == NULL) {
		exit(1);
	}

	/*
	 * Init the messaging context
	 * FIXME: This should only call messaging_init()
	 */
	msg_ctx = server_messaging_context();
	if (msg_ctx == NULL) {
		exit(1);
	}

	/*
	 * Reloading of the printers will not work here as we don't have a
	 * server info and rpc services set up. It will be called later.
	 */
	if (!reload_services(NULL, NULL, false)) {
		exit(1);
	}

	if (lp_server_role() == ROLE_ACTIVE_DIRECTORY_DC
	    && !lp_parm_bool(-1, "server role check", "inhibit", false)) {
		DEBUG(0, ("server role = 'active directory domain controller' not compatible with running smbd standalone. \n"));
		DEBUGADD(0, ("You should start 'samba' instead, and it will control starting smbd if required\n"));
		exit(1);
	}

	/* ...NOTE... Log files are working from this point! */

	DEBUG(3,("loaded services\n"));

	init_structs();

	if (!profile_setup(msg_ctx, False)) {
		DEBUG(0,("ERROR: failed to setup profiling\n"));
		return -1;
	}

	if (profile_level != NULL) {
		profiling_level = atoi(profile_level);
	} else {
		profiling_level = lp_smbd_profiling_level();
	}
	set_profile_level(profiling_level, messaging_server_id(msg_ctx));

	if (!is_daemon && !is_a_socket(0)) {
		if (!interactive) {
			DEBUG(3, ("Standard input is not a socket, "
				  "assuming -D option\n"));
		}

		/*
		 * Setting is_daemon here prevents us from eventually calling
		 * the open_sockets_inetd()
		 */

		is_daemon = True;
	}

	if (is_daemon && !interactive) {
		DEBUG(3, ("Becoming a daemon.\n"));
		become_daemon(Fork, no_process_group, log_stdout);
	}

#if HAVE_SETPGID
	/*
	 * If we're interactive we want to set our own process group for
	 * signal management.
	 */
	if (interactive && !no_process_group)
		setpgid( (pid_t)0, (pid_t)0);
#endif

	if (!directory_exist(lp_lock_directory()))
		mkdir(lp_lock_directory(), 0755);

	if (!directory_exist(lp_pid_directory()))
		mkdir(lp_pid_directory(), 0755);

	if (is_daemon)
		pidfile_create(lp_pid_directory(), "smbd");

	status = reinit_after_fork(msg_ctx, ev_ctx, false, NULL);
	if (!NT_STATUS_IS_OK(status)) {
		exit_daemon("reinit_after_fork() failed", map_errno_from_nt_status(status));
	}

	if (!interactive) {
		/*
		 * Do not initialize the parent-child-pipe before becoming a
		 * daemon: this is used to detect a died parent in the child
		 * process.
		 */
		status = init_before_fork();
		if (!NT_STATUS_IS_OK(status)) {
			exit_daemon(nt_errstr(status), map_errno_from_nt_status(status));
		}
	}

	parent = talloc_zero(ev_ctx, struct smbd_parent_context);
	if (!parent) {
		exit_server("talloc(struct smbd_parent_context) failed");
	}
	parent->interactive = interactive;
	parent->ev_ctx = ev_ctx;
	parent->msg_ctx = msg_ctx;
	am_parent = parent;

	se = tevent_add_signal(parent->ev_ctx,
			       parent,
			       SIGTERM, 0,
			       smbd_parent_sig_term_handler,
			       parent);
	if (!se) {
		exit_server("failed to setup SIGTERM handler");
	}
	se = tevent_add_signal(parent->ev_ctx,
			       parent,
			       SIGHUP, 0,
			       smbd_parent_sig_hup_handler,
			       parent);
	if (!se) {
		exit_server("failed to setup SIGHUP handler");
	}

	/* Setup all the TDB's - including CLEAR_IF_FIRST tdb's. */

	if (smbd_memcache() == NULL) {
		exit_daemon("no memcache available", EACCES);
	}

	memcache_set_global(smbd_memcache());

	/* Initialise the password backed before the global_sam_sid
	   to ensure that we fetch from ldap before we make a domain sid up */

	if(!initialize_password_db(false, ev_ctx))
		exit(1);

	if (!secrets_init()) {
		exit_daemon("smbd can not open secrets.tdb", EACCES);
	}

	if (lp_server_role() == ROLE_DOMAIN_BDC || lp_server_role() == ROLE_DOMAIN_PDC) {
		struct loadparm_context *lp_ctx = loadparm_init_s3(NULL, loadparm_s3_helpers());
		if (!open_schannel_session_store(NULL, lp_ctx)) {
			exit_daemon("ERROR: Samba cannot open schannel store for secured NETLOGON operations.", EACCES);
		}
		TALLOC_FREE(lp_ctx);
	}

	if(!get_global_sam_sid()) {
		exit_daemon("Samba cannot create a SAM SID", EACCES);
	}

	server_id = messaging_server_id(msg_ctx);
	status = smbXsrv_version_global_init(&server_id);
	if (!NT_STATUS_IS_OK(status)) {
		exit_daemon("Samba cannot init server context", EACCES);
	}

	status = smbXsrv_session_global_init();
	if (!NT_STATUS_IS_OK(status)) {
		exit_daemon("Samba cannot init session context", EACCES);
	}

	status = smbXsrv_tcon_global_init();
	if (!NT_STATUS_IS_OK(status)) {
		exit_daemon("Samba cannot init tcon context", EACCES);
	}

	if (!locking_init())
		exit_daemon("Samba cannot init locking", EACCES);

	if (!leases_db_init(false)) {
		exit_daemon("Samba cannot init leases", EACCES);
	}

	if (!smbd_notifyd_init(msg_ctx, interactive)) {
		exit_daemon("Samba cannot init notification", EACCES);
	}

	if (!messaging_parent_dgm_cleanup_init(msg_ctx)) {
		exit(1);
	}

	if (!smbd_scavenger_init(NULL, msg_ctx, ev_ctx)) {
		exit_daemon("Samba cannot init scavenging", EACCES);
	}

	if (!serverid_parent_init(ev_ctx)) {
		exit_daemon("Samba cannot init server id", EACCES);
	}

	if (!W_ERROR_IS_OK(registry_init_full()))
		exit_daemon("Samba cannot init registry", EACCES);

	/* Open the share_info.tdb here, so we don't have to open
	   after the fork on every single connection.  This is a small
	   performance improvment and reduces the total number of system
	   fds used. */
	if (!share_info_db_init()) {
		exit_daemon("ERROR: failed to load share info db.", EACCES);
	}

	status = init_system_session_info();
	if (!NT_STATUS_IS_OK(status)) {
		DEBUG(1, ("ERROR: failed to setup system user info: %s.\n",
			  nt_errstr(status)));
		return -1;
	}

	if (!init_guest_info()) {
		DEBUG(0,("ERROR: failed to setup guest info.\n"));
		return -1;
	}

	if (!file_init_global()) {
		DEBUG(0, ("ERROR: file_init_global() failed\n"));
		return -1;
	}
	status = smbXsrv_open_global_init();
	if (!NT_STATUS_IS_OK(status)) {
		exit_daemon("Samba cannot init global open", map_errno_from_nt_status(status));
	}

	/* This MUST be done before start_epmd() because otherwise
	 * start_epmd() forks and races against dcesrv_ep_setup() to
	 * call directory_create_or_exist() */
	if (!directory_create_or_exist(lp_ncalrpc_dir(), 0755)) {
		DEBUG(0, ("Failed to create pipe directory %s - %s\n",
			  lp_ncalrpc_dir(), strerror(errno)));
		return -1;
	}

	np_dir = talloc_asprintf(talloc_tos(), "%s/np", lp_ncalrpc_dir());
	if (!np_dir) {
		DEBUG(0, ("%s: Out of memory\n", __location__));
		return -1;
	}

	if (!directory_create_or_exist_strict(np_dir, geteuid(), 0700)) {
		DEBUG(0, ("Failed to create pipe directory %s - %s\n",
			  np_dir, strerror(errno)));
		return -1;
	}

	if (is_daemon && !interactive) {
		if (rpc_epmapper_daemon() == RPC_DAEMON_FORK) {
			start_epmd(ev_ctx, msg_ctx);
		}
	}

	if (!dcesrv_ep_setup(ev_ctx, msg_ctx)) {
		exit_daemon("Samba cannot setup ep pipe", EACCES);
	}

	if (is_daemon && !interactive) {
		daemon_ready("smbd");
	}

	/* only start other daemons if we are running as a daemon
	 * -- bad things will happen if smbd is launched via inetd
	 *  and we fork a copy of ourselves here */
	if (is_daemon && !interactive) {

		if (rpc_lsasd_daemon() == RPC_DAEMON_FORK) {
			start_lsasd(ev_ctx, msg_ctx);
		}

		if (rpc_fss_daemon() == RPC_DAEMON_FORK) {
			start_fssd(ev_ctx, msg_ctx);
		}

		if (!lp__disable_spoolss() &&
		    (rpc_spoolss_daemon() != RPC_DAEMON_DISABLED)) {
			bool bgq = lp_parm_bool(-1, "smbd", "backgroundqueue", true);

			if (!printing_subsystem_init(ev_ctx, msg_ctx, true, bgq)) {
				exit_daemon("Samba failed to init printing subsystem", EACCES);
			}
		}

#ifdef WITH_SPOTLIGHT
		if ((rpc_mdssvc_mode() == RPC_SERVICE_MODE_EXTERNAL) &&
		    (rpc_mdssd_daemon() == RPC_DAEMON_FORK)) {
			start_mdssd(ev_ctx, msg_ctx);
		}
#endif
	} else if (!lp__disable_spoolss() &&
		   (rpc_spoolss_daemon() != RPC_DAEMON_DISABLED)) {
		if (!printing_subsystem_init(ev_ctx, msg_ctx, false, false)) {
			exit(1);
		}
	}

	if (!is_daemon) {
		int sock;

		/* inetd mode */
		TALLOC_FREE(frame);

		/* Started from inetd. fd 0 is the socket. */
		/* We will abort gracefully when the client or remote system
		   goes away */
		sock = dup(0);

		/* close stdin, stdout (if not logging to it), but not stderr */
		close_low_fds(true, !debug_get_output_is_stdout(), false);

#ifdef HAVE_ATEXIT
		atexit(killkids);
#endif

	        /* Stop zombies */
		smbd_setup_sig_chld_handler(parent);

		smbd_process(ev_ctx, msg_ctx, sock, true);

		exit_server_cleanly(NULL);
		return(0);
	}

	if (!open_sockets_smbd(parent, ev_ctx, msg_ctx, ports))
		exit_server("open_sockets_smbd() failed");

	/* do a printer update now that all messaging has been set up,
	 * before we allow clients to start connecting */
	if (!lp__disable_spoolss() &&
	    (rpc_spoolss_daemon() != RPC_DAEMON_DISABLED)) {
		printing_subsystem_update(ev_ctx, msg_ctx, false);
	}

	TALLOC_FREE(frame);
	/* make sure we always have a valid stackframe */
	frame = talloc_stackframe();

	if (!Fork) {
		/* if we are running in the foreground then look for
		   EOF on stdin, and exit if it happens. This allows
		   us to die if the parent process dies
		   Only do this on a pipe or socket, no other device.
		*/
		struct stat st;
		if (fstat(0, &st) != 0) {
			return false;
		}
		if (S_ISFIFO(st.st_mode) || S_ISSOCK(st.st_mode)) {
			tevent_add_fd(ev_ctx,
					parent,
					0,
					TEVENT_FD_READ,
					smbd_stdin_handler,
					NULL);
		}
	}

	smbd_parent_loop(ev_ctx, parent);

	exit_server_cleanly(NULL);
	TALLOC_FREE(frame);
	return(0);
}
Exemple #25
0
void usage(poptContext optCon, int exitcode, char *error) {
	poptPrintUsage(optCon, stderr, 0);
	if (error) fprintf(stderr, "%s\n", error);
	poptFreeContext(optCon);
	exit(exitcode);
}
int main(int argc, const char **argv)
{
	NET_API_STATUS status;
	struct libnetapi_ctx *ctx = NULL;
	const char *hostname = NULL;
	const char *groupname = NULL;
	struct LOCALGROUP_MEMBERS_INFO_0 *g0;
	struct LOCALGROUP_MEMBERS_INFO_3 *g3;
	uint32_t total_entries = 0;
	uint8_t *buffer = NULL;
	uint32_t level = 3;
	const char **names = NULL;
	int i = 0;

	poptContext pc;
	int opt;

	struct poptOption long_options[] = {
		POPT_AUTOHELP
		POPT_COMMON_LIBNETAPI_EXAMPLES
		POPT_TABLEEND
	};

	status = libnetapi_init(&ctx);
	if (status != 0) {
		return status;
	}

	pc = poptGetContext("localgroup_addmembers", argc, argv, long_options, 0);

	poptSetOtherOptionHelp(pc, "hostname groupname member1 member2 ...");
	while((opt = poptGetNextOpt(pc)) != -1) {
	}

	if (!poptPeekArg(pc)) {
		poptPrintHelp(pc, stderr, 0);
		goto out;
	}
	hostname = poptGetArg(pc);

	if (!poptPeekArg(pc)) {
		poptPrintHelp(pc, stderr, 0);
		goto out;
	}
	groupname = poptGetArg(pc);

	if (!poptPeekArg(pc)) {
		poptPrintHelp(pc, stderr, 0);
		goto out;
	}

	names = poptGetArgs(pc);
	for (i=0; names[i] != NULL; i++) {
		total_entries++;
	}

	switch (level) {
		case 0:
			status = NetApiBufferAllocate(sizeof(struct LOCALGROUP_MEMBERS_INFO_0) * total_entries,
						      (void **)&g0);
			if (status) {
				printf("NetApiBufferAllocate failed with: %s\n",
					libnetapi_get_error_string(ctx, status));
				goto out;
			}

			for (i=0; i<total_entries; i++) {
				if (!ConvertStringSidToSid(names[i], &g0[i].lgrmi0_sid)) {
					printf("could not convert sid\n");
					goto out;
				}
			}

			buffer = (uint8_t *)g0;
			break;
		case 3:
			status = NetApiBufferAllocate(sizeof(struct LOCALGROUP_MEMBERS_INFO_3) * total_entries,
						      (void **)&g3);
			if (status) {
				printf("NetApiBufferAllocate failed with: %s\n",
					libnetapi_get_error_string(ctx, status));
				goto out;
			}

			for (i=0; i<total_entries; i++) {
				g3[i].lgrmi3_domainandname = names[i];
			}

			buffer = (uint8_t *)g3;
			break;
		default:
			break;
	}

	/* NetLocalGroupAddMembers */

	status = NetLocalGroupAddMembers(hostname,
					 groupname,
					 level,
					 buffer,
					 total_entries);
	if (status != 0) {
		printf("NetLocalGroupAddMembers failed with: %s\n",
			libnetapi_get_error_string(ctx, status));
	}

 out:
	libnetapi_free(ctx);
	poptFreeContext(pc);

	return status;
}
int
main (int argc, const char *argv[])
{
    gboolean got_version_request = FALSE;
    gboolean got_help_command_request = FALSE;
    gboolean accept_pipe_commands = FALSE;

    const char **da_args = NULL;
    int da_arg_count = 0;
    char *prog_name = g_strdup(argv[0]);

    rra_cli_init();
    rra_cli_init_from_env();

#ifdef RRA_HAVE_POPT_H
    struct poptOption entries[] =
        {
            {
                "version",
                'V',
                POPT_ARG_VAL,
                &got_version_request,
                TRUE,
                "Get version number",
                NULL
            },

            {
                "help-commands",
                '\0',
                POPT_ARG_VAL,
                &got_help_command_request,
                TRUE,
                "Get help on available sub commands.",
                NULL
            },

            {
                "pipe-commands",
                'p',
                POPT_ARG_NONE,
                &accept_pipe_commands,
                TRUE,
                "Accept commands from stdin and write output to stdout.",
                NULL
            },

            POPT_AUTOHELP

            rra_util_options_get()[0],
            rra_cli_options_get()[0],

            POPT_TABLEEND
        };

    poptContext ctxt;

    ctxt = poptGetContext(NULL, argc, argv, entries, 0);

    poptSetOtherOptionHelp(
        ctxt, "[OPTIONS] <windows dir> <command> [<command args>]");

    int rc;
    while ((rc = poptGetNextOpt(ctxt)) >= 0)
    {
    }

    da_args = poptGetArgs(ctxt);

    if (da_args != NULL)
    {
        for (da_arg_count = 0; da_args[da_arg_count] != NULL; da_arg_count++)
        {
        }
    }

#else
    da_args = argv + 1;
    da_arg_count = argc - 1;
#endif

    gchar *basename = g_path_get_basename(prog_name);
    if (got_version_request)
    {
        printf("Version for %s is %s\n", basename, RRA_VERSION);
        exit(0);
    }

    if (got_help_command_request)
    {
        printf(
            "Available commands:\n%s",
            rra_cli_state_help_message(NULL));
        exit(0);
    }

    if (da_arg_count < 2)
    {
        fprintf (
            stderr,
            "Not enough arguments: %d\n"
            "Usage: %s [OPTIONS] <windows dir> [<arguments>]\n",
            da_arg_count, basename);
        exit(1);
    }

    if (!g_file_test(da_args[0], G_FILE_TEST_IS_DIR))
    {
        fprintf (stderr, "First argument, %s, is not a directory\n",
                 da_args[0]);
        exit(1);
    }

    RRACliState *state = rra_cli_state_new_from_win_dir(da_args[0]);

    if (state == NULL)
    {
        fprintf (stderr, "Error creating basic state\n");
        exit(1);
    }

    RRACliResult *result = rra_cli_state_apply(state, da_arg_count - 1,
                                               da_args + 1);
    int exit_val = 0;

    if (rra_cli_result_is_error(result))
    {
        if (rra_cli_result_has_content(result))
        {
            fprintf (stderr, "Error Encountered: %s\n",
                     rra_cli_result_get_content(result));
        }
        exit_val = 1;
    }
    else
    {
        if (rra_cli_result_has_data(result))
        {
            const GByteArray *data = rra_cli_result_get_data(result);
            if (data->len > 0)
            {
                fwrite(data->data, data->len, sizeof(guint8), stdout);
            }
        }
        else if (rra_cli_result_has_content(result))
        {
            printf ("%s\n", rra_cli_result_get_content(result));
        }
    }

    rra_cli_state_free(state);
    rra_cli_result_free(result);

    g_free(prog_name);

#if RRA_HAVE_POPT_H
    poptFreeContext(ctxt);
#endif

exit(exit_val);
}
Exemple #28
0
int main(int argc, const char *argv[])
{
    int np, verbose;
    int rank, i, rc;
    int dup_argc;
    char **dup_argv;

    int waittime, killtime;
    unsigned int magic;

    /*
     * We can't use popt for argument parsing here. popt is not
     * capable to stop at the first unrecogniced option, i.e. at the
     * executable separation options to the mpirun command from
     * options to the application.
     */

    poptContext optCon;   /* context for parsing command-line options */

    struct poptOption optionsTable[] = {
	{ "np", '\0', POPT_ARG_INT | POPT_ARGFLAG_ONEDASH,
	  &np, 0, "number of processes to start", "num"},
	{ "wait", 'w', POPT_ARG_INT, &waittime, 0,
	  "Wait <n> seconds between each spawning step", "n"},
	{ "kill", 'k', POPT_ARG_INT, &killtime, 0,
	  "Kill all processes <n> seconds after the first exits", "n"},
	{ NULL, 'v', POPT_ARG_NONE,
	  &verbose, 0, "verbose mode", NULL},
	{ NULL, '\0', 0, NULL, 0, NULL, NULL}
    };

    /* The duplicated argv will contain the apps commandline */
    poptDupArgv(argc, argv, &dup_argc, (const char ***)&dup_argv);

    optCon = poptGetContext(NULL, dup_argc, (const char **)dup_argv,
			    optionsTable, 0);
    poptSetOtherOptionHelp(optCon, OTHER_OPTIONS_STR);

    /*
     * Split the argv into two parts:
     *  - first one containing the mpirun options
     *  - second one containing the apps argv
     * The first one is already parsed while splitting
     */
    while (1) {
	const char *unknownArg;

	np = -1;
	verbose = 0;
	waittime = 0;
	killtime = -1;

	rc = poptGetNextOpt(optCon);

	if ((unknownArg=poptGetArg(optCon))) {
	    /*
	     * Find the first unknown argument (which is the apps
	     * name) within dup_argv. Start searching from dup_argv's end
	     * since the apps name might be used within another
	     * options argument.
	     */
	    for (i=argc-1; i>0; i--) {
		if (strcmp(dup_argv[i], unknownArg)==0) {
		    dup_argc = i;
		    dup_argv[dup_argc] = NULL;
		    poptFreeContext(optCon);
		    optCon = poptGetContext(NULL,
					    dup_argc, (const char **)dup_argv,
					    optionsTable, 0);
		    poptSetOtherOptionHelp(optCon, OTHER_OPTIONS_STR);
		    break;
		}
	    }
	    if (i==0) {
		printf("unknownArg '%s' not found !?\n", unknownArg);
		exit(1);
	    }
	} else {
	    /* No unknownArg left, we are finished */
	    break;
	}
    }

    if (rc < -1) {
	/* an error occurred during option processing */
	poptPrintUsage(optCon, stderr, 0);
	fprintf(stderr, "%s: %s\n",
		poptBadOption(optCon, POPT_BADOPTION_NOALIAS),
		poptStrerror(rc));
	exit(1);
    }

    if (np == -1) {
	poptPrintUsage(optCon, stderr, 0);
	fprintf(stderr, "You have to give at least the -np argument.\n");
	exit(1);
    }

    if (!argv[dup_argc]) {
	poptPrintUsage(optCon, stderr, 0);
	fprintf(stderr, "No <command> specified.\n");
	exit(1);
    }

    free(dup_argv);

    if (verbose) {
	printf("The 'gmspawner' command-line is:\n");
	for (i=0; i<dup_argc; i++) {
	    printf("%s ", argv[i]);
	}
	printf("\b\n\n");

	printf("The applications command-line is:\n");
	for (i=dup_argc; i<argc; i++) {
	    printf("%s ", argv[i]);
	}
	printf("\b\n\n");
    }

    /* init PSI */
    if (!PSI_initClient(TG_GMSPAWNER)) {
	fprintf(stderr, "Initialization of PSI failed.");
	exit(10);
    }

    PSI_infoInt(-1, PSP_INFO_TASKRANK, NULL, &rank, 0);
    if (rank != np) {
	fprintf(stderr, "%s: rank(%d) != np(%d).\n", argv[dup_argc], rank, np);

	exit(1);
    }

    /* Propagate some environment variables */
    PSI_propEnv();
    PSI_propEnvList("PSI_EXPORTS");
    PSI_propEnvList("__PSI_EXPORTS");

    srandom(time(NULL));
    magic = random()%9999999;
    setIntEnv("GMPI_MAGIC", magic);

    setIntEnv("GMPI_NP", np);

    {
	char hostname[256];
	gethostname(hostname, sizeof(hostname));

	setPSIEnv("GMPI_MASTER", hostname, 1);
    }

    {
	int port = createListener(8000, np, magic, verbose);

	if (port>=0) setIntEnv("GMPI_PORT", port);
    }

    propagateEnv("GMPI_SHMEM", 1);
    propagateEnv("DISPLAY", 0);
    propagateEnv("GMPI_EAGER", 0);
    propagateEnv("GMPI_RECV", 1);

    PSC_setSigHandler(SIGALRM, sighandler);

    /* spawn all processes */

    PSI_RemoteArgs(argc - dup_argc, (char **)&argv[dup_argc],
		   &dup_argc, &dup_argv);

    for (rank=0; rank<np; rank++) {
	if (waittime && rank) sleep(waittime);

	setIntEnv("GMPI_ID", rank);
	setIntEnv("GMPI_BOARD", -1);

	char slavestring[20];
	PSnodes_ID_t node;
	struct in_addr ip;
	int err;

	err = PSI_infoNodeID(-1, PSP_INFO_RANKID, &rank, &node, 1);
	if (err) {
	    fprintf(stderr, "Could not determine rank %d's node.\n", rank);
	    exit(1);
	}

	err = PSI_infoUInt(-1, PSP_INFO_NODE, &node, &ip.s_addr, 1);
	if (err) {
	    fprintf(stderr, "Could not determine node %d's IP\n", node);
	    exit(1);
	}

	snprintf(slavestring, sizeof(slavestring), "%s", inet_ntoa(ip));
	setPSIEnv("GMPI_SLAVE", slavestring, 1);

	/* spawn the process */
	int error;
	if (!PSI_spawnRank(rank, ".", dup_argc, dup_argv, &error)) {
	    if (error) {
		char *errstr = strerror(error);
		fprintf(stderr, "Could not spawn process %d (%s) error = %s.\n",
			rank, dup_argv[0], errstr ? errstr : "UNKNOWN");
		exit(1);
	    }
	}
    }

    /* Wait for the spawned processes to complete */
    while (np) {
	static int firstClient=1;
	DDErrorMsg_t msg;
	int ret;

	ret = PSI_recvMsg((DDMsg_t *)&msg, sizeof(msg));
	if (msg.header.type != PSP_CD_SPAWNFINISH || ret != sizeof(msg)) {
	    fprintf(stderr, "got strange message type %s\n",
		    PSP_printMsg(msg.header.type));
	} else {
	    if (firstClient && killtime!=-1) {
		// printf("Alarm set to %d\n", killtime);
		if (killtime) {
		    alarm(killtime);
		    firstClient=0;
		} else {
		    /* Stop immediately */
		    exit(0);
		}
	    }
	    np--;
	    // printf("%d clients left\n", np);
	}
    }
    PSI_release(PSC_getMyTID());
    PSI_exitClient();

    return 0;
}
Exemple #29
0
/*
 * The 'list <options>' first level command
 */
int cmd_list(int argc, const char **argv)
{
	int opt, ret = CMD_SUCCESS;
	const char *session_name;
	static poptContext pc;
	struct lttng_domain domain;
	struct lttng_domain *domains = NULL;

	memset(&domain, 0, sizeof(domain));

	if (argc < 1) {
		usage(stderr);
		ret = CMD_ERROR;
		goto end;
	}

	pc = poptGetContext(NULL, argc, argv, long_options, 0);
	poptReadDefaultConfig(pc, 0);

	while ((opt = poptGetNextOpt(pc)) != -1) {
		switch (opt) {
		case OPT_HELP:
			usage(stdout);
			goto end;
		case OPT_USERSPACE:
			opt_userspace = 1;
			break;
		case OPT_LIST_OPTIONS:
			list_cmd_options(stdout, long_options);
			goto end;
		default:
			usage(stderr);
			ret = CMD_UNDEFINED;
			goto end;
		}
	}

	/* Mi check */
	if (lttng_opt_mi) {
		writer = mi_lttng_writer_create(fileno(stdout), lttng_opt_mi);
		if (!writer) {
			ret = CMD_ERROR;
			goto end;
		}

		/* Open command element */
		ret = mi_lttng_writer_command_open(writer,
				mi_lttng_element_command_list);
		if (ret) {
			ret = CMD_ERROR;
			goto end;
		}

		/* Open output element */
		ret = mi_lttng_writer_open_element(writer,
				mi_lttng_element_command_output);
		if (ret) {
			ret = CMD_ERROR;
			goto end;
		}
	}

	/* Get session name (trailing argument) */
	session_name = poptGetArg(pc);
	DBG2("Session name: %s", session_name);

	if (opt_kernel) {
		domain.type = LTTNG_DOMAIN_KERNEL;
	} else if (opt_userspace) {
		DBG2("Listing userspace global domain");
		domain.type = LTTNG_DOMAIN_UST;
	} else if (opt_jul) {
		DBG2("Listing JUL domain");
		domain.type = LTTNG_DOMAIN_JUL;
	} else if (opt_log4j) {
		domain.type = LTTNG_DOMAIN_LOG4J;
	} else if (opt_python) {
		domain.type = LTTNG_DOMAIN_PYTHON;
	}

	if (!opt_kernel && opt_syscall) {
		WARN("--syscall will only work with the Kernel domain (-k)");
		ret = CMD_ERROR;
		goto end;
	}

	if (opt_kernel || opt_userspace || opt_jul || opt_log4j || opt_python) {
		handle = lttng_create_handle(session_name, &domain);
		if (handle == NULL) {
			ret = CMD_FATAL;
			goto end;
		}
	}

	if (session_name == NULL) {
		if (!opt_kernel && !opt_userspace && !opt_jul && !opt_log4j
				&& !opt_python) {
			ret = list_sessions(NULL);
			if (ret) {
				goto end;
			}
		}
		if (opt_kernel) {
			if (opt_syscall) {
				ret = list_syscalls();
				if (ret) {
					goto end;
				}
			} else {
				ret = list_kernel_events();
				if (ret) {
					goto end;
				}
			}
		}
		if (opt_userspace) {
			if (opt_fields) {
				ret = list_ust_event_fields();
			} else {
				ret = list_ust_events();
			}
			if (ret) {
				goto end;
			}
		}
		if (opt_jul || opt_log4j || opt_python) {
			ret = list_agent_events();
			if (ret) {
				goto end;
			}
		}
	} else {
		/* List session attributes */
		if (lttng_opt_mi) {
			/* Open element sessions
			 * Present for xml consistency */
			ret = mi_lttng_sessions_open(writer);
			if (ret) {
				goto end;
			}
		}
		/* MI: the ouptut of list_sessions is an unclosed session element */
		ret = list_sessions(session_name);
		if (ret) {
			goto end;
		}

		/* Domain listing */
		if (opt_domain) {
			ret = list_domains(session_name);
			goto end;
		}

		/* Channel listing */
		if (opt_kernel || opt_userspace) {
			if (lttng_opt_mi) {
				/* Add of domains and domain element for xml
				 * consistency and validation
				 */
				ret = mi_lttng_domains_open(writer);
				if (ret) {
					goto end;
				}

				/* Open domain and leave it open for
				 * nested channels printing */
				ret = mi_lttng_domain(writer, &domain, 1);
				if (ret) {
					goto end;
				}

			}

			ret = list_tracker_pids();
			if (ret) {
				goto end;
			}

			ret = list_channels(opt_channel);
			if (ret) {
				goto end;
			}

			if (lttng_opt_mi) {
				/* Close domain and domain element */
				ret = mi_lttng_close_multi_element(writer, 2);
			}
			if (ret) {
				goto end;
			}


		} else {
			int i, nb_domain;

			/* We want all domain(s) */
			nb_domain = lttng_list_domains(session_name, &domains);
			if (nb_domain < 0) {
				ret = CMD_ERROR;
				ERR("%s", lttng_strerror(nb_domain));
				goto end;
			}

			if (lttng_opt_mi) {
				ret = mi_lttng_domains_open(writer);
				if (ret) {
					ret = CMD_ERROR;
					goto end;
				}
			}

			for (i = 0; i < nb_domain; i++) {
				switch (domains[i].type) {
				case LTTNG_DOMAIN_KERNEL:
					MSG("=== Domain: Kernel ===\n");
					break;
				case LTTNG_DOMAIN_UST:
					MSG("=== Domain: UST global ===\n");
					MSG("Buffer type: %s\n",
							domains[i].buf_type ==
							LTTNG_BUFFER_PER_PID ? "per PID" : "per UID");
					break;
				case LTTNG_DOMAIN_JUL:
					MSG("=== Domain: JUL (Java Util Logging) ===\n");
					break;
				case LTTNG_DOMAIN_LOG4J:
					MSG("=== Domain: LOG4j (Logging for Java) ===\n");
					break;
				case LTTNG_DOMAIN_PYTHON:
					MSG("=== Domain: Python (logging) ===\n");
					break;
				default:
					MSG("=== Domain: Unimplemented ===\n");
					break;
				}

				if (lttng_opt_mi) {
					ret = mi_lttng_domain(writer, &domains[i], 1);
					if (ret) {
						ret = CMD_ERROR;
						goto end;
					}
				}

				/* Clean handle before creating a new one */
				if (handle) {
					lttng_destroy_handle(handle);
				}

				handle = lttng_create_handle(session_name, &domains[i]);
				if (handle == NULL) {
					ret = CMD_FATAL;
					goto end;
				}

				if (domains[i].type == LTTNG_DOMAIN_JUL ||
						domains[i].type == LTTNG_DOMAIN_LOG4J ||
						domains[i].type == LTTNG_DOMAIN_PYTHON) {
					ret = list_session_agent_events();
					if (ret) {
						goto end;
					}
					continue;
				}

				switch (domains[i].type) {
				case LTTNG_DOMAIN_KERNEL:
				case LTTNG_DOMAIN_UST:
					ret = list_tracker_pids();
					if (ret) {
						goto end;
					}
					break;
				default:
					break;
				}

				ret = list_channels(opt_channel);
				if (ret) {
					goto end;
				}

				if (lttng_opt_mi) {
					/* Close domain element */
					ret = mi_lttng_writer_close_element(writer);
					if (ret) {
						ret = CMD_ERROR;
						goto end;
					}
				}

			}
			if (lttng_opt_mi) {
				/* Close the domains, session and sessions element */
				ret = mi_lttng_close_multi_element(writer, 3);
				if (ret) {
					ret = CMD_ERROR;
					goto end;
				}
			}
		}
	}

	/* Mi closing */
	if (lttng_opt_mi) {
		/* Close  output element */
		ret = mi_lttng_writer_close_element(writer);
		if (ret) {
			ret = CMD_ERROR;
			goto end;
		}

		/* Command element close */
		ret = mi_lttng_writer_command_close(writer);
		if (ret) {
			ret = CMD_ERROR;
			goto end;
		}
	}
end:
	/* Mi clean-up */
	if (writer && mi_lttng_writer_destroy(writer)) {
		/* Preserve original error code */
		ret = ret ? ret : -LTTNG_ERR_MI_IO_FAIL;
	}

	free(domains);
	if (handle) {
		lttng_destroy_handle(handle);
	}

	poptFreeContext(pc);
	return ret;
}
Exemple #30
0
int main(int argc, const char *argv[])
{
	poptContext pc;
	const char **extra_argv;
	char *src_url = NULL;
	char *dst_url = NULL;
	struct iscsi_url *iscsi_url;
	struct scsi_task *task;
	struct scsi_readcapacity10 *rc10;
	int extra_argc = 0;
	int res;
	struct pollfd pfd[2];
	struct client client;

	struct poptOption popt_options[] = {
		POPT_AUTOHELP
		{ "initiator-name", 'i', POPT_ARG_STRING, &initiator, 0, "Initiatorname to use", "iqn-name" },
		{ "src", 0, POPT_ARG_STRING, &src_url, 0, "SRC lun", "iscsi url" },
		{ "dst", 0, POPT_ARG_STRING, &dst_url, 0, "DST lun", "iscsi url" },
		POPT_TABLEEND
	};

	pc = poptGetContext(argv[0], argc, argv, popt_options, POPT_CONTEXT_POSIXMEHARDER);
	if ((res = poptGetNextOpt(pc)) < -1) {
		fprintf(stderr, "Failed to parse option : %s %s\n",
			poptBadOption(pc, 0), poptStrerror(res));
		exit(10);
	}
	extra_argv = poptGetArgs(pc);
	poptFreeContext(pc);

	if (src_url == NULL) {
		fprintf(stderr, "You must specify source url\n");
		fprintf(stderr, "  --src iscsi://<host>[:<port>]/<target-iqn>/<lun>\n", argv[0]);
		exit(10);
	}
	if (dst_url == NULL) {
		fprintf(stderr, "You must specify destination url\n");
		fprintf(stderr, "  --dst iscsi://<host>[:<port>]/<target-iqn>/<lun>\n", argv[0]);
		exit(10);
	}


	memset(&client, 0, sizeof(client));


	client.src_iscsi = iscsi_create_context(initiator);
	if (client.src_iscsi == NULL) {
		fprintf(stderr, "Failed to create context\n");
		exit(10);
	}
	iscsi_url = iscsi_parse_full_url(client.src_iscsi, src_url);
	if (iscsi_url == NULL) {
		fprintf(stderr, "Failed to parse URL: %s\n", 
			iscsi_get_error(client.src_iscsi));
		exit(10);
	}
	iscsi_set_targetname(client.src_iscsi, iscsi_url->target);
	iscsi_set_session_type(client.src_iscsi, ISCSI_SESSION_NORMAL);
	iscsi_set_header_digest(client.src_iscsi, ISCSI_HEADER_DIGEST_NONE_CRC32C);
	if (iscsi_url->user != NULL) {
		if (iscsi_set_initiator_username_pwd(client.src_iscsi, iscsi_url->user, iscsi_url->passwd) != 0) {
			fprintf(stderr, "Failed to set initiator username and password\n");
			exit(10);
		}
	}
	if (iscsi_full_connect_sync(client.src_iscsi, iscsi_url->portal, iscsi_url->lun) != 0) {
		fprintf(stderr, "Login Failed. %s\n", iscsi_get_error(client.src_iscsi));
		iscsi_destroy_url(iscsi_url);
		iscsi_destroy_context(client.src_iscsi);
		exit(10);
	}
	client.src_lun = iscsi_url->lun;
	iscsi_destroy_url(iscsi_url);

	task = iscsi_readcapacity10_sync(client.src_iscsi, client.src_lun, 0, 0);
	if (task == NULL || task->status != SCSI_STATUS_GOOD) {
		fprintf(stderr, "failed to send readcapacity command\n");
		exit(10);
	}
	rc10 = scsi_datain_unmarshall(task);
	if (rc10 == NULL) {
		fprintf(stderr, "failed to unmarshall readcapacity10 data\n");
		exit(10);
	}
	client.src_blocksize  = rc10->block_size;
	client.src_num_blocks  = rc10->lba;
	scsi_free_scsi_task(task);





	client.dst_iscsi = iscsi_create_context(initiator);
	if (client.dst_iscsi == NULL) {
		fprintf(stderr, "Failed to create context\n");
		exit(10);
	}
	iscsi_url = iscsi_parse_full_url(client.dst_iscsi, dst_url);
	if (iscsi_url == NULL) {
		fprintf(stderr, "Failed to parse URL: %s\n", 
			iscsi_get_error(client.dst_iscsi));
		exit(10);
	}
	iscsi_set_targetname(client.dst_iscsi, iscsi_url->target);
	iscsi_set_session_type(client.dst_iscsi, ISCSI_SESSION_NORMAL);
	iscsi_set_header_digest(client.dst_iscsi, ISCSI_HEADER_DIGEST_NONE_CRC32C);
	if (iscsi_url->user != NULL) {
		if (iscsi_set_initiator_username_pwd(client.dst_iscsi, iscsi_url->user, iscsi_url->passwd) != 0) {
			fprintf(stderr, "Failed to set initiator username and password\n");
			exit(10);
		}
	}
	if (iscsi_full_connect_sync(client.dst_iscsi, iscsi_url->portal, iscsi_url->lun) != 0) {
		fprintf(stderr, "Login Failed. %s\n", iscsi_get_error(client.dst_iscsi));
		iscsi_destroy_url(iscsi_url);
		iscsi_destroy_context(client.dst_iscsi);
		exit(10);
	}
	client.dst_lun = iscsi_url->lun;
	iscsi_destroy_url(iscsi_url);

	task = iscsi_readcapacity10_sync(client.dst_iscsi, client.dst_lun, 0, 0);
	if (task == NULL || task->status != SCSI_STATUS_GOOD) {
		fprintf(stderr, "failed to send readcapacity command\n");
		exit(10);
	}
	rc10 = scsi_datain_unmarshall(task);
	if (rc10 == NULL) {
		fprintf(stderr, "failed to unmarshall readcapacity10 data\n");
		exit(10);
	}
	client.dst_blocksize  = rc10->block_size;
	client.dst_num_blocks  = rc10->lba;
	scsi_free_scsi_task(task);

	fill_read_queue(&client);

	while (client.finished == 0) {
		pfd[0].fd = iscsi_get_fd(client.src_iscsi);
		pfd[0].events = iscsi_which_events(client.src_iscsi);
		pfd[1].fd = iscsi_get_fd(client.dst_iscsi);
		pfd[1].events = iscsi_which_events(client.dst_iscsi);

		if (poll(&pfd[0], 2, -1) < 0) {
			printf("Poll failed");
			exit(10);
		}
		if (iscsi_service(client.src_iscsi, pfd[0].revents) < 0) {
			printf("iscsi_service failed with : %s\n", iscsi_get_error(client.src_iscsi));
			break;
		}
		if (iscsi_service(client.dst_iscsi, pfd[1].revents) < 0) {
			printf("iscsi_service failed with : %s\n", iscsi_get_error(client.dst_iscsi));
			break;
		}
	}

	iscsi_logout_sync(client.src_iscsi);
	iscsi_destroy_context(client.src_iscsi);
	iscsi_logout_sync(client.dst_iscsi);
	iscsi_destroy_context(client.dst_iscsi);

	return 0;
}