Ejemplo n.º 1
0
/********************************************************************
*   DrvGetTwinPrefsFName
*
*	Get the full path name of the "Twin Preferences" file.
********************************************************************/
static char *DrvGetTwinPrefsFName(void)
{
        int length;
	static char twinrc[256];
	char *p;
   	struct   stat sbuf; 	 
	struct   passwd *pw;

	/* OPTION 1: if TWINRC set, use its value */
	if((p = (char *) getenv("TWINRC"))) {
		strcat(twinrc,p);
		return twinrc;
	}

	/* OPTION 2: check to see if a twinrc in current directory */
	getcwd(twinrc,256);

        /* Add slash/backslash? */
        length = strlen( twinrc );
	p = twinrc + (length - 1 );
        if( *p != '/' && *p != '\\' )
        {
          strcat(twinrc,TWIN_SLASHSTRING);
        }
	strcat(twinrc,"twinrc");

  	/* should be mfs_stat */
	/* also check stat value for a file vs. other type. */
	if(stat(twinrc,&sbuf) == 0) {
		if(S_ISREG(sbuf.st_mode)) {
			return twinrc;
		}
	}

	/* OPTION 3: get user home directory, use .twinrc */
	p = (char *)getenv("HOME");
	if (p == 0) {
		if((pw = getpwuid(getpid()))) {
			p = pw->pw_dir;	
		}
	}
	if (p) {
		sprintf(twinrc,"%s/%s",p,TWINRCFILE);
	}
	else 
        {
          /* If none, use current working directory */
	  getcwd(twinrc,256);

          /* Add slash/backslash? */
          length = strlen( twinrc );
	  p = twinrc + (length - 1 );
          if( *p != '/' && *p != '\\' )
          {
            strcat(twinrc,TWIN_SLASHSTRING);
          }
	  strcat(twinrc,"twinrc");
	}

	return twinrc;
}
Ejemplo n.º 2
0
int
testAPI()
{
	struct logininfo *li1;
	struct passwd *pw;
	struct hostent *he;
	struct sockaddr_in sa_in4;
	char cmdstring[256], stripline[8];
	char username[32];
#ifdef HAVE_TIME_H
	time_t t0, t1, t2, logintime, logouttime;
	char s_t0[64],s_t1[64],s_t2[64];
	char s_logintime[64], s_logouttime[64]; /* ctime() strings */
#endif

	printf("**\n** Testing the API...\n**\n");

	pw = getpwuid(getuid());
	strlcpy(username, pw->pw_name, sizeof(username));

	/* gethostname(hostname, sizeof(hostname)); */

	printf("login_alloc_entry test (no host info):\n");

	/* FIXME fake tty more effectively - this could upset some platforms */
	li1 = login_alloc_entry((int)getpid(), username, NULL, ttyname(0));
	strlcpy(li1->progname, "OpenSSH-logintest", sizeof(li1->progname));

	if (be_verbose)
		dump_logininfo(li1, "li1");

	printf("Setting host address info for 'localhost' (may call out):\n");
	if (! (he = gethostbyname("localhost"))) {
		printf("Couldn't set hostname(lookup failed)\n");
	} else {
		/* NOTE: this is messy, but typically a program wouldn't have to set
		 *  any of this, a sockaddr_in* would be already prepared */
		memcpy((void *)&(sa_in4.sin_addr), (void *)&(he->h_addr_list[0][0]),
		       sizeof(struct in_addr));
		login_set_addr(li1, (struct sockaddr *) &sa_in4, sizeof(sa_in4));
		strlcpy(li1->hostname, "localhost", sizeof(li1->hostname));
	}
	if (be_verbose)
		dump_logininfo(li1, "li1");

	if ((int)geteuid() != 0) {
		printf("NOT RUNNING LOGIN TESTS - you are not root!\n");
		return 1;
	}

	if (nologtest)
		return 1;

	line_stripname(stripline, li1->line, sizeof(stripline));

	printf("Performing an invalid login attempt (no type field)\n--\n");
	login_write(li1);
	printf("--\n(Should have written errors to stderr)\n");

#ifdef HAVE_TIME_H
	(void)time(&t0);
	strlcpy(s_t0, ctime(&t0), sizeof(s_t0));
	t1 = login_get_lastlog_time(getuid());
	strlcpy(s_t1, ctime(&t1), sizeof(s_t1));
	printf("Before logging in:\n\tcurrent time is %d - %s\t"
	       "lastlog time is %d - %s\n",
	       (int)t0, s_t0, (int)t1, s_t1);
#endif

	printf("Performing a login on line %s ", stripline);
#ifdef HAVE_TIME_H
	(void)time(&logintime);
	strlcpy(s_logintime, ctime(&logintime), sizeof(s_logintime));
	printf("at %d - %s", (int)logintime, s_logintime);
#endif
	printf("--\n");
	login_login(li1);

	snprintf(cmdstring, sizeof(cmdstring), "who | grep '%s '",
		 stripline);
	system(cmdstring);

	printf("--\nPausing for %d second(s)...\n", PAUSE_BEFORE_LOGOUT);
	sleep(PAUSE_BEFORE_LOGOUT);

	printf("Performing a logout ");
#ifdef HAVE_TIME_H
	(void)time(&logouttime);
	strlcpy(s_logouttime, ctime(&logouttime), sizeof(s_logouttime));
	printf("at %d - %s", (int)logouttime, s_logouttime);
#endif
	printf("\nThe root login shown above should be gone.\n"
	       "If the root login hasn't gone, but another user on the same\n"
	       "pty has, this is OK - we're hacking it here, and there\n"
	       "shouldn't be two users on one pty in reality...\n"
	       "-- ('who' output follows)\n");
	login_logout(li1);

	system(cmdstring);
	printf("-- ('who' output ends)\n");

#ifdef HAVE_TIME_H
	t2 = login_get_lastlog_time(getuid());
	strlcpy(s_t2, ctime(&t2), sizeof(s_t2));
	printf("After logging in, lastlog time is %d - %s\n", (int)t2, s_t2);
	if (t1 == t2)
		printf("The lastlog times before and after logging in are the "
		       "same.\nThis indicates that lastlog is ** NOT WORKING "
		       "CORRECTLY **\n");
	else if (t0 != t2)
		/* We can be off by a second or so, even when recording works fine.
		 * I'm not 100% sure why, but it's true. */
		printf("** The login time and the lastlog time differ.\n"
		       "** This indicates that lastlog is either recording the "
		       "wrong time,\n** or retrieving the wrong entry.\n"
		       "If it's off by less than %d second(s) "
		       "run the test again.\n", PAUSE_BEFORE_LOGOUT);
	else
		printf("lastlog agrees with the login time. This is a good thing.\n");

#endif

	printf("--\nThe output of 'last' shown next should have "
	       "an entry for root \n  on %s for the time shown above:\n--\n",
	       stripline);
	snprintf(cmdstring, sizeof(cmdstring), "last | grep '%s ' | head -3",
		 stripline);
	system(cmdstring);

	printf("--\nEnd of login test.\n");

	login_free_entry(li1);

	return 1;
} /* testAPI() */
Ejemplo n.º 3
0
static void SFgetHomeDirs (void) {
    struct passwd *pw;
    int           alloc;
    int           i;
    SFEntry       *entries = NULL;
    int           len;
    int           maxChars;

    alloc = 1;
    i = 1;
    entries = (SFEntry *) XtMalloc (sizeof (SFEntry));
    SFlogins = (SFLogin *) XtMalloc (sizeof (SFLogin));
    entries[0].real = XtMalloc (3);
    strcpy (entries[0].real, "~");
    entries[0].shown = entries[0].real;
    entries[0].statDone = 1;
    SFlogins[0].name = "";
    pw = getpwuid ((int) getuid ());
    SFstrdup (&SFlogins[0].dir, pw ? pw->pw_dir : "/");
    maxChars = 0;

    setpwent ();
    while ((pw = getpwent ()) && (*(pw->pw_name))) {
        if (i >= alloc) {
            alloc *= 2;
            entries = (SFEntry *) XtRealloc (
                (char *) entries, (unsigned) (alloc * sizeof (SFEntry))
            );
            SFlogins = (SFLogin *) XtRealloc (
                (char *) SFlogins, (unsigned) (alloc * sizeof (SFLogin))
            );
        }
        len = strlen (pw->pw_name);
        entries[i].real = XtMalloc ((unsigned) (len + 3));
        strcat (strcpy (entries[i].real, "~"), pw->pw_name);
        entries[i].shown = entries[i].real;
        entries[i].statDone = 1;
        if (len > maxChars) {
            maxChars = len;
        }
        SFstrdup (&SFlogins[i].name, pw->pw_name);
        SFstrdup (&SFlogins[i].dir, pw->pw_dir);
        i++;
    }
    SFhomeDir.dir            = XtMalloc (1);
    SFhomeDir.dir[0]         = 0;
    SFhomeDir.path           = SFcurrentPath;
    SFhomeDir.entries        = entries;
    SFhomeDir.nEntries       = i;
    SFhomeDir.vOrigin        = 0;  /* :-) */
    SFhomeDir.nChars         = maxChars + 2;
    SFhomeDir.hOrigin        = 0;
    SFhomeDir.changed        = 1;
    SFhomeDir.beginSelection = -1;
    SFhomeDir.endSelection   = -1;

#if defined (SVR4) || defined (SYSV) || defined (USG)
    qsort ((char *) entries, (unsigned)i, sizeof (SFEntry), SFcompareEntries);
    qsort ((char *) SFlogins, (unsigned)i, sizeof (SFLogin), SFcompareLogins);
#else /* defined (SVR4) || defined (SYSV) || defined (USG) */
    qsort ((char *) entries, i, sizeof (SFEntry), SFcompareEntries);
    qsort ((char *) SFlogins, i, sizeof (SFLogin), SFcompareLogins);
#endif /* defined (SVR4) || defined (SYSV) || defined (USG) */

    for (i--; i >= 0; i--) {
        strcat (entries[i].real, "/");
    }
}
Ejemplo n.º 4
0
Config *init_paths(const char *talk_ref)
{
	Config *config = new Config();
	const char *sys_prefix = "/usr/local/share";
	
	config->talk_path = replace_extension(talk_ref, "talk");
	config->graph_path = replace_extension(talk_ref, "graph");
	config->project_dir = get_path(talk_ref);
	config->latex_dir = replace_extension(talk_ref, "latex");
	config->html_dir = replace_extension(talk_ref, "html");
	config->sys_dir = combine_path(sys_prefix, "multitalk");
	config->sys_image_dir = combine_path(config->sys_dir, "gfx");
	config->sys_style_dir = combine_path(config->sys_dir, "styles");
	config->sys_font_dir = combine_path(config->sys_dir, "fonts");
	config->proj_style_dir = combine_path(config->project_dir, "styles");
	config->proj_font_dir = combine_path(config->project_dir, "fonts");
	config->sys_rc_dir = sdup("/etc");

	config->caption = new char[strlen(config->talk_path) + 20];
	sprintf(config->caption, "Multitalk - %s", config->talk_path);
	
	char *e = getenv("MULTITALK_DIR");
	if(e == NULL)
	{
		config->env_dir = NULL;
		config->env_style_dir = NULL;
		config->env_font_dir = NULL;
		config->env_image_dir = NULL;
	}
	else
	{
		config->env_dir = sdup(e);
		config->env_style_dir = combine_path(config->env_dir, "styles");
		config->env_font_dir = combine_path(config->env_dir, "fonts");
		config->env_image_dir = combine_path(config->env_dir, "gfx");
	}
	
	uid_t id;
	struct passwd *pw;
	
	id = getuid();
	pw = getpwuid(id);
	if(pw == NULL)
		error("Can't lookup home directory");
	config->home_dir = sdup(pw->pw_dir);
	config->home_style_dir = combine_path(config->home_dir, ".multitalk/styles");
	config->home_font_dir = combine_path(config->home_dir, ".multitalk/fonts");
	config->home_image_dir = combine_path(config->home_dir, ".multitalk/gfx");
	config->home_rc_dir = combine_path(config->home_dir, ".multitalk");

	if(debug & DEBUG_PATHS)
	{	
		printf("=== Directories ===\n");
		printf("talk_path = %s\n", config->talk_path);
		printf("project_dir = %s\n", config->project_dir);
		printf("latex_dir = %s\n", config->latex_dir);
		printf("html_dir = %s\n", config->html_dir);
		printf("sys_style_dir = %s\n", config->sys_style_dir);
		printf("home_style_dir = %s\n", config->home_style_dir);
		printf("===================\n");
	}
	
	return config;
}
Ejemplo n.º 5
0
int
main(int argc, char **argv) {
#ifndef HAVE_BSD_AUTH
	const char *pws;
#endif
	Display *dpy;
	int screen;

#ifdef SLOCK_QUIET
	freopen("/dev/null", "a", stdout);
	freopen("/dev/null", "a", stderr);
#endif

	char buf[255] = {0};
	snprintf(buf, sizeof(buf), "%s/.slock_passwd", getenv("HOME"));
	g_pw = read_tfile(buf);

	if((argc >= 2) && !strcmp("-v", argv[1])) {
		die("slock-%s, © 2006-2012 Anselm R Garbe\n", VERSION);
	} else if(argc != 1) {
		usage();
	}

#ifdef __linux__
	dontkillme();
#endif

	if(!g_pw && !getpwuid(getuid()))
		die("slock: no passwd entry for you\n");

#ifndef HAVE_BSD_AUTH
	pws = getpw();
#endif

	if(!(dpy = XOpenDisplay(0)))
		die("slock: cannot open display\n");
	/* Get the number of screens in display "dpy" and blank them all. */
	nscreens = ScreenCount(dpy);
	locks = malloc(sizeof(Lock *) * nscreens);
	if(locks == NULL)
		die("slock: malloc: %s\n", strerror(errno));
	int nlocks = 0;
	for(screen = 0; screen < nscreens; screen++) {
		if ( (locks[screen] = lockscreen(dpy, screen)) != NULL)
			nlocks++;
	}
	XSync(dpy, False);

	/* Did we actually manage to lock something? */
	if (nlocks == 0) { // nothing to protect
		free(locks);
		XCloseDisplay(dpy);
		return 1;
	}

	/* Everything is now blank. Now wait for the correct password. */
#ifdef HAVE_BSD_AUTH
	readpw(dpy);
#else
	readpw(dpy, pws);
#endif

	/* Password ok, unlock everything and quit. */
	for(screen = 0; screen < nscreens; screen++)
		unlockscreen(dpy, locks[screen]);

	free(locks);
	XCloseDisplay(dpy);

	return 0;
}
Ejemplo n.º 6
0
int add_file(N *head,char *file_path,char * file_name)
{
	struct stat buf;
	struct passwd *pw = NULL;
	struct group *gr = NULL;
	file_info *file;
	int j = 0;
	char *temp = NULL;
	char file_path_name[MAX_SIZE];
	struct tm *tm = NULL;
	int permission[9]=
	{
		S_IRUSR,S_IWUSR,S_IXUSR,

		S_IRGRP,S_IWGRP,S_IXGRP,

		S_IROTH,S_IWOTH,S_IXOTH
	};

	file = (file_info *)malloc(sizeof(file_info));
	if(file == NULL)
		return -1;
	file->permission[0] = 0;
	file->permission[1] = 0;
	file->permission[2] = 0;
	strcpy(file->file_name,file_name);
	strcpy(file->file_path,file_path);
	file->file_name_length = strlen(file_name);
	
	strcpy(file_path_name,file_path);
	temp = strcat(file_path_name,"/");
	temp = strcat(file_path_name,file_name);
	stat(temp,&buf);
	switch(buf.st_mode & S_IFMT)
	{
		case S_IFREG:
			file->file_type = '-';
			break;
		case S_IFDIR:
			file->file_type = 'd';
			break;
		case S_IFLNK:
			file->file_type = 'l';
			break;
		case S_IFBLK:
			file->file_type = 'b';
			break;
		case S_IFCHR:
			file->file_type = 'c';
			break;
		case S_IFIFO:
			file->file_type = 'p';
			break;
		case S_IFSOCK:
			file->file_type = 's';
			break;
		default :
			break;
	}
	for(j = 8;j >= 0;j--)
	{
		if(permission[8-j] == (buf.st_mode & (1 << j)))
		{
			switch(j%3)
			{
				case 2:
					file->permission[(8-j)/3] += 4;
					break;
				case 1:
					file->permission[(8-j)/3] += 2;
					break;
				case 0:
					file->permission[(8-j)/3] += 1;
					break;
				default :
					break;
			}
		}
		else
		{
		}
	}

	pw = getpwuid(buf.st_uid);
	gr=getgrgid(buf.st_gid);
	strcpy(file->user,pw->pw_name);
	strcpy(file->group,gr->gr_name);
	file->file_size = buf.st_size;
	tm = localtime(&buf.st_ctime);
	file->ctime = buf.st_ctime;
	file->tm.tm_year = tm->tm_year;
	file->tm.tm_mon = tm->tm_mon;
	file->tm.tm_mday = tm->tm_mday;
	file->tm.tm_hour = tm->tm_hour;
	file->tm.tm_min = tm->tm_min;
	file->tm.tm_sec = tm->tm_sec;
	file->link = buf.st_nlink;
	add(head,(void *)file);
	return 0;

}
Ejemplo n.º 7
0
/*
 * expand tilde from the passwd file.
 */
static const Char *
globtilde(const Char *pattern, Char *patbuf, size_t patbuf_len, glob_t *pglob)
{
        char *h;
        const Char *p;
        Char *b, *eb;

        if (*pattern != BG_TILDE || !(pglob->gl_flags & GLOB_TILDE))
                return pattern;

        /* Copy up to the end of the string or / */
        eb = &patbuf[patbuf_len - 1];
        for (p = pattern + 1, h = (char *) patbuf;
             h < (char*)eb && *p && *p != BG_SLASH; *h++ = (char)*p++)
                ;

        *h = BG_EOS;

#if 0
        if (h == (char *)eb)
                return what;
#endif

        if (((char *) patbuf)[0] == BG_EOS) {
                /*
                 * handle a plain ~ or ~/ by expanding $HOME
                 * first and then trying the password file
                 * or $USERPROFILE on DOSISH systems
                 */
                if ((h = getenv("HOME")) == NULL) {
#ifdef HAS_PASSWD
                        struct passwd *pwd;
                        if ((pwd = getpwuid(getuid())) == NULL)
                                return pattern;
                        else
                                h = pwd->pw_dir;
#elif DOSISH
                        /*
                         * When no passwd file, fallback to the USERPROFILE
                         * environment variable on DOSish systems.
                         */
                        if ((h = getenv("USERPROFILE")) == NULL) {
                            return pattern;
                        }
#else
                        return pattern;
#endif
                }
        } else {
                /*
                 * Expand a ~user
                 */
#ifdef HAS_PASSWD
                struct passwd *pwd;
                if ((pwd = getpwnam((char*) patbuf)) == NULL)
                        return pattern;
                else
                        h = pwd->pw_dir;
#else
                return pattern;
#endif
        }

        /* Copy the home directory */
        for (b = patbuf; b < eb && *h; *b++ = *h++)
                ;

        /* Append the rest of the pattern */
        while (b < eb && (*b++ = *p++) != BG_EOS)
                ;
        *b = BG_EOS;

        return patbuf;
}
Ejemplo n.º 8
0
int
main(int argc, char **argv)
{
	int opt, all_users = 0;
	int ret = 1;
	extern int optind;

	/* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
	sanitise_stdfd();

	__progname = ssh_get_progname(argv[0]);

	SSLeay_add_all_algorithms();
	log_init(argv[0], SYSLOG_LEVEL_INFO, SYSLOG_FACILITY_USER, 1);

	/* We don't need the RNG ourselves, but symbol references here allow
	 * ld to link us properly.
	 */
	seed_rng();

	while ((opt = getopt(argc, argv, "ahq")) != -1) {
		switch (opt) {
		case 'a':
			all_users = 1;
			break;
		case 'q':
			quiet = 1;
			break;
		case 'h':
		default:
			usage();
		}
	}

	if (all_users) {
		struct passwd *pw;

		if (!do_host())
			ret = 0;

		while ((pw = getpwent()) != NULL) {
			if (pw->pw_dir) {
				if (!do_user(pw->pw_dir))
					ret = 0;
			}
		}
	} else if (optind == argc) {
		struct passwd *pw;

		if (!do_host())
			ret = 0;

		if ((pw = getpwuid(getuid())) == NULL)
			fprintf(stderr, "No user found with uid %u\n",
			    (u_int)getuid());
		else {
			if (!do_user(pw->pw_dir))
				ret = 0;
		}
	} else {
		while (optind < argc)
			if (!do_filename(argv[optind++], 0))
				ret = 0;
	}

	return ret;
}
Ejemplo n.º 9
0
struct passwd *
getpwnam(const char *name)
{
	return (getpwuid(getuid()));
}
Ejemplo n.º 10
0
int
enqueue(int argc, char *argv[])
{
	int			 i, ch, tflag = 0, noheader;
	char			*fake_from = NULL, *buf;
	struct passwd		*pw;
	FILE			*fp, *fout;
	size_t			 len, envid_sz = 0;
	int			 fd;
	char			 sfn[] = "/tmp/smtpd.XXXXXXXXXX";
	char			*line;
	int			 dotted;
	int			 inheaders = 0;
	int			 save_argc;
	char			**save_argv;

	memset(&msg, 0, sizeof(msg));
	time(&timestamp);

	save_argc = argc;
	save_argv = argv;

	while ((ch = getopt(argc, argv,
	    "A:B:b:E::e:F:f:iJ::L:mN:o:p:qR:tvV:x")) != -1) {
		switch (ch) {
		case 'f':
			fake_from = optarg;
			break;
		case 'F':
			msg.fromname = optarg;
			break;
		case 'N':
			msg.dsn_notify = optarg;
			break;
		case 'R':
			msg.dsn_ret = optarg;
			break;
		case 't':
			tflag = 1;
			break;
		case 'v':
			verbose = 1;
			break;
		case 'V':
			msg.dsn_envid = optarg;
			break;
		/* all remaining: ignored, sendmail compat */
		case 'A':
		case 'B':
		case 'b':
		case 'E':
		case 'e':
		case 'i':
		case 'L':
		case 'm':
		case 'o':
		case 'p':
		case 'x':
			break;
		case 'q':
			/* XXX: implement "process all now" */
			return (EX_SOFTWARE);
		default:
			usage();
		}
	}

	argc -= optind;
	argv += optind;

	if (getmailname(host, sizeof(host)) == -1)
		err(EX_NOHOST, "getmailname");
	if ((user = getlogin()) != NULL && *user != '\0')
		pw = getpwnam(user);
	else if ((pw = getpwuid(getuid())) == NULL)
		user = "******";
	user = xstrdup(pw ? pw->pw_name : user, "enqueue");

	build_from(fake_from, pw);

	while (argc > 0) {
		rcpt_add(argv[0]);
		argv++;
		argc--;
	}

	if ((fd = mkstemp(sfn)) == -1 ||
	    (fp = fdopen(fd, "w+")) == NULL) {
		int saved_errno = errno;
		if (fd != -1) {
			unlink(sfn);
			close(fd);
		}
		errc(EX_UNAVAILABLE, saved_errno, "mkstemp");
	}
	unlink(sfn);
	noheader = parse_message(stdin, fake_from == NULL, tflag, fp);

	if (msg.rcpt_cnt == 0)
		errx(EX_SOFTWARE, "no recipients");

	/* init session */
	rewind(fp);

	/* try to connect */
	/* If the server is not running, enqueue the message offline */

	if (!srv_connect())
		return (enqueue_offline(save_argc, save_argv, fp));

	if ((msg.fd = open_connection()) == -1)
		errx(EX_UNAVAILABLE, "server too busy");

	fout = fdopen(msg.fd, "a+");
	if (fout == NULL)
		err(EX_UNAVAILABLE, "fdopen");

	/* 
	 * We need to call get_responses after every command because we don't
	 * support PIPELINING on the server-side yet.
	 */

	/* banner */
	get_responses(fout, 1);

	send_line(fout, verbose, "EHLO localhost\n");
	get_responses(fout, 1);

	if (msg.dsn_envid != NULL)
		envid_sz = strlen(msg.dsn_envid);

	send_line(fout, verbose, "MAIL FROM:<%s> %s%s %s%s\n",
	    msg.from,
	    msg.dsn_ret ? "RET=" : "",
	    msg.dsn_ret ? msg.dsn_ret : "",
	    envid_sz ? "ENVID=" : "",
	    envid_sz ? msg.dsn_envid : "");
	get_responses(fout, 1);

	for (i = 0; i < msg.rcpt_cnt; i++) {
		send_line(fout, verbose, "RCPT TO:<%s> %s%s\n",
		    msg.rcpts[i],
		    msg.dsn_notify ? "NOTIFY=" : "",
		    msg.dsn_notify ? msg.dsn_notify : "");
		get_responses(fout, 1);
	}

	send_line(fout, verbose, "DATA\n");
	get_responses(fout, 1);

	/* add From */
	if (!msg.saw_from)
		send_line(fout, 0, "From: %s%s<%s>\n",
		    msg.fromname ? msg.fromname : "",
		    msg.fromname ? " " : "",
		    msg.from);

	/* add Date */
	if (!msg.saw_date)
		send_line(fout, 0, "Date: %s\n", time_to_text(timestamp));

	/* add Message-Id */
	if (!msg.saw_msgid)
		send_line(fout, 0, "Message-Id: <%"PRIu64".enqueue@%s>\n",
		    generate_uid(), host);

	if (msg.need_linesplit) {
		/* we will always need to mime encode for long lines */
		if (!msg.saw_mime_version)
			send_line(fout, 0, "MIME-Version: 1.0\n");
		if (!msg.saw_content_type)
			send_line(fout, 0, "Content-Type: text/plain; "
			    "charset=unknown-8bit\n");
		if (!msg.saw_content_disposition)
			send_line(fout, 0, "Content-Disposition: inline\n");
		if (!msg.saw_content_transfer_encoding)
			send_line(fout, 0, "Content-Transfer-Encoding: "
			    "quoted-printable\n");
	}

	/* add separating newline */
	if (noheader)
		send_line(fout, 0, "\n");
	else
		inheaders = 1;

	for (;;) {
		buf = fgetln(fp, &len);
		if (buf == NULL && ferror(fp))
			err(EX_UNAVAILABLE, "fgetln");
		if (buf == NULL && feof(fp))
			break;
		/* newlines have been normalized on first parsing */
		if (buf[len-1] != '\n')
			errx(EX_SOFTWARE, "expect EOL");

		dotted = 0;
		if (buf[0] == '.') {
			fputc('.', fout);
			dotted = 1;
		}

		line = buf;

		if (msg.saw_content_transfer_encoding || noheader ||
		    inheaders || !msg.need_linesplit) {
			if (inheaders)
				send_header(fout, line, len);
			else
				send_line(fout, 0, "%.*s", (int)len, line);
			if (inheaders && buf[0] == '\n')
				inheaders = 0;
			continue;
		}

		/* we don't have a content transfer encoding, use our default */
		do {
			if (len < LINESPLIT) {
				qp_encoded_write(fout, line, len);
				break;
			}
			else {
				qp_encoded_write(fout, line,
				    LINESPLIT - 2 - dotted);
				send_line(fout, 0, "=\n");
				line += LINESPLIT - 2 - dotted;
				len -= LINESPLIT - 2 - dotted;
			}
		} while (len);
	}
	send_line(fout, verbose, ".\n");
	get_responses(fout, 1);

	send_line(fout, verbose, "QUIT\n");
	get_responses(fout, 1);

	fclose(fp);
	fclose(fout);

	exit(EX_OK);
}
Ejemplo n.º 11
0
/**
 * Create the log sink according to configuration.
 *
 * @param psink Location for the created sink pointer.
 * @param conf  Configuration JSON object.
 *
 * @return Global return code.
 */
static tlog_grc
create_log_sink(struct tlog_sink **psink, struct json_object *conf)
{
    tlog_grc grc;
    int64_t num;
    const char *str;
    struct json_object *obj;
    struct tlog_sink *sink = NULL;
    struct tlog_json_writer *writer = NULL;
    int fd = -1;
    char *fqdn = NULL;
    struct passwd *passwd;
    unsigned int session_id;

    /*
     * Create the writer
     */
    if (!json_object_object_get_ex(conf, "writer", &obj)) {
        fprintf(stderr, "Writer type is not specified\n");
        grc = TLOG_RC_FAILURE;
        goto cleanup;
    }
    str = json_object_get_string(obj);
    if (strcmp(str, "file") == 0) {
        struct json_object *conf_file;

        /* Get file writer conf container */
        if (!json_object_object_get_ex(conf, "file", &conf_file)) {
            fprintf(stderr, "File writer parameters are not specified\n");
            grc = TLOG_RC_FAILURE;
            goto cleanup;
        }

        /* Get the file path */
        if (!json_object_object_get_ex(conf_file, "path", &obj)) {
            fprintf(stderr, "Log file path is not specified\n");
            grc = TLOG_RC_FAILURE;
            goto cleanup;
        }
        str = json_object_get_string(obj);

        /* Open the file */
        fd = open(str, O_WRONLY | O_CREAT | O_APPEND, S_IRWXU | S_IRWXG);
        if (fd < 0) {
            grc = TLOG_GRC_ERRNO;
            fprintf(stderr, "Failed opening log file \"%s\": %s\n",
                    str, tlog_grc_strerror(grc));
            goto cleanup;
        }

        /* Create the writer, letting it take over the FD */
        grc = tlog_fd_json_writer_create(&writer, fd, true);
        if (grc != TLOG_RC_OK) {
            fprintf(stderr, "Failed creating file writer: %s\n",
                    tlog_grc_strerror(grc));
            goto cleanup;
        }
        fd = -1;
    } else if (strcmp(str, "syslog") == 0) {
        struct json_object *conf_syslog;
        int facility;
        int priority;

        /* Get syslog writer conf container */
        if (!json_object_object_get_ex(conf, "syslog", &conf_syslog)) {
            fprintf(stderr, "Syslog writer parameters are not specified\n");
            grc = TLOG_RC_FAILURE;
            goto cleanup;
        }

        /* Get facility */
        if (!json_object_object_get_ex(conf_syslog, "facility", &obj)) {
            fprintf(stderr, "Syslog facility is not specified\n");
            grc = TLOG_RC_FAILURE;
            goto cleanup;
        }
        str = json_object_get_string(obj);
        facility = tlog_syslog_facility_from_str(str);
        if (facility < 0) {
            fprintf(stderr, "Unknown syslog facility: %s\n", str);
            grc = TLOG_RC_FAILURE;
            goto cleanup;
        }

        /* Get priority */
        if (!json_object_object_get_ex(conf_syslog, "priority", &obj)) {
            fprintf(stderr, "Syslog priority is not specified\n");
            grc = TLOG_RC_FAILURE;
            goto cleanup;
        }
        str = json_object_get_string(obj);
        priority = tlog_syslog_priority_from_str(str);
        if (priority < 0) {
            fprintf(stderr, "Unknown syslog priority: %s\n", str);
            grc = TLOG_RC_FAILURE;
            goto cleanup;
        }

        /* Create the writer */
        openlog("tlog", LOG_NDELAY, facility);
        grc = tlog_syslog_json_writer_create(&writer, priority);
        if (grc != TLOG_RC_OK) {
            fprintf(stderr, "Failed creating syslog writer: %s\n",
                    tlog_grc_strerror(grc));
            goto cleanup;
        }
    } else {
        fprintf(stderr, "Unknown writer type: %s\n", str);
        grc = TLOG_RC_FAILURE;
        goto cleanup;
    }

    /*
     * Create the sink
     */
    /* Get host FQDN */
    grc = get_fqdn(&fqdn);
    if (grc != TLOG_RC_OK) {
        fprintf(stderr, "Failed retrieving host FQDN: %s\n",
                tlog_grc_strerror(grc));
        goto cleanup;
    }

    /* Get session ID */
    grc = get_session_id(&session_id);
    if (grc != TLOG_RC_OK) {
        fprintf(stderr, "Failed retrieving session ID: %s\n",
                tlog_grc_strerror(grc));
        goto cleanup;
    }

    /* Get effective user entry */
    errno = 0;
    passwd = getpwuid(geteuid());
    if (passwd == NULL) {
        if (errno == 0) {
            grc = TLOG_RC_FAILURE;
            fprintf(stderr, "User entry not found\n");
        } else {
            grc = TLOG_GRC_ERRNO;
            fprintf(stderr, "Failed retrieving user entry: %s\n",
                    tlog_grc_strerror(grc));
        }
        goto cleanup;
    }

    /* Get the maximum payload size */
    if (!json_object_object_get_ex(conf, "payload", &obj)) {
        fprintf(stderr, "Maximum payload size is not specified\n");
        grc = TLOG_RC_FAILURE;
        goto cleanup;
    }
    num = json_object_get_int64(obj);

    /* Create the sink, letting it take over the writer */
    grc = tlog_json_sink_create(&sink, writer, true,
                                fqdn, passwd->pw_name,
                                session_id, (size_t)num);
    if (grc != TLOG_RC_OK) {
        fprintf(stderr, "Failed creating log sink: %s\n",
                tlog_grc_strerror(grc));
        goto cleanup;
    }
    writer = NULL;

    *psink = sink;
    sink = NULL;
    grc = TLOG_RC_OK;
cleanup:

    if (fd >= 0) {
        close(fd);
    }
    tlog_json_writer_destroy(writer);
    free(fqdn);
    tlog_sink_destroy(sink);
    return grc;
}
Ejemplo n.º 12
0
void
makemsg(char *fname)
{
	int cnt;
	wchar_t ch;
	struct tm *lt;
	struct passwd *pw;
	struct stat sbuf;
	time_t now;
	FILE *fp;
	int fd;
	char hostname[MAXHOSTNAMELEN], tmpname[64];
	wchar_t *p, *tmp, lbuf[256], codebuf[13];
	const char *tty;
	const char *whom;
	gid_t egid;

	(void)snprintf(tmpname, sizeof(tmpname), "%s/wall.XXXXXX", _PATH_TMP);
	if ((fd = mkstemp(tmpname)) == -1 || !(fp = fdopen(fd, "r+")))
		err(1, "can't open temporary file");
	(void)unlink(tmpname);

	if (!nobanner) {
		tty = ttyname(STDERR_FILENO);
		if (tty == NULL)
			tty = "no tty";

		if (!(whom = getlogin()))
			whom = (pw = getpwuid(getuid())) ? pw->pw_name : "???";
		(void)gethostname(hostname, sizeof(hostname));
		(void)time(&now);
		lt = localtime(&now);

		/*
		 * all this stuff is to blank out a square for the message;
		 * we wrap message lines at column 79, not 80, because some
		 * terminals wrap after 79, some do not, and we can't tell.
		 * Which means that we may leave a non-blank character
		 * in column 80, but that can't be helped.
		 */
		(void)fwprintf(fp, L"\r%79s\r\n", " ");
		(void)swprintf(lbuf, sizeof(lbuf)/sizeof(wchar_t),
		    L"Broadcast Message from %s@%s",
		    whom, hostname);
		(void)fwprintf(fp, L"%-79.79S\007\007\r\n", lbuf);
		(void)swprintf(lbuf, sizeof(lbuf)/sizeof(wchar_t),
		    L"        (%s) at %d:%02d %s...", tty,
		    lt->tm_hour, lt->tm_min, lt->tm_zone);
		(void)fwprintf(fp, L"%-79.79S\r\n", lbuf);
	}
	(void)fwprintf(fp, L"%79s\r\n", " ");

	if (fname) {
		egid = getegid();
		setegid(getgid());
		if (freopen(fname, "r", stdin) == NULL)
			err(1, "can't read %s", fname);
		if (setegid(egid) != 0)
			err(1, "setegid failed");
	}
	cnt = 0;
	while (fgetws(lbuf, sizeof(lbuf)/sizeof(wchar_t), stdin)) {
		for (p = lbuf; (ch = *p) != L'\0'; ++p, ++cnt) {
			if (ch == L'\r') {
				putwc(L'\r', fp);
				cnt = 0;
				continue;
			} else if (ch == L'\n') {
				for (; cnt < 79; ++cnt)
					putwc(L' ', fp);
				putwc(L'\r', fp);
				putwc(L'\n', fp);
				break;
			}
			if (cnt == 79) {
				putwc(L'\r', fp);
				putwc(L'\n', fp);
				cnt = 0;
			}
			if (iswprint(ch) || iswspace(ch) || ch == L'\a' || ch == L'\b') {
				putwc(ch, fp);
			} else {
				(void)swprintf(codebuf, sizeof(codebuf)/sizeof(wchar_t), L"<0x%X>", ch);
				for (tmp = codebuf; *tmp != L'\0'; ++tmp) {
					putwc(*tmp, fp);
					if (++cnt == 79) {
						putwc(L'\r', fp);
						putwc(L'\n', fp);
						cnt = 0;
					}
				}
				--cnt;
			}
		}
	}
	(void)fwprintf(fp, L"%79s\r\n", " ");
	rewind(fp);

	if (fstat(fd, &sbuf))
		err(1, "can't stat temporary file");
	mbufsize = sbuf.st_size;
	if (!(mbuf = malloc((u_int)mbufsize)))
		err(1, "out of memory");
	if ((int)fread(mbuf, sizeof(*mbuf), mbufsize, fp) != mbufsize)
		err(1, "can't read temporary file");
	(void)close(fd);
}
Ejemplo n.º 13
0
/*
 * User shell for authenticating gateways. Sole purpose is to allow
 * a user to ssh to a gateway, and have the gateway modify packet
 * filters to allow access, then remove access when the user finishes
 * up. Meant to be used only from ssh(1) connections.
 */
int
main(int argc, char *argv[])
{
	int		 lockcnt = 0, n;
	FILE		*config;
	struct in6_addr	 ina;
	struct passwd	*pw;
	char		*cp;
	gid_t		 gid;
	uid_t		 uid;
	char		*shell;
	login_cap_t	*lc;

	if (strcmp(__progname, "-authpf-noip") == 0)
                user_ip = 0;

	config = fopen(PATH_CONFFILE, "r");
	if (config == NULL) {
		syslog(LOG_ERR, "cannot open %s (%m)", PATH_CONFFILE);
		exit(1);
	}

	if ((cp = getenv("SSH_TTY")) == NULL) {
		syslog(LOG_ERR, "non-interactive session connection for authpf");
		exit(1);
	}

	if ((cp = getenv("SSH_CLIENT")) == NULL) {
		syslog(LOG_ERR, "cannot determine connection source");
		exit(1);
	}

	if (strlcpy(ipsrc, cp, sizeof(ipsrc)) >= sizeof(ipsrc)) {
		syslog(LOG_ERR, "SSH_CLIENT variable too long");
		exit(1);
	}
	cp = strchr(ipsrc, ' ');
	if (!cp) {
		syslog(LOG_ERR, "corrupt SSH_CLIENT variable %s", ipsrc);
		exit(1);
	}
	*cp = '\0';
	if (inet_pton(AF_INET, ipsrc, &ina) != 1 &&
	    inet_pton(AF_INET6, ipsrc, &ina) != 1) {
		syslog(LOG_ERR,
		    "cannot determine IP from SSH_CLIENT %s", ipsrc);
		exit(1);
	}
	/* open the pf device */
	dev = open(PATH_DEVFILE, O_RDWR);
	if (dev == -1) {
		syslog(LOG_ERR, "cannot open packet filter device (%m)");
		goto die;
	}

	uid = getuid();
	pw = getpwuid(uid);
	if (pw == NULL) {
		syslog(LOG_ERR, "cannot find user for uid %u", uid);
		goto die;
	}

	if ((lc = login_getclass(pw->pw_class)) != NULL)
		shell = login_getcapstr(lc, "shell", pw->pw_shell,
		    pw->pw_shell);
	else
		shell = pw->pw_shell;

	login_close(lc);

	if (strcmp(shell, PATH_AUTHPF_SHELL) &&
	    strcmp(shell, PATH_AUTHPF_SHELL_NOIP)) {
		syslog(LOG_ERR, "wrong shell for user %s, uid %u",
		    pw->pw_name, pw->pw_uid);
		if (shell != pw->pw_shell)
			free(shell);
		goto die;
	}

	if (shell != pw->pw_shell)
		free(shell);

	/*
	 * Paranoia, but this data _does_ come from outside authpf, and
	 * truncation would be bad.
	 */
	if (strlcpy(luser, pw->pw_name, sizeof(luser)) >= sizeof(luser)) {
		syslog(LOG_ERR, "username too long: %s", pw->pw_name);
		goto die;
	}

	if ((n = snprintf(rulesetname, sizeof(rulesetname), "%s(%ld)",
	    luser, (long)getpid())) < 0 || (u_int)n >= sizeof(rulesetname)) {
		syslog(LOG_INFO, "%s(%ld) too large, ruleset name will be %ld",
		    luser, (long)getpid(), (long)getpid());
		if ((n = snprintf(rulesetname, sizeof(rulesetname), "%ld",
		    (long)getpid())) < 0 || (u_int)n >= sizeof(rulesetname)) {
			syslog(LOG_ERR, "pid too large for ruleset name");
			goto die;
		}
	}


	/* Make our entry in /var/authpf as ipaddr or username */
	n = snprintf(pidfile, sizeof(pidfile), "%s/%s",
	    PATH_PIDFILE, user_ip ? ipsrc : luser);
	if (n < 0 || (u_int)n >= sizeof(pidfile)) {
		syslog(LOG_ERR, "path to pidfile too long");
		goto die;
	}

	signal(SIGTERM, need_death);
	signal(SIGINT, need_death);
	signal(SIGALRM, need_death);
	signal(SIGPIPE, need_death);
	signal(SIGHUP, need_death);
	signal(SIGQUIT, need_death);
	signal(SIGTSTP, need_death);

	/*
	 * If someone else is already using this ip, then this person
	 * wants to switch users - so kill the old process and exit
	 * as well.
	 *
	 * Note, we could print a message and tell them to log out, but the
	 * usual case of this is that someone has left themselves logged in,
	 * with the authenticated connection iconized and someone else walks
	 * up to use and automatically logs in before using. If this just
	 * gets rid of the old one silently, the new user never knows they
	 * could have used someone else's old authentication. If we
	 * tell them to log out before switching users it is an invitation
	 * for abuse.
	 */

	do {
		int	save_errno, otherpid = -1;
		char	otherluser[MAXLOGNAME];

		if ((pidfd = open(pidfile, O_RDWR|O_CREAT, 0644)) == -1 ||
		    (pidfp = fdopen(pidfd, "r+")) == NULL) {
			if (pidfd != -1)
				close(pidfd);
			syslog(LOG_ERR, "cannot open or create %s: %s", pidfile,
			    strerror(errno));
			goto die;
		}

		if (flock(fileno(pidfp), LOCK_EX|LOCK_NB) == 0)
			break;
		save_errno = errno;

		/* Mark our pid, and username to our file. */

		rewind(pidfp);
		/* 31 == MAXLOGNAME - 1 */
		if (fscanf(pidfp, "%d\n%31s\n", &otherpid, otherluser) != 2)
			otherpid = -1;
		syslog(LOG_DEBUG, "tried to lock %s, in use by pid %d: %s",
		    pidfile, otherpid, strerror(save_errno));

		if (otherpid > 0) {
			syslog(LOG_INFO,
			    "killing prior auth (pid %d) of %s by user %s",
			    otherpid, ipsrc, otherluser);
			if (kill((pid_t) otherpid, SIGTERM) == -1) {
				syslog(LOG_INFO,
				    "could not kill process %d: (%m)",
				    otherpid);
			}
		}

		/*
		 * We try to kill the previous process and acquire the lock
		 * for 10 seconds, trying once a second. if we can't after
		 * 10 attempts we log an error and give up.
		 */
		if (want_death || ++lockcnt > 10) {
			if (!want_death)
				syslog(LOG_ERR, "cannot kill previous authpf (pid %d)",
				    otherpid);
			fclose(pidfp);
			pidfp = NULL;
			pidfd = -1;
			goto dogdeath;
		}
		sleep(1);

		/* re-open, and try again. The previous authpf process
		 * we killed above should unlink the file and release
		 * it's lock, giving us a chance to get it now
		 */
		fclose(pidfp);
		pidfp = NULL;
		pidfd = -1;
	} while (1);

	/* whack the group list */
	gid = getegid();
	if (setgroups(1, &gid) == -1) {
		syslog(LOG_INFO, "setgroups: %s", strerror(errno));
		do_death(0);
	}

	/* revoke privs */
	uid = getuid();
	if (setresuid(uid, uid, uid) == -1) {
		syslog(LOG_INFO, "setresuid: %s", strerror(errno));
		do_death(0);
	}
	openlog("authpf", LOG_PID | LOG_NDELAY, LOG_DAEMON);

	if (!check_luser(PATH_BAN_DIR, luser) || !allowed_luser(pw)) {
		syslog(LOG_INFO, "user %s prohibited", luser);
		do_death(0);
	}

	if (read_config(config)) {
		syslog(LOG_ERR, "invalid config file %s", PATH_CONFFILE);
		do_death(0);
	}

	if (remove_stale_rulesets()) {
		syslog(LOG_INFO, "error removing stale rulesets");
		do_death(0);
	}

	/* We appear to be making headway, so actually mark our pid */
	rewind(pidfp);
	fprintf(pidfp, "%ld\n%s\n", (long)getpid(), luser);
	fflush(pidfp);
	(void) ftruncate(fileno(pidfp), ftello(pidfp));

	if (change_filter(1, luser, ipsrc) == -1) {
		printf("Unable to modify filters\r\n");
		do_death(0);
	}
	if (user_ip && change_table(1, ipsrc) == -1) {
		printf("Unable to modify table\r\n");
		change_filter(0, luser, ipsrc);
		do_death(0);
	}

	while (1) {
		struct stat sb;
		char *path_message;
		printf("\r\nHello %s. ", luser);
		printf("You are authenticated from host \"%s\"\r\n", ipsrc);
		setproctitle("%s@%s", luser, ipsrc);
		if (asprintf(&path_message, "%s/%s/authpf.message",
		    PATH_USER_DIR, luser) == -1)
			do_death(1);
		if (stat(path_message, &sb) == -1 || ! S_ISREG(sb.st_mode)) {
			free(path_message);
			if ((path_message = strdup(PATH_MESSAGE)) == NULL)
				do_death(1);
		}
		print_message(path_message);
		while (1) {
			sleep(10);
			if (want_death)
				do_death(1);
		}
	}

	/* NOTREACHED */
dogdeath:
	printf("\r\n\r\nSorry, this service is currently unavailable due to ");
	printf("technical difficulties\r\n\r\n");
	print_message(PATH_PROBLEM);
	printf("\r\nYour authentication process (pid %ld) was unable to run\n",
	    (long)getpid());
	sleep(180); /* them lusers read reaaaaal slow */
die:
	do_death(0);
}
Ejemplo n.º 14
0
int main(int argc, char *argv[]) {
    struct passwd *pw;
    char *username;
    char *image_path = NULL;
    int ret;
    struct pam_conv conv = {conv_callback, NULL};
    int curs_choice = CURS_NONE;
    int o;
    int optind = 0;
    struct option longopts[] = {
        {"version", no_argument, NULL, 'v'},
        {"nofork", no_argument, NULL, 'n'},
        {"beep", no_argument, NULL, 'b'},
        {"dpms", no_argument, NULL, 'd'},
        {"color", required_argument, NULL, 'c'},
        {"pointer", required_argument, NULL, 'p'},
        {"debug", no_argument, NULL, 0},
        {"help", no_argument, NULL, 'h'},
        {"no-unlock-indicator", no_argument, NULL, 'u'},
        {"image", required_argument, NULL, 'i'},
        {"tiling", no_argument, NULL, 't'},
        {"ignore-empty-password", no_argument, NULL, 'e'},
        {"inactivity-timeout", required_argument, NULL, 'I'},
        {"show-failed-attempts", no_argument, NULL, 'f'},
        {NULL, no_argument, NULL, 0}};

    if ((pw = getpwuid(getuid())) == NULL)
        err(EXIT_FAILURE, "getpwuid() failed");
    if ((username = pw->pw_name) == NULL)
        errx(EXIT_FAILURE, "pw->pw_name is NULL.\n");

    char *optstring = "hvnbdc:p:ui:teI:f";
    while ((o = getopt_long(argc, argv, optstring, longopts, &optind)) != -1) {
        switch (o) {
            case 'v':
                errx(EXIT_SUCCESS, "version " VERSION " © 2010 Michael Stapelberg");
            case 'n':
                dont_fork = true;
                break;
            case 'b':
                beep = true;
                break;
            case 'd':
                dpms = true;
                break;
            case 'I': {
                int time = 0;
                if (sscanf(optarg, "%d", &time) != 1 || time < 0)
                    errx(EXIT_FAILURE, "invalid timeout, it must be a positive integer\n");
                inactivity_timeout = time;
                break;
            }
            case 'c': {
                char *arg = optarg;

                /* Skip # if present */
                if (arg[0] == '#')
                    arg++;

                if (strlen(arg) != 6 || sscanf(arg, "%06[0-9a-fA-F]", color) != 1)
                    errx(EXIT_FAILURE, "color is invalid, it must be given in 3-byte hexadecimal format: rrggbb\n");

                break;
            }
            case 'u':
                unlock_indicator = false;
                break;
            case 'i':
                image_path = strdup(optarg);
                break;
            case 't':
                tile = true;
                break;
            case 'p':
                if (!strcmp(optarg, "win")) {
                    curs_choice = CURS_WIN;
                } else if (!strcmp(optarg, "default")) {
                    curs_choice = CURS_DEFAULT;
                } else {
                    errx(EXIT_FAILURE, "i3lock: Invalid pointer type given. Expected one of \"win\" or \"default\".\n");
                }
                break;
            case 'e':
                ignore_empty_password = true;
                break;
            case 0:
                if (strcmp(longopts[optind].name, "debug") == 0)
                    debug_mode = true;
                break;
            case 'f':
                show_failed_attempts = true;
                break;
            default:
                errx(EXIT_FAILURE, "Syntax: i3lock [-v] [-n] [-b] [-d] [-c color] [-u] [-p win|default]"
                                   " [-i image.png] [-t] [-e] [-I timeout] [-f]");
        }
    }

    /* We need (relatively) random numbers for highlighting a random part of
     * the unlock indicator upon keypresses. */
    srand(time(NULL));

    /* Initialize PAM */
    ret = pam_start("i3lock", username, &conv, &pam_handle);
    if (ret != PAM_SUCCESS)
        errx(EXIT_FAILURE, "PAM: %s", pam_strerror(pam_handle, ret));

/* Using mlock() as non-super-user seems only possible in Linux. Users of other
 * operating systems should use encrypted swap/no swap (or remove the ifdef and
 * run i3lock as super-user). */
#if defined(__linux__)
    /* Lock the area where we store the password in memory, we don’t want it to
     * be swapped to disk. Since Linux 2.6.9, this does not require any
     * privileges, just enough bytes in the RLIMIT_MEMLOCK limit. */
    if (mlock(password, sizeof(password)) != 0)
        err(EXIT_FAILURE, "Could not lock page in memory, check RLIMIT_MEMLOCK");
#endif

    /* Double checking that connection is good and operatable with xcb */
    int screennr;
    if ((conn = xcb_connect(NULL, &screennr)) == NULL ||
        xcb_connection_has_error(conn))
        errx(EXIT_FAILURE, "Could not connect to X11, maybe you need to set DISPLAY?");

    if (xkb_x11_setup_xkb_extension(conn,
                                    XKB_X11_MIN_MAJOR_XKB_VERSION,
                                    XKB_X11_MIN_MINOR_XKB_VERSION,
                                    0,
                                    NULL,
                                    NULL,
                                    &xkb_base_event,
                                    &xkb_base_error) != 1)
        errx(EXIT_FAILURE, "Could not setup XKB extension.");

    static const xcb_xkb_map_part_t required_map_parts =
        (XCB_XKB_MAP_PART_KEY_TYPES |
         XCB_XKB_MAP_PART_KEY_SYMS |
         XCB_XKB_MAP_PART_MODIFIER_MAP |
         XCB_XKB_MAP_PART_EXPLICIT_COMPONENTS |
         XCB_XKB_MAP_PART_KEY_ACTIONS |
         XCB_XKB_MAP_PART_VIRTUAL_MODS |
         XCB_XKB_MAP_PART_VIRTUAL_MOD_MAP);

    static const xcb_xkb_event_type_t required_events =
        (XCB_XKB_EVENT_TYPE_NEW_KEYBOARD_NOTIFY |
         XCB_XKB_EVENT_TYPE_MAP_NOTIFY |
         XCB_XKB_EVENT_TYPE_STATE_NOTIFY);

    xcb_xkb_select_events(
        conn,
        xkb_x11_get_core_keyboard_device_id(conn),
        required_events,
        0,
        required_events,
        required_map_parts,
        required_map_parts,
        0);

    /* When we cannot initially load the keymap, we better exit */
    if (!load_keymap())
        errx(EXIT_FAILURE, "Could not load keymap");

    const char *locale = getenv("LC_ALL");
    if (!locale)
        locale = getenv("LC_CTYPE");
    if (!locale)
        locale = getenv("LANG");
    if (!locale) {
        if (debug_mode)
            fprintf(stderr, "Can't detect your locale, fallback to C\n");
        locale = "C";
    }

    load_compose_table(locale);

    xinerama_init();
    xinerama_query_screens();

    /* if DPMS is enabled, check if the X server really supports it */
    if (dpms) {
        xcb_dpms_capable_cookie_t dpmsc = xcb_dpms_capable(conn);
        xcb_dpms_capable_reply_t *dpmsr;
        if ((dpmsr = xcb_dpms_capable_reply(conn, dpmsc, NULL))) {
            if (!dpmsr->capable) {
                if (debug_mode)
                    fprintf(stderr, "Disabling DPMS, X server not DPMS capable\n");
                dpms = false;
            }
            free(dpmsr);
        }
    }

    screen = xcb_setup_roots_iterator(xcb_get_setup(conn)).data;

    last_resolution[0] = screen->width_in_pixels;
    last_resolution[1] = screen->height_in_pixels;

    xcb_change_window_attributes(conn, screen->root, XCB_CW_EVENT_MASK,
                                 (uint32_t[]){XCB_EVENT_MASK_STRUCTURE_NOTIFY});

    if (image_path) {
        /* Create a pixmap to render on, fill it with the background color */
        img = cairo_image_surface_create_from_png(image_path);
        /* In case loading failed, we just pretend no -i was specified. */
        if (cairo_surface_status(img) != CAIRO_STATUS_SUCCESS) {
            fprintf(stderr, "Could not load image \"%s\": %s\n",
                    image_path, cairo_status_to_string(cairo_surface_status(img)));
            img = NULL;
        }
    }

    /* Pixmap on which the image is rendered to (if any) */
    xcb_pixmap_t bg_pixmap = draw_image(last_resolution);

    /* open the fullscreen window, already with the correct pixmap in place */
    win = open_fullscreen_window(conn, screen, color, bg_pixmap);
    xcb_free_pixmap(conn, bg_pixmap);

    pid_t pid = fork();
    /* The pid == -1 case is intentionally ignored here:
     * While the child process is useful for preventing other windows from
     * popping up while i3lock blocks, it is not critical. */
    if (pid == 0) {
        /* Child */
        close(xcb_get_file_descriptor(conn));
        raise_loop(win);
        exit(EXIT_SUCCESS);
    }

    cursor = create_cursor(conn, screen, win, curs_choice);

    grab_pointer_and_keyboard(conn, screen, cursor);
    /* Load the keymap again to sync the current modifier state. Since we first
     * loaded the keymap, there might have been changes, but starting from now,
     * we should get all key presses/releases due to having grabbed the
     * keyboard. */
    (void)load_keymap();

    turn_monitors_off();

    /* Initialize the libev event loop. */
    main_loop = EV_DEFAULT;
    if (main_loop == NULL)
        errx(EXIT_FAILURE, "Could not initialize libev. Bad LIBEV_FLAGS?\n");

    struct ev_io *xcb_watcher = calloc(sizeof(struct ev_io), 1);
    struct ev_check *xcb_check = calloc(sizeof(struct ev_check), 1);
    struct ev_prepare *xcb_prepare = calloc(sizeof(struct ev_prepare), 1);

    ev_io_init(xcb_watcher, xcb_got_event, xcb_get_file_descriptor(conn), EV_READ);
    ev_io_start(main_loop, xcb_watcher);

    ev_check_init(xcb_check, xcb_check_cb);
    ev_check_start(main_loop, xcb_check);

    ev_prepare_init(xcb_prepare, xcb_prepare_cb);
    ev_prepare_start(main_loop, xcb_prepare);

    /* Invoke the event callback once to catch all the events which were
     * received up until now. ev will only pick up new events (when the X11
     * file descriptor becomes readable). */
    ev_invoke(main_loop, xcb_check, 0);
    ev_loop(main_loop, 0);
}
Ejemplo n.º 15
0
Archivo: ls.c Proyecto: Dorif/escu
void ls(DIR *d){
	struct stat fs;
	struct dirent *ent;
	while(ent=readdir(d)){
	if(stat(ent->d_name,&fs))ferr(progname);
	if(!shh & !strncmp(ent->d_name, ".",1))continue;
	if(!shdd & (!strcmp(ent->d_name, ".") || !strcmp(ent->d_name, "..")))continue;
	if(shr){
		if(fs.st_mode & S_IFDIR)putchar('d');
		else putchar('-');
		if(fs.st_mode & S_IRUSR)putchar('r');
		else putchar('-');
		if(fs.st_mode & S_IWUSR)putchar('w');
		else putchar('-');
		if(fs.st_mode & S_IXUSR){
			if(fs.st_mode & S_ISUID)putchar('s');
			else putchar('x');
		}
		else {
			if(fs.st_mode & S_ISUID)putchar('S');
			else putchar('-');
		}
		if(fs.st_mode & S_IRGRP)putchar('r');
		else putchar('-');
		if(fs.st_mode & S_IWGRP)putchar('w');
		else putchar('-');
		if(fs.st_mode & S_IXGRP){
			if(fs.st_mode & S_ISUID)putchar('s');
			else putchar('x');
		}
		else {
			if(fs.st_mode & S_ISUID)putchar('S');
			else putchar('-');
		}
		if(fs.st_mode & S_IROTH)putchar('r');
		else putchar('-');
		if(fs.st_mode & S_IWOTH)putchar('w');
		else putchar('-');
		if(fs.st_mode & S_IXOTH){
			if((fs.st_mode & S_IFDIR) & (fs.st_mode & S_ISVTX))putchar('t');
			else putchar('x');
		}
		else {
			if((fs.st_mode & S_IFDIR) & (fs.st_mode & S_ISVTX))putchar('T');
			else putchar('-');
		}
		putchar(' ');
	}
	if(!nsu&shu){
		struct passwd *pw;
		pw=getpwuid(fs.st_uid);
		printf("%s ",pw->pw_name);
		}
	if(!nsg&shg){
		struct group *grp;
		grp=getgrgid(fs.st_gid);
		printf("%s ",grp->gr_name);
		}
	if(!nsu&sui)printf("%i ",fs.st_uid);
	if(!nsg&sgi)printf("%i ",fs.st_gid);
	if(shs)printf("%li ",fs.st_size);
	if(shi)printf("%li ",fs.st_ino);
	if(smt){
		char *mt, mtn;
		if(shc)mt=ctime(&fs.st_ctime);
		else if(sat) mt=ctime(&fs.st_atime);
			else mt=ctime(&fs.st_mtime);
		strncat(&mtn, mt, strlen(mt)-1);
		printf("%s ",&mtn);
	}
	printf("%s", ent->d_name);
	if((sht || shd) & S_ISDIR(fs.st_mode))putchar('/');
	if(sht){
	if(S_ISLNK(fs.st_mode))putchar('@');
	if(S_ISFIFO(fs.st_mode))putchar('|');
	if(S_IXUSR & fs.st_mode)putchar('*');
	if(S_IFSOCK & fs.st_mode)putchar('=');
	}
	struct dirent *chk;
	if(chk=readdir(d)){
		if(wre)putchar('\n');
		else if(wrc)printf(", ");
			else putchar('\t');
	}
	}
}
Ejemplo n.º 16
0
static void
httpProcessInput(rfbScreenInfoPtr rfbScreen)
{
    struct sockaddr_in addr;
    socklen_t addrlen = sizeof(addr);
    char fullFname[256];
    char *fname;
    unsigned int maxFnameLen;
    FILE* fd;
    Bool performSubstitutions = FALSE;
    char str[256];
#ifndef WIN32
    struct passwd *user = getpwuid(getuid());
#endif

    cl.sock=rfbScreen->httpSock;

    if (strlen(rfbScreen->httpDir) > 200) {
        rfbLog("-httpd directory too long\n");
        httpCloseSock(rfbScreen);
        return;
    }
    strcpy(fullFname, rfbScreen->httpDir);
    fname = &fullFname[strlen(fullFname)];
    maxFnameLen = 255 - strlen(fullFname);

    /* Read data from the HTTP client until we get a complete request. */
    while (1) {
        ssize_t got = read (rfbScreen->httpSock, buf + buf_filled,
                            sizeof (buf) - buf_filled - 1);

        if (got <= 0) {
            if (got == 0) {
                rfbLog("httpd: premature connection close\n");
            } else {
                if (errno == EAGAIN) {
                    return;
                }
                rfbLogPerror("httpProcessInput: read");
            }
            httpCloseSock(rfbScreen);
            return;
        }

        buf_filled += got;
        buf[buf_filled] = '\0';

        /* Is it complete yet (is there a blank line)? */
        if (strstr (buf, "\r\r") || strstr (buf, "\n\n") ||
                strstr (buf, "\r\n\r\n") || strstr (buf, "\n\r\n\r"))
            break;
    }


    /* Process the request. */
    if (strncmp(buf, "GET ", 4)) {
        rfbLog("no GET line\n");
        httpCloseSock(rfbScreen);
        return;
    } else {
        /* Only use the first line. */
        buf[strcspn(buf, "\n\r")] = '\0';
    }

    if (strlen(buf) > maxFnameLen) {
        rfbLog("GET line too long\n");
        httpCloseSock(rfbScreen);
        return;
    }

    if (sscanf(buf, "GET %s HTTP/1.0", fname) != 1) {
        rfbLog("couldn't parse GET line\n");
        httpCloseSock(rfbScreen);
        return;
    }

    if (fname[0] != '/') {
        rfbLog("filename didn't begin with '/'\n");
        WriteExact(&cl, NOT_FOUND_STR, strlen(NOT_FOUND_STR));
        httpCloseSock(rfbScreen);
        return;
    }

    if (strchr(fname+1, '/') != NULL) {
        rfbLog("asking for file in other directory\n");
        WriteExact(&cl, NOT_FOUND_STR, strlen(NOT_FOUND_STR));
        httpCloseSock(rfbScreen);
        return;
    }

    getpeername(rfbScreen->httpSock, (struct sockaddr *)&addr, &addrlen);
    rfbLog("httpd: get '%s' for %s\n", fname+1,
           inet_ntoa(addr.sin_addr));

    /* If we were asked for '/', actually read the file index.vnc */

    if (strcmp(fname, "/") == 0) {
        strcpy(fname, "/index.vnc");
        rfbLog("httpd: defaulting to '%s'\n", fname+1);
    }

    /* Substitutions are performed on files ending .vnc */

    if (strlen(fname) >= 4 && strcmp(&fname[strlen(fname)-4], ".vnc") == 0) {
        performSubstitutions = TRUE;
    }

    /* Open the file */

    if ((fd = fopen(fullFname, "r")) <= 0) {
        rfbLogPerror("httpProcessInput: open");
        WriteExact(&cl, NOT_FOUND_STR, strlen(NOT_FOUND_STR));
        httpCloseSock(rfbScreen);
        return;
    }

    WriteExact(&cl, OK_STR, strlen(OK_STR));

    while (1) {
        int n = fread(buf, 1, BUF_SIZE-1, fd);
        if (n < 0) {
            rfbLogPerror("httpProcessInput: read");
            fclose(fd);
            httpCloseSock(rfbScreen);
            return;
        }

        if (n == 0)
            break;

        if (performSubstitutions) {

            /* Substitute $WIDTH, $HEIGHT, etc with the appropriate values.
               This won't quite work properly if the .vnc file is longer than
               BUF_SIZE, but it's reasonable to assume that .vnc files will
               always be short. */

            char *ptr = buf;
            char *dollar;
            buf[n] = 0; /* make sure it's null-terminated */

            while ((dollar = strchr(ptr, '$'))!=NULL) {
                WriteExact(&cl, ptr, (dollar - ptr));

                ptr = dollar;

                if (compareAndSkip(&ptr, "$WIDTH")) {

                    sprintf(str, "%d", rfbScreen->width);
                    WriteExact(&cl, str, strlen(str));

                } else if (compareAndSkip(&ptr, "$HEIGHT")) {

                    sprintf(str, "%d", rfbScreen->height);
                    WriteExact(&cl, str, strlen(str));

                } else if (compareAndSkip(&ptr, "$APPLETWIDTH")) {

                    sprintf(str, "%d", rfbScreen->width);
                    WriteExact(&cl, str, strlen(str));

                } else if (compareAndSkip(&ptr, "$APPLETHEIGHT")) {

                    sprintf(str, "%d", rfbScreen->height + 32);
                    WriteExact(&cl, str, strlen(str));

                } else if (compareAndSkip(&ptr, "$PORT")) {

                    sprintf(str, "%d", rfbScreen->rfbPort);
                    WriteExact(&cl, str, strlen(str));

                } else if (compareAndSkip(&ptr, "$DESKTOP")) {

                    WriteExact(&cl, rfbScreen->desktopName, strlen(rfbScreen->desktopName));

                } else if (compareAndSkip(&ptr, "$DISPLAY")) {

                    sprintf(str, "%s:%d", rfbScreen->rfbThisHost, rfbScreen->rfbPort-5900);
                    WriteExact(&cl, str, strlen(str));

                } else if (compareAndSkip(&ptr, "$USER")) {
#ifndef WIN32
                    if (user) {
                        WriteExact(&cl, user->pw_name,
                                   strlen(user->pw_name));
                    } else
#endif
                        WriteExact(&cl, "?", 1);
                } else {
                    if (!compareAndSkip(&ptr, "$$"))
                        ptr++;

                    if (WriteExact(&cl, "$", 1) < 0) {
                        fclose(fd);
                        httpCloseSock(rfbScreen);
                        return;
                    }
                }
            }
            if (WriteExact(&cl, ptr, (&buf[n] - ptr)) < 0)
                break;

        } else {

            /* For files not ending .vnc, just write out the buffer */

            if (WriteExact(&cl, buf, n) < 0)
                break;
        }
    }

    fclose(fd);
    httpCloseSock(rfbScreen);
}
Ejemplo n.º 17
0
int
message_finalize (mu_message_t msg, int warn)
{
  mu_header_t header = NULL;
  int have_to;
  char *value = NULL;
  
  mu_message_get_header (msg, &header);

  if (warn && from_person)
    {
      struct passwd *pwd = getpwuid (getuid ());
      char *warn = malloc (strlen (pwd->pw_name) + 1 +
			   sizeof (SENDER_WARNING));
      if (warn == NULL)
	{
	  mu_error ("%s: not enough memory", progname);
	  return 1;
	}
      sprintf (warn, "%s %s", pwd->pw_name, SENDER_WARNING);
      mu_header_set_value (header, "X-Authentication-Warning", warn, 0);
      free (warn);
    }
  
  have_to = mu_header_aget_value (header, MU_HEADER_TO, &value) == 0;
  
  if (read_recipients)
    {
      if (value)
	{
	  if (add_recipient (value))
	    {
	      mu_error ("%s: bad address %s", progname, value);
	      return 1;
	    }
	  free (value);
	}
	  
      if (mu_header_aget_value (header, MU_HEADER_CC, &value) == 0)
	{
	  if (add_recipient (value))
	    {
	      mu_error ("%s: bad address %s", progname, value);
	      return 1;
	    }
	  free (value);
	}  
	  
      if (mu_header_aget_value (header, MU_HEADER_BCC, &value) == 0)
	{
	  if (add_recipient (value))
	    {
	      mu_error ("%s: bad address %s", progname, value);
	      return 1;
	    }
	  free (value);
	  mu_header_set_value (header, MU_HEADER_BCC, NULL, 1);
	}  
    }

  if (!have_to)
    {
      size_t n;
      int c;
      
      c = mu_address_to_string (recipients, NULL, 0, &n);
      if (c)
	{
	  mu_error ("%s: mu_address_to_string failure: %s",
		    progname, mu_strerror (c));
	  return 1;
	}
      value = malloc (n + 1);
      if (!value)
	{
	  mu_error ("%s: not enough memory", progname);
	  return 1;
	}

      mu_address_to_string (recipients, value, n + 1, &n);
      mu_header_set_value (header, MU_HEADER_TO, value, 1);
      free (value);
    }
  return 0;
}
Ejemplo n.º 18
0
void DatabaseOutputDriver::finalizeOutput() {
	// This is where we'll send all the info we've received so far to the
	// database
	if (submittedResults) {
		return; // Only submit results for a test once
	}

	//write the header if necessary
	if (!wroteLogHeader) {
		// get hostname and username for log header
		// FIXME This needs to be platform-independent
#ifndef HOST_NAME_MAX
#define HOST_NAME_MAX (255)
#endif
		char hostname[HOST_NAME_MAX];
		if (gethostname(hostname, HOST_NAME_MAX)) {
			// TODO Handle error
		}
		
		std::string userName;

#ifdef os_windows_test
		char * szUserName = new char[MAX_USER_NAME + 1];
		LPDWORD lpnSize = (LPDWORD)malloc(sizeof(DWORD));
		*lpnSize = MAX_USER_NAME + 1;
		if (lpnSize == NULL) {
			fprintf(stderr, "[%s:%u] - Out of memory!\n", __FILE__, __LINE__);
			// TODO Handle error;
		}
		memset(szUserName, 0, MAX_USER_NAME + 1);
		if (!GetUserName(szUserName, lpnSize)) {
			fprintf(stderr, "[%s:%u] - Failed to get username: %s\n",
					__FILE__, __LINE__, GetLastError());
			//TODO Handle error
		}
		userName = std::string(szUserName);

		free(lpnSize);
		delete [] szUserName;
#else
		//note: geteuid() is always successful
		//FIXME: use getpwuid_r
		struct passwd * pw = getpwuid(geteuid());
		if (NULL == pw) {
			//TODO unknown user
			userName = "******";
		} else {
			userName = pw->pw_name;
		}
#endif

		std::string logHeader = userName + "@" + hostname;
                if (getenv("PLATFORM") != 0) {
                    logHeader += "\nPLATFORM=";
                    logHeader += getenv("PLATFORM");
                }
                logHeader += "\n\n";

		FILE * sqlLog = fopen(sqlLogFilename.c_str(), "wb");
		if (NULL == sqlLog) {
			fprintf(stderr, "[%s:%u] - Error opening log file: %s\n",
					__FILE__, __LINE__, sqlLogFilename.c_str());
			//TODO handle error
		}
		int size = strlen(logHeader.c_str());
		if (fwrite(logHeader.c_str(), sizeof(char), size, sqlLog) != size) {
			fprintf(stderr, "[%s:%u] - Error writing to log file.\n", __FILE__, __LINE__);
			//TODO handle error
		}
		fclose(sqlLog);

		wroteLogHeader = true;
	}
	
	writeSQLLog();
	return;

	//TODO: what about this stuff?
	submittedResults = true;
}
Ejemplo n.º 19
0
int
main(int argc, char **argv)
{
	Buffer b;
	Options options;
	Key *keys[2], *key;
	struct passwd *pw;
	int key_fd[2], i, found, version = 2, fd;
	u_char *signature, *data;
	char *host;
	u_int slen, dlen;
	u_int32_t rnd[256];

	key_fd[0] = open(_PATH_HOST_RSA_KEY_FILE, O_RDONLY);
	key_fd[1] = open(_PATH_HOST_DSA_KEY_FILE, O_RDONLY);

	seteuid(getuid());
	setuid(getuid());

	init_rng();
	seed_rng();
	arc4random_stir();

#ifdef DEBUG_SSH_KEYSIGN
	log_init("ssh-keysign", SYSLOG_LEVEL_DEBUG3, SYSLOG_FACILITY_AUTH, 0);
#endif

	/* verify that ssh-keysign is enabled by the admin */
	original_real_uid = getuid();	/* XXX readconf.c needs this */
	initialize_options(&options);
	(void)read_config_file(_PATH_HOST_CONFIG_FILE, "", &options);
	fill_default_options(&options);
	if (options.enable_ssh_keysign != 1)
		fatal("ssh-keysign not enabled in %s",
		    _PATH_HOST_CONFIG_FILE);

	if (key_fd[0] == -1 && key_fd[1] == -1)
		fatal("could not open any host key");

	if ((pw = getpwuid(getuid())) == NULL)
		fatal("getpwuid failed");
	pw = pwcopy(pw);

	SSLeay_add_all_algorithms();
	for (i = 0; i < 256; i++)
		rnd[i] = arc4random();
	RAND_seed(rnd, sizeof(rnd));

	found = 0;
	for (i = 0; i < 2; i++) {
		keys[i] = NULL;
		if (key_fd[i] == -1)
			continue;
		keys[i] = key_load_private_pem(key_fd[i], KEY_UNSPEC,
		    NULL, NULL);
		close(key_fd[i]);
		if (keys[i] != NULL)
			found = 1;
	}
	if (!found)
		fatal("no hostkey found");

	buffer_init(&b);
	if (ssh_msg_recv(STDIN_FILENO, &b) < 0)
		fatal("ssh_msg_recv failed");
	if (buffer_get_char(&b) != version)
		fatal("bad version");
	fd = buffer_get_int(&b);
	if ((fd == STDIN_FILENO) || (fd == STDOUT_FILENO))
		fatal("bad fd");
	if ((host = get_local_name(fd)) == NULL)
		fatal("cannot get sockname for fd");

	data = buffer_get_string(&b, &dlen);
	if (valid_request(pw, host, &key, data, dlen) < 0)
		fatal("not a valid request");
	xfree(host);

	found = 0;
	for (i = 0; i < 2; i++) {
		if (keys[i] != NULL &&
		    key_equal(key, keys[i])) {
			found = 1;
			break;
		}
	}
	if (!found)
		fatal("no matching hostkey found");

	if (key_sign(keys[i], &signature, &slen, data, dlen) != 0)
		fatal("key_sign failed");
	xfree(data);

	/* send reply */
	buffer_clear(&b);
	buffer_put_string(&b, signature, slen);
	ssh_msg_send(STDOUT_FILENO, version, &b);

	return (0);
}
Ejemplo n.º 20
0
int
main(int ac, char **av)
{
	int	c;
	int	i;
	pid_t	pid;
	int	pfd[2];
	char	*smvec[1024];
	char	**vec = smvec;
	char	buf[1024];
	char	Frombuf[256];	/* Long enough */
	char	frombuf[256];	/* Long enough */
	char	gecos[256];	/* Long enough */
	char	*s;

	char	*subj = NULL;
	char	*reply = NULL;
	char	*from = NULL;
	char	*From = NULL;
	char	*cc = NULL;
	char	*bcc = NULL;
	char	*delmode = NULL;
	char	*otherflags = NULL;
	char	*verbose = NULL;
	char	*hostname = NULL;
	int	headers = 0;

	struct passwd	*pw;

	Prog = av[0];

	while ((c = getopt(ac, av, "s:f:F:h:r:c:b:IBQHv")) != EOF) {
		switch (c) {

		case 's':	/* -s Subject: */
			if (subj)
				usage();
			subj = optarg;
			break;

		case 'f':	/* -f From_ */
			if (from)
				usage();
			from = optarg;
			break;

		case 'F':	/* -F From: */
			if (From)
				usage();
			From = optarg;
			break;

		case 'h':	/* -h hostname */
			if (hostname)
				usage();
			hostname = optarg;
			break;

		case 'H':	/* -H = headers coming in via stdin too */
			headers++;
			break;

		case 'r':	/* -r Reply-To: */
			if (reply)
				usage();
			reply = optarg;
			break;

		case 'b':	/* -b Bcc: */
			if (bcc)
				usage();
			bcc = optarg;
			break;

		case 'c':	/* -b cc: */
			if (cc)
				usage();
			cc = optarg;
			break;

		case 'I':	/* -I interactive delivery */
			delmode = "-odi";
			break;

		case 'B':	/* -B background delivery */
			delmode = "-odb";
			break;

		case 'Q':	/* -Q queue up only */
			delmode = "-odq";
			break;

		case 'v':
			verbose = "-v";
			break;

		default:
		case '?':	/* err */
			writestr(2, "Unknown switch: '");
			buf[0] = optopt;
			buf[1] = '\0';
			writestr(2, buf);
			writestr(2, "'\n");
			usage();
			break;
		}
	}
	ac -= optind;
	av += optind;
	if (ac < 1) {
		if (!headers)
		{
			writestr(2, "you must supply an address, or use -H option!\n");
			usage();
		}
		else
		{
			writestr(1, "get recipients from <stdin>\n");
			otherflags = "-t";
		}
	}

	if (hostname == NULL) {
		gethostname(buf, sizeof(buf));
		buf[sizeof(buf)-1] = '\0';		/* academic.. */
		hostname = buf;
	}
	Frombuf[0] = '\0';

	if (From) {
		/* From@hostname */
		snprintf(Frombuf, sizeof(Frombuf), "%s@%s", From, hostname);
		pw = getpwnam(From);
	} else {
		pw = getpwuid(getuid());
	}
	if (pw && hostname == buf) {
		if (pw->pw_gecos) {
			strncpy(gecos, pw->pw_gecos, sizeof(gecos) - 1);
			gecos[sizeof(gecos) - 1] = '\0';
			if ((s = strchr(gecos, ',')))
				*s = '\0';
			if ((s = strchr(gecos, ';')))
				*s = '\0';
			snprintf(Frombuf, sizeof(Frombuf), "%s <%s@%s>",
			    gecos, pw->pw_name, hostname);
		} else {
			/* From@hostname */
			snprintf(Frombuf, sizeof(Frombuf), "%s@%s",
			    pw->pw_name, hostname);
		}
	}
	endpwent();
	if (verbose) {
		writestr(2, "From: ");
		writestr(2, Frombuf);
		writestr(2, "\n");
	}

	*vec++ = "sendmail";
	*vec++ = "-oi";
	*vec++ = "-oem";

	if (delmode) {
		*vec++ = delmode;
	}

	if (verbose) {
		*vec++ = verbose;
	}

	if (otherflags) {
		*vec++ = otherflags;
	}

	if (from) {
		*vec++ = "-f";
		snprintf(frombuf, sizeof(frombuf), "%s@%s", from, hostname);
		*vec++ = frombuf;
	}

	for (i = 0; i < ac; i++)
		*vec++ = av[i];

	if (bcc)
		*vec++ = bcc;

	*vec++ = NULL;

	if (verbose) {
		writestr(1, "Executing:");
		vec = smvec;
		while (*vec) {
			writestr(1, " ");
			writestr(1, *vec);
			vec++;
		}
		writestr(1, "\n");
	}


	if (pipe(pfd) < 0) {
		perror("pipe");
		exit(1);
	}

	pid = fork();

	switch(pid) {

	case 0:			/* child */
		close(0);
		dup(pfd[0]);
		for (i = 3; i < 64; i++)
			close(i);
		execv(_PATH_SENDMAIL, smvec);
		perror(_PATH_SENDMAIL);
		_exit(1);
		break;

	case -1:		/* error */
		perror("fork");
		exit(1);
		break;

	default:		/* parent */
		close(pfd[0]);
		break;
	}

	if (Frombuf[0]) {
		writestr(pfd[1], "From: ");
		writestr(pfd[1], Frombuf);
		writestr(pfd[1], "\n");
	}
	writestr(pfd[1], "Date: ");
	writestr(pfd[1], makerfc822date(time(0)));
	writestr(pfd[1], "\n");

	if (subj) {
		writestr(pfd[1], "Subject: ");
		writestr(pfd[1], subj);
		writestr(pfd[1], "\n");
	}
	if (reply) {
		writestr(pfd[1], "Reply-To: ");
		writestr(pfd[1], reply);
		writestr(pfd[1], "\n");
	}
	if (cc) {
		writestr(pfd[1], "Cc: ");
		writestr(pfd[1], cc);
		writestr(pfd[1], "\n");
	}

	writestr(pfd[1], "To: ");
	writestr(pfd[1], av[0]);

	for (i = 1; i < ac; i++) {
		writestr(pfd[1], ", ");
		writestr(pfd[1], av[i]);
	}
	writestr(pfd[1], "\n");

	/* Headers from stdin */
	if (!headers)
		writestr(pfd[1], "\n");

	while ((c = read(0, buf, sizeof(buf))) > 0) {
		write(pfd[1], buf, c);
	}

	close(pfd[1]);

	alarm(600);		/* drop dead in 10 minutes */

	while (wait(NULL) > 0)
		;

	exit(0);
}
Ejemplo n.º 21
0
int su_main ( int argc, char **argv )
{
	unsigned long flags;
	int opt_preserve;
	int opt_loginshell;
	char *opt_shell = 0;
	char *opt_command = 0;
	char *opt_username = DEFAULT_USER;
	char **opt_args = 0;
	struct passwd *pw;
	uid_t cur_uid = getuid();

#if defined( SYSLOG_SUCCESS ) || defined( SYSLOG_FAILURE )
	const char *tty;
	const char *old_user;
#endif

	flags = bb_getopt_ulflags(argc, argv, "mplc:s:",
						  &opt_command, &opt_shell);
	opt_preserve = flags & 3;
	opt_loginshell = (flags & 4 ? 1 : 0);

	if (optind < argc  && argv[optind][0] == '-' && argv[optind][1] == 0) {
		opt_loginshell = 1;
		++optind;
    }

	/* get user if specified */
	if ( optind < argc )
		opt_username = argv [optind++];

	if ( optind < argc )
		opt_args = argv + optind;

#if defined( SYSLOG_SUCCESS ) || defined( SYSLOG_FAILURE )
#ifdef CONFIG_FEATURE_U_W_TMP
	/* The utmp entry (via getlogin) is probably the best way to identify
	   the user, especially if someone su's from a su-shell.  */
	old_user = getlogin ( );
	if ( !old_user )
#endif
		{
		/* getlogin can fail -- usually due to lack of utmp entry. Resort to getpwuid.  */
		pw = getpwuid ( cur_uid );
		old_user = ( pw ? pw->pw_name : "" );
	}
	tty = ttyname ( 2 );
	if(!tty)
		tty = "none";

	openlog ( bb_applet_name, 0, LOG_AUTH );
#endif

	pw = getpwnam ( opt_username );
	if ( !pw )
		bb_error_msg_and_die ( "user %s does not exist", opt_username );

	/* Make sure pw->pw_shell is non-NULL.  It may be NULL when NEW_USER
	   is a username that is retrieved via NIS (YP), but that doesn't have
	   a default shell listed.  */
	if ( !pw-> pw_shell || !pw->pw_shell [0] )
		pw-> pw_shell = (char *) DEFAULT_SHELL;

	if ((( cur_uid == 0 ) || correct_password ( pw ))) {
		log_su_successful(pw->pw_uid, old_user, tty );
	} else {
		log_su_failure (pw->pw_uid, old_user, tty );
		bb_error_msg_and_die ( "incorrect password" );
	}

#if defined( SYSLOG_SUCCESS ) || defined( SYSLOG_FAILURE )
	closelog();
#endif

	if ( !opt_shell && opt_preserve )
		opt_shell = getenv ( "SHELL" );

	if ( opt_shell && cur_uid && restricted_shell ( pw-> pw_shell )) {
		/* The user being su'd to has a nonstandard shell, and so is
		   probably a uucp account or has restricted access.  Don't
		   compromise the account by allowing access with a standard
		   shell.  */
		fputs ( "using restricted shell\n", stderr );
		opt_shell = 0;
	}

	if ( !opt_shell )
		opt_shell = pw->pw_shell;

	change_identity ( pw );
	setup_environment ( opt_shell, opt_loginshell, !opt_preserve, pw );
	run_shell ( opt_shell, opt_loginshell, opt_command, (const char**)opt_args
#ifdef CONFIG_SELINUX
	, 0
#endif
	);

	return EXIT_FAILURE;
}
Ejemplo n.º 22
0
gint  taxi_oth_r1(class taxi_oth_data *data)
{
    SQL_str row;
    int kodop=0;
    int kodzav=0;
    int kolvod=0;
    char kodkl[30];
    int kolklient=0;

    printf("Создаём массивы.\n");
//Определяем количество операторов, водителей и кодов завершения
    while(data->cur.read_cursor(&row) != 0)
    {
//    printf("%s %s\n",row[0],row[1]);
        if(iceb_u_proverka(data->kodop.ravno(),row[3],0,0) != 0)
            continue;
        if(iceb_u_proverka(data->kodvod.ravno(),row[1],0,0) != 0)
            continue;
        if(iceb_u_proverka(data->kodzav.ravno(),row[0],0,0) != 0)
            continue;

        if(iceb_u_proverka(data->kodklienta.ravno(),row[4],0,0) != 0)
            continue;

        kodzav=atoi(row[0]);
        kodop=atoi(row[3]);

        if(data->vod.find(row[1]) == -1)
            data->vod.plus(row[1]);
        if(data->zav.find(kodzav) == -1)
            data->zav.plus(kodzav,-1);
        if(data->op.find(kodop) == -1)
            data->op.plus(kodop,-1);

        memset(kodkl,'\0',sizeof(kodkl));
        if(row[4][0] == '\0')
            strcpy(kodkl,"000");
        else
            strncpy(kodkl,row[4],sizeof(kodkl)-1);

//    printf("kolkl=%s\n",kodkl);

        if(data->klient.find(kodkl) == -1)
            data->klient.plus(kodkl);
    }

    sort_vod(&data->vod,data->window);

    data->cur.poz_cursor(0);

    data->vod_zav.make_class(data->zav.kolih()*data->vod.kolih());
    data->op_zav.make_class(data->zav.kolih()*data->op.kolih());

    kolvod=data->vod.kolih();
    data->vod_bp.make_class(kolvod);
    data->vod_pp.make_class(kolvod);
    data->vod_sum_pp.make_class(kolvod);
    data->vod_sum_bp.make_class(kolvod);

    kolklient=data->klient.kolih();
    printf("Количество клиентов=%d\n",kolklient);
    data->kli_kp_o.make_class(kolklient);
    data->kli_kp_b.make_class(kolklient);
    data->sum_op.make_class(kolklient);
    data->sum_bp.make_class(kolklient);

    sprintf(data->imafprot,"vodprot%d.lst",getpid());

    if((data->ffprot = fopen(data->imafprot,"w")) == NULL)
    {
        iceb_er_op_fil(data->imafprot,"",errno,data->window);
        return(FALSE);
    }
    iceb_u_startfil(data->ffprot);

//printf("Просматриваем записи.\n");

    int nomer_vod=0;
    int nomer_kli=0;
    int nomer_zav=0;
    int nomer_op=0;
    int nomer=0;
    int kolzav=data->zav.kolih();
    double suma;
    while(data->cur.read_cursor(&row) != 0)
    {

        iceb_pbar(data->bar,data->kolstr,++data->kolstr1);

        if(iceb_u_proverka(data->kodop.ravno(),row[3],0,0) != 0)
            continue;
        if(iceb_u_proverka(data->kodvod.ravno(),row[1],0,0) != 0)
            continue;
        if(iceb_u_proverka(data->kodzav.ravno(),row[0],0,0) != 0)
            continue;

        if(iceb_u_proverka(data->kodklienta.ravno(),row[4],0,0) != 0)
            continue;

        kodzav=atoi(row[0]);
        kodop=atoi(row[3]);

//  printf("%s %s %s %s\n",row[0],row[1],row[2],row[3]);
        fprintf(data->ffprot,"%s %s %s %s\n",row[0],row[1],row[2],row[3]);

        nomer_op=data->op.find(kodop);
        nomer_zav=data->zav.find(kodzav);
        nomer_vod=data->vod.find(row[1]);

        memset(kodkl,'\0',sizeof(kodkl));
        if(row[4][0] == '\0')
            strcpy(kodkl,"000");
        else
            strncpy(kodkl,row[4],sizeof(kodkl)-1);

        nomer_kli=data->klient.find(kodkl);

        fprintf(data->ffprot,"nomer_op=%d nomer_zav=%d nomer_vod=%d\n",
                nomer_op,nomer_zav, nomer_vod);

        nomer=(nomer_vod*kolzav)+nomer_zav;
        data->vod_zav.plus(1,nomer);

        fprintf(data->ffprot,"nomer=%d\n",nomer);

        nomer=(nomer_op*kolzav)+nomer_zav;
        data->op_zav.plus(1,nomer);
        fprintf(data->ffprot,"nomer=%d\n",nomer);
        suma=atof(row[2]);

        if(kodzav == 1 && row[4][0] != '\0')
        {
            if(suma < 0.)
            {
                data->vod_bp.plus(1,nomer_vod);
                data->vod_sum_bp.plus(suma,nomer_vod);
                if(nomer_kli >= 0)
                {
                    data->kli_kp_b.plus(1,nomer_kli);
                    data->sum_bp.plus(suma,nomer_kli);
                }
            }
            else
            {
                data->vod_pp.plus(1,nomer_vod);
                data->vod_sum_pp.plus(suma,nomer_vod);
                if(nomer_kli >= 0)
                {
                    data->kli_kp_o.plus(1,nomer_kli);
                    data->sum_op.plus(suma,nomer_kli);
                }
            }

        }

    }

//printf("Распечатываем.\n");

    time_t vrem;
    struct tm *bf;
    time(&vrem);
    bf=localtime(&vrem);

    kolvod=data->vod.kolih();
    char naim[100];
    char kodvod[20];
    char gosnomer[20];
    char strsql[300];
    short dlinna=37+(4+1)*(kolzav+1)+1;
    char stroka[dlinna];
    int kolz=0;
    int itogo=0;
    FILE *ff;

    short hasn,minn,sekn;
    short hask,mink,sekk;

    iceb_u_rstime(&hasn,&minn,&sekn,data->vremn.ravno());
    if(data->vremk.getdlinna() <= 1)
    {
        hask=24;
        mink=0;
        sekk=0;
    }
    else
        iceb_u_rstime(&hask,&mink,&sekk,data->vremk.ravno());

//распечатка по водителям

    char imaf[40];

    sprintf(imaf,"vod%d.lst",getpid());
    printf("Имя файла:%s\n",imaf);

    if((ff = fopen(imaf,"w")) == NULL)
    {
        iceb_er_op_fil(imaf,"",errno,data->window);
        return(FALSE);
    }

    iceb_u_startfil(ff);
    fprintf(ff,"\x1B\x4D"); /*12-знаков*/

    fprintf(ff,"\nОтчет по водителям:\n");


    fprintf(ff,"%s %s%s %02d:%02d:%02d %s %s%s %02d:%02d:%02d\n",
            gettext("Период с"),
            data->datn.ravno(),
            gettext("г."),
            hasn,minn,sekn,
            gettext("по"),
            data->datk.ravno(),
            gettext("г."),
            hask,mink,sekk);

    fprintf(ff,"\
%s %d.%d.%d%s  %s:%02d:%02d\n",
            gettext("По состоянию на"),
            bf->tm_mday,bf->tm_mon+1,bf->tm_year+1900,
            gettext("г."),
            gettext("Время"),
            bf->tm_hour,bf->tm_min);
    SQLCURSOR cur;
    if(data->metkarr == 0)
        fprintf(ff,"Отчёт по времени записи.\n");
    if(data->metkarr == 1)
        fprintf(ff,"Отчёт по времени заказа.\n");


//Распечатываем список кодов завершения
    fprintf(ff,"\nСписок кодов завершения:\n");
    for(nomer_zav=0; nomer_zav < kolzav; nomer_zav++)
    {
        kodzav=data->zav.ravno(nomer_zav);
        if(kodzav == 0)
            continue;

        memset(naim,'\0',sizeof(naim));
        sprintf(strsql,"select naik from Taxikzz where kod=%d",kodzav);
        if(sql_readkey(&bd,strsql,&row,&cur) == 1)
            strncpy(naim,row[0],sizeof(naim)-1);
        fprintf(ff,"%d %s\n",kodzav,naim);
    }
    fprintf(ff,"\n");

    if(data->kodvod.getdlinna() > 1)
        fprintf(ff,"Код водителя:%s\n",data->kodvod.ravno());
    if(data->kodop.getdlinna() > 1)
        fprintf(ff,"Код оператора:%s\n",data->kodop.ravno());
    if(data->kodzav.getdlinna() > 1)
        fprintf(ff,"Код завершения:%s\n",data->kodzav.ravno());

    if(data->kodklienta.getdlinna() > 1)
        fprintf(ff,"Код клиента:%s\n",data->kodklienta.ravno());

    memset(stroka,'-',dlinna);
    stroka[dlinna-1]='\0';

    fprintf(ff,"%s\n",stroka);

    fprintf(ff,"\
Код |    Фамилия         | Номер    |");

    for(nomer_zav=0; nomer_zav < kolzav; nomer_zav++)
        fprintf(ff,"%4d|",data->zav.ravno(nomer_zav));
    fprintf(ff,"Итог|\n");

    fprintf(ff,"%s\n",stroka);

    for(nomer_vod=0 ; nomer_vod < kolvod; nomer_vod++)
    {
        strncpy(kodvod,data->vod.ravno(nomer_vod),sizeof(kodvod)-1);

        memset(naim,'\0',sizeof(naim));
        memset(gosnomer,'\0',sizeof(gosnomer));

        sprintf(strsql,"select fio,gosn from Taxivod where kod='%s'",kodvod);

        if(sql_readkey(&bd,strsql,&row,&cur) == 1)
        {
            strncpy(naim,row[0],sizeof(naim)-1);
            strncpy(gosnomer,row[1],sizeof(gosnomer)-1);

        }
        else
            strncpy(naim,"Без водителя",sizeof(naim)-1);

//  printf("%4s %-20.20s %-10.10s\n",kodvod,naim,gosnomer);

        fprintf(ff,"%4s %-20.20s %-10.10s",
                kodvod,naim,gosnomer);
        itogo=0;
        kolz=0;
        for(nomer_zav=0; nomer_zav < kolzav; nomer_zav++)
        {
            kolz=data->vod_zav.ravno((nomer_vod*kolzav)+nomer_zav);
            itogo+=kolz;
            fprintf(ff," %4d",kolz);
        }
        fprintf(ff," %4d\n",itogo);

    }

    fprintf(ff,"%s\n",stroka);
    fprintf(ff,"%36s","Итого");
    itogo=0;
    int itogozav=0;
    for(nomer_zav=0; nomer_zav < kolzav; nomer_zav++)
    {
        itogozav=0;
        for(nomer_vod=0 ; nomer_vod < kolvod; nomer_vod++)
            itogozav+=data->vod_zav.ravno((nomer_vod*kolzav)+nomer_zav);
        fprintf(ff," %4d",itogozav);
        itogo+=itogozav;
    }
    fprintf(ff," %4d\n",itogo);
    fprintf(ff,"%s\n",stroka);

    iceb_podpis(ff,data->window);
    fprintf(ff,"\x1B\x50"); /*10-знаков*/
    fclose(ff);

    char imafvp[30];
    sprintf(imafvp,"vodvp%d.lst",getpid());
    printf("Имя файла:%s\n",imafvp);

    if((ff = fopen(imafvp,"w")) == NULL)
    {
        iceb_er_op_fil(imafvp,"",errno,data->window);
        return(FALSE);
    }

    iceb_u_startfil(ff);
    fprintf(ff,"\x1B\x4D"); /*12-знаков*/

    fprintf(ff,"\nОтчёт по выполненым заказам:\n");
    fprintf(ff,"%s %s%s %02d:%02d:%02d %s %s%s %02d:%02d:%02d\n",
            gettext("Период с"),
            data->datn.ravno(),
            gettext("г."),
            hasn,minn,sekn,
            gettext("по"),
            data->datk.ravno(),
            gettext("г."),
            hask,mink,sekk);

    fprintf(ff,"\
%s %d.%d.%d%s  %s:%02d:%02d\n",
            gettext("По состоянию на"),
            bf->tm_mday,bf->tm_mon+1,bf->tm_year+1900,
            gettext("г."),
            gettext("Время"),
            bf->tm_hour,bf->tm_min);
    if(data->metkarr == 0)
        fprintf(ff,"Отчёт по времени записи.\n");
    if(data->metkarr == 1)
        fprintf(ff,"Отчёт по времени заказа.\n");

    if(data->kodvod.getdlinna() > 1)
        fprintf(ff,"Код водителя:%s\n",data->kodvod.ravno());
    if(data->kodop.getdlinna() > 1)
        fprintf(ff,"Код оператора:%s\n",data->kodop.ravno());
    if(data->kodzav.getdlinna() > 1)
        fprintf(ff,"Код завершения:%s\n",data->kodzav.ravno());

    if(data->kodklienta.getdlinna() > 1)
        fprintf(ff,"Код клиента:%s\n",data->kodklienta.ravno());

    fprintf(ff,"\
-------------------------------------------------------------------------------------------\n\
Код |    Фамилия         | Номер    |Количество| Сумма    |Количество|   Сумма  |К оплате\n\
    |                    |          |платных   | платных  |бесплатных|бесплатных|\n\
-------------------------------------------------------------------------------------------\n");
    itogo=0;
    int kolz1;
    double sum,sum1;
    int itogo1=0;
    double itsum=0.;
    double itsum1=0.;
    double k_oplate;
    double itogo_k_oplate=0.;

    for(nomer_vod=0 ; nomer_vod < kolvod; nomer_vod++)
    {
        strncpy(kodvod,data->vod.ravno(nomer_vod),sizeof(kodvod)-1);
        if(kodvod[0] == '\0')
            continue;
        memset(naim,'\0',sizeof(naim));
        memset(gosnomer,'\0',sizeof(gosnomer));

        sprintf(strsql,"select fio,gosn from Taxivod where kod='%s'",kodvod);

        if(sql_readkey(&bd,strsql,&row,&cur) == 1)
        {
            strncpy(naim,row[0],sizeof(naim)-1);
            strncpy(gosnomer,row[1],sizeof(gosnomer)-1);

        }
        else
            strncpy(naim,"Без водителя",sizeof(naim)-1);

        kolz=data->vod_pp.ravno(nomer_vod);
        kolz1=data->vod_bp.ravno(nomer_vod);
        sum=data->vod_sum_pp.ravno(nomer_vod);
        sum1=data->vod_sum_bp.ravno(nomer_vod);
        itogo+=kolz;
        itogo1+=kolz1;
        itsum+=sum;
        itsum1+=sum1;
//  k_oplate=sum+sum1+kolz1;
        k_oplate=sum+sum1;
        itogo_k_oplate+=k_oplate;
        fprintf(ff,"%4s %-20.20s %-10.10s %10d %10.2f %10d %10.2f %10.2f\n",
                kodvod,naim,gosnomer,kolz,sum,kolz1,sum1,k_oplate);

    }
    fprintf(ff,"\
-------------------------------------------------------------------------------------------\n");
    fprintf(ff,"%36s %10d %10.2f %10d %10.2f %10.2f\n","Итого",itogo,itsum,itogo1,itsum1,itogo_k_oplate);

    iceb_podpis(ff,data->window);

    fprintf(ff,"\x1B\x50"); /*10-знаков*/

    fclose(ff);

    char imafkl[30];
    sprintf(imafkl,"vodkl%d.lst",getpid());
    printf("Имя файла:%s\n",imafkl);

    if((ff = fopen(imafkl,"w")) == NULL)
    {
        iceb_er_op_fil(imafkl,"",errno,data->window);
        return(FALSE);
    }

    iceb_u_startfil(ff);
    fprintf(ff,"\x1B\x4D"); /*12-знаков*/

    fprintf(ff,"\nОтчёт по клиентам:\n");
    fprintf(ff,"%s %s%s %02d:%02d:%02d %s %s%s %02d:%02d:%02d\n",
            gettext("Период с"),
            data->datn.ravno(),
            gettext("г."),
            hasn,minn,sekn,
            gettext("по"),
            data->datk.ravno(),
            gettext("г."),
            hask,mink,sekk);

    fprintf(ff,"\
%s %d.%d.%d%s  %s:%02d:%02d\n",
            gettext("По состоянию на"),
            bf->tm_mday,bf->tm_mon+1,bf->tm_year+1900,
            gettext("г."),
            gettext("Время"),
            bf->tm_hour,bf->tm_min);

    if(data->metkarr == 0)
        fprintf(ff,"Отчёт по времени записи.\n");
    if(data->metkarr == 1)
        fprintf(ff,"Отчёт по времени заказа.\n");

    if(data->kodvod.getdlinna() > 1)
        fprintf(ff,"Код водителя:%s\n",data->kodvod.ravno());
    if(data->kodop.getdlinna() > 1)
        fprintf(ff,"Код оператора:%s\n",data->kodop.ravno());
    if(data->kodzav.getdlinna() > 1)
        fprintf(ff,"Код завершения:%s\n",data->kodzav.ravno());

    if(data->kodklienta.getdlinna() > 1)
        fprintf(ff,"Код клиента:%s\n",data->kodklienta.ravno());

    fprintf(ff,"\
----------------------------------------------------------------------------\n\
   Код    |    Фамилия         |Количество| Сумма    |Количество|   Сумма  |\n\
          |                    |платных   | платных  |бесплатных|бесплатных|\n\
----------------------------------------------------------------------------\n");
    itogo=0;
    itogo1=0;
    itsum=0.;
    itsum1=0.;
    kolklient=data->klient.kolih();
    for(nomer_vod=0 ; nomer_vod < kolklient; nomer_vod++)
    {
        strncpy(kodvod,data->klient.ravno(nomer_vod),sizeof(kodvod)-1);
        if(kodvod[0] == '\0')
            continue;
        memset(naim,'\0',sizeof(naim));

        sprintf(strsql,"select fio from Taxiklient where kod='%s'",kodvod);

        if(sql_readkey(&bd,strsql,&row,&cur) == 1)
        {
            strncpy(naim,row[0],sizeof(naim)-1);
        }
        else
            strncpy(naim,"Не клиент",sizeof(naim)-1);

        kolz=data->kli_kp_o.ravno(nomer_vod);
        kolz1=data->kli_kp_b.ravno(nomer_vod);
        sum=data->sum_op.ravno(nomer_vod);
        sum1=data->sum_bp.ravno(nomer_vod);
        itogo+=kolz;
        itogo1+=kolz1;
        itsum+=sum;
        itsum1+=sum1;

        fprintf(ff,"%10s %-20.20s %10d %10.2f %10d %10.2f\n",
                kodvod,naim,kolz,sum,kolz1,sum1);

    }
    fprintf(ff,"\
----------------------------------------------------------------------------\n");
    fprintf(ff,"%31s %10d %10.2f %10d %10.2f\n","Итого",itogo,itsum,itogo1,itsum1);

    iceb_podpis(ff,data->window);

    fprintf(ff,"\x1B\x50"); /*10-знаков*/

    fclose(ff);



//распечатка по операторам

    char imafop[40];

    sprintf(imafop,"oper%d.lst",getpid());

    if((ff = fopen(imafop,"w")) == NULL)
    {
        iceb_er_op_fil(imafop,"",errno,data->window);
        return(FALSE);
    }
    iceb_u_startfil(ff);
    fprintf(ff,"\x1B\x4D"); /*12-знаков*/
    fprintf(ff,"\nОтчет по операторам:\n");


    fprintf(ff,"%s %s%s %02d:%02d:%02d %s %s%s %02d:%02d:%02d\n",
            gettext("Период с"),
            data->datn.ravno(),
            gettext("г."),
            hasn,minn,sekn,
            gettext("до"),
            data->datk.ravno(),
            gettext("г."),
            hask,mink,sekk);

    fprintf(ff,"\
%s %d.%d.%d%s  %s:%02d:%02d\n",
            gettext("По состоянию на"),
            bf->tm_mday,bf->tm_mon+1,bf->tm_year+1900,
            gettext("г."),
            gettext("Время"),
            bf->tm_hour,bf->tm_min);

    if(data->metkarr == 0)
        fprintf(ff,"Отчёт по времени записи.\n");
    if(data->metkarr == 1)
        fprintf(ff,"Отчёт по времени заказа.\n");

//Распечатываем список кодов завершения
    fprintf(ff,"\nСписок кодов завершения:\n");
    for(nomer_zav=0; nomer_zav < kolzav; nomer_zav++)
    {
        kodzav=data->zav.ravno(nomer_zav);
        if(kodzav == 0)
            continue;

        memset(naim,'\0',sizeof(naim));
        sprintf(strsql,"select naik from Taxikzz where kod=%d",kodzav);
        if(sql_readkey(&bd,strsql,&row,&cur) == 1)
            strncpy(naim,row[0],sizeof(naim)-1);
        fprintf(ff,"%d %s\n",kodzav,naim);
    }
    fprintf(ff,"\n");

    if(data->kodvod.getdlinna() > 1)
        fprintf(ff,"Код водителя:%s\n",data->kodvod.ravno());
    if(data->kodop.getdlinna() > 1)
        fprintf(ff,"Код оператора:%s\n",data->kodop.ravno());
    if(data->kodzav.getdlinna() > 1)
        fprintf(ff,"Код завершения:%s\n",data->kodzav.ravno());
    if(data->kodklienta.getdlinna() > 1)
        fprintf(ff,"Код клиента:%s\n",data->kodklienta.ravno());

    dlinna=26+(4+1)*(kolzav+1)+1;
    memset(stroka,'-',dlinna);
    stroka[dlinna-1]='\0';

    fprintf(ff,"%s\n",stroka);

    fprintf(ff,"\
Код |    Фамилия         |");

    for(nomer_zav=0; nomer_zav < kolzav; nomer_zav++)
        fprintf(ff,"%4d|",data->zav.ravno(nomer_zav));
    fprintf(ff,"Итог|\n");

    fprintf(ff,"%s\n",stroka);

    struct  passwd  *ktoz; /*Кто записал*/
    kolvod=data->op.kolih();
    for(nomer_vod=0 ; nomer_vod < kolvod; nomer_vod++)
    {
        kodop=data->op.ravno(nomer_vod);
        memset(naim,'\0',sizeof(naim));

        if((ktoz=getpwuid(kodop)) != NULL)
            strncpy(naim,ktoz->pw_gecos,sizeof(naim)-1);
        else
            strncpy(naim,gettext("Неизвестный логин"),sizeof(naim)-1);



//  printf("%4d %-20.20s\n",kodop,naim);

        fprintf(ff,"%4d %-20.20s",
                kodop,naim);

        itogo=0;
        kolz=0;
        for(nomer_zav=0; nomer_zav < kolzav; nomer_zav++)
        {
            kolz=data->op_zav.ravno((nomer_vod*kolzav)+nomer_zav);
            itogo+=kolz;
            fprintf(ff," %4d",kolz);
        }
        fprintf(ff," %4d\n",itogo);

    }

    fprintf(ff,"%s\n",stroka);
    fprintf(ff,"%25s","Итого");
    itogo=0;
    itogozav=0;
    for(nomer_zav=0; nomer_zav < kolzav; nomer_zav++)
    {
        itogozav=0;
        for(nomer_vod=0 ; nomer_vod < kolvod; nomer_vod++)
            itogozav+=data->op_zav.ravno((nomer_vod*kolzav)+nomer_zav);
        fprintf(ff," %4d",itogozav);
        itogo+=itogozav;
    }
    fprintf(ff," %4d\n",itogo);
    fprintf(ff,"%s\n",stroka);
    iceb_podpis(ff,data->window);


    fprintf(ff,"\x1B\x50"); /*10-знаков*/
    fclose(ff);


    fclose(data->ffprot);

    data->imafil.plus(imaf);
    data->imafil.plus(imafvp);
    data->imafil.plus(imafkl);
    data->imafil.plus(imafop);
    data->imafil.plus(data->imafprot);
    data->nameoth.plus("Отчет по водителям.");
    data->nameoth.plus("Отчет по водителям по выполненным заказам.");
    data->nameoth.plus("Отчет по клиентам.");
    data->nameoth.plus("Отчет по операторам.");
    data->nameoth.plus("Протокол работы программы.");

    gtk_widget_destroy(data->window);
    return(FALSE);


}
Ejemplo n.º 23
0
int
main (int argc, char *argv[])
{
  WispObject *database;
  int do_long_listing = 0;
  int matches_found = 0;
  int arguments_found = 0;
  char *database_filename = (char *)NULL;

  if (strcmp (argv[0], "rolodex") == 0)
    {
      database_filename = getenv ("ROLODEX");
      if (database_filename == (char *)NULL)
	database_filename = rolodex_file;
    }
  else
    {
      struct passwd *entry;

      entry = getpwuid (getuid ());
      if (entry)
	{
	  database_filename = (char *) xmalloc
	    (strlen (user_file_template) + strlen (entry->pw_dir) + 4);

	  sprintf (database_filename, user_file_template, entry->pw_dir);
	}
    }

  if (!database_filename)
    {
      fprintf (stderr, "Who are you?\n");
      return (-1);
    }

  database = read_database (database_filename);

  while (--argc)
    {
      char *arg = *++argv;

      if (strcmp (arg, "-l") == 0)
	{
	  do_long_listing = 1;
	}
      else
	{
	  WispObject *matches;

	  arguments_found++;
	  matches = find_matches (database, "name:", arg);
	  if (matches != NIL)
	    {
	      matches_found += list_length (matches);
	      print_entries (stdout, matches, do_long_listing);
	    }

	  matches = find_matches (database, "email:", arg);
	  if (matches != NIL)
	    {
	      matches_found += list_length (matches);
	      print_entries (stdout, matches, do_long_listing);
	    }

	  matches = find_matches (database, "e-mail:", arg);
	  if (matches != NIL)
	    {
	      matches_found += list_length (matches);
	      print_entries (stdout, matches, do_long_listing);
	    }
	}
    }

  if (!arguments_found)
    {
      /* Just find birthdays for today's date. */
      WispObject *matches;
      char todays_date[20], yesterdays_date[20], tomorrows_date[20];
      time_t ticks;
      struct tm *now;

      ticks = (time_t)time ((time_t *)NULL);
      now = localtime (&ticks);

      sprintf (todays_date, "%02d/%02d", 1 + now->tm_mon, now->tm_mday);

      ticks -= 60 * 60 * 24;
      now = localtime (&ticks);
      sprintf (yesterdays_date, "%02d/%02d", 1 + now->tm_mon, now->tm_mday);

      ticks += 2 * (60 * 60 * 24);
      now = localtime (&ticks);
      sprintf (tomorrows_date, "%02d/%02d", 1 + now->tm_mon, now->tm_mday);

      matches = find_date_matches (database, "birthday:", todays_date);
      if (matches != NIL)
	{
	  matches_found += list_length (matches);
	  print_entries (stdout, matches, do_long_listing);
	}

      matches = find_date_matches (database, "birthday:", yesterdays_date);
      if (matches != NIL)
	{
	  matches_found += list_length (matches);
	  print_entries (stdout, matches, do_long_listing);
	}

     matches = find_date_matches (database, "birthday:", tomorrows_date);
     if (matches != NIL)
       {
	 matches_found += list_length (matches);
	 print_entries (stdout, matches, do_long_listing);
       }
    }

  return (matches_found != 0);
}
Ejemplo n.º 24
0
/**
 * Whilst the actual mraa init function is now called imraa_init, it's only
 * callable externally if IMRAA is enabled
 */
mraa_result_t
imraa_init()
{
    if (plat != NULL) {
        return MRAA_SUCCESS;
    }
    char* env_var;
    mraa_result_t ret;
    mraa_platform_t platform_type = MRAA_NULL_PLATFORM;
    uid_t proc_euid = geteuid();
    struct passwd* proc_user = getpwuid(proc_euid);

#ifdef DEBUG
    setlogmask(LOG_UPTO(LOG_DEBUG));
#else
    setlogmask(LOG_UPTO(LOG_NOTICE));
#endif

    openlog("libmraa", LOG_CONS | LOG_PID | LOG_NDELAY, LOG_LOCAL1);
    syslog(LOG_NOTICE, "libmraa version %s initialised by user '%s' with EUID %d",
           mraa_get_version(), (proc_user != NULL) ? proc_user->pw_name : "<unknown>", proc_euid);

    // Check to see if the enviroment variable has been set
    env_var = getenv(MRAA_JSONPLAT_ENV_VAR);
    if (env_var != NULL) {
        // We only care about success, the init will write to syslog if things went wrong
        switch ((ret = mraa_init_json_platform(env_var))) {
            case MRAA_SUCCESS:
                platform_type = plat->platform_type;
                break;
            default:
                syslog(LOG_NOTICE, "libmraa was unable to initialise a platform from json");
        }
    }

    // Not an else because if the env var didn't load what we wanted maybe we can still load something
    if (platform_type == MRAA_NULL_PLATFORM) {
#if defined(X86PLAT)
        // Use runtime x86 platform detection
        platform_type = mraa_x86_platform();
#elif defined(ARMPLAT)
        // Use runtime ARM platform detection
        platform_type = mraa_arm_platform();
#elif defined(MOCKPLAT)
        // Use mock platform
        platform_type = mraa_mock_platform();
#else
#error mraa_ARCH NOTHING
#endif
    }

    if (plat != NULL) {
        plat->platform_type = platform_type;
    } else {
        platform_name = NULL;
    }

    // Create null base platform if one doesn't already exist
    if (plat == NULL) {
        plat = (mraa_board_t*) calloc(1, sizeof(mraa_board_t));
        if (plat != NULL) {
            plat->platform_type = MRAA_NULL_PLATFORM;
            plat->platform_name = "Unknown platform";
        }
    }

#if defined(USBPLAT)
    // Now detect sub platform, note this is not an else since we could be in
    // an error case and fall through to MRAA_ERROR_PLATFORM_NOT_INITIALISED
    if (plat != NULL) {
        mraa_platform_t usb_platform_type = mraa_usb_platform_extender(plat);
        // if we have no known platform just replace usb platform with platform
        if (plat->platform_type == MRAA_UNKNOWN_PLATFORM && usb_platform_type != MRAA_UNKNOWN_PLATFORM) {
            plat->platform_type = usb_platform_type;
        }
    }
    if (plat == NULL) {
        printf("mraa: FATAL error, failed to initialise platform\n");
        return MRAA_ERROR_PLATFORM_NOT_INITIALISED;
    }
#endif

#if defined(IMRAA)
    const char* subplatform_lockfile = "/tmp/imraa.lock";
    mraa_add_from_lockfile(subplatform_lockfile);
#endif

    // Look for IIO devices
    mraa_iio_detect();

    if (plat != NULL) {
        int length = strlen(plat->platform_name) + 1;
        if (mraa_has_sub_platform()) {
            // Account for ' + ' chars
            length += strlen(plat->sub_platform->platform_name) + 3;
        }
        platform_name = calloc(length, sizeof(char));
        if (mraa_has_sub_platform()) {
            snprintf(platform_name, length, "%s + %s", plat->platform_name, plat->sub_platform->platform_name);
        } else {
            strncpy(platform_name, plat->platform_name, length);
        }
    }

    lang_func = (mraa_lang_func_t*) calloc(1, sizeof(mraa_lang_func_t));
    if (lang_func == NULL) {
        return MRAA_ERROR_NO_RESOURCES;
    }

    syslog(LOG_NOTICE, "libmraa initialised for platform '%s' of type %d", mraa_get_platform_name(), mraa_get_platform_type());
    return MRAA_SUCCESS;
}
Ejemplo n.º 25
0
/**
 * Redirects the output streams to point to the log file with the given path.
 *
 * @param path specifies the location of log file, may start with ~
 * @param append should be nonzero if it should not truncate the log file.
 */
static int setup_logging(const char *path, int append) {
#ifdef _WIN32
  // Does it start with a tilde?  Perform tilde expansion if so.
  wchar_t pathw[MAX_PATH * 2];
  size_t offset = 0;
  if (path[0] == '~' && (path[1] == 0 || path[1] == '/' || path[1] == '\\')) {
    // Strip off the tilde.
    ++path;

    // Get the home directory path for the current user.
    if (!SUCCEEDED(SHGetFolderPathW(NULL, CSIDL_PROFILE, NULL, 0, pathw))) {
      return 0;
    }
    offset = wcslen(pathw);
  }

  // We need to convert the rest of the path from UTF-8 to UTF-16.
  if (MultiByteToWideChar(CP_UTF8, 0, path, -1, pathw + offset,
                          (int)(_countof(pathw) - offset)) == 0) {
    return 0;
  }

  DWORD access = append ? FILE_APPEND_DATA : (GENERIC_READ | GENERIC_WRITE);
  int creation = append ? OPEN_ALWAYS : CREATE_ALWAYS;
  HANDLE handle = CreateFileW(pathw, access, FILE_SHARE_DELETE | FILE_SHARE_READ,
                              NULL, creation, FILE_ATTRIBUTE_NORMAL, NULL);

  if (handle == INVALID_HANDLE_VALUE) {
    // Make the parent directories first.
    mkdir_parent(pathw);
    handle = CreateFileW(pathw, access, FILE_SHARE_DELETE | FILE_SHARE_READ,
                         NULL, creation, FILE_ATTRIBUTE_NORMAL, NULL);
  }

  if (handle == INVALID_HANDLE_VALUE) {
    return 0;
  }

  if (append) {
    SetFilePointer(handle, 0, NULL, FILE_END);
  }

  SetStdHandle(STD_OUTPUT_HANDLE, handle);
  SetStdHandle(STD_ERROR_HANDLE, handle);

  // If we are running under the UCRT in a GUI application, we can't be sure
  // that we have valid fds for stdout and stderr, so we have to set them up.
  // One way to do this is to reopen them to something silly (like NUL).
  if (_fileno(stdout) < 0) {
    _close(1);
    _wfreopen(L"\\\\.\\NUL", L"w", stdout);
  }

  if (_fileno(stderr) < 0) {
    _close(2);
    _wfreopen(L"\\\\.\\NUL", L"w", stderr);
  }

  // Now replace the stdout and stderr file descriptors with one pointing to
  // our desired handle.
  int fd = _open_osfhandle((intptr_t)handle, _O_WRONLY | _O_TEXT | (append ? _O_APPEND : 0));
  _dup2(fd, _fileno(stdout));
  _dup2(fd, _fileno(stderr));
  _close(fd);

  return 1;
#else
  // Does it start with a tilde?  Perform tilde expansion if so.
  char buffer[PATH_MAX * 2];
  size_t offset = 0;
  if (path[0] == '~' && (path[1] == 0 || path[1] == '/')) {
    // Strip off the tilde.
    ++path;

    // Get the home directory path for the current user.
    const char *home_dir = getenv("HOME");
    if (home_dir == NULL) {
      home_dir = getpwuid(getuid())->pw_dir;
    }
    offset = strlen(home_dir);
    assert(offset < sizeof(buffer));
    strncpy(buffer, home_dir, sizeof(buffer));
  }

  // Copy over the rest of the path.
  strcpy(buffer + offset, path);

  mode_t mode = O_CREAT | O_WRONLY | (append ? O_APPEND : O_TRUNC);
  int fd = open(buffer, mode, 0644);
  if (fd == -1) {
    // Make the parent directories first.
    mkdir_parent(buffer);
    fd = open(buffer, mode, 0644);
  }

  if (fd == -1) {
    perror(buffer);
    return 0;
  }

  fflush(stdout);
  fflush(stderr);

  dup2(fd, 1);
  dup2(fd, 2);

  close(fd);
  return 1;
#endif
}
Ejemplo n.º 26
0
int main(int argc, char **argv, char **envp) {
// the line they enter
	char line[BUFFER_LENGTH];

// the holder for search paths
	char search[MAX_PATHS][MAX_PATH_LEN];
	int path_len = 0;

	register struct passwd *pw;
	register uid_t uid;
	char **env;
	env = envp;

	int dirchange;

	char* pipeptr;
	char* inptr;
	char* outptr;
	char* user;
	Command* basic;
	Command* firstC;
	Command* SecondC;
	char *buffer;

	uid = geteuid();
	pw = getpwuid(uid);
	if (pw) {
		user = pw->pw_name;
	}

// get the host name and put it in a buffer
	char hostname[64];
	hostname[0] = '\0';
	gethostname(hostname, sizeof(hostname));

// retrieve our path and put it into an array of search paths
// not really needed if we're using execvp... oops
	/*char* path;
	 path = getenv("PATH");
	 char* pch = strtok(path, ":");
	 while (pch != NULL) {
	 strcpy(search[path_len], pch);
	 pch = strtok(NULL, ":");
	 path_len++;
	 }*/
	dirchange = -1;
	while (TRUE) {
		printf("%s@%s$ ", pw->pw_name, hostname);
		fflush(stdout);
		
		//Make sure our line/buffer is indeed empty
		memset(line, '\0', sizeof(line));
		
		//Set line to stuff from terminal
		//Also set buffer to alias line
		buffer = accept(line);
		
		//Check for various things in the line
		//to determine what combination of commands to run
		pipeptr = strpbrk(buffer, "|");
		inptr = strpbrk(buffer, "<");
		outptr = strpbrk(buffer, ">");

		//Handle exit command
		if (strncmp(buffer, "exit", 4) == 0
				|| strncmp(buffer, "quit", 4) == 0) {
			return EXIT_SUCCESS;
		}
		
		//Handle CD command
		if (strncmp(buffer, "cd", 2) == 0) {
			change_dir(buffer);
		} else {
			//If we have an inbound redirect, nothing else can happen.
			if (inptr != NULL ) {
				char* pch = strtok(buffer, "<\n");
				char first[256];
				strcpy(first, pch);
				char second[256];
				pch = strtok(NULL, "<\n");
				strcpy(second, pch);

				basic = build_regular_command(first, env);
				execute_redirect_in(&(basic->argv), basic->is_background,
						basic->envv, second);

				memset(first, '\0', sizeof(char) * 256);
				memset(second, '\0', sizeof(char) * 256);
				memset(buffer, '\0', sizeof(buffer));
				free(basic);
				basic = NULL;
			} else {
				//Otherwise, figure out what combo we have and run it.
				if (pipeptr != NULL && outptr != NULL ) {
					//Redirect out AND pipe
					
					//Tokenize once on pipe ( } )
					char* pch = strtok(buffer, "|\n");
					char first[256];
					strcpy(first, pch);
					char second[256];
					pch = strtok(NULL, "|\n");
					strcpy(second, pch);

					char third[256];
					
					//Tokenzie twice on >
					//Being sure to copy stuff to buffers
					//to avoid tampering with the pointer
					pch = strtok(second, ">\n");
					strcpy(third, pch);
					char fourth[256];
					pch = strtok(NULL, ">\n");
					strcpy(fourth, pch);
					
					
					//Build our commands
					firstC = build_regular_command(first, env);

					SecondC = build_regular_command(third, env);
					
					
					//Execute everything
					execute_piped_out_redir(&(firstC->argv),
							firstC->is_background, firstC->envv,
							&(SecondC->argv), SecondC->is_background,
							SecondC->envv, fourth);
							
					//Free and clear stuff
					free(firstC);
					free(SecondC);
					firstC = NULL;
					SecondC = NULL;
					memset(first, '\0', sizeof(char) * 256);
					memset(second, '\0', sizeof(char) * 256);
					memset(third, '\0', sizeof(char) * 256);
					memset(fourth, '\0', sizeof(char) * 256);
					memset(buffer, '\0', sizeof(buffer));
				} else if (pipeptr != NULL && outptr == NULL ) {
					//Just a pipe

					char* pch = strtok(buffer, "|\n");
					char first[256];
					strcpy(first, pch);
					char second[256];
					pch = strtok(NULL, "|\n");
					strcpy(second, pch);
					firstC = build_regular_command(first, env);

					SecondC = build_regular_command(second, env);

					execute_piped(&(firstC->argv), firstC->is_background,
							firstC->envv, &(SecondC->argv),
							SecondC->is_background, SecondC->envv);
					free(firstC);
					free(SecondC);
					firstC = NULL;
					SecondC = NULL;
					memset(first, '\0', sizeof(char) * 256);
					memset(second, '\0', sizeof(char) * 256);
					memset(buffer, '\0', sizeof(buffer));

				} else if (pipeptr == NULL && outptr != NULL ) {

					char* pch = strtok(buffer, ">\n");
					char first[256];
					strcpy(first, pch);
					char second[256];
					pch = strtok(NULL, ">\n");
					strcpy(second, pch);

					basic = build_regular_command(first, env);
					execute_redirect_out(&(basic->argv), basic->is_background,
							basic->envv, second);

					memset(first, '\0', sizeof(char) * 256);
					memset(second, '\0', sizeof(char) * 256);
					memset(buffer, '\0', sizeof(buffer));
					free(basic);
					basic = NULL;

					//Just an outbound redirect
				} else if (pipeptr == NULL && outptr == NULL ) {
					basic = build_regular_command(buffer, env);

					execute(&(basic->argv), basic->is_background, basic->envv);
					memset(basic, 0, sizeof(*basic));
					memset(buffer, '\0', sizeof(buffer));
					free(basic);
					basic = NULL;

				}
			}
		}
		
		//Clear buffer/line again. Just to be sure
		memset(buffer, '\0', sizeof(buffer));
		memset(line, '\0', sizeof(line));

	}
	return EXIT_SUCCESS;
}
Ejemplo n.º 27
0
EIF_POINTER posix_getpwuid(EIF_INTEGER uid)
{
  return getpwuid(uid);
}
Ejemplo n.º 28
0
/*
 * Convert network-name into unix credential
 */
int
netname2user(char netname[MAXNETNAMELEN + 1], uid_t *uidp, gid_t *gidp,
    int *gidlenp, gid_t *gidlist)
{
	char           *p;
	int             gidlen;
	uid_t           uid;
	long		luid;
	struct passwd  *pwd;
	char            val[1024];
	char           *val1, *val2;
	char           *domain;
	int             vallen;
	int             err;

	if (getnetid(netname, val)) {
		char *res = val;

		p = strsep(&res, ":");
		if (p == NULL)
			return (0);
		*uidp = (uid_t) atol(p);
		p = strsep(&res, "\n,");
		if (p == NULL) {
			return (0);
		}
		*gidp = (gid_t) atol(p);
		for (gidlen = 0; gidlen < NGRPS; gidlen++) {
			p = strsep(&res, "\n,");
			if (p == NULL)
				break;
			gidlist[gidlen] = (gid_t) atol(p);
		}
		*gidlenp = gidlen;

		return (1);
	}
	val1 = strchr(netname, '.');
	if (val1 == NULL)
		return (0);
	if (strncmp(netname, OPSYS, (val1-netname)))
		return (0);
	val1++;
	val2 = strchr(val1, '@');
	if (val2 == NULL)
		return (0);
	vallen = val2 - val1;
	if (vallen > (1024 - 1))
		vallen = 1024 - 1;
	(void) strncpy(val, val1, 1024);
	val[vallen] = 0;

	err = __rpc_get_default_domain(&domain);	/* change to rpc */
	if (err)
		return (0);

	if (strcmp(val2 + 1, domain))
		return (0);	/* wrong domain */

	if (sscanf(val, "%ld", &luid) != 1)
		return (0);
	uid = luid;

	/* use initgroups method */
	pwd = getpwuid(uid);
	if (pwd == NULL)
		return (0);
	*uidp = pwd->pw_uid;
	*gidp = pwd->pw_gid;
	*gidlenp = _getgroups(pwd->pw_name, gidlist);
	return (1);
}
Ejemplo n.º 29
0
Archivo: lprm.c Proyecto: OPSF/uClinux
int
main(int argc, char **argv)
{
	struct passwd *pw;
	char *cp;
	long l;
	int ch;

	/*
	 * Simulate setuid daemon w/ PRIV_END called.
	 * We don't want lpr to actually be setuid daemon since that
	 * requires that the lpr binary be owned by user daemon, which
	 * is potentially unsafe.
	 */
	if ((pw = getpwnam(DEFUID)) == NULL)
		errx(1, "'lp' uid not in password file");
	effective_uid = pw->pw_uid;
	real_uid = getuid();
	effective_gid = pw->pw_gid;
	real_gid = getgid();
	setresgid(real_gid, real_gid, effective_gid);
	setresuid(real_uid, real_uid, effective_uid);

	gethostname(host, sizeof(host));
	openlog("lprm", 0, LOG_LPR);
	if ((pw = getpwuid(real_uid)) == NULL)
		fatal("Who are you?");
	if (strlen(pw->pw_name) >= sizeof(luser))
		fatal("Your name is too long");
	strlcpy(luser, pw->pw_name, sizeof(luser));
	person = luser;
	while ((ch = getopt(argc, argv, "P:w:-")) != -1) {
		switch (ch) {
		case '-':
			users = -1;
			break;
		case 'P':
			printer = optarg;
			break;
		case 'w':
			l = strtol(optarg, &cp, 10);
			if (*cp != '\0' || l < 0 || l >= INT_MAX)
				errx(1, "wait time must be postive integer: %s",
				    optarg);
			wait_time = (u_int)l;
			if (wait_time < 30)
				warnx("warning: wait time less than 30 seconds");
			break;
		default:
			usage();
		}
	}
	argc -= optind;
	argv += optind;

	if (printer == NULL && (printer = getenv("PRINTER")) == NULL)
		printer = DEFLP;
	if (users < 0 && argc != 0)
		usage();
	while (argc > 0) {
		if (isdigit(*argv[0])) {
			if (requests >= MAXREQUESTS)
				fatal("Too many requests");
			requ[requests++] = atoi(argv[0]);
		} else {
			if (users >= MAXUSERS)
				fatal("Too many users");
			user[users++] = argv[0];
		}
		argc--;
		argv++;
	}

	rmjob();
	exit(0);
}
Ejemplo n.º 30
0
//-----------------------------------------------------------------------------
// Returns the pathname of the JSON file containing the stored profiles
String GetBaseOVRPath(bool create_dir)
{
    String path;

#if defined(OVR_OS_WIN32)

    TCHAR data_path[MAX_PATH];
    SHGetFolderPath(0, CSIDL_LOCAL_APPDATA, NULL, 0, data_path);
    path = String(data_path);
    
    path += "/Oculus";

    if (create_dir)
    {   // Create the Oculus directory if it doesn't exist
        WCHAR wpath[128];
        OVR::UTF8Util::DecodeString(wpath, path.ToCStr());

        DWORD attrib = GetFileAttributes(wpath);
        bool exists = attrib != INVALID_FILE_ATTRIBUTES && (attrib & FILE_ATTRIBUTE_DIRECTORY);
        if (!exists)
        {   
            CreateDirectory(wpath, NULL);
        }
    }
        
#elif defined(OVR_OS_MAC)

    const char* home = getenv("HOME");
    path = home;
    path += "/Library/Preferences/Oculus";

    if (create_dir)
    {   // Create the Oculus directory if it doesn't exist
        DIR* dir = opendir(path);
        if (dir == NULL)
        {
            mkdir(path, S_IRWXU | S_IRWXG | S_IRWXO);
        }
        else
        {
            closedir(dir);
        }
    }

#else

    passwd* pwd = getpwuid(getuid());
    const char* home = pwd->pw_dir;
    path = home;
    path += "/.config/Oculus";

    if (create_dir)
    {   // Create the Oculus directory if it doesn't exist
        DIR* dir = opendir(path);
        if (dir == NULL)
        {
            mkdir(path, S_IRWXU | S_IRWXG | S_IRWXO);
        }
        else
        {
            closedir(dir);
        }
    }

#endif

    return path;
}