コード例 #1
0
ファイル: main_ln.c プロジェクト: 0871087123/rtems
static int
main_ln(rtems_shell_ln_globals* globals, int argc, char *argv[])
{
	struct stat sb;
	int ch, exitval;
	char *sourcedir;

	struct getopt_data getopt_reent;
	memset(&getopt_reent, 0, sizeof(getopt_data));

#if RTEMS_REMOVED
	setprogname(argv[0]);
	(void)setlocale(LC_ALL, "");
#endif

	while ((ch = getopt_r(argc, argv, "fhinsv", &getopt_reent)) != -1)
		switch (ch) {
		case 'f':
			fflag = 1;
			iflag = 0;
			break;
		case 'h':
		case 'n':
			hflag = 1;
			break;
		case 'i':
			iflag = 1;
			fflag = 0;
			break;
		case 's':
			sflag = 1;
			break;
		case 'v':
			vflag = 1;
			break;
		case '?':
		default:
			usage(globals);
			/* NOTREACHED */
		}

	argv += getopt_reent.optind;
	argc -= getopt_reent.optind;

	if (sflag) {
		linkf  = symlink;
		linkch = '-';
	} else {
		linkf  = link;
		linkch = '=';
	}

	switch(argc) {
	case 0:
		usage(globals);
		/* NOTREACHED */
	case 1:				/* ln target */
		exit(linkit(globals, argv[0], ".", 1));
		/* NOTREACHED */
	case 2:				/* ln target source */
		exit(linkit(globals, argv[0], argv[1], 0));
		/* NOTREACHED */
	}

					/* ln target1 target2 directory */
	sourcedir = argv[argc - 1];
	if (hflag && lstat(sourcedir, &sb) == 0 && S_ISLNK(sb.st_mode)) {
		/* we were asked not to follow symlinks, but found one at
		   the target--simulate "not a directory" error */
		errno = ENOTDIR;
		err(exit_jump, EXIT_FAILURE, "%s", sourcedir);
		/* NOTREACHED */
	}
	if (stat(sourcedir, &sb)) {
		err(exit_jump, EXIT_FAILURE, "%s", sourcedir);
		/* NOTREACHED */
	}
	if (!S_ISDIR(sb.st_mode)) {
		usage(globals);
		/* NOTREACHED */
	}
	for (exitval = 0; *argv != sourcedir; ++argv)
		exitval |= linkit(globals, *argv, sourcedir, 1);
	exit(exitval);
	/* NOTREACHED */
  return 0;
}
コード例 #2
0
ファイル: kdc-replay.c プロジェクト: 2asoft/freebsd
int
main(int argc, char **argv)
{
    krb5_error_code ret;
    krb5_context context;
    krb5_kdc_configuration *config;
    krb5_storage *sp;
    int fd, optidx = 0;

    setprogname(argv[0]);

    if(getarg(args, num_args, argc, argv, &optidx))
	usage(1);

    if(help_flag)
	usage(0);

    if(version_flag){
	print_version(NULL);
	exit(0);
    }

    ret = krb5_init_context(&context);
    if (ret)
	errx (1, "krb5_init_context failed to parse configuration file");

    ret = krb5_kdc_get_config(context, &config);
    if (ret)
	krb5_err(context, 1, ret, "krb5_kdc_default_config");

    kdc_openlog(context, "kdc-replay", config);

    ret = krb5_kdc_set_dbinfo(context, config);
    if (ret)
	krb5_err(context, 1, ret, "krb5_kdc_set_dbinfo");

#ifdef PKINIT
    if (config->enable_pkinit) {
	if (config->pkinit_kdc_identity == NULL)
	    krb5_errx(context, 1, "pkinit enabled but no identity");

	if (config->pkinit_kdc_anchors == NULL)
	    krb5_errx(context, 1, "pkinit enabled but no X509 anchors");

	krb5_kdc_pk_initialize(context, config,
			       config->pkinit_kdc_identity,
			       config->pkinit_kdc_anchors,
			       config->pkinit_kdc_cert_pool,
			       config->pkinit_kdc_revoke);

    }
#endif /* PKINIT */

    if (argc != 2)
	errx(1, "argc != 2");

    printf("kdc replay\n");

    fd = open(argv[1], O_RDONLY);
    if (fd < 0)
	err(1, "open: %s", argv[1]);

    sp = krb5_storage_from_fd(fd);
    if (sp == NULL)
	krb5_errx(context, 1, "krb5_storage_from_fd");

    while(1) {
	struct sockaddr_storage sa;
	krb5_socklen_t salen = sizeof(sa);
	struct timeval tv;
	krb5_address a;
	krb5_data d, r;
	uint32_t t, clty, tag;
	char astr[80];

	ret = krb5_ret_uint32(sp, &t);
	if (ret == HEIM_ERR_EOF)
	    break;
	else if (ret)
	    krb5_errx(context, 1, "krb5_ret_uint32(version)");
	if (t != 1)
	    krb5_errx(context, 1, "version not 1");
	ret = krb5_ret_uint32(sp, &t);
	if (ret)
	    krb5_errx(context, 1, "krb5_ret_uint32(time)");
	ret = krb5_ret_address(sp, &a);
	if (ret)
	    krb5_errx(context, 1, "krb5_ret_address");
	ret = krb5_ret_data(sp, &d);
	if (ret)
	    krb5_errx(context, 1, "krb5_ret_data");
	ret = krb5_ret_uint32(sp, &clty);
	if (ret)
	    krb5_errx(context, 1, "krb5_ret_uint32(class|type)");
	ret = krb5_ret_uint32(sp, &tag);
	if (ret)
	    krb5_errx(context, 1, "krb5_ret_uint32(tag)");


	ret = krb5_addr2sockaddr (context, &a, (struct sockaddr *)&sa,
				  &salen, 88);
	if (ret == KRB5_PROG_ATYPE_NOSUPP)
	    goto out;
	else if (ret)
	    krb5_err(context, 1, ret, "krb5_addr2sockaddr");

	ret = krb5_print_address(&a, astr, sizeof(astr), NULL);
	if (ret)
	    krb5_err(context, 1, ret, "krb5_print_address");

	printf("processing request from %s, %lu bytes\n",
	       astr, (unsigned long)d.length);

	r.length = 0;
	r.data = NULL;

	tv.tv_sec = t;
	tv.tv_usec = 0;

	krb5_kdc_update_time(&tv);
	krb5_set_real_time(context, tv.tv_sec, 0);

	ret = krb5_kdc_process_request(context, config, d.data, d.length,
				       &r, NULL, astr,
				       (struct sockaddr *)&sa, 0);
	if (ret)
	    krb5_err(context, 1, ret, "krb5_kdc_process_request");

	if (r.length) {
	    Der_class cl;
	    Der_type ty;
	    unsigned int tag2;
	    ret = der_get_tag (r.data, r.length,
			       &cl, &ty, &tag2, NULL);
	    if (MAKE_TAG(cl, ty, 0) != clty)
		krb5_errx(context, 1, "class|type mismatch: %d != %d",
			  (int)MAKE_TAG(cl, ty, 0), (int)clty);
	    if (tag != tag2)
		krb5_errx(context, 1, "tag mismatch");

	    krb5_data_free(&r);
	} else {
	    if (clty != 0xffffffff)
		krb5_errx(context, 1, "clty not invalid");
	    if (tag != 0xffffffff)
		krb5_errx(context, 1, "tag not invalid");
	}

    out:
	krb5_data_free(&d);
	krb5_free_address(context, &a);
    }

    krb5_storage_free(sp);
    krb5_free_context(context);

    printf("done\n");

    return 0;
}
コード例 #3
0
ファイル: tip.c プロジェクト: ryo/netbsd-src
int
main(int argc, char *argv[])
{
	char *System = NULL;
	int c, i;
	char *p;
	const char *q;
	char sbuf[12];
	int cmdlineBR;
	int fcarg;

	setprogname(argv[0]);
	gid = getgid();
	egid = getegid();
	uid = getuid();
	euid = geteuid();
	if (strcmp(getprogname(), "cu") == 0) {
		cumode = 1;
		cumain(argc, argv);
		goto cucommon;
	}

	if (argc > 4)
		tipusage();

	if (!isatty(0))
		errx(EXIT_FAILURE, "must be interactive");

	cmdlineBR = 0;
	while((c = getopt(argc, argv, "v0123456789")) != -1) {
		switch(c) {

		case 'v':
			vflag++;
			break;

		case '0': case '1': case '2': case '3': case '4':
		case '5': case '6': case '7': case '8': case '9':
			cmdlineBR = cmdlineBR * 10 + (c - '0');
			BR = cmdlineBR;
			break;

		default:
			warnx("%s, unknown option", argv[1]);
			break;
		}
	}

	argc -= optind;
	argv += optind;

	if (argc != 1)
		tipusage();
	else
		System = argv[0];


	if (System == NULL)
		goto notnumber;
	if (isalpha((unsigned char)*System))
		goto notnumber;
	/*
	 * System name is really a phone number...
	 * Copy the number then stomp on the original (in case the number
	 *	is private, we don't want 'ps' or 'w' to find it).
	 */
	if (strlen(System) > sizeof PNbuf - 1) {
		errx(1, "phone number too long (max = %d bytes)",
			(int)sizeof(PNbuf) - 1);
	}
	(void)strlcpy(PNbuf, System, sizeof(PNbuf));
	for (p = System; *p; p++)
		*p = '\0';
	PN = PNbuf;
	(void)snprintf(sbuf, sizeof sbuf, "tip%d", (int)BR);
	System = sbuf;

notnumber:
	(void)signal(SIGINT, cleanup);
	(void)signal(SIGQUIT, cleanup);
	(void)signal(SIGHUP, cleanup);
	(void)signal(SIGTERM, cleanup);

	if ((i = hunt(System)) == 0) {
		errx(3, "all ports busy");
	}
	if (i == -1) {
		errx(3, "link down");
	}
	setbuf(stdout, NULL);

	/*
	 * Kludge, their's no easy way to get the initialization
	 *   in the right order, so force it here
	 */
	if ((PH = getenv("PHONES")) == NULL)
		PH = path_phones;
	vinit();				/* init variables */
	setparity("none");			/* set the parity table */

	/*
	 * Hardwired connections require the
	 *  line speed set before they make any transmissions
	 *  (this is particularly true of things like a DF03-AC)
	 */
	if (HW) {
		if (ttysetup((speed_t)number(value(BAUDRATE))) != 0) {
			errx(3, "bad baud rate %d",
			    (int)number(value(BAUDRATE)));
		}
	}
	if ((q = tip_connect()) != NULL) {
		errx(1, "\07%s\n[EOT]", q);
	}
	if (!HW) {
		if (ttysetup((speed_t)number(value(BAUDRATE))) != 0) {
			errx(3, "bad baud rate %d",
			    (int)number(value(BAUDRATE)));
		}
	}


cucommon:
	/*
	 * From here down the code is shared with
	 * the "cu" version of tip.
	 */

	/*
	 * Direct connections with no carrier require using O_NONBLOCK on
	 * open, but we don't want to keep O_NONBLOCK after open because it
	 * will cause busy waits.
	 */
	if (DC &&
	    ((fcarg = fcntl(FD, F_GETFL, 0)) < 0 ||
	     fcntl(FD, F_SETFL, fcarg & ~O_NONBLOCK) < 0)) {
		err(1, "can't clear O_NONBLOCK");
	}

	(void)tcgetattr(0, &defterm);
	term = defterm;
	term.c_lflag &= ~(ICANON|IEXTEN|ECHO);
	term.c_iflag &= ~(INPCK|ICRNL);
	term.c_oflag &= ~OPOST;
	term.c_cc[VMIN] = 1;
	term.c_cc[VTIME] = 0;
	defchars = term;
	term.c_cc[VINTR] = term.c_cc[VQUIT] = term.c_cc[VSUSP] =
		term.c_cc[VDSUSP] = term.c_cc[VDISCARD] =
	 	term.c_cc[VLNEXT] = _POSIX_VDISABLE;
	raw();

	(void)pipe(attndes);
	(void)pipe(fildes);
	(void)pipe(repdes);
	(void)signal(SIGALRM, alrmtimeout);

	/*
	 * Everything's set up now:
	 *	connection established (hardwired or dialup)
	 *	line conditioned (baud rate, mode, etc.)
	 *	internal data structures (variables)
	 * so, fork one process for local side and one for remote.
	 */
	(void)printf("%s", cumode ? "Connected\r\n" : "\07connected\r\n");
	switch (pid = fork()) {
	default:
		tipin();
		break;
	case 0:
		tipout();
		break;
	case -1:
		err(1, "can't fork");
	}
	/*NOTREACHED*/
	exit(0);	/* XXX: pacify gcc */
}
コード例 #4
0
ファイル: rump_lfs.c プロジェクト: ryo/netbsd-src
int
main(int argc, char *argv[])
{
	struct ulfs_args args;
	char canon_dev[UKFS_DEVICE_MAXPATHLEN], canon_dir[MAXPATHLEN];
	char rawdev[MAXPATHLEN];
	struct p2k_mount *p2m;
	pthread_t cleanerthread;
	struct ukfs_part *part;
	int mntflags;
	int rv;

	setprogname(argv[0]);
	puffs_unmountonsignal(SIGINT, true);
	puffs_unmountonsignal(SIGTERM, true);

	if (argc >= 3) {
		UKFS_DEVICE_ARGVPROBE(&part);
		if (part != ukfs_part_none) {
			errx(1, "lfs does not currently support "
			    "embedded partitions");
		}
	}
	mount_lfs_parseargs(argc, argv, &args, &mntflags, canon_dev, canon_dir);

	/* Reset getopt for lfs_cleaner_main.  */
	optreset = 1;
	optind = 1;

	p2m = p2k_init(0);
	if (!p2m)
		err(1, "init p2k");
	/*
	 * XXX: this particular piece inspired by the cleaner code.
	 * obviously FIXXXME along with the cleaner.
	 */
	sprintf(rawdev, "/dev/r%s", canon_dev+5);
	rump_pub_etfs_register(rawdev, canon_dev, RUMP_ETFS_CHR);

	/*
	 * We basically have two choices:
	 *  1) run the cleaner in another process and do rump ipc syscalls
	 *  2) run it off a thread in this process and do rump syscalls
	 *     as function calls.
	 *
	 * opt for "2" for now
	 */
#ifdef CLEANER_TESTING
	ukfs_mount(MOUNT_LFS, canon_dev, canon_dir, mntflags,
	    &args, sizeof(args));
	cleaner(canon_dir);
#endif
	if (p2k_setup_diskfs(p2m, MOUNT_LFS, canon_dev, part, canon_dir,
	    mntflags, &args, sizeof(args)) == -1)
		err(1, "mount");
	ukfs_part_release(part);

#ifndef CLEANER_TESTING
	if ((mntflags & MNT_RDONLY) == 0) {
		if (pthread_create(&cleanerthread, NULL,
		    cleaner, canon_dir) == -1)
			err(1, "cannot start cleaner");
	}
#endif

	rv = p2k_mainloop(p2m);
	if (rv == -1)
		err(1, "fs service");

	return 0;
}
コード例 #5
0
int
main(int argc, char *argv[])
{
	int c, tout, flags, flush, restore;
	const char *spath, **blsock;
	size_t nblsock, maxblsock;

	setprogname(argv[0]);

	spath = NULL;
	blsock = NULL;
	maxblsock = nblsock = 0;
	flush = 0;
	restore = 0;
	tout = 0;
	flags = O_RDWR|O_EXCL|O_CLOEXEC;
	while ((c = getopt(argc, argv, "C:c:D:dfP:rR:s:t:v")) != -1) {
		switch (c) {
		case 'C':
			controlprog = optarg;
			break;
		case 'c':
			configfile = optarg;
			break;
		case 'D':
			dbfile = optarg;
			break;
		case 'd':
			debug++;
			break;
		case 'f':
			flush++;
			break;
		case 'P':
			spath = optarg;
			break;
		case 'R':
			rulename = optarg;
			break;
		case 'r':
			restore++;
			break;
		case 's':
			if (nblsock >= maxblsock) {
				maxblsock += 10;
				void *p = realloc(blsock,
				    sizeof(*blsock) * maxblsock);
				if (p == NULL)
				    err(EXIT_FAILURE,
					"Can't allocate memory for %zu sockets",
					maxblsock);
				blsock = p;
			}
			blsock[nblsock++] = optarg;
			break;
		case 't':
			tout = atoi(optarg) * 1000;
			break;
		case 'v':
			vflag++;
			break;
		default:
			usage(c);
		}
	}

	argc -= optind;
	if (argc)
		usage(0);

	signal(SIGHUP, sighup);
	signal(SIGINT, sigdone);
	signal(SIGQUIT, sigdone);
	signal(SIGTERM, sigdone);
	signal(SIGUSR1, sigusr1);
	signal(SIGUSR2, sigusr2);

	openlog(getprogname(), LOG_PID, LOG_DAEMON);

	if (debug) {
		lfun = dlog;
		if (tout == 0)
			tout = 5000;
	} else {
		if (tout == 0)
			tout = 15000;
	}

	update_interfaces();
	conf_parse(configfile);
	if (flush) {
		rules_flush();
		flags |= O_TRUNC;
	}

	struct pollfd *pfd = NULL;
	bl_t *bl = NULL;
	size_t nfd = 0;
	size_t maxfd = 0;

	for (size_t i = 0; i < nblsock; i++)
		addfd(&pfd, &bl, &nfd, &maxfd, blsock[i]);
	free(blsock);

	if (spath) {
		FILE *fp = fopen(spath, "r");
		char *line;
		if (fp == NULL)
			err(EXIT_FAILURE, "Can't open `%s'", spath);
		for (; (line = fparseln(fp, NULL, NULL, NULL, 0)) != NULL;
		    free(line))
			addfd(&pfd, &bl, &nfd, &maxfd, line);
		fclose(fp);
	}
	if (nfd == 0)
		addfd(&pfd, &bl, &nfd, &maxfd, _PATH_BLSOCK);

	state = state_open(dbfile, flags, 0600);
	if (state == NULL)
		state = state_open(dbfile,  flags | O_CREAT, 0600);
	if (state == NULL)
		return EXIT_FAILURE;

	if (restore)
		rules_restore();

	if (!debug) {
		if (daemon(0, 0) == -1)
			err(EXIT_FAILURE, "daemon failed");
		if (pidfile(NULL) == -1)
			err(EXIT_FAILURE, "Can't create pidfile");
	}

	for (size_t t = 0; !done; t++) {
		if (readconf) {
			readconf = 0;
			conf_parse(configfile);
		}
		switch (poll(pfd, (nfds_t)nfd, tout)) {
		case -1:
			if (errno == EINTR)
				continue;
			(*lfun)(LOG_ERR, "poll (%m)");
			return EXIT_FAILURE;
		case 0:
			state_sync(state);
			break;
		default:
			for (size_t i = 0; i < nfd; i++)
				if (pfd[i].revents & POLLIN)
					process(bl[i]);
		}
		if (t % 100 == 0)
			state_sync(state);
		if (t % 10000 == 0)
			update_interfaces();
		update();
	}
	state_close(state);
	return 0;
}
コード例 #6
0
ファイル: kverify.c プロジェクト: 2asoft/freebsd
int
main(int argc, char **argv)
{
    krb5_context context;
    krb5_error_code ret;
    krb5_creds cred;
    krb5_preauthtype pre_auth_types[] = {KRB5_PADATA_ENC_TIMESTAMP};
    krb5_get_init_creds_opt *get_options;
    krb5_verify_init_creds_opt verify_options;
    krb5_principal principal = NULL;
    int optidx = 0;

    setprogname (argv[0]);

    if(getarg(args, sizeof(args) / sizeof(args[0]), argc, argv, &optidx))
	usage(1);

    if (help_flag)
	usage (0);

    if(version_flag) {
	print_version(NULL);
	exit(0);
    }

    argc -= optidx;
    argv += optidx;

    ret = krb5_init_context(&context);
    if (ret)
	errx (1, "krb5_init_context failed: %d", ret);

    ret = krb5_get_init_creds_opt_alloc (context, &get_options);
    if (ret)
	krb5_err(context, 1, ret, "krb5_get_init_creds_opt_alloc");

    krb5_get_init_creds_opt_set_preauth_list (get_options,
					      pre_auth_types,
					      1);

    krb5_verify_init_creds_opt_init (&verify_options);

    if (argc) {
	ret = krb5_parse_name(context, argv[0], &principal);
	if (ret)
	    krb5_err(context, 1, ret, "krb5_parse_name: %s", argv[0]);
    } else {
	ret = krb5_get_default_principal(context, &principal);
	if (ret)
	    krb5_err(context, 1, ret, "krb5_get_default_principal");

    }

    ret = krb5_get_init_creds_password (context,
					&cred,
					principal,
					NULL,
					krb5_prompter_posix,
					NULL,
					0,
					NULL,
					get_options);
    if (ret)
	krb5_err(context, 1, ret,  "krb5_get_init_creds");

    ret = krb5_verify_init_creds (context,
				  &cred,
				  NULL,
				  NULL,
				  NULL,
				  &verify_options);
    if (ret)
	krb5_err(context, 1, ret, "krb5_verify_init_creds");
    krb5_free_cred_contents (context, &cred);
    krb5_free_context (context);
    return 0;
}
コード例 #7
0
int
main(int argc, char **argv)
{
	int	ch, status;
	unsigned int	i;
	int	cflag, Cflag, Dflag, Uflag, wflag;
	char	*dir, *p;
	FILE	*spec1, *spec2;

	setprogname(argv[0]);

	cflag = Cflag = Dflag = Uflag = wflag = 0;
	dir = NULL;
	init_excludes();
	spec1 = stdin;
	spec2 = NULL;

	while ((ch = getopt(argc, argv,
	    "bcCdDeE:f:F:I:ijk:K:lLmMnN:O:p:PqrR:s:StuUwWxX:"))
	    != -1) {
		switch((char)ch) {
		case 'b':
			bflag = 1;
			break;
		case 'c':
			cflag = 1;
			break;
		case 'C':
			Cflag = 1;
			break;
		case 'd':
			dflag = 1;
			break;
		case 'D':
			Dflag = 1;
			break;
		case 'E':
			parsetags(&excludetags, optarg);
			break;
		case 'e':
			eflag = 1;
			break;
		case 'f':
			if (spec1 == stdin) {
				spec1 = fopen(optarg, "r");
				if (spec1 == NULL)
					mtree_err("%s: %s", optarg,
					    strerror(errno));
			} else if (spec2 == NULL) {
				spec2 = fopen(optarg, "r");
				if (spec2 == NULL)
					mtree_err("%s: %s", optarg,
					    strerror(errno));
			} else
				usage();
			break;
		case 'F':
			for (i = 0; i < __arraycount(flavors); i++)
				if (strcmp(optarg, flavors[i].name) == 0) {
					flavor = flavors[i].flavor;
					break;
				}
			if (i == __arraycount(flavors))
				usage();
			break;
		case 'i':
			iflag = 1;
			break;
		case 'I':
			parsetags(&includetags, optarg);
			break;
		case 'j':
			jflag = 1;
			break;
		case 'k':
			keys = F_TYPE;
			while ((p = strsep(&optarg, " \t,")) != NULL)
				if (*p != '\0')
					keys |= parsekey(p, NULL);
			break;
		case 'K':
			while ((p = strsep(&optarg, " \t,")) != NULL)
				if (*p != '\0')
					keys |= parsekey(p, NULL);
			break;
		case 'l':
			lflag = 1;
			break;
		case 'L':
			ftsoptions &= ~FTS_PHYSICAL;
			ftsoptions |= FTS_LOGICAL;
			break;
		case 'm':
			mflag = 1;
			break;
		case 'M':
			mtree_Mflag = 1;
			break;
		case 'n':
			nflag = 1;
			break;
		case 'N':
			if (! setup_getid(optarg))
				mtree_err(
			    "Unable to use user and group databases in `%s'",
				    optarg);
			break;
		case 'O':
			load_only(optarg);
			break;
		case 'p':
			dir = optarg;
			break;
		case 'P':
			ftsoptions &= ~FTS_LOGICAL;
			ftsoptions |= FTS_PHYSICAL;
			break;
		case 'q':
			qflag = 1;
			break;
		case 'r':
			rflag++;
			break;
		case 'R':
			while ((p = strsep(&optarg, " \t,")) != NULL)
				if (*p != '\0')
					keys &= ~parsekey(p, NULL);
			break;
		case 's':
			sflag = 1;
			crc_total = ~strtol(optarg, &p, 0);
			if (*p)
				mtree_err("illegal seed value -- %s", optarg);
			break;
		case 'S':
			mtree_Sflag = 1;
			break;
		case 't':
			tflag = 1;
			break;
		case 'u':
			uflag = 1;
			break;
		case 'U':
			Uflag = uflag = 1;
			break;
		case 'w':
			wflag = 1;
			break;
		case 'W':
			mtree_Wflag = 1;
			break;
		case 'x':
			ftsoptions |= FTS_XDEV;
			break;
		case 'X':
			read_excludes_file(optarg);
			break;
		case '?':
		default:
			usage();
		}
	}
	argc -= optind;
	argv += optind;

	if (argc)
		usage();

	switch (flavor) {
	case F_FREEBSD9:
		if (cflag && iflag) {
			warnx("-c and -i passed, replacing -i with -j for "
			    "FreeBSD compatibility");
			iflag = 0;
			jflag = 1;
		}
		if (dflag && !bflag) {
			warnx("Adding -b to -d for FreeBSD compatibility");
			bflag = 1;
		}
		if (uflag && !iflag) {
			warnx("Adding -i to -%c for FreeBSD compatibility",
			    Uflag ? 'U' : 'u');
			iflag = 1;
		}
		if (uflag && !tflag) {
			warnx("Adding -t to -%c for FreeBSD compatibility",
			    Uflag ? 'U' : 'u');
			tflag = 1;
		}
		if (wflag)
			warnx("The -w flag is a no-op");
		break;
	default:
		if (wflag)
			usage();
	}

	if (spec2 && (cflag || Cflag || Dflag))
		mtree_err("Double -f, -c, -C and -D flags are mutually "
		    "exclusive");

	if (dir && spec2)
		mtree_err("Double -f and -p flags are mutually exclusive");

	if (dir && chdir(dir))
		mtree_err("%s: %s", dir, strerror(errno));

	if ((cflag || sflag) && !getcwd(fullpath, sizeof(fullpath)))
		mtree_err("%s", strerror(errno));

	if ((cflag && Cflag) || (cflag && Dflag) || (Cflag && Dflag))
		mtree_err("-c, -C and -D flags are mutually exclusive");

	if (iflag && mflag)
		mtree_err("-i and -m flags are mutually exclusive");

	if (lflag && uflag)
		mtree_err("-l and -u flags are mutually exclusive");

	if (cflag) {
		cwalk(stdout);
		exit(0);
	}
	if (Cflag || Dflag) {
		dump_nodes(stdout, "", spec(spec1), Dflag);
		exit(0);
	}
	if (spec2 != NULL)
		status = mtree_specspec(spec1, spec2);
	else
		status = verify(spec1);
	if (Uflag && (status == MISMATCHEXIT))
		status = 0;
	exit(status);
}
コード例 #8
0
ファイル: ipropd_slave.c プロジェクト: Henauxg/minix
int
main(int argc, char **argv)
{
    krb5_error_code ret;
    krb5_context context;
    krb5_auth_context auth_context;
    void *kadm_handle;
    kadm5_server_context *server_context;
    kadm5_config_params conf;
    int master_fd;
    krb5_ccache ccache;
    krb5_principal server;
    char **files;
    int optidx = 0;
    time_t reconnect_min;
    time_t backoff;
    time_t reconnect_max;
    time_t reconnect;
    time_t before = 0;

    const char *master;

    setprogname(argv[0]);

    if(getarg(args, num_args, argc, argv, &optidx))
	usage(1);

    if(help_flag)
	usage(0);
    if(version_flag) {
	print_version(NULL);
	exit(0);
    }

    ret = krb5_init_context(&context);
    if (ret)
	errx (1, "krb5_init_context failed: %d", ret);

    setup_signal();

    if (config_file == NULL) {
	if (asprintf(&config_file, "%s/kdc.conf", hdb_db_dir(context)) == -1
	    || config_file == NULL)
	    errx(1, "out of memory");
    }

    ret = krb5_prepend_config_files_default(config_file, &files);
    if (ret)
	krb5_err(context, 1, ret, "getting configuration files");

    ret = krb5_set_config_files(context, files);
    krb5_free_config_files(files);
    if (ret)
	krb5_err(context, 1, ret, "reading configuration files");

    argc -= optidx;
    argv += optidx;

    if (argc != 1)
	usage(1);

    master = argv[0];

#ifdef SUPPORT_DETACH
    if (detach_from_console)
	daemon(0, 0);
#endif
    pidfile (NULL);
    krb5_openlog (context, "ipropd-slave", &log_facility);
    krb5_set_warn_dest(context, log_facility);

    ret = krb5_kt_register(context, &hdb_kt_ops);
    if(ret)
	krb5_err(context, 1, ret, "krb5_kt_register");

    time_before_lost = parse_time (server_time_lost,  "s");
    if (time_before_lost < 0)
	krb5_errx (context, 1, "couldn't parse time: %s", server_time_lost);

    memset(&conf, 0, sizeof(conf));
    if(realm) {
	conf.mask |= KADM5_CONFIG_REALM;
	conf.realm = realm;
    }
    ret = kadm5_init_with_password_ctx (context,
					KADM5_ADMIN_SERVICE,
					NULL,
					KADM5_ADMIN_SERVICE,
					&conf, 0, 0,
					&kadm_handle);
    if (ret)
	krb5_err (context, 1, ret, "kadm5_init_with_password_ctx");

    server_context = (kadm5_server_context *)kadm_handle;

    ret = kadm5_log_init (server_context);
    if (ret)
	krb5_err (context, 1, ret, "kadm5_log_init");

    get_creds(context, keytab_str, &ccache, master);

    ret = krb5_sname_to_principal (context, master, IPROP_NAME,
				   KRB5_NT_SRV_HST, &server);
    if (ret)
	krb5_err (context, 1, ret, "krb5_sname_to_principal");

    auth_context = NULL;
    master_fd = -1;

    krb5_appdefault_time(context, config_name, NULL, "reconnect-min",
			 10, &reconnect_min);
    krb5_appdefault_time(context, config_name, NULL, "reconnect-max",
			 300, &reconnect_max);
    krb5_appdefault_time(context, config_name, NULL, "reconnect-backoff",
			 10, &backoff);
    reconnect = reconnect_min;

    while (!exit_flag) {
	time_t now, elapsed;
	int connected = FALSE;

	now = time(NULL);
	elapsed = now - before;

	if (elapsed < reconnect) {
	    time_t left = reconnect - elapsed;
	    krb5_warnx(context, "sleeping %d seconds before "
		       "retrying to connect", (int)left);
	    sleep(left);
	}
	before = now;

	master_fd = connect_to_master (context, master, port_str);
	if (master_fd < 0)
	    goto retry;

	reconnect = reconnect_min;

	if (auth_context) {
	    krb5_auth_con_free(context, auth_context);
	    auth_context = NULL;
	    krb5_cc_destroy(context, ccache);
	    get_creds(context, keytab_str, &ccache, master);
	}
	ret = krb5_sendauth (context, &auth_context, &master_fd,
			     IPROP_VERSION, NULL, server,
			     AP_OPTS_MUTUAL_REQUIRED, NULL, NULL,
			     ccache, NULL, NULL, NULL);
	if (ret) {
	    krb5_warn (context, ret, "krb5_sendauth");
	    goto retry;
	}

	krb5_warnx(context, "ipropd-slave started at version: %ld",
		   (long)server_context->log_context.version);

	ret = ihave (context, auth_context, master_fd,
		     server_context->log_context.version);
	if (ret)
	    goto retry;

	connected = TRUE;

	while (connected && !exit_flag) {
	    krb5_data out;
	    krb5_storage *sp;
	    int32_t tmp;
	    fd_set readset;
	    struct timeval to;

#ifndef NO_LIMIT_FD_SETSIZE
	    if (master_fd >= FD_SETSIZE)
		krb5_errx (context, 1, "fd too large");
#endif

	    FD_ZERO(&readset);
	    FD_SET(master_fd, &readset);

	    to.tv_sec = time_before_lost;
	    to.tv_usec = 0;

	    ret = select (master_fd + 1,
			  &readset, NULL, NULL, &to);
	    if (ret < 0) {
		if (errno == EINTR)
		    continue;
		else
		    krb5_err (context, 1, errno, "select");
	    }
	    if (ret == 0)
		krb5_errx (context, 1, "server didn't send a message "
			   "in %d seconds", time_before_lost);

	    ret = krb5_read_priv_message(context, auth_context, &master_fd, &out);
	    if (ret) {
		krb5_warn (context, ret, "krb5_read_priv_message");
		connected = FALSE;
		continue;
	    }

	    sp = krb5_storage_from_mem (out.data, out.length);
	    krb5_ret_int32 (sp, &tmp);
	    switch (tmp) {
	    case FOR_YOU :
		receive (context, sp, server_context);
		ret = ihave (context, auth_context, master_fd,
			     server_context->log_context.version);
		if (ret)
		    connected = FALSE;
		break;
	    case TELL_YOU_EVERYTHING :
		ret = receive_everything (context, master_fd, server_context,
					  auth_context);
		if (ret)
		    connected = FALSE;
		break;
	    case ARE_YOU_THERE :
		send_im_here (context, master_fd, auth_context);
		break;
	    case NOW_YOU_HAVE :
	    case I_HAVE :
	    case ONE_PRINC :
	    case I_AM_HERE :
	    default :
		krb5_warnx (context, "Ignoring command %d", tmp);
		break;
	    }
	    krb5_storage_free (sp);
	    krb5_data_free (&out);

	}
    retry:
	if (connected == FALSE)
	    krb5_warnx (context, "disconnected for server");
	if (exit_flag)
	    krb5_warnx (context, "got an exit signal");

	if (master_fd >= 0)
	    close(master_fd);

	reconnect += backoff;
	if (reconnect > reconnect_max)
	    reconnect = reconnect_max;
    }

    if (0);
#ifndef NO_SIGXCPU
    else if(exit_flag == SIGXCPU)
	krb5_warnx(context, "%s CPU time limit exceeded", getprogname());
#endif
    else if(exit_flag == SIGINT || exit_flag == SIGTERM)
	krb5_warnx(context, "%s terminated", getprogname());
    else
	krb5_warnx(context, "%s unexpected exit reason: %ld",
		       getprogname(), (long)exit_flag);

    return 0;
}
コード例 #9
0
ファイル: hpropd.c プロジェクト: tombibsd/netbsd-src
int
main(int argc, char **argv)
{
    krb5_error_code ret;
    krb5_context context;
    krb5_auth_context ac = NULL;
    krb5_principal c1, c2;
    krb5_authenticator authent;
    krb5_keytab keytab;
    krb5_socket_t sock = rk_INVALID_SOCKET;
    HDB *db = NULL;
    int optidx = 0;
    char *tmp_db;
    krb5_log_facility *fac;
    int nprincs;

    setprogname(argv[0]);

    ret = krb5_init_context(&context);
    if(ret)
	exit(1);

    ret = krb5_openlog(context, "hpropd", &fac);
    if(ret)
	errx(1, "krb5_openlog");
    krb5_set_warn_dest(context, fac);

    if(getarg(args, num_args, argc, argv, &optidx))
	usage(1);

    if(local_realm != NULL)
	krb5_set_default_realm(context, local_realm);

    if(help_flag)
	usage(0);
    if(version_flag) {
	print_version(NULL);
	exit(0);
    }

    argc -= optidx;
    argv += optidx;

    if (argc != 0)
	usage(1);

    if (database == NULL)
	database = hdb_default_db(context);

    if(from_stdin) {
	sock = STDIN_FILENO;
    } else {
	struct sockaddr_storage ss;
	struct sockaddr *sa = (struct sockaddr *)&ss;
	socklen_t sin_len = sizeof(ss);
	char addr_name[256];
	krb5_ticket *ticket;
	char *server;

	sock = STDIN_FILENO;
#ifdef SUPPORT_INETD
	if (inetd_flag == -1) {
	    if (getpeername (sock, sa, &sin_len) < 0) {
		inetd_flag = 0;
	    } else {
		inetd_flag = 1;
	    }
	}
#else
	inetd_flag = 0;
#endif
	if (!inetd_flag) {
	    mini_inetd (krb5_getportbyname (context, "hprop", "tcp",
					    HPROP_PORT), &sock);
	}
	sin_len = sizeof(ss);
	if(getpeername(sock, sa, &sin_len) < 0)
	    krb5_err(context, 1, errno, "getpeername");

	if (inet_ntop(sa->sa_family,
		      socket_get_address (sa),
		      addr_name,
		      sizeof(addr_name)) == NULL)
	    strlcpy (addr_name, "unknown address",
		     sizeof(addr_name));

	krb5_log(context, fac, 0, "Connection from %s", addr_name);

	ret = krb5_kt_register(context, &hdb_kt_ops);
	if(ret)
	    krb5_err(context, 1, ret, "krb5_kt_register");

	if (ktname != NULL) {
	    ret = krb5_kt_resolve(context, ktname, &keytab);
	    if (ret)
		krb5_err (context, 1, ret, "krb5_kt_resolve %s", ktname);
	} else {
	    ret = krb5_kt_default (context, &keytab);
	    if (ret)
		krb5_err (context, 1, ret, "krb5_kt_default");
	}

	ret = krb5_recvauth(context, &ac, &sock, HPROP_VERSION, NULL,
			    0, keytab, &ticket);
	if(ret)
	    krb5_err(context, 1, ret, "krb5_recvauth");

	ret = krb5_unparse_name(context, ticket->server, &server);
	if (ret)
	    krb5_err(context, 1, ret, "krb5_unparse_name");
	if (strncmp(server, "hprop/", 5) != 0)
	    krb5_errx(context, 1, "ticket not for hprop (%s)", server);

	free(server);
	krb5_free_ticket (context, ticket);

	ret = krb5_auth_con_getauthenticator(context, ac, &authent);
	if(ret)
	    krb5_err(context, 1, ret, "krb5_auth_con_getauthenticator");

	ret = krb5_make_principal(context, &c1, NULL, "kadmin", "hprop", NULL);
	if(ret)
	    krb5_err(context, 1, ret, "krb5_make_principal");
	_krb5_principalname2krb5_principal(context, &c2,
					   authent->cname, authent->crealm);
	if(!krb5_principal_compare(context, c1, c2)) {
	    char *s;
	    ret = krb5_unparse_name(context, c2, &s);
	    if (ret)
		s = unparseable_name;
	    krb5_errx(context, 1, "Unauthorized connection from %s", s);
	}
	krb5_free_principal(context, c1);
	krb5_free_principal(context, c2);

	ret = krb5_kt_close(context, keytab);
	if(ret)
	    krb5_err(context, 1, ret, "krb5_kt_close");
    }

    if(!print_dump) {
	asprintf(&tmp_db, "%s~", database);

	ret = hdb_create(context, &db, tmp_db);
	if(ret)
	    krb5_err(context, 1, ret, "hdb_create(%s)", tmp_db);
	ret = db->hdb_open(context, db, O_RDWR | O_CREAT | O_TRUNC, 0600);
	if(ret)
	    krb5_err(context, 1, ret, "hdb_open(%s)", tmp_db);
    }

    nprincs = 0;
    while(1){
	krb5_data data;
	hdb_entry_ex entry;

	if(from_stdin) {
	    ret = krb5_read_message(context, &sock, &data);
	    if(ret != 0 && ret != HEIM_ERR_EOF)
		krb5_err(context, 1, ret, "krb5_read_message");
	} else {
	    ret = krb5_read_priv_message(context, ac, &sock, &data);
	    if(ret)
		krb5_err(context, 1, ret, "krb5_read_priv_message");
	}

	if(ret == HEIM_ERR_EOF || data.length == 0) {
	    if(!from_stdin) {
		data.data = NULL;
		data.length = 0;
		krb5_write_priv_message(context, ac, &sock, &data);
	    }
	    if(!print_dump) {
		ret = db->hdb_close(context, db);
		if(ret)
		    krb5_err(context, 1, ret, "db_close");
		ret = db->hdb_rename(context, db, database);
		if(ret)
		    krb5_err(context, 1, ret, "db_rename");
	    }
	    break;
	}
	memset(&entry, 0, sizeof(entry));
	ret = hdb_value2entry(context, &data, &entry.entry);
	krb5_data_free(&data);
	if(ret)
	    krb5_err(context, 1, ret, "hdb_value2entry");
	if(print_dump)
	    hdb_print_entry(context, db, &entry, stdout);
	else {
	    ret = db->hdb_store(context, db, 0, &entry);
	    if(ret == HDB_ERR_EXISTS) {
		char *s;
		ret = krb5_unparse_name(context, entry.entry.principal, &s);
		if (ret)
		    s = strdup(unparseable_name);
		krb5_warnx(context, "Entry exists: %s", s);
		free(s);
	    } else if(ret)
		krb5_err(context, 1, ret, "db_store");
	    else
		nprincs++;
	}
	hdb_free_entry(context, &entry);
    }
    if (!print_dump)
	krb5_log(context, fac, 0, "Received %d principals", nprincs);

    if (inetd_flag == 0)
	rk_closesocket(sock);

    exit(0);
}
コード例 #10
0
ファイル: mkdep.c プロジェクト: AgamAgarwal/minix
int
main(int argc, char **argv)
{
	int 	aflag, dflag, oflag, qflag;
	const char *filename;
	int	dependfile;
	char	*buf, *lim, *ptr, *line, *suf, *colon, *eol;
	int	ok_ind, ch;
	size_t	sz;
	int	fd;
	size_t  slen;
	const char *fname;
	const char *suffixes = NULL, *s;
	suff_list_t *suff_list = NULL, *sl;
#ifdef __minix
	size_t nr;
#endif

	suf = NULL;		/* XXXGCC -Wuninitialized [sun2] */
	sl = NULL;		/* XXXGCC -Wuninitialized [sun2] */

	setlocale(LC_ALL, "");
	setprogname(argv[0]);

	aflag = O_WRONLY | O_APPEND | O_CREAT | O_TRUNC;
	dflag = 0;
	oflag = 0;
	qflag = 0;
	filename = DEFAULT_FILENAME;
	dependfile = -1;

	opterr = 0;	/* stop getopt() bleating about errors. */
	for (;;) {
		ok_ind = optind;
		ch = getopt(argc, argv, "aDdf:opqs:");
		switch (ch) {
		case -1:
			ok_ind = optind;
			break;
		case 'a':	/* Append to output file */
			aflag &= ~O_TRUNC;
			continue;
		case 'D':	/* Process *.d files (don't run cc -M) */
			dflag = 2;	/* Read names from stdin */
			opterr = 1;
			continue;
		case 'd':	/* Process *.d files (don't run cc -M) */
			dflag = 1;
			opterr = 1;
			continue;
		case 'f':	/* Name of output file */
			filename = optarg;
			continue;
		case 'o':	/* Mark dependant files .OPTIONAL */
			oflag = 1;
			continue;
		case 'p':	/* Program mode (x.o: -> x:) */
			suffixes = "";
			continue;
		case 'q':	/* Quiet */
			qflag = 1;
			continue;
		case 's':	/* Suffix list */
			suffixes = optarg;
			continue;
		default:
			if (dflag)
				usage();
			/* Unknown arguments are passed to "${CC} -M" */
			break;
		}
		break;
	}

	argc -= ok_ind;
	argv += ok_ind;
	if ((argc == 0 && !dflag) || (argc != 0 && dflag == 2))
		usage();

	if (suffixes != NULL) {
		/* parse list once and save names and lengths */
		/* allocate an extra entry to mark end of list */
		for (sz = 1, s = suffixes; *s != 0; s++)
			if (*s == '.')
			    sz++;
		suff_list = calloc(sz, sizeof *suff_list);
		if (suff_list == NULL)
			err(2, "malloc");
		sl = suff_list;
		for (s = suffixes; (s = strchr(s, '.')); s += sz, sl++) {
			sz = strcspn(s, ", ");
			if (sz > sizeof sl->suff)
				errx(2, "suffix too long");
			sl->len = sz;
			memcpy(sl->suff, s, sz);
		}
	}

	dependfile = open(filename, aflag, 0666);
	if (dependfile == -1)
		err(EXIT_FAILURE, "unable to %s to file %s\n",
		    aflag & O_TRUNC ? "write" : "append", filename);

	while (dflag == 2 || *argv != NULL) {
		if (dflag) {
			if (dflag == 2) {
				fname = read_fname();
				if (fname == NULL)
					break;
			} else
				fname = *argv++;
			fd = open(fname, O_RDONLY, 0);
			if (fd == -1) {
				if (!qflag)
					warn("ignoring %s", fname);
				continue;
			}
		} else {
			fd = run_cc(argc, argv, &fname);
			/* consume all args... */
			argv += argc;
		}

		sz = lseek(fd, 0, SEEK_END);
		if (sz == 0) {
			close(fd);
			continue;
		}
#ifndef __minix
		buf = mmap(NULL, sz, PROT_READ|PROT_WRITE, MAP_PRIVATE, fd, 0);
		close(fd);

		if (buf == MAP_FAILED)
			err(EXIT_FAILURE, "unable to mmap file %s", fname);
#else
		buf = malloc(sz);
		if (buf == NULL)
			err(EXIT_FAILURE, "malloc");
		if ((nr = pread(fd, buf, sz, 0)) != sz)
			err(EXIT_FAILURE, "read error %s", fname);
		close(fd);		
#endif
		lim = buf + sz - 1;

		/* Remove leading "./" from filenames */
		for (ptr = buf; ptr < lim; ptr++) {
			if (ptr[1] != '.' || ptr[2] != '/'
			    || !isspace((unsigned char)ptr[0]))
				continue;
			ptr[1] = ' ';
			ptr[2] = ' ';
		}

		for (line = eol = buf; eol <= lim;) {
			while (eol <= lim && *eol++ != '\n')
				/* Find end of this line */
				continue;
			if (line == eol - 1) {
				/* empty line - ignore */
				line = eol;
				continue;
			}
			if (eol[-2] == '\\')
				/* Assemble continuation lines */
				continue;
			for (colon = line; *colon != ':'; colon++) {
				if (colon >= eol) {
					colon = NULL;
					break;
				}
			}
			if (isspace((unsigned char)*line) || colon == NULL) {
				/* No dependency - just transcribe line */
				write(dependfile, line, eol - line);
				line = eol;
				continue;
			}
			if (suff_list != NULL) {
				/* Find the .o: */
				/* First allow for any whitespace */
				for (suf = colon; suf > buf; suf--) {
					if (!isspace((unsigned char)suf[-1]))
						break;
				}
				if (suf == buf)
					errx(EXIT_FAILURE,
					    "Corrupted file `%s'", fname);
				/* Then look for any valid suffix */
				for (sl = suff_list; sl->len != 0; sl++) {
					if (!memcmp(suf - sl->len, sl->suff,
						    sl->len))
						break;
				}
				/*
				 * Not found, check for .o, since the
				 * original file will have it.
				 */
				if (sl->len == 0 && suff_list->len != 0) {
					if (memcmp(suf - 2, ".o", 2) == 0)
						slen = 2;
					else
						slen = 0;
				} else
					slen = sl->len;
			}
			if (suff_list != NULL && slen != 0) {
				suf -= slen;
				for (sl = suff_list; sl->len != 0; sl++) {
					if (sl != suff_list)
						write(dependfile, " ", 1);
					write(dependfile, line, suf - line);
					write(dependfile, sl->suff, sl->len);
				}
				write(dependfile, colon, eol - colon);
			} else
				write(dependfile, line, eol - line);

			if (oflag)
				save_for_optional(colon + 1, eol);
			line = eol;
		}
#ifndef __minix
		munmap(buf, sz);
#else
		free(buf);
#endif
	}

	if (oflag && opt != NULL) {
		write(dependfile, ".OPTIONAL:", 10);
		width = 9;
		sz = write_optional(dependfile, opt, 0);
		/* 'depth' is about 39 for an i386 kernel */
		/* fprintf(stderr, "Recursion depth %d\n", sz); */
	}
	close(dependfile);

	exit(EXIT_SUCCESS);
}
コード例 #11
0
ファイル: hprop.c プロジェクト: alexzhang2015/osx-10.9
int
main(int argc, char **argv)
{
    krb5_error_code ret;
    krb5_context context;
    krb5_ccache ccache = NULL;
    HDB *db = NULL;
    int optidx = 0;

    int type, exit_code;

    setprogname(argv[0]);

    if(getarg(args, num_args, argc, argv, &optidx))
	usage(1);

    if(help_flag)
	usage(0);

    if(version_flag){
	print_version(NULL);
	exit(0);
    }

    ret = krb5_init_context(&context);
    if(ret)
	exit(1);

    /* We may be reading an old database encrypted with a DES master key. */
    ret = krb5_allow_weak_crypto(context, 1);
    if(ret)
        krb5_err(context, 1, ret, "krb5_allow_weak_crypto");

    if(local_realm)
	krb5_set_default_realm(context, local_realm);

    if(encrypt_flag && decrypt_flag)
	krb5_errx(context, 1,
		  "only one of `--encrypt' and `--decrypt' is meaningful");

    if(source_type != NULL) {
	type = parse_source_type(source_type);
	if(type == 0)
	    krb5_errx(context, 1, "unknown source type `%s'", source_type);
    } else
	type = HPROP_HEIMDAL;

    if(!to_stdout)
	get_creds(context, &ccache);

    if(decrypt_flag || encrypt_flag) {
	ret = hdb_read_master_key(context, mkeyfile, &mkey5);
	if(ret && ret != ENOENT)
	    krb5_err(context, 1, ret, "hdb_read_master_key");
	if(ret)
	    krb5_errx(context, 1, "No master key file found");
    }

    switch(type) {
    case HPROP_MIT_DUMP:
	if (database == NULL)
	    krb5_errx(context, 1, "no dump file specified");
	break;
    case HPROP_HEIMDAL:
	ret = hdb_create (context, &db, database);
	if(ret)
	    krb5_err(context, 1, ret, "hdb_create: %s", database);
	ret = db->hdb_open(context, db, O_RDONLY, 0);
	if(ret)
	    krb5_err(context, 1, ret, "db->hdb_open");
	break;
    default:
	krb5_errx(context, 1, "unknown dump type `%d'", type);
	break;
    }

    if (to_stdout)
	exit_code = dump_database (context, type, database, db);
    else
	exit_code = propagate_database (context, type, database,
					db, ccache, optidx, argc, argv);

    if(ccache != NULL)
	krb5_cc_destroy(context, ccache);

    if(db != NULL)
	(*db->hdb_destroy)(context, db);

    krb5_free_context(context);
    return exit_code;
}
コード例 #12
0
ファイル: lpr.c プロジェクト: ryo/netbsd-src
int
main(int argc, char *argv[])
{
	struct passwd *pw;
	struct group *gptr;
	char *arg;
	const char *cp;
	char buf[MAXPATHLEN];
	int i, f, errs, c;
	struct stat stb;
	int oerrno;

	euid = geteuid();
	uid = getuid();
	seteuid(uid);

	if (signal(SIGHUP, SIG_IGN) != SIG_IGN)
		signal(SIGHUP, cleanup);
	if (signal(SIGINT, SIG_IGN) != SIG_IGN)
		signal(SIGINT, cleanup);
	if (signal(SIGQUIT, SIG_IGN) != SIG_IGN)
		signal(SIGQUIT, cleanup);
	if (signal(SIGTERM, SIG_IGN) != SIG_IGN)
		signal(SIGTERM, cleanup);

	setprogname(*argv);
	gethostname(host, sizeof (host));
	host[sizeof(host) - 1] = '\0';
	openlog("lpd", 0, LOG_LPR);

	errs = 0;
	while ((c = getopt(argc, argv,
	    ":#:1:2:3:4:C:J:P:RT:U:cdfghi:lmnopqrstvw:")) != -1) {
		switch (c) {

		case '#':		/* n copies */
			if (isdigit((unsigned char)*optarg)) {
				i = atoi(optarg);
				if (i > 0)
					ncopies = i;
			}
			break;

		case '4':		/* troff fonts */
		case '3':
		case '2':
		case '1':
			fonts[optopt - '1'] = optarg;
			break;

		case 'C':		/* classification spec */
			hdr++;
			class = optarg;
			break;

		case 'J':		/* job name */
			hdr++;
			jobname = optarg;
			break;

		case 'P':		/* specifiy printer name */
			printer = optarg;
			break;

		case 'R':		/* print request id */
			Rflag++;
			break;
			
		case 'T':		/* pr's title line */
			title = optarg;
			break;

		case 'U':		/* user name */
			hdr++;
			person = optarg;
			break;

		case 'c':		/* print cifplot output */
		case 'd':		/* print tex output (dvi files) */
		case 'g':		/* print graph(1G) output */
		case 'l':		/* literal output */
		case 'o':		/* print postscript output */
		case 'n':		/* print ditroff output */
		case 'p':		/* print using ``pr'' */
		case 't':		/* print troff output (cat files) */
		case 'v':		/* print vplot output */
			format = optopt;
			break;

		case 'f':		/* print fortran output */
			format = 'r';
			break;

		case 'h':		/* toggle want of header page */
			hdr = !hdr;
			break;

		case 'i':		/* indent output */
			iflag++;
			indent = atoi(optarg);
			if (indent < 0)
				indent = 8;
			break;

		case 'm':		/* send mail when done */
			mailflg++;
			break;

		case 'q':		/* just q job */
			qflag++;
			break;

		case 'r':		/* remove file when done */
			rflag++;
			break;

		case 's':		/* try to link files */
			sflag++;
			break;

		case 'w':		/* versatec page width */
			width = optarg;
			break;

		case ':':               /* catch "missing argument" error */
			if (optopt == 'i') {
				iflag++; /* -i without args is valid */
				indent = 8;
			} else
				errs++;
			break;

		default:
			errs++;
		}
	}
	argc -= optind;
	argv += optind;
	if (errs)
		usage();
	if (printer == NULL && (printer = getenv("PRINTER")) == NULL)
		printer = DEFLP;
	chkprinter(printer);
	if (SC && ncopies > 1)
		errx(EXIT_FAILURE, "multiple copies are not allowed");
	if (MC > 0 && ncopies > MC)
		errx(EXIT_FAILURE, "only %ld copies are allowed", MC);
	/*
	 * Get the identity of the person doing the lpr using the same
	 * algorithm as lprm. 
	 */
	userid = getuid();
	if (userid != DU || person == 0) {
		if ((pw = getpwuid(userid)) == NULL)
			errx(EXIT_FAILURE, "Who are you?");
		person = pw->pw_name;
	}
	/*
	 * Check for restricted group access.
	 */
	if (RG != NULL && userid != DU) {
		if ((gptr = getgrnam(RG)) == NULL)
			errx(EXIT_FAILURE,
			     "Restricted group specified incorrectly");
		if (gptr->gr_gid != getgid()) {
			while (*gptr->gr_mem != NULL) {
				if ((strcmp(person, *gptr->gr_mem)) == 0)
					break;
				gptr->gr_mem++;
			}
			if (*gptr->gr_mem == NULL)
				errx(EXIT_FAILURE,
				     "Not a member of the restricted group");
		}
	}
	/*
	 * Check to make sure queuing is enabled if userid is not root.
	 */
	(void)snprintf(buf, sizeof buf, "%s/%s", SD, LO);
	if (userid && stat(buf, &stb) == 0 && (stb.st_mode & S_IXGRP))
		errx(EXIT_FAILURE, "Printer queue is disabled");
	/*
	 * Initialize the control file.
	 */
	mktemps();
	tfd = nfile(tfname);
	seteuid(euid);
	(void)fchown(tfd, DU, -1);	/* owned by daemon for protection */
	seteuid(uid);
	card('H', host);
	card('P', person);
	if (hdr && !SH) {
		if (jobname == NULL) {
			if (argc == 0)
				jobname = "stdin";
			else
				jobname = (arg = strrchr(argv[0], '/')) ?
				    arg+1 : argv[0];
		}
		card('J', jobname);
		card('C', class);
		card('L', person);
	}
	if (iflag)
		card('I', itoa(indent));
	if (mailflg)
		card('M', person);
	if (format == 't' || format == 'n' || format == 'd')
		for (i = 0; i < 4; i++)
			if (fonts[i] != NULL)
				card('1'+i, fonts[i]);
	if (width != NULL)
		card('W', width);

	/*
	 * Read the files and spool them.
	 */
	if (argc == 0)
		copy(0, " ");
	else while (argc--) {
		if (argv[0][0] == '-' && argv[0][1] == '\0') {
			/* use stdin */
			copy(0, " ");
			argv++;
			continue;
		}
		if ((f = test(arg = *argv++)) < 0)
			continue;	/* file unreasonable */

		if (sflag && (cp = linked(arg)) != NULL) {
			(void)snprintf(buf, sizeof buf,
			    "%llu %llu",
			    (unsigned long long)statb.st_dev,
			    (unsigned long long)statb.st_ino);
			card('S', buf);
			if (format == 'p')
				card('T', title ? title : arg);
			for (i = 0; i < ncopies; i++)
				card(format, &dfname[inchar-2]);
			card('U', &dfname[inchar-2]);
			if (f)
				card('U', cp);
			card('N', arg);
			dfname[inchar]++;
			nact++;
			continue;
		}
		if (sflag)
			warnx("%s: not linked, copying instead", arg);
		seteuid(uid);
		if ((i = open(arg, O_RDONLY)) < 0) {
			oerrno = errno;
			seteuid(uid);
			errno = oerrno;
			warn("cannot open %s", arg);
			continue;
		} else {
			copy(i, arg);
			(void)close(i);
			if (f && unlink(arg) < 0)
				warn("%s: not removed", arg);
		}
		seteuid(uid);
	}

	if (nact) {
		(void)close(tfd);
		tfname[inchar]--;
		/*
		 * Touch the control file to fix position in the queue.
		 */
		seteuid(euid);
		if ((tfd = open(tfname, O_RDWR)) >= 0) {
			char ch;

			if (read(tfd, &ch, 1) == 1 &&
			    lseek(tfd, (off_t)0, 0) == 0 &&
			    write(tfd, &ch, 1) != 1) {
				warn("cannot touch %s", tfname);
				tfname[inchar]++;
				cleanup(0);
			}
			(void)close(tfd);
		}
		if (link(tfname, cfname) < 0) {
			warn("cannot rename %s", cfname);
			tfname[inchar]++;
			cleanup(0);
		}
		unlink(tfname);
		seteuid(uid);
		if (Rflag)
			printf("request id is %d\n", reqid);
		if (qflag)		/* just queue things up */
			exit(0);
		if (!startdaemon(printer))
			printf("jobs queued, but cannot start daemon.\n");
		exit(0);
	}
	cleanup(0);
#ifdef __GNUC__
	return (0);
#endif
	/* NOTREACHED */
}
コード例 #13
0
ファイル: kx.c プロジェクト: alexzhang2015/osx-10.9
int
main(int argc, char **argv)
{
    int port	= 0;
    int optidx	= 0;
    int ret	= 1;
    char *host	= NULL;

    setprogname (argv[0]);

    if (getarg (args, sizeof(args) / sizeof(args[0]), argc, argv,
		&optidx))
	usage (1);

    if (help_flag)
	usage (0);

    if (version_flag) {
	print_version (NULL);
	return 0;
    }

    if (optidx != argc - 1)
	usage (1);

    host = argv[optidx];

    if (port_str) {
	struct servent *s = roken_getservbyname (port_str, "tcp");

	if (s)
	    port = s->s_port;
	else {
	    char *ptr;

	    port = strtol (port_str, &ptr, 10);
	    if (port == 0 && ptr == port_str)
		errx (1, "Bad port `%s'", port_str);
	    port = htons(port);
	}
    }

    if (user == NULL) {
	user = get_default_username ();
	if (user == NULL)
	    errx (1, "who are you?");
    }

    if (!passive_flag)
	passive_flag = check_for_passive (getenv("DISPLAY"));

#if defined(HAVE_KERNEL_ENABLE_DEBUG)
    if (krb_debug_flag)
	krb_enable_debug ();
#endif

#ifdef KRB5
    if (ret && use_v5) {
	if (port == 0)
	    port = krb5_getportbyname(NULL, "kx", "tcp", KX_PORT);
	ret = doit_v5 (host, port, user,
		       passive_flag, debug_flag, keepalive_flag, tcp_flag);
    }
#endif
    return ret;
}
コード例 #14
0
int
main(int argc, char **argv)
{
    OM_uint32 major, minor;
    gss_cred_id_t from_cred = GSS_C_NO_CREDENTIAL;
    gss_cred_id_t to_cred = GSS_C_NO_CREDENTIAL;
    gss_cred_id_t cred = GSS_C_NO_CREDENTIAL;
    char *from_env;
    char *to_env;
    int optidx = 0;

    setprogname(argv[0]);
    if (getarg(args, sizeof(args) / sizeof(args[0]), argc, argv, &optidx))
        usage(1);

    if (help_flag)
        usage (0);

    if (version_flag){
        print_version(NULL);
        exit(0);
    }

    argc -= optidx;
    argv += optidx;

    if (argc < 2)
        errx(1, "required arguments missing");
    if (argc > 2)
        errx(1, "too many arguments");

    if (asprintf(&from_env, "KRB5CCNAME=%s", argv[0]) == -1 || from_env == NULL)
        err(1, "out of memory");
    if (asprintf(&to_env, "KRB5CCNAME=%s", argv[1]) == -1 || to_env == NULL)
        err(1, "out of memory");

    putenv(from_env);
    major = gss_add_cred(&minor, GSS_C_NO_CREDENTIAL, GSS_C_NO_NAME,
                         GSS_KRB5_MECHANISM, GSS_C_INITIATE, GSS_C_INDEFINITE,
                         GSS_C_INDEFINITE, &from_cred, NULL, NULL, NULL);
    if (major != GSS_S_COMPLETE)
        gss_err(1, major, minor, GSS_KRB5_MECHANISM,
                "failed to acquire creds from %s", argv[0]);

    putenv(to_env);
    major = gss_store_cred(&minor, from_cred, GSS_C_INITIATE,
                           GSS_KRB5_MECHANISM, 1, 1, NULL, NULL);
    if (major != GSS_S_COMPLETE)
        gss_err(1, major, minor, GSS_KRB5_MECHANISM,
                "failed to store creds into %s", argv[1]);

    (void) gss_release_cred(&minor, &from_cred);
    (void) gss_release_cred(&minor, &to_cred);

    major = gss_add_cred(&minor, GSS_C_NO_CREDENTIAL, GSS_C_NO_NAME,
                         GSS_KRB5_MECHANISM, GSS_C_INITIATE, GSS_C_INDEFINITE,
                         GSS_C_INDEFINITE, &cred, NULL, NULL, NULL);
    if (major != GSS_S_COMPLETE)
        gss_err(1, major, minor, GSS_KRB5_MECHANISM,
                "failed to acquire creds from %s", argv[1]);
    (void) gss_release_cred(&minor, &cred);
    putenv("KRB5CCNAME");
    free(from_env);
    free(to_env);

    return 0;
}
コード例 #15
0
ファイル: mailwrapper.c プロジェクト: AhmadTux/DragonFlyBSD
int
main(int argc, char **argv, char **envp)
{
	FILE *config;
	char *line, *cp, *from, *to, *ap;
	const char *progname;
	size_t len, lineno = 0;
	int i;
	struct arglist al;

	/* change progname to mailwrapper so we get sensible error messages */
	progname = getprogname();
	setprogname("mailwrapper");

	if ((config = fopen(_PATH_MAILERCONF, "r")) == NULL) {
		openlog("mailwrapper", LOG_PID, LOG_MAIL);
		syslog(LOG_INFO, "can't open %s, using %s as default MTA",
		    _PATH_MAILERCONF, _PATH_DEFAULTMTA);
		closelog();
		execve(_PATH_DEFAULTMTA, argv, envp);
		err(1, "cannot exec %s", _PATH_DEFAULTMTA);
		/*NOTREACHED*/
	}

	initarg(&al);
	addarg(&al, argv[0], 0);

	for (;;) {
		if ((line = fparseln(config, &len, &lineno, NULL, 0)) == NULL) {
			if (feof(config))
				errx(1, "no mapping in %s", _PATH_MAILERCONF);
			err(1, NULL);
		}

#define	WS	" \t\n"
		cp = line;

		cp += strspn(cp, WS);
		if (cp[0] == '\0') {
			/* empty line */
			free(line);
			continue;
		}

		if ((from = strsep(&cp, WS)) == NULL)
			goto parse_error;

		cp += strspn(cp, WS);

		if ((to = strsep(&cp, WS)) == NULL)
			goto parse_error;

		if (strcmp(from, progname) == 0) {
			for (ap = strsep(&cp, WS); ap != NULL;
			    ap = strsep(&cp, WS))
			    if (*ap)
				    addarg(&al, ap, 0);
			break;
		}

		free(line);
	}

	fclose(config);

	for (i = 1; i < argc; i++)
		addarg(&al, argv[i], 0);
	addarg(&al, NULL, 0);

	execve(to, al.argv, envp);
	err(1, "cannot exec %s", to);
	/*NOTREACHED*/
parse_error:
	errx(1, "parse error in %s at line %lu",
	    _PATH_MAILERCONF, (u_long)lineno);
	/*NOTREACHED*/
}
コード例 #16
0
ファイル: main.c プロジェクト: 2asoft/freebsd
int
main(int argc, char **argv)
{
    int ret;
    const char *file;
    const char *name = NULL;
    int optidx = 0;
    char **arg = NULL;
    size_t len = 0, i;

    setprogname(argv[0]);
    if(getarg(args, num_args, argc, argv, &optidx))
	usage(1);
    if(help_flag)
	usage(0);
    if(version_flag) {
	print_version(NULL);
	exit(0);
    }
    if (argc == optidx) {
	file = "stdin";
	name = "stdin";
	yyin = stdin;
    } else {
	file = argv[optidx];
	yyin = fopen (file, "r");
	if (yyin == NULL)
	    err (1, "open %s", file);
	if (argc == optidx + 1) {
	    char *p;
	    name = estrdup(file);
	    p = strrchr(name, '.');
	    if (p)
		*p = '\0';
	} else
	    name = argv[optidx + 1];
    }

    /*
     * Parse extra options file
     */
    if (option_file) {
	char buf[1024];
	FILE *opt;

	opt = fopen(option_file, "r");
	if (opt == NULL) {
	    perror("open");
	    exit(1);
	}

	arg = calloc(2, sizeof(arg[0]));
	if (arg == NULL) {
	    perror("calloc");
	    exit(1);
	}
	arg[0] = option_file;
	arg[1] = NULL;
	len = 1;

	while (fgets(buf, sizeof(buf), opt) != NULL) {
	    buf[strcspn(buf, "\n\r")] = '\0';

	    arg = realloc(arg, (len + 2) * sizeof(arg[0]));
	    if (arg == NULL) {
		perror("malloc");
		exit(1);
	    }
	    arg[len] = strdup(buf);
	    if (arg[len] == NULL) {
		perror("strdup");
		exit(1);
	    }
	    arg[len + 1] = NULL;
	    len++;
	}
	fclose(opt);

	optidx = 0;
	if(getarg(args, num_args, len, arg, &optidx))
	    usage(1);

	if (len != optidx) {
	    fprintf(stderr, "extra args");
	    exit(1);
	}
    }


    init_generate (file, name);

    if (one_code_file)
	generate_header_of_codefile(name);

    initsym ();
    ret = yyparse ();
    if(ret != 0 || error_flag != 0)
	exit(1);
    close_generate ();
    if (argc != optidx)
	fclose(yyin);

    if (one_code_file)
	close_codefile();

    if (arg) {
	for (i = 1; i < len; i++)
	    free(arg[i]);
	free(arg);
    }

    return 0;
}
コード例 #17
0
ファイル: gsstest.c プロジェクト: aosm/gssd
int main(int argc, char *argv[])
{
	char *bname_server = NULL, *bname_client = NULL;
	int i, j, ch;
	int error;
	int num = 1;
	int Servers = 1;
	int use_kerberos = 0;
	int refcnt = 0;
	pthread_t thread;
	pthread_attr_t attr[1];
	char hostbuf[MAXHOSTNAME];
	char *host = hostbuf;
	char *realm = NULL;
	char *ServicePrincipal = NULL;
	struct passwd *pent = NULL;
	kern_return_t kr;

	uid = getuid();
	if (seteuid(uid)) {
		Log("Could not drop privilege");
		exit(EXIT_FAILURE);
	}

	setprogname(argv[0]);

	/* Set up mech table */
	mechtab[GSSD_KRB5_MECH] = GSS_KRB5_MECHANISM;
	mechtab[GSSD_SPNEGO_MECH] = GSS_SPNEGO_MECHANISM;
	mechtab[GSSD_NTLM_MECH] = GSS_NTLM_MECHANISM;

	while ((ch = getopt(argc, argv, "b:B:CdDef:hHikN:n:M:m:p:r:Rs:S:t:u:v:V")) != -1) {
		switch (ch) {
		case 'b':
			bname_client = optarg;
			break;
		case 'B':
			bname_server = optarg;
			break;
		case 'C':
			gssd_flags |= GSSD_NO_CANON;
			break;
		case 'd':
			debug++;
			break;
		case 'D':
			gssd_flags |= GSSD_NO_DEFAULT;
			break;
		case 'e':
			exitonerror = 1;
			break;
		case 'f':
			flags |= atoi(optarg);
			break;
		case 'H':
			gssd_flags &= ~GSSD_HOME_ACCESS_OK;
			break;
		case 'i':
			interactive = 1;
			break;
		case 'k':
			use_kerberos = 1;
			break;
		case 'M':
			max_retries = atoi(optarg);
			break;
		case 'm':
			if (strcmp(optarg, "krb5") == 0)
				mech = GSSD_KRB5_MECH;
			else if (strcmp(optarg, "spnego") == 0)
				mech = GSSD_SPNEGO_MECH;
			else if (strcmp(optarg, "ntlm") == 0)
				mech = GSSD_NTLM_MECH;
			else {
				Log("Unavailable gss mechanism %s\n", optarg);
				exit(EXIT_FAILURE);
			}
			break;
		case 'n':
			num = atoi(optarg);
			break;

		case 'N':
			if (strcmp(optarg, "uid") == 0)
				name_type = GSSD_MACHINE_UID;
			else if (strcmp(optarg, "suid") == 0)
				name_type = GSSD_STRING_UID;
			else if (strcmp(optarg, "user") == 0)
				name_type = GSSD_USER;
			else if (strcmp(optarg, "krb5") == 0)
				name_type = GSSD_KRB5_PRINCIPAL;
			else if (strcmp(optarg, "ntlm") == 0)
				name_type = GSSD_NTLM_PRINCIPAL;
			else {
				Log("Unsupported name type %s\n", optarg);
				exit(EXIT_FAILURE);
			}
			break;
		case 'p':
			principal = optarg;
			break;
		case 'r':
			realm = optarg;
			break;
		case 'R':
			refcnt = 1;
			break;
		case 's':
			Servers = atoi(optarg);
			break;
		case 'S':
			ServicePrincipal = optarg;
			break;
		case 't':
			timeout = atoi(optarg);
			break;
		case 'u':
			pent = getpwnam(optarg);
			if (pent)
				uid = pent->pw_uid;
			else
				Log("Could no find user %s\n", optarg);
			break;
		case 'V':
			verbose++;
			break;
		case 'v':
			version = atoi(optarg);
			break;
		default:
			Usage();
			break;
		}
	}
	argc -= optind;
	argv += optind;

	if (argc == 0) {
		gethostname(hostbuf, MAXHOSTNAME);
	} else if (argc == 1) {
		host = argv[0];
	} else {
		Usage();
	}


	if (principal == NULL || *principal == '\0') {
		if (pent == NULL)
			pent = getpwuid(uid);
		principal = pent->pw_name;
		name_type = GSSD_USER;
	}

	clientp.nt = name_type;
	switch (name_type) {
		case GSSD_USER:
		case GSSD_STRING_UID:
		case GSSD_KRB5_PRINCIPAL:
		case GSSD_NTLM_PRINCIPAL:
			clientp.name = (gssd_byte_buffer) principal;
			clientp.len = (uint32_t) strlen(principal);
			break;
		default:
			Log("Unsupported name type for principal %s\n", principal);
			exit(EXIT_FAILURE);
			break;
	}
	printf("Using creds for %s  host=%s\n", principal, host);

	if (bname_client) {
		kr = bootstrap_look_up(bootstrap_port, bname_client, &client_mp);
		if (kr != KERN_SUCCESS) {
			Log("bootstrap_look_up(): %s\n", bootstrap_strerror(kr));
			exit(EXIT_FAILURE);
		}
	} else {
		client_mp = get_gssd_port();
	}

	if (!MACH_PORT_VALID(client_mp)) {
		Log("Could not get a valid client port (%d)\n", client_mp);
		exit(EXIT_FAILURE);
	}

	if (refcnt)
		return do_refcount(mech, name_type, principal);

	if (ServicePrincipal)
		strlcpy(svcname, ServicePrincipal, sizeof(svcname));
	else if (use_kerberos) {
		strlcpy(svcname, "nfs/", sizeof(svcname));
		strlcat(svcname, host, sizeof(svcname));
		if (realm) {
			strlcat(svcname, "@", sizeof(svcname));
			strlcat(svcname, realm, sizeof(svcname));
		}
	} else {
		strlcpy(svcname, "nfs@", sizeof(svcname));
		strlcat(svcname, host, sizeof(svcname));
	}

	if (!use_kerberos) {
		targetp.nt = GSSD_HOSTBASED;
		targetp.name = (gssd_byte_buffer)svcname;
		targetp.len = (uint32_t) strlen(svcname);
	}
	printf("Service name = %s\n", svcname);

	if (bname_server) {
		kr = bootstrap_look_up(bootstrap_port, bname_server, &server_mp);
		if (kr != KERN_SUCCESS) {
			Log("bootstrap_look_up(): %s\n", bootstrap_strerror(kr));
			exit(EXIT_FAILURE);
		}
	} else {
		server_mp = get_gssd_port();
	}

	if (!MACH_PORT_VALID(server_mp)) {
		Log("Could not get a valid server port (%d)\n", server_mp);
		exit(EXIT_FAILURE);
	}

	if (interactive) {
		printf("Hit enter to start ");
		(void) getchar();
	}

	pthread_attr_init(attr);
	pthread_attr_setdetachstate(attr, PTHREAD_CREATE_DETACHED);

	pthread_mutex_init(num_servers_lock, NULL);
	pthread_cond_init(num_servers_cv, NULL);

	for (i = 0; i < num; i++) {
		num_servers = Servers;
		for (j = 0; j < num_servers; j++) {
			error = pthread_create(&thread, attr, server, NULL);
			if (error)
				Log("Could not start server: %s\n",
						strerror(error));
		}
		waitall();
	}
	report_errors();

	pthread_attr_destroy(attr);

	kr = mach_port_deallocate(mach_task_self(), client_mp);
	if (kr != KERN_SUCCESS) {
		Log("Could not delete send right!\n");
	}

	kr = mach_port_deallocate(mach_task_self(), server_mp);
	if (kr != KERN_SUCCESS) {
		Log("Could not delete send right!\n");
	}

	if (interactive) {
		printf("Hit enter to stop\n");
		(void) getchar();
	}

	return (0);
}
コード例 #18
0
ファイル: su.c プロジェクト: Sp1l/heimdal
int
main(int argc, char **argv)
{
    int i, optidx = 0;
    char *su_user;
    struct passwd *su_info;
    struct passwd *login_info;

    struct passwd *pwd;

    char *shell;

    int ok = 0;

    setprogname (argv[0]);

    if(getarg(args, sizeof(args) / sizeof(args[0]), argc, argv, &optidx))
	usage(1);

    for (i=0; i < optidx; i++)
      if (strcmp(argv[i], "-") == 0) {
	 full_login = 1;
	 break;
      }

    if(help_flag)
	usage(0);
    if(version_flag) {
	print_version(NULL);
	exit(0);
    }
    if(optidx >= argc)
	su_user = "******";
    else
	su_user = argv[optidx++];

    if (!issuid() && getuid() != 0)
	warnx("Not setuid and you are not root, expect this to fail");

    pwd = k_getpwnam(su_user);
    if(pwd == NULL)
	errx (1, "unknown login %s", su_user);
    if (pwd->pw_uid == 0 && strcmp ("root", su_user) != 0) {
	syslog (LOG_ALERT, "NIS attack, user %s has uid 0", su_user);
	errx (1, "unknown login %s", su_user);
    }
    su_info = dup_info(pwd);
    if (su_info == NULL)
	errx (1, "malloc: out of memory");

	pwd = getpwuid(getuid());
    if(pwd == NULL)
	errx(1, "who are you?");
    login_info = dup_info(pwd);
    if (login_info == NULL)
	errx (1, "malloc: out of memory");
    if(env_flag)
	shell = login_info->pw_shell;
    else
	shell = su_info->pw_shell;
    if(shell == NULL || *shell == '\0')
	shell = _PATH_BSHELL;


#ifdef KRB5
    if(kerberos_flag && ok == 0 &&
       krb5_verify(login_info, su_info, kerberos_instance) == 0)
	ok = 5;
#endif

    if(ok == 0 && login_info->pw_uid && verify_unix(login_info, su_info) != 0) {
	printf("Sorry!\n");
	exit(1);
    }

#ifdef HAVE_GETSPNAM
   {  struct spwd *sp;
      long    today;

    sp = getspnam(su_info->pw_name);
    if (sp != NULL) {
	today = time(0)/(24L * 60 * 60);
	if (sp->sp_expire > 0) {
	    if (today >= sp->sp_expire) {
		if (login_info->pw_uid)
		    errx(1,"Your account has expired.");
		else
		    printf("Your account has expired.");
            }
            else if (sp->sp_expire - today < 14)
                printf("Your account will expire in %d days.\n",
		       (int)(sp->sp_expire - today));
	}
	if (sp->sp_max > 0) {
	    if (today >= sp->sp_lstchg + sp->sp_max) {
		if (login_info->pw_uid)
		    errx(1,"Your password has expired. Choose a new one.");
		else
		    printf("Your password has expired. Choose a new one.");
	    }
	    else if (today >= sp->sp_lstchg + sp->sp_max - sp->sp_warn)
		printf("Your account will expire in %d days.\n",
		       (int)(sp->sp_lstchg + sp->sp_max -today));
	}
    }
    }
#endif
    {
	char *tty = ttyname (STDERR_FILENO);
	if (tty)
	    syslog (LOG_NOTICE | LOG_AUTH, "%s to %s on %s",
		    login_info->pw_name, su_info->pw_name, tty);
	else
	    syslog (LOG_NOTICE | LOG_AUTH, "%s to %s",
		    login_info->pw_name, su_info->pw_name);
    }


    if(!env_flag) {
	if(full_login) {
	    char *t = getenv ("TERM");
	    char **newenv = NULL;
	    int j;

	    i = read_environment(_PATH_ETC_ENVIRONMENT, &newenv);

	    environ = malloc ((10 + i) * sizeof (char *));
	    if (environ == NULL)
		err (1, "malloc");
	    environ[0] = NULL;

	    for (j = 0; j < i; j++) {
		char *p = strchr(newenv[j], '=');
		if (p == NULL)
		    errx(1, "environment '%s' missing '='", newenv[j]);
		*p++ = 0;
		esetenv (newenv[j], p, 1);
	    }
	    free(newenv);

	    esetenv ("PATH", _PATH_DEFPATH, 1);
	    if (t)
		esetenv ("TERM", t, 1);
	    if (chdir (su_info->pw_dir) < 0)
		errx (1, "no directory");
	}
	if (full_login || su_info->pw_uid)
	    esetenv ("USER", su_info->pw_name, 1);
	esetenv("HOME", su_info->pw_dir, 1);
	esetenv("SHELL", shell, 1);
    }

    {
	char **new_argv;
	char *p;

	p = strrchr(shell, '/');
	if(p)
	    p++;
	else
	    p = shell;

	if (strcmp(p, "csh") != 0)
	    csh_f_flag = 0;

        new_argv = malloc(((cmd ? 2 : 0) + 1 + argc - optidx + 1 + csh_f_flag)
	    * sizeof(*new_argv));
	if (new_argv == NULL)
	    err (1, "malloc");
	i = 0;
	if(full_login) {
	    if (asprintf(&new_argv[i++], "-%s", p) == -1)
		errx (1, "malloc");
	} else
	    new_argv[i++] = p;
	if (cmd) {
	   new_argv[i++] = "-c";
	   new_argv[i++] = cmd;
	}

	if (csh_f_flag)
	    new_argv[i++] = "-f";

	for (argv += optidx; *argv; ++argv)
	   new_argv[i++] = *argv;
	new_argv[i] = NULL;

	if(setgid(su_info->pw_gid) < 0)
	    err(1, "setgid");
	if (initgroups (su_info->pw_name, su_info->pw_gid) < 0)
	    err (1, "initgroups");
	if(setuid(su_info->pw_uid) < 0
	   || (su_info->pw_uid != 0 && setuid(0) == 0))
	    err(1, "setuid");

#ifdef KRB5
        if (ok == 5)
           krb5_start_session();
#endif
	execve(shell, new_argv, environ);
    }

    exit(1);
}
コード例 #19
0
int
main(int argc, char **argv)
{
    krb5_error_code ret;
    int optidx = 0;
    int exit_status = 0;

    setprogname (argv[0]);

    setlocale (LC_ALL, "");
    bindtextdomain ("heimdal_kuser", HEIMDAL_LOCALEDIR);
    textdomain("heimdal_kuser");

    ret = krb5_init_context(&kcc_context);
    if (ret == KRB5_CONFIG_BADFORMAT)
	errx (1, "krb5_init_context failed to parse configuration file");
    else if (ret)
	errx(1, "krb5_init_context failed: %d", ret);

    /*
     * Support linking of kcc to commands
     */

    if (!command_alias(getprogname())) {

	if (argc == 1) {
	    sl_slc_help(commands, 0, NULL);
	    return 1;
	}

	if(getarg(args, sizeof(args) / sizeof(args[0]), argc, argv, &optidx))
	    usage(1);

	if (help_flag)
	    usage (0);

	if(version_flag) {
	    print_version(NULL);
	    exit(0);
	}

    } else {
	argv[0] = rk_UNCONST(getprogname());
    }

    argc -= optidx;
    argv += optidx;

    if (argc != 0) {
	ret = sl_command(commands, argc, argv);
	if(ret == -1)
	    krb5_warnx(kcc_context, "unrecognized command: %s", argv[0]);
	else if (ret == -2)
	    ret = 0;
	if(ret != 0)
	    exit_status = 1;
    } else {
	sl_slc_help(commands, argc, argv);
	exit_status = 1;
    }

    krb5_free_context(kcc_context);
    return exit_status;
}
コード例 #20
0
ファイル: kinit.c プロジェクト: martinssonj/heimdal
int
main (int argc, char **argv)
{
    krb5_error_code ret;
    krb5_context context;
    krb5_ccache  ccache;
    krb5_principal principal;
    int optidx = 0;
    krb5_deltat ticket_life = 0;
    int parseflags = 0;

    setprogname (argv[0]);

    setlocale (LC_ALL, "");
    bindtextdomain ("heimdal_kuser", HEIMDAL_LOCALEDIR);
    textdomain("heimdal_kuser");

    ret = krb5_init_context (&context);
    if (ret == KRB5_CONFIG_BADFORMAT)
	errx (1, "krb5_init_context failed to parse configuration file");
    else if (ret)
	errx(1, "krb5_init_context failed: %d", ret);

    if(getarg(args, sizeof(args) / sizeof(args[0]), argc, argv, &optidx))
	usage(1);

    if (help_flag)
	usage (0);

    if(version_flag) {
	print_version(NULL);
	exit(0);
    }

    argc -= optidx;
    argv += optidx;

    if (canonicalize_flag || enterprise_flag)
	parseflags |= KRB5_PRINCIPAL_PARSE_ENTERPRISE;

    if (pk_enterprise_flag) {
	ret = krb5_pk_enterprise_cert(context, pk_user_id,
				      argv[0], &principal,
				      &ent_user_id);
	if (ret)
	    krb5_err(context, 1, ret, "krb5_pk_enterprise_certs");

	pk_user_id = NULL;

    } else if (anonymous_flag) {

	ret = krb5_make_principal(context, &principal, argv[0],
				  KRB5_WELLKNOWN_NAME, KRB5_ANON_NAME,
				  NULL);
	if (ret)
	    krb5_err(context, 1, ret, "krb5_make_principal");
	krb5_principal_set_type(context, principal, KRB5_NT_WELLKNOWN);

    } else {
	if (argv[0]) {
	    ret = krb5_parse_name_flags (context, argv[0], parseflags,
					 &principal);
	    if (ret)
		krb5_err (context, 1, ret, "krb5_parse_name");
	} else {
	    ret = krb5_get_default_principal (context, &principal);
	    if (ret)
		krb5_err (context, 1, ret, "krb5_get_default_principal");
	}
    }

    if(fcache_version)
	krb5_set_fcache_version(context, fcache_version);

    if(renewable_flag == -1)
	/* this seems somewhat pointless, but whatever */
	krb5_appdefault_boolean(context, "kinit",
				krb5_principal_get_realm(context, principal),
				"renewable", FALSE, &renewable_flag);
    if(do_afslog == -1)
	krb5_appdefault_boolean(context, "kinit",
				krb5_principal_get_realm(context, principal),
				"afslog", TRUE, &do_afslog);

    if(cred_cache)
	ret = krb5_cc_resolve(context, cred_cache, &ccache);
    else {
	if(argc > 1) {
	    char s[1024];
	    ret = krb5_cc_new_unique(context, NULL, NULL, &ccache);
	    if(ret)
		krb5_err(context, 1, ret, "creating cred cache");
	    snprintf(s, sizeof(s), "%s:%s",
		     krb5_cc_get_type(context, ccache),
		     krb5_cc_get_name(context, ccache));
	    setenv("KRB5CCNAME", s, 1);
	} else {
	    ret = krb5_cc_cache_match(context, principal, &ccache);
	    if (ret) {
		const char *type;
		ret = krb5_cc_default (context, &ccache);
		if (ret)
		    krb5_err (context, 1, ret, N_("resolving credentials cache", ""));

		/*
		 * Check if the type support switching, and we do,
		 * then do that instead over overwriting the current
		 * default credential
		 */
		type = krb5_cc_get_type(context, ccache);
		if (krb5_cc_support_switch(context, type)) {
		    krb5_cc_close(context, ccache);
		    ret = krb5_cc_new_unique(context, type, NULL, &ccache);
		}
	    }
	}
    }
    if (ret)
	krb5_err (context, 1, ret, N_("resolving credentials cache", ""));

#ifndef NO_AFS
    if(argc > 1 && k_hasafs ())
	k_setpag();
#endif

    if (lifetime) {
	int tmp = parse_time (lifetime, "s");
	if (tmp < 0)
	    errx (1, N_("unparsable time: %s", ""), lifetime);

	ticket_life = tmp;
    }

    if(addrs_flag == 0 && extra_addresses.num_strings > 0)
	krb5_errx(context, 1,
		  N_("specifying both extra addresses and "
		     "no addresses makes no sense", ""));
    {
	int i;
	krb5_addresses addresses;
	memset(&addresses, 0, sizeof(addresses));
	for(i = 0; i < extra_addresses.num_strings; i++) {
	    ret = krb5_parse_address(context, extra_addresses.strings[i],
				     &addresses);
	    if (ret == 0) {
		krb5_add_extra_addresses(context, &addresses);
		krb5_free_addresses(context, &addresses);
	    }
	}
	free_getarg_strings(&extra_addresses);
    }

    if(renew_flag || validate_flag) {
	ret = renew_validate(context, renew_flag, validate_flag,
			     ccache, server_str, ticket_life);
	exit(ret != 0);
    }

    get_new_tickets(context, principal, ccache, ticket_life, 1);

#ifndef NO_AFS
    if(do_afslog && k_hasafs())
	krb5_afslog(context, ccache, NULL, NULL);
#endif
    if(argc > 1) {
	struct renew_ctx ctx;
	time_t timeout;

	timeout = ticket_lifetime(context, ccache, principal,
				  server_str, NULL) / 2;

	ctx.context = context;
	ctx.ccache = ccache;
	ctx.principal = principal;
	ctx.ticket_life = ticket_life;

	ret = simple_execvp_timed(argv[1], argv+1,
				  renew_func, &ctx, timeout);
#define EX_NOEXEC	126
#define EX_NOTFOUND	127
	if(ret == EX_NOEXEC)
	    krb5_warnx(context, N_("permission denied: %s", ""), argv[1]);
	else if(ret == EX_NOTFOUND)
	    krb5_warnx(context, N_("command not found: %s", ""), argv[1]);

	krb5_cc_destroy(context, ccache);
#ifndef NO_AFS
	if(k_hasafs())
	    k_unlog();
#endif
    } else {
	krb5_cc_close (context, ccache);
	ret = 0;
    }
    krb5_free_principal(context, principal);
    krb5_free_context (context);
    return ret;
}
コード例 #21
0
ファイル: test_ap-req.c プロジェクト: DavidMulder/heimdal
int
main(int argc, char **argv)
{
    krb5_context context;
    krb5_error_code ret;
    int optidx = 0;
    const char *principal, *keytab, *ccache;
    krb5_ccache id;
    krb5_keytab kt;
    krb5_principal sprincipal, server;

    setprogname(argv[0]);

    if(getarg(args, sizeof(args) / sizeof(args[0]), argc, argv, &optidx))
	usage(1);

    if (help_flag)
	usage (0);

    if(version_flag){
	print_version(NULL);
	exit(0);
    }

    argc -= optidx;
    argv += optidx;

    if (argc < 3)
	usage(1);

    principal = argv[0];
    keytab = argv[1];
    ccache = argv[2];

    ret = krb5_init_context(&context);
    if (ret)
	errx (1, "krb5_init_context failed: %d", ret);

    ret = krb5_cc_resolve(context, ccache, &id);
    if (ret)
	krb5_err(context, 1, ret, "krb5_cc_resolve");

    ret = krb5_parse_name(context, principal, &sprincipal);
    if (ret)
	krb5_err(context, 1, ret, "krb5_parse_name");

    ret = krb5_kt_resolve(context, keytab, &kt);
    if (ret)
	krb5_err(context, 1, ret, "krb5_kt_resolve");

    if (server_any)
	server = NULL;
    else
	server = sprincipal;

    test_ap(context, sprincipal, server, kt, id, 0);
    test_ap(context, sprincipal, server, kt, id, AP_OPTS_MUTUAL_REQUIRED);

    krb5_cc_close(context, id);
    krb5_kt_close(context, kt);
    krb5_free_principal(context, sprincipal);

    krb5_free_context(context);

    return ret;
}
コード例 #22
0
int
main(int argc, char *argv[])
{
	struct info i;
	enum FMT fmt;
	int ch;

	setprogname(argv[0]);
	(void)setlocale(LC_ALL, "");

	fmt = STTY_NOTSET;
	i.fd = STDIN_FILENO;

	opterr = 0;
	while (optind < argc &&
	    strspn(argv[optind], "-aefg") == strlen(argv[optind]) &&
	    (ch = getopt(argc, argv, "aef:g")) != -1)
		switch(ch) {
		case 'a':		/* undocumented: POSIX compatibility */
			fmt = STTY_POSIX;
			break;
		case 'e':
			fmt = STTY_BSD;
			break;
		case 'f':
			if ((i.fd = open(optarg, O_RDONLY | O_NONBLOCK)) < 0)
				err(1, "%s", optarg);
			break;
		case 'g':
			fmt = STTY_GFLAG;
			break;
		case '?':
		default:
			goto args;
		}

args:	argc -= optind;
	argv += optind;

	if (ioctl(i.fd, TIOCGETD, &i.ldisc) < 0)
		err(1, "TIOCGETD");
	if (tcgetattr(i.fd, &i.t) < 0)
		err(1, "tcgetattr");
	if (ioctl(i.fd, TIOCGWINSZ, &i.win) < 0)
		warn("TIOCGWINSZ");

	switch(fmt) {
	case STTY_NOTSET:
		if (*argv)
			break;
		/* FALLTHROUGH */
	case STTY_BSD:
	case STTY_POSIX:
		print(&i.t, &i.win, i.ldisc, fmt);
		break;
	case STTY_GFLAG:
		gprint(&i.t);
		break;
	}

	for (i.set = i.wset = 0; *argv; ++argv) {
		if (ksearch(&argv, &i))
			continue;

		if (csearch(&argv, &i))
			continue;

		if (msearch(&argv, &i))
			continue;

		if (isdigit((unsigned char)**argv)) {
			int speed;

			speed = atoi(*argv);
			cfsetospeed(&i.t, speed);
			cfsetispeed(&i.t, speed);
			i.set = 1;
			continue;
		}

		if (!strncmp(*argv, "gfmt1", sizeof("gfmt1") - 1)) {
			gread(&i.t, *argv + sizeof("gfmt1") - 1);
			i.set = 1;
			continue;
		}

		warnx("illegal option -- %s", *argv);
		usage();
	}

	if (i.set && tcsetattr(i.fd, 0, &i.t) < 0)
		err(1, "tcsetattr");
	if (i.wset && ioctl(i.fd, TIOCSWINSZ, &i.win) < 0)
		warn("TIOCSWINSZ");
	exit(0);
	/* NOTREACHED */
}
コード例 #23
0
ファイル: rm.c プロジェクト: 0111abhi/platform_system_core
/*
 * rm --
 *	This rm is different from historic rm's, but is expected to match
 *	POSIX 1003.2 behavior.  The most visible difference is that -f
 *	has two specific effects now, ignore non-existent files and force
 * 	file removal.
 */
int
main(int argc, char *argv[])
{
	int ch, rflag;

	setprogname(argv[0]);
	(void)setlocale(LC_ALL, "");

	Pflag = rflag = xflag = 0;
	while ((ch = getopt(argc, argv, "dfiPRrvWx")) != -1)
		switch (ch) {
		case 'd':
			dflag = 1;
			break;
		case 'f':
			fflag = 1;
			iflag = 0;
			break;
		case 'i':
			fflag = 0;
			iflag = 1;
			break;
		case 'P':
			Pflag = 1;
			break;
		case 'R':
		case 'r':			/* Compatibility. */
			rflag = 1;
			break;
		case 'v':
			vflag = 1;
			break;
		case 'x':
			xflag = 1;
			break;
#ifndef __ANDROID__
		case 'W':
			Wflag = 1;
			break;
#endif
		case '?':
		default:
			usage();
		}
	argc -= optind;
	argv += optind;

	if (argc < 1) {
		if (fflag)
			return 0;
		usage();
	}

	(void)signal(SIGINFO, progress);

	checkdot(argv);

	if (*argv) {
		stdin_ok = isatty(STDIN_FILENO);

		if (rflag)
			rm_tree(argv);
		else
			rm_file(argv);
	}

	exit(eval);
	/* NOTREACHED */
}
コード例 #24
0
ファイル: kill.c プロジェクト: jkoshy/netbsd-elftoolchain
int
main(int argc, char *argv[])
{
	int errors;
	intmax_t numsig, pid;
	char *ep;

	setprogname(argv[0]);
	setlocale(LC_ALL, "");
	if (argc < 2)
		usage();

	numsig = SIGTERM;

	argc--, argv++;
	if (strcmp(*argv, "-l") == 0) {
		argc--, argv++;
		if (argc > 1)
			usage();
		if (argc == 1) {
			if (isdigit((unsigned char)**argv) == 0)
				usage();
			numsig = strtoimax(*argv, &ep, 10);
			/* check for correctly parsed number */
			if (*ep != '\0' || numsig == INTMAX_MIN || numsig == INTMAX_MAX) {
				errx(EXIT_FAILURE, "illegal signal number: %s",
						*argv);
				/* NOTREACHED */
			}
			if (numsig >= 128)
				numsig -= 128;
			/* and whether it fits into signals range */
			if (numsig <= 0 || numsig >= NSIG)
				nosig(*argv);
			printf("%s\n", sys_signame[(int) numsig]);
			exit(0);
		}
		printsignals(stdout);
		exit(0);
	}

	if (!strcmp(*argv, "-s")) {
		argc--, argv++;
		if (argc < 1) {
			warnx("option requires an argument -- s");
			usage();
		}
		if (strcmp(*argv, "0")) {
			if ((numsig = signame_to_signum(*argv)) < 0)
				nosig(*argv);
		} else
			numsig = 0;
		argc--, argv++;
	} else if (**argv == '-') {
		char *sn = *argv + 1;
		if (isalpha((unsigned char)*sn)) {
			if ((numsig = signame_to_signum(sn)) < 0)
				nosig(sn);
		} else if (isdigit((unsigned char)*sn)) {
			numsig = strtoimax(sn, &ep, 10);
			/* check for correctly parsed number */
			if (*ep || numsig == INTMAX_MIN || numsig == INTMAX_MAX ) {
				errx(EXIT_FAILURE, "illegal signal number: %s",
						sn);
				/* NOTREACHED */
			}
			/* and whether it fits into signals range */
			if (numsig < 0 || numsig >= NSIG)
				nosig(sn);
		} else
			nosig(sn);
		argc--, argv++;
	}

	if (argc == 0)
		usage();

	for (errors = 0; argc; argc--, argv++) {
#ifdef SHELL
		extern int getjobpgrp(const char *);
		if (*argv[0] == '%') {
			pid = getjobpgrp(*argv);
			if (pid == 0) {
				warnx("illegal job id: %s", *argv);
				errors = 1;
				continue;
			}
		} else 
#endif
		{
			pid = strtoimax(*argv, &ep, 10);
			/* make sure the pid is a number and fits into pid_t */
			if (!**argv || *ep || pid == INTMAX_MIN ||
				pid == INTMAX_MAX || pid != (pid_t) pid) {

				warnx("illegal process id: %s", *argv);
				errors = 1;
				continue;
			}
		}
		if (kill((pid_t) pid, (int) numsig) == -1) {
			warn("%s", *argv);
			errors = 1;
		}
#ifdef SHELL
		/* Wakeup the process if it was suspended, so it can
		   exit without an explicit 'fg'. */
		if (numsig == SIGTERM || numsig == SIGHUP)
			kill((pid_t) pid, SIGCONT);
#endif
	}

	exit(errors);
	/* NOTREACHED */
}
コード例 #25
0
ファイル: main.c プロジェクト: Spenser309/CS551
int
main(int argc, char **argv)
{
	int     ch, error=0;
	lpkg_head_t pkgs;

	setprogname(argv[0]);
	while ((ch = getopt(argc, argv, Options)) != -1) {
		switch (ch) {
		case 'A':
			Automatic = TRUE;
			break;

		case 'C':
			config_file = optarg;

		case 'P':
			Destdir = optarg;
			break;

		case 'f':
			Force = TRUE;
			ForceDepends = TRUE;
			break;

		case 'I':
			NoInstall = TRUE;
			break;

		case 'K':
			pkgdb_set_dir(optarg, 3);
			break;

		case 'L':
			NoView = TRUE;
			break;

		case 'R':
			NoRecord = TRUE;
			break;

		case 'm':
			OverrideMachine = optarg;
			break;

		case 'n':
			Fake = TRUE;
			Verbose = TRUE;
			break;

		case 'p':
			Prefix = optarg;
			break;

		case 'U':
			ReplaceSame = 1;
			Replace = 1;
			break;

		case 'u':
			Replace = 1;
			break;

		case 'V':
			show_version();
			/* NOTREACHED */

		case 'v':
			Verbose = TRUE;
			break;

		case 'W':
			Viewbase = optarg;
			break;

		case 'w':
			View = optarg;
			break;

		case 'h':
		case '?':
		default:
			usage();
			break;
		}
	}
	argc -= optind;
	argv += optind;

	pkg_install_config();

	if (Destdir != NULL) {
		char *pkgdbdir;

		pkgdbdir = xasprintf("%s/%s", Destdir, config_pkg_dbdir);
		pkgdb_set_dir(pkgdbdir, 4);
		free(pkgdbdir);
	}

	process_pkg_path();
	TAILQ_INIT(&pkgs);

	if (argc == 0) {
		/* If no packages, yelp */
		warnx("missing package name(s)");
		usage();
	}

	if (strcasecmp(do_license_check, "no") == 0)
		LicenseCheck = 0;
	else if (strcasecmp(do_license_check, "yes") == 0)
		LicenseCheck = 1;
	else if (strcasecmp(do_license_check, "always") == 0)
		LicenseCheck = 2;
	else
		errx(1, "Unknown value of the configuration variable"
		    "CHECK_LICENSE");

	if (LicenseCheck)
		load_license_lists();

	/* Get all the remaining package names, if any */
	for (; argc > 0; --argc, ++argv) {
		lpkg_t *lpp;

		if (IS_STDIN(*argv))
			lpp = alloc_lpkg("-");
		else
			lpp = alloc_lpkg(*argv);

		TAILQ_INSERT_TAIL(&pkgs, lpp, lp_link);
	}

	error += pkg_perform(&pkgs);
	if (error != 0) {
		warnx("%d package addition%s failed", error, error == 1 ? "" : "s");
		exit(1);
	}
	exit(0);
}
コード例 #26
0
ファイル: ls.c プロジェクト: IIJ-NetBSD/netbsd-src
int
ls_main(int argc, char *argv[])
{
	static char dot[] = ".", *dotav[] = { dot, NULL };
	struct winsize win;
	int ch, fts_options;
	int kflag = 0;
	const char *p;

	setprogname(argv[0]);
	(void)setlocale(LC_ALL, "");

	/* Terminal defaults to -Cq, non-terminal defaults to -1. */
	if (isatty(STDOUT_FILENO)) {
		if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &win) == 0 &&
		    win.ws_col > 0)
			termwidth = win.ws_col;
		f_column = f_nonprint = 1;
	} else
		f_singlecol = 1;

	/* Root is -A automatically. */
	if (!getuid())
		f_listdot = 1;

	fts_options = FTS_PHYSICAL;
	while ((ch = getopt(argc, argv, "1AaBbCcdFfghikLlMmnOoPpqRrSsTtuWwXx"))
	    != -1) {
		switch (ch) {
		/*
		 * The -1, -C, -l, -m and -x options all override each other so
		 * shell aliasing works correctly.
		 */
		case '1':
			f_singlecol = 1;
			f_column = f_columnacross = f_longform = f_stream = 0;
			break;
		case 'C':
			f_column = 1;
			f_columnacross = f_longform = f_singlecol = f_stream =
			    0;
			break;
		case 'g':
			if (f_grouponly != -1)
				f_grouponly = 1;
			f_longform = 1;
			f_column = f_columnacross = f_singlecol = f_stream = 0;
			break;
		case 'l':
			f_longform = 1;
			f_column = f_columnacross = f_singlecol = f_stream = 0;
			/* Never let -g take precedence over -l. */
			f_grouponly = -1;
			break;
		case 'm':
			f_stream = 1;
			f_column = f_columnacross = f_longform = f_singlecol =
			    0;
			break;
		case 'x':
			f_columnacross = 1;
			f_column = f_longform = f_singlecol = f_stream = 0;
			break;
		/* The -c and -u options override each other. */
		case 'c':
			f_statustime = 1;
			f_accesstime = 0;
			break;
		case 'u':
			f_accesstime = 1;
			f_statustime = 0;
			break;
		case 'F':
			f_type = 1;
			break;
		case 'L':
			fts_options &= ~FTS_PHYSICAL;
			fts_options |= FTS_LOGICAL;
			break;
		case 'R':
			f_recursive = 1;
			break;
		case 'f':
			f_nosort = 1;
			/* FALLTHROUGH */
		case 'a':
			fts_options |= FTS_SEEDOT;
			/* FALLTHROUGH */
		case 'A':
			f_listdot = 1;
			break;
		/* The -B option turns off the -b, -q and -w options. */
		case 'B':
			f_nonprint = 0;
			f_octal = 1;
			f_octal_escape = 0;
			break;
		/* The -b option turns off the -B, -q and -w options. */
		case 'b':
			f_nonprint = 0;
			f_octal = 0;
			f_octal_escape = 1;
			break;
		/* The -d option turns off the -R option. */
		case 'd':
			f_listdir = 1;
			f_recursive = 0;
			break;
		case 'i':
			f_inode = 1;
			break;
		case 'k':
			blocksize = 1024;
			kflag = 1;
			f_humanize = 0;
			break;
		/* The -h option forces all sizes to be measured in bytes. */
		case 'h':
			f_humanize = 1;
			kflag = 0;
			f_commas = 0;
			break;
		case 'M':
			f_humanize = 0;
			f_commas = 1;
			break;
		case 'n':
			f_numericonly = 1;
			f_longform = 1;
			f_column = f_columnacross = f_singlecol = f_stream = 0;
			break;
		case 'O':
			f_leafonly = 1;
			break;
		case 'o':
			f_flags = 1;
			break;
		case 'P':
			f_fullpath = 1;
			break;
		case 'p':
			f_typedir = 1;
			break;
		/* The -q option turns off the -B, -b and -w options. */
		case 'q':
			f_nonprint = 1;
			f_octal = 0;
			f_octal_escape = 0;
			break;
		case 'r':
			f_reversesort = 1;
			break;
		case 'S':
			sortkey = BY_SIZE;
			break;
		case 's':
			f_size = 1;
			break;
		case 'T':
			f_sectime = 1;
			break;
		case 't':
			sortkey = BY_TIME;
			break;
		case 'W':
			f_whiteout = 1;
			break;
		/* The -w option turns off the -B, -b and -q options. */
		case 'w':
			f_nonprint = 0;
			f_octal = 0;
			f_octal_escape = 0;
			break;
		case 'X':
			fts_options |= FTS_XDEV;
			break;
		default:
		case '?':
			usage();
		}
	}
	argc -= optind;
	argv += optind;

	if (f_column || f_columnacross || f_stream) {
		if ((p = getenv("COLUMNS")) != NULL)
			termwidth = atoi(p);
	}

	/*
	 * If both -g and -l options, let -l take precedence.
	 */
	if (f_grouponly == -1)
		f_grouponly = 0;

	/*
	 * If not -F, -i, -l, -p, -S, -s or -t options, don't require stat
	 * information.
	 */
	if (!f_inode && !f_longform && !f_size && !f_type && !f_typedir &&
	    sortkey == BY_NAME)
		fts_options |= FTS_NOSTAT;

	/*
	 * If not -F, -d or -l options, follow any symbolic links listed on
	 * the command line.
	 */
	if (!f_longform && !f_listdir && !f_type)
		fts_options |= FTS_COMFOLLOW;

	/*
	 * If -W, show whiteout entries
	 */
#ifdef FTS_WHITEOUT
	if (f_whiteout)
		fts_options |= FTS_WHITEOUT;
#endif

	/* If -i, -l, or -s, figure out block size. */
	if (f_inode || f_longform || f_size) {
		if (!kflag)
			(void)getbsize(NULL, &blocksize);
		blocksize /= 512;
	}

	/* Select a sort function. */
	if (f_reversesort) {
		switch (sortkey) {
		case BY_NAME:
			sortfcn = revnamecmp;
			break;
		case BY_SIZE:
			sortfcn = revsizecmp;
			break;
		case BY_TIME:
			if (f_accesstime)
				sortfcn = revacccmp;
			else if (f_statustime)
				sortfcn = revstatcmp;
			else /* Use modification time. */
				sortfcn = revmodcmp;
			break;
		}
	} else {
		switch (sortkey) {
		case BY_NAME:
			sortfcn = namecmp;
			break;
		case BY_SIZE:
			sortfcn = sizecmp;
			break;
		case BY_TIME:
			if (f_accesstime)
				sortfcn = acccmp;
			else if (f_statustime)
				sortfcn = statcmp;
			else /* Use modification time. */
				sortfcn = modcmp;
			break;
		}
	}

	/* Select a print function. */
	if (f_singlecol)
		printfcn = printscol;
	else if (f_columnacross)
		printfcn = printacol;
	else if (f_longform)
		printfcn = printlong;
	else if (f_stream)
		printfcn = printstream;
	else
		printfcn = printcol;

	if (argc)
		traverse(argc, argv, fts_options);
	else
		traverse(1, dotav, fts_options);
	return rval;
	/* NOTREACHED */
}
コード例 #27
0
ファイル: getaddrinfo.c プロジェクト: 2trill2spill/freebsd
int
main(int argc, char **argv)
{
	static const struct addrinfo zero_addrinfo;
	struct addrinfo hints = zero_addrinfo;
	struct addrinfo *addrinfo;
	const char *hostname = NULL, *service = NULL;
	int ch;
	int error;

	setprogname(argv[0]);

	hints.ai_family = AF_UNSPEC;
	hints.ai_socktype = 0;
	hints.ai_protocol = 0;
	hints.ai_flags = 0;

	while ((ch = getopt(argc, argv, "cf:nNp:Ps:t:")) != -1) {
		switch (ch) {
		case 'c':
			hints.ai_flags |= AI_CANONNAME;
			break;

		case 'f':
			if (!parse_af(optarg, &hints.ai_family)) {
				warnx("invalid address family: %s", optarg);
				usage();
			}
			break;

		case 'n':
			hints.ai_flags |= AI_NUMERICHOST;
			break;

		case 'N':
			hints.ai_flags |= AI_NUMERICSERV;
			break;

		case 's':
			service = optarg;
			break;

		case 'p':
			if (!parse_protocol(optarg, &hints.ai_protocol)) {
				warnx("invalid protocol: %s", optarg);
				usage();
			}
			break;

		case 'P':
			hints.ai_flags |= AI_PASSIVE;
			break;

		case 't':
			if (!parse_socktype(optarg, &hints.ai_socktype)) {
				warnx("invalid socket type: %s", optarg);
				usage();
			}
			break;

		case '?':
		default:
			usage();
		}
	}

	argc -= optind;
	argv += optind;

	if (!((argc == 1) || ((argc == 0) && (hints.ai_flags & AI_PASSIVE))))
		usage();
	if (argc == 1)
		hostname = argv[0];

	if (service != NULL) {
		char *p;

		if ((p = strchr(service, '/')) != NULL) {
			if (hints.ai_protocol != 0) {
				warnx("protocol already specified");
				usage();
			}
			*p = '\0';
			p++;

			if (!parse_protocol(p, &hints.ai_protocol)) {
				warnx("invalid protocol: %s", p);
				usage();
			}
		}
	}

	error = getaddrinfo(hostname, service, &hints, &addrinfo);
	if (error)
		errx(1, "%s", gai_strerror(error));

	if ((hints.ai_flags & AI_CANONNAME) && (addrinfo != NULL)) {
		if (printf("canonname %s\n", addrinfo->ai_canonname) < 0)
			err(1, "printf");
	}

	printaddrinfo(addrinfo);

	freeaddrinfo(addrinfo);

	return 0;
}
コード例 #28
0
ファイル: test_blowfish.C プロジェクト: gildafnai82/craq
int
main (int argc, char **argv)
{
  int i;
  blowfish c;
  u_int32_t l, r;

  setprogname (argv[0]);

  for (i = 0; i < NUM_VARIABLE_KEY_TESTS; i++) {
    c.setkey (variable_key[i], 8);
    l = plaintext_l[i];
    r = plaintext_r[i];
    c.encipher (&l, &r);
    if (l != ciphertext_l[i] || r != ciphertext_r[i])
      panic ("variable_key encryption failed on test %d\n", i + 1);
    c.decipher (&l, &r);
    if (l != plaintext_l[i] || r != plaintext_r[i])
      panic ("variable_key decryption failed on test %d\n", i + 1);
  }

  for (i = NUM_VARIABLE_KEY_TESTS;
       i < NUM_VARIABLE_KEY_TESTS + NUM_SET_KEY_TESTS; i++) {
    int len = i - NUM_VARIABLE_KEY_TESTS + 1;
    c.setkey (set_key, len);
    l = plaintext_l[i];
    r = plaintext_r[i];
    c.encipher (&l, &r);
    if (l != ciphertext_l[i] || r != ciphertext_r[i])
      panic ("set_key encryption failed on test %d\n", len);
    c.decipher (&l, &r);
    if (l != plaintext_l[i] || r != plaintext_r[i])
      panic ("set_key decryption failed on test %d\n", len);
  }

  u_int32_t buf[256];
  for (i = 0; i < 256; i++)
    buf[i] = i;

  cbc64iv cbc (c);

  cbc.setiv (0, 0);
  cbc.encipher_words (buf, sizeof (buf));
  cbc.setiv (0, 0);
  cbc.decipher_words (buf, sizeof (buf));
  for (i = 0; i < 256; i++)
    if (int (buf[i]) != i)
      panic ("CBC test 1 failed\n");

  cbc.setiv (0, 0);
  cbc.encipher_words (buf, sizeof (buf) / 2);
  cbc.encipher_words (buf + 128, sizeof (buf) / 2);
  cbc.setiv (0, 0);
  cbc.decipher_words (buf, sizeof (buf) / 2);
  cbc.decipher_words (buf + 128, sizeof (buf) / 2);
  for (i = 0; i < 256; i++)
    if (int (buf[i]) != i)
      panic ("CBC test 2 failed\n");

  cbc.setiv (0, 0);
  cbc.encipher_bytes (buf, sizeof (buf));
  cbc.setiv (0, 0);
  cbc.decipher_bytes (buf, sizeof (buf));
  for (i = 0; i < 256; i++)
    if (int (buf[i]) != i)
      panic ("CBC test 3 failed\n");

  cbc.setiv (0, 0);
  cbc.encipher_bytes (buf, sizeof (buf) / 2);
  cbc.encipher_bytes (buf + 128, sizeof (buf) / 2);
  cbc.setiv (0, 0);
  cbc.decipher_bytes (buf, sizeof (buf) / 2);
  cbc.decipher_bytes (buf + 128, sizeof (buf) / 2);
  for (i = 0; i < 256; i++)
    if (int (buf[i]) != i)
      panic ("CBC test 4 failed\n");

  return 0;
}
コード例 #29
0
ファイル: csh.c プロジェクト: ajinkya93/netbsd-src
int
main(int argc, char *argv[])
{
    struct sigaction oact;
    Char *cp;
    char *tcp, **tempv;
    const char *ecp;
    sigset_t nsigset;
    int f;

    cshin = stdin;
    cshout = stdout;
    csherr = stderr;

    setprogname(argv[0]);
    settimes();			/* Immed. estab. timing base */

    /*
     * Initialize non constant strings
     */
#ifdef _PATH_BSHELL
    STR_BSHELL = SAVE(_PATH_BSHELL);
#endif
#ifdef _PATH_CSHELL
    STR_SHELLPATH = SAVE(_PATH_CSHELL);
#endif
    STR_environ = blk2short(environ);
    environ = short2blk(STR_environ);	/* So that we can free it */
    STR_WORD_CHARS = SAVE(WORD_CHARS);

    HIST = '!';
    HISTSUB = '^';
    word_chars = STR_WORD_CHARS;

    tempv = argv;
    if (eq(str2short(tempv[0]), STRaout))	/* A.out's are quittable */
	quitit = 1;
    uid = getuid();
    gid = getgid();
    euid = geteuid();
    egid = getegid();
    /*
     * We are a login shell if: 1. we were invoked as -<something> and we had
     * no arguments 2. or we were invoked only with the -l flag
     */
    loginsh = (**tempv == '-' && argc == 1) ||
	(argc == 2 && tempv[1][0] == '-' && tempv[1][1] == 'l' &&
	 tempv[1][2] == '\0');

    if (loginsh && **tempv != '-') {
	/*
	 * Mangle the argv space
	 */
	tempv[1][0] = '\0';
	tempv[1][1] = '\0';
	tempv[1] = NULL;
	for (tcp = *tempv; *tcp++;)
	    continue;
	for (tcp--; tcp >= *tempv; tcp--)
	    tcp[1] = tcp[0];
	*++tcp = '-';
	argc--;
    }
    if (loginsh)
	(void)time(&chktim);

    AsciiOnly = 1;
#ifdef NLS
    (void)setlocale(LC_ALL, "");
    {
	int k;

	for (k = 0200; k <= 0377 && !Isprint(k); k++)
	    continue;
	AsciiOnly = k > 0377;
    }
#else
    AsciiOnly = getenv("LANG") == NULL && getenv("LC_CTYPE") == NULL;
#endif				/* NLS */

    /*
     * Move the descriptors to safe places. The variable didfds is 0 while we
     * have only FSH* to work with. When didfds is true, we have 0,1,2 and
     * prefer to use these.
     */
    initdesc();
    /*
     * XXX: This is to keep programs that use stdio happy.
     *	    what we really want is freunopen() ....
     *	    Closing cshin cshout and csherr (which are really stdin stdout
     *	    and stderr at this point and then reopening them in the same order
     *	    gives us again stdin == cshin stdout == cshout and stderr == csherr.
     *	    If that was not the case builtins like printf that use stdio
     *	    would break. But in any case we could fix that with memcpy and
     *	    a bit of pointer manipulation...
     *	    Fortunately this is not needed under the current implementation
     *	    of stdio.
     */
    (void)fclose(cshin);
    (void)fclose(cshout);
    (void)fclose(csherr);
    if (!(cshin  = funopen2((void *) &SHIN,  readf, writef, seekf, NULL,
	closef)))
	exit(1);
    if (!(cshout = funopen2((void *) &SHOUT, readf, writef, seekf, NULL,
	closef)))
	exit(1);
    if (!(csherr = funopen2((void *) &SHERR, readf, writef, seekf, NULL,
	closef)))
	exit(1);
    (void)setvbuf(cshin,  NULL, _IOLBF, 0);
    (void)setvbuf(cshout, NULL, _IOLBF, 0);
    (void)setvbuf(csherr, NULL, _IOLBF, 0);

    /*
     * Initialize the shell variables. ARGV and PROMPT are initialized later.
     * STATUS is also munged in several places. CHILD is munged when
     * forking/waiting
     */
    set(STRstatus, Strsave(STR0));

    if ((ecp = getenv("HOME")) != NULL)
	cp = quote(SAVE(ecp));
    else
	cp = NULL;

    if (cp == NULL)
	fast = 1;		/* No home -> can't read scripts */
    else
	set(STRhome, cp);
    dinit(cp);			/* dinit thinks that HOME == cwd in a login
				 * shell */
    /*
     * Grab other useful things from the environment. Should we grab
     * everything??
     */
    if ((ecp = getenv("LOGNAME")) != NULL ||
	(ecp = getenv("USER")) != NULL)
	set(STRuser, quote(SAVE(ecp)));
    if ((ecp = getenv("TERM")) != NULL)
	set(STRterm, quote(SAVE(ecp)));

    /*
     * Re-initialize path if set in environment
     */
    if ((ecp = getenv("PATH")) == NULL) {
#ifdef _PATH_DEFPATH
	importpath(str2short(_PATH_DEFPATH));
#else
	setq(STRpath, defaultpath(), &shvhed);
#endif
    } else {
	importpath(str2short(ecp));
    }

    set(STRshell, Strsave(STR_SHELLPATH));

    doldol = putn((int) getpid());	/* For $$ */
    shtemp = Strspl(STRtmpsh, doldol);	/* For << */

    /*
     * Record the interrupt states from the parent process. If the parent is
     * non-interruptible our hand must be forced or we (and our children) won't
     * be either. Our children inherit termination from our parent. We catch it
     * only if we are the login shell.
     */
    /* parents interruptibility */
    (void)sigaction(SIGINT, NULL, &oact);
    parintr = oact.sa_handler;
    (void)sigaction(SIGTERM, NULL, &oact);
    parterm = oact.sa_handler;

    /* catch these all, login shell or not */
    (void)signal(SIGHUP, phup);	/* exit processing on HUP */
    (void)signal(SIGXCPU, phup);	/* ...and on XCPU */
    (void)signal(SIGXFSZ, phup);	/* ...and on XFSZ */

    /*
     * Process the arguments.
     *
     * Note that processing of -v/-x is actually delayed till after script
     * processing.
     *
     * We set the first character of our name to be '-' if we are a shell
     * running interruptible commands.  Many programs which examine ps'es
     * use this to filter such shells out.
     */
    argc--, tempv++;
    while (argc > 0 && (tcp = tempv[0])[0] == '-' && *++tcp != '\0' && !batch) {
	do
	    switch (*tcp++) {
	    case 0:		/* -	Interruptible, no prompt */
		prompt = 0;
		setintr = 1;
		nofile = 1;
		break;
	    case 'b':		/* -b	Next arg is input file */
		batch = 1;
		break;
	    case 'c':		/* -c	Command input from arg */
		if (argc == 1)
		    xexit(0);
		argc--, tempv++;
		arginp = SAVE(tempv[0]);
		prompt = 0;
		nofile = 1;
		break;
	    case 'e':		/* -e	Exit on any error */
		exiterr = 1;
		break;
	    case 'f':		/* -f	Fast start */
		fast = 1;
		break;
	    case 'i':		/* -i	Interactive, even if !intty */
		intact = 1;
		nofile = 1;
		break;
	    case 'm':		/* -m	read .cshrc (from su) */
		mflag = 1;
		break;
	    case 'n':		/* -n	Don't execute */
		noexec = 1;
		break;
	    case 'q':		/* -q	(Undoc'd) ... die on quit */
		quitit = 1;
		break;
	    case 's':		/* -s	Read from std input */
		nofile = 1;
		break;
	    case 't':		/* -t	Read one line from input */
		onelflg = 2;
		prompt = 0;
		nofile = 1;
		break;
	    case 'v':		/* -v	Echo hist expanded input */
		nverbose = 1;	/* ... later */
		break;
	    case 'x':		/* -x	Echo just before execution */
		nexececho = 1;	/* ... later */
		break;
	    case 'V':		/* -V	Echo hist expanded input */
		setNS(STRverbose);	/* NOW! */
		break;
	    case 'X':		/* -X	Echo just before execution */
		setNS(STRecho);	/* NOW! */
		break;

	} while (*tcp);
	tempv++, argc--;
    }

    if (quitit)			/* With all due haste, for debugging */
	(void)signal(SIGQUIT, SIG_DFL);

    /*
     * Unless prevented by -, -c, -i, -s, or -t, if there are remaining
     * arguments the first of them is the name of a shell file from which to
     * read commands.
     */
    if (nofile == 0 && argc > 0) {
	nofile = open(tempv[0], O_RDONLY);
	if (nofile < 0) {
	    child = 1;		/* So this doesn't return */
	    stderror(ERR_SYSTEM, tempv[0], strerror(errno));
	}
	ffile = SAVE(tempv[0]);
	/*
	 * Replace FSHIN. Handle /dev/std{in,out,err} specially
	 * since once they are closed we cannot open them again.
	 * In that case we use our own saved descriptors
	 */
	if ((SHIN = dmove(nofile, FSHIN)) < 0)
	    switch(nofile) {
	    case 0:
		SHIN = FSHIN;
		break;
	    case 1:
		SHIN = FSHOUT;
		break;
	    case 2:
		SHIN = FSHERR;
		break;
	    default:
		stderror(ERR_SYSTEM, tempv[0], strerror(errno));
		/* NOTREACHED */
	    }
	(void)ioctl(SHIN, FIOCLEX, NULL);
	prompt = 0;
	 /* argc not used any more */ tempv++;
    }

    intty = isatty(SHIN);
    intty |= intact;
    if (intty || (intact && isatty(SHOUT))) {
	if (!batch && (uid != euid || gid != egid)) {
	    errno = EACCES;
	    child = 1;		/* So this doesn't return */
	    stderror(ERR_SYSTEM, "csh", strerror(errno));
	}
    }
    /*
     * Decide whether we should play with signals or not. If we are explicitly
     * told (via -i, or -) or we are a login shell (arg0 starts with -) or the
     * input and output are both the ttys("csh", or "csh</dev/ttyx>/dev/ttyx")
     * Note that in only the login shell is it likely that parent may have set
     * signals to be ignored
     */
    if (loginsh || intact || (intty && isatty(SHOUT)))
	setintr = 1;
    settell();
    /*
     * Save the remaining arguments in argv.
     */
    setq(STRargv, blk2short(tempv), &shvhed);

    /*
     * Set up the prompt.
     */
    if (prompt) {
	set(STRprompt, Strsave(uid == 0 ? STRsymhash : STRsymcent));
	/* that's a meta-questionmark */
	set(STRprompt2, Strsave(STRmquestion));
    }

    /*
     * If we are an interactive shell, then start fiddling with the signals;
     * this is a tricky game.
     */
    shpgrp = getpgrp();
    opgrp = tpgrp = -1;
    if (setintr) {
	**argv = '-';
	if (!quitit)		/* Wary! */
	    (void)signal(SIGQUIT, SIG_IGN);
	(void)signal(SIGINT, pintr);
	sigemptyset(&nsigset);
	(void)sigaddset(&nsigset, SIGINT);
	(void)sigprocmask(SIG_BLOCK, &nsigset, NULL);
	(void)signal(SIGTERM, SIG_IGN);
	if (quitit == 0 && arginp == 0) {
	    (void)signal(SIGTSTP, SIG_IGN);
	    (void)signal(SIGTTIN, SIG_IGN);
	    (void)signal(SIGTTOU, SIG_IGN);
	    /*
	     * Wait till in foreground, in case someone stupidly runs csh &
	     * dont want to try to grab away the tty.
	     */
	    if (isatty(FSHERR))
		f = FSHERR;
	    else if (isatty(FSHOUT))
		f = FSHOUT;
	    else if (isatty(OLDSTD))
		f = OLDSTD;
	    else
		f = -1;
    retry:
	    if ((tpgrp = tcgetpgrp(f)) != -1) {
		if (tpgrp != shpgrp) {
		    sig_t old = signal(SIGTTIN, SIG_DFL);
		    (void)kill(0, SIGTTIN);
		    (void)signal(SIGTTIN, old);
		    goto retry;
		}
		opgrp = shpgrp;
		shpgrp = getpid();
		tpgrp = shpgrp;
		/*
		 * Setpgid will fail if we are a session leader and
		 * mypid == mypgrp (POSIX 4.3.3)
		 */
		if (opgrp != shpgrp)
		    if (setpgid(0, shpgrp) == -1)
			goto notty;
		/*
		 * We do that after we set our process group, to make sure
		 * that the process group belongs to a process in the same
		 * session as the tty (our process and our group) (POSIX 7.2.4)
		 */
		if (tcsetpgrp(f, shpgrp) == -1)
		    goto notty;
		(void)ioctl(dcopy(f, FSHTTY), FIOCLEX, NULL);
	    }
	    if (tpgrp == -1) {
notty:
		(void)fprintf(csherr, "Warning: no access to tty (%s).\n",
			       strerror(errno));
		(void)fprintf(csherr, "Thus no job control in this shell.\n");
	    }
	}
    }
    if ((setintr == 0) && (parintr == SIG_DFL))
	setintr = 1;
    (void)signal(SIGCHLD, pchild);	/* while signals not ready */

    /*
     * Set an exit here in case of an interrupt or error reading the shell
     * start-up scripts.
     */
    reenter = setexit();	/* PWP */
    haderr = 0;			/* In case second time through */
    if (!fast && reenter == 0) {
	/* Will have value(STRhome) here because set fast if don't */
	{
	    sig_t oparintr;
	    sigset_t osigset;
	    int osetintr;

	    oparintr = parintr;
	    osetintr = setintr;
	    sigemptyset(&nsigset);
	    (void)sigaddset(&nsigset, SIGINT);
	    (void)sigprocmask(SIG_BLOCK, &nsigset, &osigset);

	    setintr = 0;
	    parintr = SIG_IGN;	/* Disable onintr */
#ifdef _PATH_DOTCSHRC
	    (void)srcfile(_PATH_DOTCSHRC, 0, 0);
#endif
	    if (!fast && !arginp && !onelflg)
		dohash(NULL, NULL);
#ifdef _PATH_DOTLOGIN
	    if (loginsh)
		(void)srcfile(_PATH_DOTLOGIN, 0, 0);
#endif
	    (void)sigprocmask(SIG_SETMASK, &osigset, NULL);
	    setintr = osetintr;
	    parintr = oparintr;
	}
	(void)srccat(value(STRhome), STRsldotcshrc);

	if (!fast && !arginp && !onelflg && !havhash)
	    dohash(NULL, NULL);
	/*
	 * Source history before .login so that it is available in .login
	 */
	if ((cp = value(STRhistfile)) != STRNULL)
	    tildehist[2] = cp;
	dosource(tildehist, NULL);
        if (loginsh)
	      (void)srccat(value(STRhome), STRsldotlogin);
    }

    /*
     * Now are ready for the -v and -x flags
     */
    if (nverbose)
	setNS(STRverbose);
    if (nexececho)
	setNS(STRecho);

    /*
     * All the rest of the world is inside this call. The argument to process
     * indicates whether it should catch "error unwinds".  Thus if we are a
     * interactive shell our call here will never return by being blown past on
     * an error.
     */
    process(setintr);

    /*
     * Mop-up.
     */
    if (intty) {
	if (loginsh) {
	    (void)fprintf(cshout, "logout\n");
	    (void)close(SHIN);
	    child = 1;
	    goodbye();
	}
	else {
	    (void)fprintf(cshout, "exit\n");
	}
    }
    rechist();
    exitstat();
    /* NOTREACHED */
}
コード例 #30
0
ファイル: main.c プロジェクト: faf0/sws
/*
 * Parses flags and starts the server.
 */
int
main(int argc, char *argv[])
{
  struct flags flag;
  int ch;

  flags_init(&flag);
  setprogname((char *) argv[0]);

  while ((ch = getopt(argc, argv, FLAGS_SUPPORTED)) != -1) {
    switch (ch) {
    case 'c':
      flag.c_dir = optarg;
      if (!is_dir(flag.c_dir)) {
        errx(EXIT_FAILURE, "invalid CGI dir");
      }
      break;
    case 'd':
      flag.dflag = 1;
      break;
    case 'h':
      usage();
      exit(EXIT_SUCCESS);
      /* NOTREACHED */
      break;
    case 'i':
      flag.i_address = optarg;
      {
        struct in_addr addr4;
        struct in6_addr addr6;
        if (inet_pton(AF_INET, flag.i_address, &addr4) == 1) {
          flag.ipv6 = 0;
        } else if (inet_pton(AF_INET6, flag.i_address, &addr6) == 1) {
          flag.ipv6 = 1;
        } else {
          errx(EXIT_FAILURE, "neither valid IPv4 nor IPv6 address %s",
              flag.i_address);
        }
      }
      break;
    case 'l':
      flag.lflag=1;
      flag.l_log_file = optarg;
      if((flag.logfd=open(flag.l_log_file,O_CREAT | O_APPEND | O_WRONLY,0666))<0){
        perror("Logfile error");
        exit(EXIT_FAILURE);
      }
      break;
    case 'p':
      flag.p_port = atoi(optarg);
      if ((flag.p_port < MIN_PORT) || (flag.p_port > MAX_PORT)) {
        errx(EXIT_FAILURE, "port must be between %d and %d", MIN_PORT,
        MAX_PORT);
      }
      break;
    default:
      usage();
      exit(EXIT_FAILURE);
      /* NOTREACHED */
      break;
    }
  }
  argc -= optind;
  argv += optind;

  /* get mandatory dir parameter */
  if (argc != 1) {
    usage();
    exit(EXIT_FAILURE);
  }
  flag.dir = argv[0];

  if (!is_dir(flag.dir)) {
    errx(EXIT_FAILURE, "invalid dir");
  }

#if DEBUG
  /* enable debugging flag */
  flag.dflag = 1;
#endif

  run_server(&flag);
  close(flag.logfd);
  return EXIT_SUCCESS;
}