Example #1
0
/*more like canceling threads at the moment, not sure if need to clean up properly*/
void join_threads() {
    void * returns;
    //   char msg[256];
    /*sleep to give threads a chance to clean up a little*/
    sleep(1);

    /*Check to see if this function was called because of sleep T/U */
    if (ops.sleep) {
        record("in ops.sleep\n");

        /*Gracefully close down sci_ti (making sure the shutter is closed)*/
        sciti_alive = 0;
        ops.seq_run = FALSE;
        pthread_cond_broadcast(&lqueue[sequence].cond);
        pthread_join(threads[sci_timeline_thread], NULL);


        img_wr_alive = 0;

        /* Wait until image writer is done saving images*/
        pthread_cond_broadcast(&lqueue[fpga_image].cond);
        pthread_join(threads[image_writer_thread], &returns);
        
        log_backup();
        
        /* Turn off subsytems*/
        set_power(tcs1, ON); // inverse logic for TCS subsystems
        set_power(tcs2, ON);
        set_power(tcs3, ON);
        set_power(shutter, OFF);
        set_power(roe, OFF);
        //set_power(halpha, OFF);
       // set_power(premod, OFF);
        set_power(ps5v, OFF);
        set_power(psdual12v, OFF);
        record("All Subsystems turned off\n");
        
        set_power(11, ON); // hit cc_power
        sleep(1);

//        ts_alive = 0;
//
//        pthread_cond_broadcast(&lqueue[telem_image].cond);
//        pthread_cond_broadcast(&lqueue[scit_image].cond);

        /* Cancel the threads that dont need to be joined*/
        int i;
        for (i = 0; i < num_threads; i++) {
            if (threads[i] != 0) {
                if (i != sci_timeline_thread && i != image_writer_thread) {
                    pthread_cancel(threads[i]);
                }
            }
        }

       
        /* Goodnight MOSES */
        execlp("shutdown", "shutdown", "-h", "now", (char *) 0);

        return;

    } // end if sleep

    int i;
    for (i = 0; i < num_threads; i++) {
        if (threads[i] != 0) {
            pthread_cancel(threads[i]);
        }
    }


}
Example #2
0
int
main(int argc, char *argv[])
{
	struct group	*gp;
	struct passwd	*pw;
	char		*endp, *p, *user, *group, *grouplist;
	const char	*shell;
	gid_t		gid, *gidlist;
	uid_t		uid;
	int		ch, gids;
	long		ngroups_max;

	gid = 0;
	uid = 0;
	user = group = grouplist = NULL;
	while ((ch = getopt(argc, argv, "G:g:u:")) != -1) {
		switch(ch) {
		case 'u':
			user = optarg;
			if (*user == '\0')
				usage();
			break;
		case 'g':
			group = optarg;
			if (*group == '\0')
				usage();
			break;
		case 'G':
			grouplist = optarg;
			if (*grouplist == '\0')
				usage();
			break;
		case '?':
		default:
			usage();
		}
	}
	argc -= optind;
	argv += optind;

	if (argc < 1)
		usage();

	if (group != NULL) {
		if (isdigit((unsigned char)*group)) {
			gid = (gid_t)strtoul(group, &endp, 0);
			if (*endp != '\0')
				goto getgroup;
		} else {
 getgroup:
			if ((gp = getgrnam(group)) != NULL)
				gid = gp->gr_gid;
			else
				errx(1, "no such group `%s'", group);
		}
	}

	ngroups_max = sysconf(_SC_NGROUPS_MAX) + 1;
	if ((gidlist = malloc(sizeof(gid_t) * ngroups_max)) == NULL)
		err(1, "malloc");
	for (gids = 0;
	    (p = strsep(&grouplist, ",")) != NULL && gids < ngroups_max; ) {
		if (*p == '\0')
			continue;

		if (isdigit((unsigned char)*p)) {
			gidlist[gids] = (gid_t)strtoul(p, &endp, 0);
			if (*endp != '\0')
				goto getglist;
		} else {
 getglist:
			if ((gp = getgrnam(p)) != NULL)
				gidlist[gids] = gp->gr_gid;
			else
				errx(1, "no such group `%s'", p);
		}
		gids++;
	}
	if (p != NULL && gids == ngroups_max)
		errx(1, "too many supplementary groups provided");

	if (user != NULL) {
		if (isdigit((unsigned char)*user)) {
			uid = (uid_t)strtoul(user, &endp, 0);
			if (*endp != '\0')
				goto getuser;
		} else {
 getuser:
			if ((pw = getpwnam(user)) != NULL)
				uid = pw->pw_uid;
			else
				errx(1, "no such user `%s'", user);
		}
	}

	if (chdir(argv[0]) == -1 || chroot(".") == -1)
		err(1, "%s", argv[0]);

	if (gids && setgroups(gids, gidlist) == -1)
		err(1, "setgroups");
	if (group && setgid(gid) == -1)
		err(1, "setgid");
	if (user && setuid(uid) == -1)
		err(1, "setuid");

	if (argv[1]) {
		execvp(argv[1], &argv[1]);
		err(1, "%s", argv[1]);
	}

	if (!(shell = getenv("SHELL")))
		shell = _PATH_BSHELL;
	execlp(shell, shell, "-i", (char *)NULL);
	err(1, "%s", shell);
	/* NOTREACHED */
}
Example #3
0
stack_trace_::stack_trace_() {

#if defined(SYSTEM_UNIX) && !defined(SYSTEM_MAC)
	std::string programName = get_program_name();
	std::string pid         = get_pid();

	_stack_trace.push_back(std::string("\t[trace] back trace for ") + programName + " (" + pid + "):");

	// create a pipe to read gdb's output
	int pipefds[2];
	int res = pipe(pipefds);
	if (res < 0)
		return;

	// create a pipe to be used as a barrier
	int barrierfds[2];
	res = pipe(barrierfds);
	if (res < 0)
		return;

	// fork
	int childPid = fork();

	// child:
	if (!childPid) {

		LOG_ALL(tracelog) << "[child] waiting for parent process to allow attaching" << std::endl;

		// close writing end of barrier pipe
		close(barrierfds[1]);

		// wait until parent closes barrier pipe
		char buf[1];
		while (read(barrierfds[0], buf, sizeof(buf)) > 0)
			LOG_ALL(tracelog) << "[child] " << buf[0] << std::endl;

		LOG_ALL(tracelog) << "[child] parent process closed barrier pipe, preparing gdb invocation" << std::endl;

		// close barrier pipe
		close(barrierfds[0]);

		// close reading end of output pipe
		close(pipefds[0]);

		// redirect stdout and stderr to output pipe
		dup2(pipefds[1], 1);
		dup2(pipefds[1], 2);

		// close writing end of pipe (_we_ don't need it any longer)
		close(pipefds[1]);

		// start gdb
		execlp("gdb", "gdb", "--batch", "-n", "-ex", "bt full", programName.c_str(), pid.c_str(), NULL);

	// parent:
	} else {

		LOG_ALL(tracelog) << "[parent] allowing child to attach" << std::endl;

		// allow our child process to attach
		prctl(PR_SET_PTRACER, childPid, 0, 0, 0);

		LOG_ALL(tracelog) << "[parent] closing barrier pipe" << std::endl;

		// close barrier pipe to let child proceed
		close(barrierfds[0]);
		close(barrierfds[1]);

		LOG_ALL(tracelog) << "[parent] barrier pipe closed" << std::endl;

		// close the write end of pipe
		close(pipefds[1]);

		// capture child's output
		std::string output;

		// read the whole output of gdb
		char   buf[1];
		size_t n;
		while ((n = read(pipefds[0], buf, sizeof(buf))))
			output += std::string(buf, n);

		LOG_ALL(tracelog) << "[parent] end of pipe; I read: " << std::endl << output << std::endl;

		// split it at newline characters
		std::stringstream oss(output);
		std::string       line;

		// ignore every line until '#0 ...'
		while (std::getline(oss, line) && (line.size() < 2 || (line[0] != '#' && line[1] != '0')));

		// copy remaining lines to stack trace
		do {

			if (line.size() > 0 && line[0] != '\n')
				_stack_trace.push_back(std::string("\t[trace] ") + line);

		} while (std::getline(oss, line));

		// wait for the child to finish
		waitpid(childPid, NULL, 0);
	}

#endif // SYSTEM_UNIX && !SYSTEM_MAC

	return;
}
Example #4
0
void main()
{
  struct termios buf, back;
  assert(!setvbuf(stdin, NULL, _IONBF, 0));
  assert(!tcgetattr(0, &buf));
  assert(!tcgetattr(0, &back));
  buf.c_lflag &= ~(ECHO|ICANON);
  buf.c_cc[VMIN] = 0;
  buf.c_cc[VTIME] = 0;
  assert(tcsetattr(0, TCSAFLUSH, &buf) >= 0);

  struct timeval z;
  z.tv_sec = 0;
  z.tv_usec = 0;
  fd_set fds;
  srand(time(NULL));
  int i, e, dir;
  ms = newScreen(60, 20);
  bg = newScreen(60, 20);
  moveFood(&f, 1 + rand() % (ms->w - 2), 1 + rand() % (ms->h - 2));
  for(i = 0; i < bg->w; i++)
  {
    set(bg, i, 0, '0');
    set(bg, i, bg->h - 1, '0');
  }
  for(i = 0; i < bg->h; i++)
  {
    set(bg, 0, i, '0');
    set(bg, bg->w - 1, i, '0');
  }
  s.dir = 1;
  s.head = 0;
  s.length = 0;
  add(&s, SNAKESTARTX, SNAKESTARTY);
  
  drawAll();

  while(!gameover)
  {
    FD_ZERO(&fds);
    FD_SET(0, &fds);
    if(select(1, &fds, NULL, NULL, &z))
    {
      switch(getchar())
      {
      case 'w':
	dir = S_UP;
	break;
      case 'd':
	dir = S_RIGHT;
	break;
      case 's':
	dir = S_DOWN;
	break;
      case 'a':
	dir = S_LEFT;
      }
      turn(&s, dir);
      while(1)
      {
	FD_ZERO(&fds);
	FD_SET(0, &fds);
	if(select(1, &fds, NULL, NULL, &z))
	{
	  getchar();
	}
	else
	{
	  break;
	}
      }
    }
    move(&s);
    if(get(ms, s.head->x, s.head->y) == '0')
    {
      gameover = 1;
    }
    if(e = eat(&s, &f))
    {
      for(i = 0; i * i < e; i++);
      score += 1 + (int)(10000 / i);
      f.x = -1;
    }
    drawAll();
    usleep(250000 - 3 * score < 100000 ? 100000 : 250000 - 3 * score);
    score = score + 3;
    if(e)
    {
      while(get(ms, f.x, f.y) != ' ')
      {
	moveFood(&f, 1 + rand() % (ms->w - 2), 1 + rand() % (ms->h - 2));
      }
      set(ms, f.x, f.y, '-');
    }
    draw(ms);
    printf("Length: %d\t\tScore: %d", s.length, score);
    fflush(stdout);
  }
  assert(tcsetattr(0, TCSAFLUSH, &back) >= 0);
  assert((e = fork()) != -1);
  if(e)
  {
    wait(&e);
  }
  else
  {
    execlp("clear", "clear", NULL);
  }
  printf("\n\n\nFinal Length: %d\t\tFinal Score: %d\n\n\n\n\n", s.length, score);
}
Example #5
0
void main(int argc, char** argv)
{
  DIR* d;
  int f;
  struct dirent* entry;
  char name[555];
  char* p;
  int i = 1;
  
  do
  {
    assert((f = fork()) != -1);
    if(!f)
    {
      execlp("clear", "clear", NULL);
      exit(0);
    }
    wait(&f);

    strncpy(name, argc > 1 ? argv[i] : ".", 554);
    assert(d = opendir(name));
    
    if(inRepo(d))
    {
      printf("\tupdating svn of directory %s\n\n", argc > 1 ? argv[i++] : ".");
      assert((f = fork()) != -1);
      if(!f)
      {
	chdir(name);
	execlp("svn", "svn", "update", NULL);
	exit(0);
      }
      else
      {
	wait(&f);
	printf("\n\n");
      }
    }
    else
    {
      printf("\tlooking through subdirectories of %s for svn repositories\n\n", argc > 1 ? argv[i++] : ".");
      
      while(entry = readdir(d))
      {
	if(entry->d_type == DT_DIR && strcmp(entry->d_name, ".") && strcmp(entry->d_name, ".."))
	{
	  assert((f = fork()) != -1);
	  if(!f)
	  {
	    p = name;
	    while(*(++p));
	    if(*(p - 1) != '/')
	    {
	      *(p++) = '/';
	    }
	    strcpy(p, entry->d_name);
	    printf("%s:\n", entry->d_name);
	    chdir(name);
	    closedir(d);
	    assert(d = opendir("."));
	    if(inRepo(d))
	    {
	      execlp("svn", "svn", "update", NULL);
	    }
	    else
	    {
	      printf("Not a repository\n");
	    }
	    exit(0);
	  }
	  else
	  {
	    wait(&f);
	    printf("\n");
	  }
	}
      }
      
      closedir(d);
      printf("\n");
    }
  }
  while(i < argc);
}
Example #6
0
int main(int argc, char** argv)
{
    CSCGlobal::gAgentName = "wttbd";
    int				listenfd, connfd;
    socklen_t		addrlen, len;
    struct sockaddr*	cliaddr;
    char			buff[MAXLINE];
    char			serv[12];
    int				n;
    const int		on = 1;
    struct addrinfo	hints, *res, *ressave;

    // get the config
    CConfig::load();

    // process the version info
    if ((argc == 2) && (strcmp("-v", argv[1]) == 0))
    {
        printf("%s %s\r\n", argv[0], SC_VER_STR);
        exit(0);
    }

    // log startup to syslog
    logToSyslog(WTTBD_IDENT, SC_SYSLOG_TEXT);

    if (argc == 2)
    {
        // default to port .
        strcpy(serv, TCP_PORT_WTTBD_STR);
        daemon_init(argv[0], 0, argv[1]);
    }
    else if (argc == 3)
    {
        // take port from command line
        strcpy(serv, argv[2]);
        daemon_init(argv[0], 0, argv[1]);
    }
    else
    {
        // default to port 4451
        strcpy(serv, TCP_PORT_WTTBD_STR);
        daemon_init(argv[0], 0);
    }

    int fd = 0;
    struct flock locking;

    locking.l_type = F_WRLCK;
    locking.l_whence = SEEK_SET;
    locking.l_start = 1;
    locking.l_len = 0;

    // check to see if already running  - if so exit
    if ( ((fd = open(WTTBD_LOCK_FILE, O_RDWR | O_CREAT, 0666)) == -1) ||
            ((fcntl(fd, F_SETLK, &locking)) == -1) )
    {
        // log startup to syslog
        logToSyslog(WTTBD_IDENT, SC_SYSLOG_RUNNING);
        exit(-1);
    }

    bzero(&hints, sizeof(struct addrinfo));
    hints.ai_flags = AI_PASSIVE;
    hints.ai_family = AF_UNSPEC;
    hints.ai_socktype = SOCK_STREAM;

    if ( (n = getaddrinfo(NULL, serv, &hints, &res)) != 0)
    {
        // log startup to syslog
        logToSyslog(WTTBD_IDENT, gai_strerror(n));
        exit(-1);
    }

    ressave = res;

    do
    {
        listenfd = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
        if (listenfd < 0)
            continue;		/* error, try next one */

        setsockopt(listenfd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));

        if ((n = bind(listenfd, res->ai_addr, res->ai_addrlen)) == 0)
        {
            break;			/* success */
        }
        else if (errno == EINVAL)
        {

            logToSyslog(WTTBD_IDENT, "Exiting - Unable to bind to socket - already in use");
        }

        close(listenfd);	/* bind error, close and try next one */
    }
    while ( (res = res->ai_next) != NULL);

    if (res == NULL)	/* errno from final socket() or bind() */
    {
        logToSyslog(WTTBD_IDENT, "Exiting - No socket to bind to - Process already running.");
        exit(-1);
    }

    listen(listenfd, SC_MAX_LISTENQ);

    freeaddrinfo(ressave);

    addrlen = res->ai_addrlen;	/* size of protocol address */
    cliaddr = (struct sockaddr*)malloc(addrlen);

    // install child signal handler
    signal(SIGCHLD, sig_child);

    for ( ; ; )
    {
        pid_t pid;

        len = addrlen;
        connfd = accept(listenfd, cliaddr, &len);

        if ((pid = fork()) == 0)
        {
            close(listenfd);

            char 	str[128];	/* Unix domain is largest */
            char*   name ;
            name = str;
            std::string log;
            log = "Connection from :";
            log += inet_ntop(AF_INET, &(((sockaddr_in*)cliaddr)->sin_addr), name, sizeof(str));

            logToSyslog(WTTBD_IDENT, log.c_str());

            //****************************
            // do the work here
            //****************************
            char buffer[128];
            int numread = read(connfd, buffer, 127);
            // terminate the buffer
            buffer[numread] = '\0';

            close(connfd);

            // if input value is 0 then just testing to see if alive
            if ((buffer != NULL) && (atol(buffer) == 0))
            {
                exit(0);
            }
            else
            {
                // run the wttt program
                execlp(WTTT_APP_PATH, WTTT_APP, "0", buffer, "3", NULL);
            }

            // cleanup
            exit(0);
        }
        close(connfd);
    }
}
Example #7
0
static void startGUI(const char *directory, const char *dllName, const char *label,
	                 const char *oscUrl, const char *instanceTag)
{
    DBG (oscUrl);

    struct dirent *entry;
    char *dllBase = strdup(dllName);
    char *subpath;
    DIR *subdir;
    char *filename;
    struct stat buf;
    int fuzzy;

    if (strlen(dllBase) > 3 &&
        !strcasecmp(dllBase + strlen(dllBase) - 3, ".so"))
    {
        dllBase[strlen(dllBase) - 3] = '\0';
    }

    if (*dllBase == '/') {
        subpath = dllBase;
        dllBase = strdup(strrchr(subpath, '/') + 1);
    } else {
    	subpath = (char *)malloc(strlen(directory) + strlen(dllBase) + 2);
	    sprintf(subpath, "%s/%s", directory, dllBase);
    }

    for (fuzzy = 0; fuzzy <= 1; ++fuzzy) {

	if (!(subdir = opendir(subpath))) {
		fprintf(stderr, "%s: can't open plugin GUI directory \"%s\"\n", label, subpath);
	    free(subpath);
	    free(dllBase);
	    return;
	}

	while ((entry = readdir(subdir))) {
	    
	    if (entry->d_name[0] == '.') continue;
	    if (!strchr(entry->d_name, '_')) continue;

	    if (fuzzy) {
		    fprintf(stderr, "checking %s against %s\n", entry->d_name, dllBase);
            if (strlen(entry->d_name) <= strlen(dllBase) ||
                strncmp(entry->d_name, dllBase, strlen(dllBase)) ||
                entry->d_name[strlen(dllBase)] != '_')
                continue;
	    } else {
		    fprintf(stderr, "checking %s against %s\n", entry->d_name, label);
            if (strlen(entry->d_name) <= strlen(label) ||
                strncmp(entry->d_name, label, strlen(label)) ||
                entry->d_name[strlen(label)] != '_')
                continue;
	    }
	    
	    filename = (char *)malloc(strlen(subpath) + strlen(entry->d_name) + 2);
	    sprintf(filename, "%s/%s", subpath, entry->d_name);
	    
	    if (stat(filename, &buf)) {
		    perror("stat failed");
		    free(filename);
		    continue;
	    }
	    
	    if ((S_ISREG(buf.st_mode) || S_ISLNK(buf.st_mode)) &&
    		(buf.st_mode & (S_IXUSR | S_IXGRP | S_IXOTH)))
 		{
		    fprintf(stderr, "%s: trying to execute GUI at \"%s\"\n", label, filename);
		
		    if (fork() == 0) {
		        execlp(filename, filename, oscUrl, dllName, label, instanceTag, NULL);
		        perror("exec failed");
		        exit(1);
		    }
		
		    free(filename);
		    free(subpath);
		    free(dllBase);
		    return;
	    }
	    
	    free(filename);
	}
    }

	fprintf(stderr, "no GUI found for plugin \"%s\" in \"%s/\"\n", label, subpath);
    free(subpath);
    free(dllBase);
}
Example #8
0
void runshell_pty( int rd_pipe, int wr_pipe )
{
	/*
	char r_banner[17];
	r_banner[0] = 'r'; r_banner[ 8] = '.';
	r_banner[1] = 'o'; r_banner[ 9] = '3';
	r_banner[2] = 'o'; r_banner[10] = ' ';
	r_banner[3] = 't'; r_banner[11] = 'r';
	r_banner[4] = 'm'; r_banner[12] = 'e';
	r_banner[5] = 'e'; r_banner[13] = 'a';
	r_banner[6] = '-'; r_banner[14] = 'd';
	r_banner[7] = '0'; r_banner[15] = 'y';

	write( wr_pipe, r_banner, 16 );
	*/

    fd_set rfds;
    struct winsize ws;
    int pid, pty, tty, n;
    char *slave, *temp;
    char buffer[4096];

    /* request a pseudo-terminal */

#if defined LINUX || defined FREEBSD || defined OPENBSD || defined OSF

    if( openpty( &pty, &tty, NULL, NULL, NULL ) < 0 )
	{
        return;
	}

    if( ! ( slave = ttyname( tty ) ) )
	{
        return;
	}

#else
#if defined IRIX

    if( ! ( slave = _getpty( &pty, O_RDWR, 0622, 0 ) ) )
	{
        return;
	}

    if( ( tty = open( slave, O_RDWR | O_NOCTTY ) ) < 0 )
	{
        return;
	}

#else
#if defined CYGWIN || defined SUNOS || defined HPUX

    if( ( pty = open( "/dev/ptmx", O_RDWR | O_NOCTTY ) ) < 0 )
	{
        return;
	}

    if( grantpt( pty ) < 0 )
	{
        return;
	}

    if( unlockpt( pty ) < 0 )
	{
        return;
	}

    if( ! ( slave = ptsname( pty ) ) )
	{
        return;
	}

    if( ( tty = open( slave, O_RDWR | O_NOCTTY ) ) < 0 )
	{
        return;
	}

#if defined SUNOS || defined HPUX

    if( ioctl( tty, I_PUSH, "ptem" ) < 0 )
        return;

    if( ioctl( tty, I_PUSH, "ldterm" ) < 0 )
        return;

#if defined SUNOS

    if( ioctl( tty, I_PUSH, "ttcompat" ) < 0 )
        return;

#endif
#endif
#endif
#endif
#endif

    /* get the window size and TERM variable */

    memset( buffer, 0, sizeof( buffer ) );

    if( ( n = read( rd_pipe, buffer, 64 ) ) != 64 )
	{
        return;
	}

    ws.ws_row = ( (int) buffer[0] << 8 ) + (int) buffer[1];
    ws.ws_col = ( (int) buffer[2] << 8 ) + (int) buffer[3];

    ws.ws_xpixel = 0;
    ws.ws_ypixel = 0;

    if( ioctl( pty, TIOCSWINSZ, &ws ) < 0 )
	{
        return;
	}

    if( ! ( temp = (char *) malloc( 66 ) ) )
        return;

    temp[0] = 'T'; temp[3] = 'M';
    temp[1] = 'E'; temp[4] = '=';
    temp[2] = 'R';

    strncpy( temp + 5, buffer + 4, 61 );

    putenv( temp );

    /* fork to spawn a shell */

    if( ( pid = fork() ) < 0 )
	{
        return;
	}

    if( ! pid )
    {
        close( pty );

        if( setsid() < 0 )
            return;

        /* set controlling tty, to have job control */

#if defined LINUX || defined FREEBSD || defined OPENBSD || defined OSF

        if( ioctl( tty, TIOCSCTTY, NULL ) < 0 )
            return;

#else
#if defined CYGWIN || defined SUNOS || defined IRIX || defined HPUX

        {
            int fd = open( slave, O_RDWR );
            if( fd < 0 ) return;
            close( tty );
            tty = fd;
        }

#endif
#endif

        /* tty becomes stdin, stdout, stderr */

        dup2( tty, 0 );
        dup2( tty, 1 );
        dup2( tty, 2 );

        if( tty > 2 ) close( tty );

        /* just in case bash is run, kill the history file */

        if( ! ( temp = (char *) malloc( 10 ) ) )
            return;

        temp[0] = 'H'; temp[5] = 'I';
        temp[1] = 'I'; temp[6] = 'L';
        temp[2] = 'S'; temp[7] = 'E';
        temp[3] = 'T'; temp[8] = '=';
        temp[4] = 'F'; temp[9] = '\0';

        putenv( temp );

        /* set HOME to "/var/tmp" */

        if( ! ( temp = (char *) malloc( 14 ) ) )
            return;

        temp[0] = 'H'; temp[ 7] = 'a';
        temp[1] = 'O'; temp[ 8] = 'r';
        temp[2] = 'M'; temp[ 9] = '/';
        temp[3] = 'E'; temp[10] = 't';
        temp[4] = '='; temp[11] = 'm';
        temp[5] = '/'; temp[12] = 'p';
        temp[6] = 'v'; temp[13] = '\0';

        putenv( temp );
        chdir( temp + 5 );

        /* fire up the shell */

        buffer[0] = 'b'; buffer[2] = 's';
        buffer[1] = 'a'; buffer[3] = 'h';
        buffer[4] = '\0';
        execlp( buffer, HIDE_SHELL, (char *) 0 );

        buffer[0] = '/'; buffer[4] = '/';
        buffer[1] = 'b'; buffer[5] = 's';
        buffer[2] = 'i'; buffer[6] = 'h';
        buffer[3] = 'n'; buffer[7] = '\0';
        execlp( buffer, HIDE_SHELL, (char *) 0 );

        return;
    }

    /* tty (slave side) not needed anymore */

    close( tty );

    /* let's forward the data back and forth */

    while( 1 )
    {
        FD_ZERO( &rfds );
        FD_SET( rd_pipe, &rfds );
        FD_SET( pty, &rfds );

        n = ( pty > rd_pipe ) ? pty : rd_pipe;

        if( select( n + 1, &rfds, NULL, NULL, NULL ) < 0 )
            break;

        if( FD_ISSET( rd_pipe, &rfds ) )
        {
            n = read( rd_pipe, buffer, sizeof( buffer ) );

            if( n <= 0 ) break;

            if( write( pty, buffer, n ) != n )
                break;
        }

        if( FD_ISSET( pty, &rfds ) )
        {
            n = read( pty, buffer, sizeof( buffer ) );

            if( n <= 0 ) break;

            if( write( wr_pipe, buffer, n ) != n )
                break;
        }
    }
	kill(pid, 9);

	int status;
	wait(&status);

    return;
}
Example #9
0
int main(){
	execlp("l33t", "l33t", (char*)0);
	return 0;
}
Example #10
0
int main()
{

/*
	variaveis do socket
ptr*/
    int socket_des, *newSock, fromlen, tamanho_cliente, proc_filho, mem_id, ptr_mem, mem_aut, ptr_aut; //
    struct sockaddr_in servidor, sock_cli;
/*
	variavel mensagem que sera utilizado para escrita no socket
*/
    //int ultimoUser = 0;
/*
	inicializa em 1 o semaforo, verifica se inicializou com sucesso
*/

    if (sem_init(&semAutenticador, 1, 1) < 0)
    {
        printf("Erro ao inicializar o semáforo do autenticador.\n");
        exit(0);
    }
    if (sem_init(&semClienteCopiar, 1, 1) < 0)
    {
        printf("Erro ao iniciar o semáforo copiar\n");
        exit(0);
    }
    if (sem_init(&semClienteMover, 1, 1) < 0)
    {
        printf("Erro ao iniciar o semáforo mover\n");
        exit(0);
    }
    if (sem_init(&semClienteRemover, 1, 1) < 0)
    {
        printf("Erro ao iniciar o semáforo remover\n");
        exit(0);
    }


/*
	 socket() - cria o socket
     AF_INET - domínio do socket (internet).
     SOCK_STREAM - tipo de socket
     0 - protocolo de com. (IP)
*/
    if ((socket_des = socket(AF_INET, SOCK_STREAM, 0)) < 0)
    {
        fprintf(stderr, "Erro ao criar o socket do servidor\n");
        exit(0);
    }

    int x = 1;

    // Sobreescrever quem estiver usando o IP e porta que serão utilizados no código.
    if (setsockopt(socket_des, SOL_SOCKET, SO_REUSEADDR, &x, sizeof(int)) < 0)
        printf("setsockopt(SO_REUSEADDR) failed");

/*
 	Atribuição das características do socket.
*/
    servidor.sin_family = AF_INET;
    servidor.sin_port = htons(2000);
    servidor.sin_addr.s_addr = htonl(INADDR_ANY);
    bzero(&(servidor.sin_zero), 8);
/*
 	Relaciona o descritor a referência da struct.
*/
    if (bind(socket_des, (struct sockaddr *) &servidor, sizeof(servidor)) < 0)
    {
        printf("PROBLEMA: %s\n", strerror(errno));
        fprintf(stderr, "Erro de bind\n");
        close(socket_des);  // Fecha
        exit(0);
    }


/*
	Criacao da area de memoria compartilhada
	shmget = criação de uma área de memória compartilhada
	shmat = mapeamento de uma área de memória compartilhada

*/

    /**
     * Criação da memória compartilhada que será usada para controlar o acesso ao pipe do autenticador.
     * */

    mem_aut = shmget(CHAVE_MEMORIA_AUTENTICADOR, sizeof(sem_t), 0777 | IPC_CREAT);

    if (mem_aut < 0)
    {
        printf("Erro ao criar memória criada para o autenticador");
        exit(0);
    }

    ptrSemAutenticador = (sem_t *) shmat(mem_aut, (char *) 0, 0);

    if (ptrSemAutenticador == NULL)
    {
        printf("Erro no mapeamento de memória...\n");
        exit(0);
    }

    printf("%p\t%p\n", ptrSemAutenticador, &semAutenticador);
    *ptrSemAutenticador = semAutenticador;
    printf("Endereço do semáforo: %p\n\n", ptrSemAutenticador);

    printf("...\n");

/*
    Habilita o serv. para receber até 10 conexões.
    socket_des - socket
    10 - nº máximo de conexões.
*/
    if (listen(socket_des, 10) < 0)
    {
        fprintf(stderr, "Erro de listen\n");
        exit(0);
    }

    printf("Servidor pronto para conexoes...\n");
    // sem_init(&s_servidor, 0, 1);

    printf("%d\t", unlink("pipe.servidor"));
    printf("%d\n", unlink("pipe.autenticador"));

    if (mkfifo("pipe.servidor", 0777) < 0)
    {
        printf("Erro ao criar pipe do servidor...\n");
        exit(0);
    }

    if (mkfifo("pipe.autenticador", 0777) < 0)
    {
        printf("Erro ao criar pipe do cliente...\n");
        exit(0);
    }

    printf("pipe criado\n");

    int pid = fork();

    if (pid < 0)
    {
        printf("SERVER: erro no fork");
        exit(0);
    }
    else if (pid == 0)
    {
        printf("SERVER: filho\n");
        printf("SERVER: Exec %d\n", execlp("./user_db", "./user_db", NULL));
        printf("SERVER: depois exec\n");
    }

    printf("SERVER: iniciando...\n");

/**
* Criação do diretório raiz do sistema.
*/
    criaDir("root", &root);

    printf("Endereco do diretorio raiz %p\n", root);
    while (1)
    {/*
        listaSubDir(ptrRaiz);
        listaArquivo(ptrRaiz);*/
        printf("SERVER: A espera de conexões...\n");

        fromlen = sizeof(sock_cli); // Tamanho da struct do cliente
        if ((sock_des_cli = accept(socket_des, (struct sockaddr *) &sock_cli,
                                   (socklen_t *) &fromlen)) < 0)
        {
            fprintf(stderr, "Erro de conexao...\n");
            exit(0);
        }

        printf("------------------------------------------\n");
        printf("conexao aceita\n");

        newSock = (int *) malloc(sizeof(int));

        *newSock = sock_des_cli;
        printf("sock: %d\t%d\n", *newSock, sock_des_cli);
        pthread_t new_connection_tid;
        pthread_create(&new_connection_tid, NULL, TrataConexao, (void *) newSock);

    }
}
Example #11
0
int main(int argc, char *argv[])
{
    //IP part
    struct hostent *hptr;
    struct in_addr addr;
    socklen_t len;
    int type;
    int version_check=0;
    int result=0;
    char **pptr;
    char str[INET_ADDRSTRLEN];
    char servicebuf[MAXLINE];
    
    //child variable
    //pipe variable
    pid_t pid, childpid;
    int stat;
    int pfd[2];
    int readresult;
    char buf[SIZE];
    char buf2[SIZE];
    
    if(argc==2)
    {
        hptr=gethostbyname(argv[1]);
        if (hptr==NULL) {
            //err_msg("gethostbyname error for host: %s: %s",argv[1],hstrerror(h_errno));
            printf("host name is not exist\n");
        }
        else
        {
            printf("Official Host %s\n", hptr->h_name);
            for (pptr=hptr->h_aliases; *pptr!=NULL; pptr++) {
                printf("\talias : %s\n",*pptr);
            }
            if (hptr->h_addrtype==AF_INET)
            {
                pptr=hptr->h_addr_list;
                for (; *pptr!=NULL; pptr++)
                {
                    printf("\taddress : %s\n",inet_ntop(AF_INET, *pptr, str, sizeof(str)));
                }
            }
            else
            {
                // err_ret("unknow address type");
                printf("unknow address type\n");
            }
        }
    }
    else if (argc==3)
    {
        if (strcasecmp(argv[2], "af_inet")==0) {
            type=AF_INET;
            len=4;
            version_check=0;
        }
        else if(strcasecmp(argv[2],"af_inet6")==0)
        {
            type=AF_INET6;
            len=16;
            version_check=1;
        }
        else
        {
            printf("type wrong format in cmd\n");
            //return 0;
        }
        if (version_check==0) {
            addr.s_addr=inet_addr(argv[1]);
            hptr=gethostbyaddr((char*)&addr, len, type);
        }
        if (version_check==1) {
            result=inet_pton(AF_INET6, argv[1], &addr);
            if (result==0) {
                printf("the ipv6 addrss should be an legal address\n");
                //return 0;
            }
            else
            {
                hptr=gethostbyaddr((char*)&addr, len, type);
            }
        }
        printf("host : %s length %d\n",argv[1],len);
        printf("address type : %d\n", type);
        if(hptr==NULL)
        {
            printf("ip address is not exist\n");
            
        }
        if(hptr!=NULL)
        {
            printf("host name: %s\n", hptr->h_name);
        }
        //return 0;
    }
    else
    {
        printf("The format should be like:%s <IP_ADDRESS> <af_inet|af_inet6>\n",argv[0]);
        //return 0;
    }
    for (; ; )
    {
        printf("choose the service type: echo/time\n");
        if(gets(servicebuf)==NULL)
        {
            printf("error: %s\n", strerror(errno));
        }
        else
        {
            if(strcasecmp((servicebuf),"echo")==0)
            {
                childpid=fork();
                if(pipe(pfd)==-1)
                {
                    printf("pipe failed\n");
                    exit(1);
                }
                else
                {
                    printf("pipe successed\n");
                }
                if(childpid>=0)
                {
                    printf("fork successfully\n");
                    if(childpid==0)
                    {
                        printf("In echo child process,child pid : %d\n",childpid);
                        // child pipe part
                        close(pfd[0]);
                        sprintf(buf2,"%i",pfd[1]);
                        if ( (execlp("xterm", "xterm", "-e", "./echo2","130.245.1.44",buf2,(char *) 0)) < 0)
                        {
                            printf("error: %s \n", strerror(errno));
                            
                            exit(1);
                        }
                        close(pfd[1]);
                    }
                    if(childpid>0)
                    {
                        printf("in parent process\n");
                        //parent pipe part
                        close(pfd[1]);
                        readresult=read(pfd[0],buf2,SIZE);
                        if(readresult==-1)
                        {
                            printf("read error\n");
                            exit(1);
                        }
                        if(readresult==0)
                        {
                            //printf("no process has pipe back to parents\n");
                            //exit(1);
                        }
                        if(readresult!=-1&&readresult!=0)
                        {
                            printf("test %s\n",buf2);
                            close(pfd[0]);
                        }
                    }
                    pid=wait(&stat);
                    printf("child terminated\n");
                }
                if(childpid<0)
                {
                    printf("fork failed\n");
                }
            }
            else if(strcasecmp((servicebuf),"time")==0)
            {
                childpid=fork();
                if (pipe(pfd)==-1) {
                    printf("pipe failed");
                    exit(1);
                }
                if(childpid>=0)
                {
                    printf("fork successfully\n");
                    if(childpid==0)
                    {
                        printf("In time child process,child pid: %d\n",childpid);
                        if((execlp("xterm","xterm","-e","./time","130.245.1.44",(char *)0))<0)
                        {
                            printf("error: %s \n", strerror(errno));
                            exit(1);
                        }
                        pid=wait(&stat);
                        printf("child terminated");
                        
                    }
                    if(childpid>0)
                    {
                        printf("in parent process\n");
                    }
                    if(childpid<0)
                    {
                        printf("fork failed\n");
                    }
                }

            }
            else
            {
                printf("no such service\n");
            }

        }
        
    }
}
Example #12
0
int
main(int argc, char **argv)
{
    char *namep;
    int pflag = 0, hflag = 0, t, f, c;
    int invalid, quietlog;
    FILE *nlfd;
    char *ttyn, *tty;
    int ldisc = 0, zero = 0, i;
    char **envnew;

#ifdef	AFS_AIX32_ENV
    /*
     * The following signal action for AIX is necessary so that in case of a
     * crash (i.e. core is generated) we can include the user's data section
     * in the core dump. Unfortunately, by default, only a partial core is
     * generated which, in many cases, isn't too useful.
     */
    struct sigaction nsa;

    sigemptyset(&nsa.sa_mask);
    nsa.sa_handler = SIG_DFL;
    nsa.sa_flags = SA_FULLDUMP;
    sigaction(SIGSEGV, &nsa, NULL);
#endif
    signal(SIGALRM, timedout);
    alarm(timeout);
    signal(SIGQUIT, SIG_IGN);
    signal(SIGINT, SIG_IGN);
    setpriority(PRIO_PROCESS, 0, 0);
    quota(Q_SETUID, 0, 0, 0);

    /* create a dummy user */
    memset(&nouser, 0, sizeof(nouser));
    nouser.pw_name = "";
    nouser.pw_passwd = "*";
    nouser.pw_dir = nouser.pw_shell = "";
    nouser.pw_uid = nouser.pw_gid = -1;

    /*
     * -p is used by getty to tell login not to destroy the environment
     * -r is used by rlogind to cause the autologin protocol;
     * -h is used by other servers to pass the name of the
     * remote host to login so that it may be placed in utmp and wtmp
     */
    while (argc > 1) {
	if (strcmp(argv[1], "-r") == 0) {
	    if (rflag || hflag) {
		printf("Only one of -r and -h allowed\n");
		exit(1);
	    }
	    rflag = 1;
	    usererr = doremotelogin(argv[2]);
	    SCPYN(utmp.ut_host, argv[2]);
	    argc -= 2;
	    argv += 2;
	    continue;
	}
	if (strcmp(argv[1], "-h") == 0 && getuid() == 0) {
	    if (rflag || hflag) {
		printf("Only one of -r and -h allowed\n");
		exit(1);
	    }
	    hflag = 1;
	    SCPYN(utmp.ut_host, argv[2]);
	    argc -= 2;
	    argv += 2;
	    continue;
	}
	if (strcmp(argv[1], "-p") == 0) {
	    argc--;
	    argv++;
	    pflag = 1;
	    continue;
	}
	break;
    }
    ioctl(0, TIOCLSET, &zero);
    ioctl(0, TIOCNXCL, 0);
    ioctl(0, FIONBIO, &zero);
    ioctl(0, FIOASYNC, &zero);
    ioctl(0, TIOCGETP, &ttyb);
    /*
     * If talking to an rlogin process,
     * propagate the terminal type and
     * baud rate across the network.
     */
    if (rflag)
	doremoteterm(term, &ttyb);
    ttyb.sg_erase = CERASE;
    ttyb.sg_kill = CKILL;
    ioctl(0, TIOCSLTC, &ltc);
    ioctl(0, TIOCSETC, &tc);
    ioctl(0, TIOCSETP, &ttyb);
    for (t = getdtablesize(); t > 2; t--)
	close(t);
    ttyn = ttyname(0);
    if (ttyn == (char *)0 || *ttyn == '\0')
	ttyn = "/dev/tty??";
    tty = strrchr(ttyn, '/');
    if (tty == NULL)
	tty = ttyn;
    else
	tty++;
    openlog("login", LOG_ODELAY, LOG_AUTH);
    t = 0;
    invalid = FALSE;
    do {
	ldisc = 0;
	ioctl(0, TIOCSETD, &ldisc);
	SCPYN(utmp.ut_name, "");
	/*
	 * Name specified, take it.
	 */
	if (argc > 1) {
	    SCPYN(utmp.ut_name, argv[1]);
	    argc = 0;
	}
	/*
	 * If remote login take given name,
	 * otherwise prompt user for something.
	 */
	if (rflag && !invalid)
	    SCPYN(utmp.ut_name, lusername);
	else
	    getloginname(&utmp);
	invalid = FALSE;
	if (!strcmp(pwd->pw_shell, "/bin/csh")) {
	    ldisc = NTTYDISC;
	    ioctl(0, TIOCSETD, &ldisc);
	}
	/*
	 * If no remote login authentication and
	 * a password exists for this user, prompt
	 * for one and verify it.
	 */
	if (usererr == -1 && *pwd->pw_passwd != '\0') {
#ifdef KAUTH
	    char password[BUFSIZ];
	    char *reason;
	    if (ka_UserReadPassword
		("Password:", password, sizeof(password), &reason)) {
		printf("Unable to login because %s,\n", reason);
		invalid = TRUE;
	    } else
		if (ka_UserAuthenticate
		    (pwd->pw_name, /*inst */ 0, /*realm */ 0, password,
		     /*sepag */ 1, &reason)) {
		printf("Unable to authenticate to AFS because %s.\n", reason);
		printf("  proceeding with local authentication... \n");
		/* try local login */
		namep = crypt(password, pwd->pw_passwd);
		if (strcmp(namep, pwd->pw_passwd))
		    invalid = TRUE;
	    }
#else
	    char *pp;
	    setpriority(PRIO_PROCESS, 0, -4);
	    pp = getpass("Password:");
	    namep = crypt(pp, pwd->pw_passwd);
	    setpriority(PRIO_PROCESS, 0, 0);
	    if (strcmp(namep, pwd->pw_passwd))
		invalid = TRUE;
#endif
	}
	/*
	 * If user not super-user, check for logins disabled.
	 */
	if (pwd->pw_uid != 0 && (nlfd = fopen(nolog, "r")) != 0) {
	    while ((c = getc(nlfd)) != EOF)
		putchar(c);
	    fflush(stdout);
	    sleep(5);
	    exit(0);
	}
	/*
	 * If valid so far and root is logging in,
	 * see if root logins on this terminal are permitted.
	 */
	if (!invalid && pwd->pw_uid == 0 && !rootterm(tty)) {
	    if (utmp.ut_host[0])
		syslog(LOG_CRIT, "ROOT LOGIN REFUSED ON %s FROM %.*s", tty,
		       HMAX, utmp.ut_host);
	    else
		syslog(LOG_CRIT, "ROOT LOGIN REFUSED ON %s", tty);
	    invalid = TRUE;
	}
	if (invalid) {
	    printf("Login incorrect\n");
	    if (++t >= 5) {
		if (utmp.ut_host[0])
		    syslog(LOG_CRIT,
			   "REPEATED LOGIN FAILURES ON %s FROM %.*s, %.*s",
			   tty, HMAX, utmp.ut_host, NMAX, utmp.ut_name);
		else
		    syslog(LOG_CRIT, "REPEATED LOGIN FAILURES ON %s, %.*s",
			   tty, NMAX, utmp.ut_name);
		ioctl(0, TIOCHPCL, NULL);
		close(0), close(1), close(2);
		sleep(10);
		exit(1);
	    }
	}
	if (*pwd->pw_shell == '\0')
	    pwd->pw_shell = "/bin/sh";
	if (chdir(pwd->pw_dir) < 0 && !invalid) {
	    if (chdir("/") < 0) {
		printf("No directory!\n");
		invalid = TRUE;
	    } else {
		printf("No directory! %s\n", "Logging in with home=/");
		pwd->pw_dir = "/";
	    }
	}
	/*
	 * Remote login invalid must have been because
	 * of a restriction of some sort, no extra chances.
	 */
	if (!usererr && invalid)
	    exit(1);
    } while (invalid);
/* committed to login turn off timeout */
    alarm(0);

    if (quota(Q_SETUID, pwd->pw_uid, 0, 0) < 0 && errno != EINVAL) {
	if (errno == EUSERS)
	    printf("%s.\n%s.\n", "Too many users logged on already",
		   "Try again later");
	else if (errno == EPROCLIM)
	    printf("You have too many processes running.\n");
	else
	    perror("quota (Q_SETUID)");
	sleep(5);
	exit(0);
    }
    time(&utmp.ut_time);
    t = ttyslot();
    if (t > 0 && (f = open("/etc/utmp", O_WRONLY)) >= 0) {
	lseek(f, (afs_int32) (t * sizeof(utmp)), 0);
	SCPYN(utmp.ut_line, tty);
	write(f, (char *)&utmp, sizeof(utmp));
	close(f);
    }
    if ((f = open("/usr/adm/wtmp", O_WRONLY | O_APPEND)) >= 0) {
	write(f, (char *)&utmp, sizeof(utmp));
	close(f);
    }
    quietlog = access(qlog, F_OK) == 0;
    if ((f = open(lastlog, O_RDWR)) >= 0) {
	struct lastlog ll;

	lseek(f, (afs_int32) pwd->pw_uid * sizeof(struct lastlog), 0);
	if (read(f, (char *)&ll, sizeof ll) == sizeof ll && ll.ll_time != 0
	    && !quietlog) {
	    printf("Last login: %.*s ", 24 - 5, (char *)ctime(&ll.ll_time));
	    if (*ll.ll_host != '\0')
		printf("from %.*s\n", sizeof(ll.ll_host), ll.ll_host);
	    else
		printf("on %.*s\n", sizeof(ll.ll_line), ll.ll_line);
	}
	lseek(f, (afs_int32) pwd->pw_uid * sizeof(struct lastlog), 0);
	time(&ll.ll_time);
	SCPYN(ll.ll_line, tty);
	SCPYN(ll.ll_host, utmp.ut_host);
	write(f, (char *)&ll, sizeof ll);
	close(f);
    }
    chown(ttyn, pwd->pw_uid, TTYGID(pwd->pw_gid));
    if (!hflag && !rflag)	/* XXX */
	ioctl(0, TIOCSWINSZ, &win);
    chmod(ttyn, 0620);
    setgid(pwd->pw_gid);
    strncpy(name, utmp.ut_name, NMAX);
    name[NMAX] = '\0';
    initgroups(name, pwd->pw_gid);
    quota(Q_DOWARN, pwd->pw_uid, (dev_t) - 1, 0);
    setuid(pwd->pw_uid);
    /* destroy environment unless user has asked to preserve it */
    if (!pflag)
	environ = envinit;

    /* set up environment, this time without destruction */
    /* copy the environment before setenving */
    i = 0;
    while (environ[i] != NULL)
	i++;
    envnew = malloc(sizeof(char *) * (i + 1));
    for (; i >= 0; i--)
	envnew[i] = environ[i];
    environ = envnew;

    setenv("HOME=", pwd->pw_dir, 1);
    setenv("SHELL=", pwd->pw_shell, 1);
    if (term[0] == '\0')
	strncpy(term, stypeof(tty), sizeof(term));
    setenv("TERM=", term, 0);
    setenv("USER=", pwd->pw_name, 1);
    setenv("PATH=", ":/usr/ucb:/bin:/usr/bin", 0);

    if ((namep = strrchr(pwd->pw_shell, '/')) == NULL)
	namep = pwd->pw_shell;
    else
	namep++;
    strcat(minusnam, namep);
    if (tty[sizeof("tty") - 1] == 'd')
	syslog(LOG_INFO, "DIALUP %s, %s", tty, pwd->pw_name);
    if (pwd->pw_uid == 0)
	if (utmp.ut_host[0])
	    syslog(LOG_NOTICE, "ROOT LOGIN %s FROM %.*s", tty, HMAX,
		   utmp.ut_host);
	else
	    syslog(LOG_NOTICE, "ROOT LOGIN %s", tty);
    if (!quietlog) {
	struct stat st;

	showmotd();
	strcat(maildir, pwd->pw_name);
	if (stat(maildir, &st) == 0 && st.st_size != 0)
	    printf("You have %smail.\n",
		   (st.st_mtime > st.st_atime) ? "new " : "");
    }
    signal(SIGALRM, SIG_DFL);
    signal(SIGQUIT, SIG_DFL);
    signal(SIGINT, SIG_DFL);
    signal(SIGTSTP, SIG_IGN);
    execlp(pwd->pw_shell, minusnam, 0);
    perror(pwd->pw_shell);
    printf("No shell\n");
    exit(0);
}
Example #13
0
int
edit_entry (const char *datafile, long pos)
{
  FILE *fp = NULL;
  char filename[PATH_MAX];
  pid_t process_id = 0;
  int status = 0;
  struct stat sb;
  time_t modified_time = 0;
  vc_component *v = NULL;
  int ret_val = -1;

  /* retrieve the entry for editing */
  fp = fopen (datafile, "r");
  fseek (fp, pos, SEEK_SET);
  v = parse_vcard_file (fp);
  fclose (fp);
  fp = NULL;

  /* open a temp file for editing */
  tmpnam (filename);
  fp = fopen (filename, "w");

  /* dump the entry into the temp file for editing */
  fprintf_vcard (fp, v);
  fclose (fp);
  fp = NULL;

  /* record when the file has been modified */
  stat (filename, &sb);
  modified_time = sb.st_mtime;

  endwin ();

  process_id = fork ();
  if (process_id < 0)
    {
      /* could not fork... check errno */
    }
  else if (0 == process_id)
    {
      /* child is running */

      /* replace process image with the editor */
      execlp (editor, editor_basename, filename, NULL);
      _exit (2);                /* execlp failed */
    }
  else
    {
      /* parent is running */
      waitpid (process_id, &status, 0);
    }

  /* check if the temp file has been modified */
  stat (filename, &sb);
  if (modified_time != sb.st_mtime)
    {
      /* need to change the datafile */
      update_datafile (datafile, pos, filename);
      ret_val = EDIT_SUCCESSFUL;
    }
  else
    {
      ret_val = EDIT_ABORTED;
    }

  remove (filename);

  /* put everything back to normal */
  refresh ();
  initscr ();
  keypad (stdscr, TRUE);        /* enable keypad for use of arrow keys */
  nonl ();                      /* tell curses not to do NL->CR/NL on output */
  cbreak ();                    /* take input chars immediately */
  noecho ();
  return ret_val;
}
Example #14
0
/* Run the given command (if specified), using the given descriptor as the
 * controlling terminal. */
static int
_pty_run_on_pty(int fd, gboolean login,
			  int stdin_fd, int stdout_fd, int stderr_fd, 
			  int ready_reader, int ready_writer,
			  char **env_add, const char *command, char **argv,
			  const char *directory)
{
	int i;
	char c;
	char **args, *arg;

#ifdef HAVE_STROPTS_H
	if (!ioctl (fd, I_FIND, "ptem") && ioctl (fd, I_PUSH, "ptem") == -1) {
		close (fd);
		_exit (0);
		return -1;
	}

	if (!ioctl (fd, I_FIND, "ldterm") && ioctl (fd, I_PUSH, "ldterm") == -1) {
		close (fd);
		_exit (0);
		return -1;
	}

	if (!ioctl (fd, I_FIND, "ttcompat") && ioctl (fd, I_PUSH, "ttcompat") == -1) {
		perror ("ioctl (fd, I_PUSH, \"ttcompat\")");
		close (fd);
		_exit (0);
		return -1;
	}
#endif /* HAVE_STROPTS_H */

	/* Set any environment variables. */
	for (i = 0; (env_add != NULL) && (env_add[i] != NULL); i++) {
		if (putenv(g_strdup(env_add[i])) != 0) {
			g_warning("Error adding `%s' to environment, "
				    "continuing.", env_add[i]);
		}
	}

	/* Reset our signals -- our parent may have done any number of
	 * weird things to them. */
	_pty_reset_signal_handlers();

	/* Change to the requested directory. */
	if (directory != NULL) {
		i = chdir(directory);
	}

#ifdef HAVE_UTMP_H
	/* This sets stdin, stdout, stderr to the socket */	
	if (login && login_tty (fd) == -1) {
		g_printerr ("mount child process login_tty failed: %s\n", g_strerror (errno));
		return -1;
	}
#endif
	
	/* Signal to the parent that we've finished setting things up by
	 * sending an arbitrary byte over the status pipe and waiting for
	 * a response.  This synchronization step ensures that the pty is
	 * fully initialized before the parent process attempts to do anything
	 * with it, and is required on systems where additional setup, beyond
	 * merely opening the device, is required.  This is at least the case
	 * on Solaris. */
	/* Initialize so valgrind doesn't complain */
	c = 0;
	n_write(ready_writer, &c, 1);
	fsync(ready_writer);
	n_read(ready_reader, &c, 1);
	close(ready_writer);
	if (ready_writer != ready_reader) {
		close(ready_reader);
	}

	/* If the caller provided a command, we can't go back, ever. */
	if (command != NULL) {
		/* Outta here. */
		if (argv != NULL) {
			for (i = 0; (argv[i] != NULL); i++) ;
			args = g_malloc0(sizeof(char*) * (i + 1));
			for (i = 0; (argv[i] != NULL); i++) {
				args[i] = g_strdup(argv[i]);
			}
			execvp(command, args);
		} else {
			arg = g_strdup(command);
			execlp(command, arg, NULL);
		} 

		/* Avoid calling any atexit() code. */
		_exit(0);
		g_assert_not_reached();
	}

	return 0;
}
Example #15
0
void open_web_link(const char * url)
{
#ifdef OSX
	CFURLRef newurl = CFURLCreateWithString(kCFAllocatorDefault,CFStringCreateWithCStringNoCopy(NULL,url,kCFStringEncodingMacRoman, NULL),NULL);
	LSOpenCFURLRef(newurl,NULL);
	CFRelease(newurl);
#else
	// browser name can override the windows default, and if not defined in Linux, don't error
	if(*browser_name){
#ifndef WINDOWS
		static int have_set_signal = 0;
#ifdef SOUND_FORK_BUGFIX
		int sound_on_copy = sound_on;
		int music_on_copy = music_on;
#endif

		/* we're not interested in the exit status of the child so
		   set SA_NOCLDWAIT to stop it becoming a zombie if we don't wait() */
		if (!have_set_signal)
		{
			struct sigaction act;
			memset(&act, 0, sizeof(act));
			act.sa_handler = SIG_DFL;
			act.sa_flags = SA_NOCLDWAIT;
			sigaction(SIGCHLD, &act, NULL);
			have_set_signal = 1;
		}

#ifdef SOUND_FORK_BUGFIX
		if (sound_on_copy)
			toggle_sounds(&sound_on);
		if (music_on_copy)
			toggle_music(&music_on);
#endif

		if (fork() == 0){
			execlp(browser_name, browser_name, url, NULL);
			// in case the exec errors
			_exit(1);
		}

#ifdef SOUND_FORK_BUGFIX
		if (sound_on_copy)
			toggle_sounds(&sound_on);
		if (music_on_copy)
			toggle_music(&music_on);
#endif

#else
		// make a copy of the url string as it may be freed by the caller
		// will be freed as the only_call_from_open_web_link__go_to_url() exits
		char *cp_url = malloc(strlen(url)+1);
		safe_strncpy(cp_url, url, strlen(url)+1);

		// windows needs to spawn it in its own thread
		SDL_CreateThread(only_call_from_open_web_link__go_to_url, cp_url);
	} else {
		ShellExecute(NULL, "open", url, NULL, NULL, SW_SHOWNOACTIVATE); //this returns an int we could check for errors, but that's mainly when you use shellexecute for local files
#endif  //_WIN32
	}
#endif // OSX
}
Example #16
0
int exo1(int argc, char * argv[]){

    int tube1[2], tube2[2];
    char fichier[126];

    strcpy(fichier, argv[1]);
    
    if(pipe(tube1) || pipe(tube2)){

        perror("pb sur la creation du tube 1\n");
        exit(-1);
    }
    switch(fork()){         //Fork pour la création du fils 0, qui contient cut

        case -1 : {     //Cas d'erreur de creation du processus
                      
                      perror("Pb fork\n");
                      exit(-1);
        }
        case 0 : {      //Fils n°0 (contient la commande cut et un second fork)
            
                     close(tube1[1]);    //on ferme l'entrée écriture du tube1 car le fils0 n'écrit pas dans le tube
                     
                     close(0);          //On ferme l'entrée 0 dans la liste des descripteurs locaux.
                     dup(tube1[0]);      //on associe la lecture du tube 1 à l'entrée 0 des descrpteurs locaux
                     close(tube1[0]);       //on ferme la lecture du tube1

                     close(tube2[0]);       //Puisque le fils O ne lit pas dans tube 2, on ferme l'accès lecture du tube 2

                     close(1);              //On ferme l'entrée 1 dans la liste des descripteurs locaux
                     dup(tube2[1]);         //On associe l'entrée du tube à la première case libre de la table des descripteurs locaux, c'est à dire 1 qu'on vient de fermer
                     close(tube2[1]);       //On ferme l'accès en écriture au tube 2

                     execlp("cut", "cut", "-d:" , "F2", NULL);    //on execute la commande cut en donnant la liste des paramètres.
                     printf("Problème sur l'éxécution de cut\n");
                  
                 }
    }
    switch(fork()){

         case -1 :   //Cas d'erreur de creation du processus
                      
                      perror("Pb fork\n");
                      exit(-1);
                      break;
         case 0 :   //Création du fils 1, contenant sort
                      close(tube1[0]);
                      close(tube1[1]);      //on utilise pas le tube 1 dans ce processus

                      close(0);
                      dup(tube2[0]);        //on associe la lecture du tube 2 à l'entrée 0 des descripteurs locaux
                      close(tube1[0]);

                      close(tube2[1]);      //ce processus n'ecrit pas dans tube2

                      exelp("sort", "sort", NULL);      //execution de sort
                      printf("erreur dans l'execution de sort\n");
                      exit(-1);
    }
    close (tube1[0]);   //Ne lit pas dans le tube 1

    close (1);
    dup(tube1[1]);      //redirection de l'ecriture du tube1 dans l'entrée 1 des descripteurs locaux
    close(tube1[1]);

    close(tube2[0]);
    close(tube2[1]);        //n'utilise pas le tube2

    execlp("cat", "cat", Fichier, NULL);    //execution  de cat avec liste des paramètres

    printf("Pb dans l'éxecution de cat\n");

}
Example #17
0
static int setup_machine_raw(uint64_t size, sd_bus_error *error) {
        _cleanup_free_ char *tmp = NULL;
        _cleanup_close_ int fd = -1;
        struct statvfs ss;
        pid_t pid = 0;
        int r;

        /* We want to be able to make use of btrfs-specific file
         * system features, in particular subvolumes, reflinks and
         * quota. Hence, if we detect that /var/lib/machines.raw is
         * not located on btrfs, let's create a loopback file, place a
         * btrfs file system into it, and mount it to
         * /var/lib/machines. */

        fd = open("/var/lib/machines.raw", O_RDWR|O_CLOEXEC|O_NONBLOCK|O_NOCTTY);
        if (fd >= 0)
                return TAKE_FD(fd);

        if (errno != ENOENT)
                return sd_bus_error_set_errnof(error, errno, "Failed to open /var/lib/machines.raw: %m");

        r = tempfn_xxxxxx("/var/lib/machines.raw", NULL, &tmp);
        if (r < 0)
                return r;

        (void) mkdir_p_label("/var/lib", 0755);
        fd = open(tmp, O_RDWR|O_CREAT|O_EXCL|O_NOCTTY|O_CLOEXEC, 0600);
        if (fd < 0)
                return sd_bus_error_set_errnof(error, errno, "Failed to create /var/lib/machines.raw: %m");

        if (fstatvfs(fd, &ss) < 0) {
                r = sd_bus_error_set_errnof(error, errno, "Failed to determine free space on /var/lib/machines.raw: %m");
                goto fail;
        }

        if (ss.f_bsize * ss.f_bavail < VAR_LIB_MACHINES_FREE_MIN) {
                r = sd_bus_error_setf(error, SD_BUS_ERROR_FAILED, "Not enough free disk space to set up /var/lib/machines.");
                goto fail;
        }

        if (ftruncate(fd, size) < 0) {
                r = sd_bus_error_set_errnof(error, errno, "Failed to enlarge /var/lib/machines.raw: %m");
                goto fail;
        }

        r = safe_fork("(mkfs)", FORK_RESET_SIGNALS|FORK_DEATHSIG, &pid);
        if (r < 0) {
                sd_bus_error_set_errnof(error, r, "Failed to fork mkfs.btrfs: %m");
                goto fail;
        }
        if (r == 0) {

                /* Child */

                fd = safe_close(fd);

                execlp("mkfs.btrfs", "-Lvar-lib-machines", tmp, NULL);
                if (errno == ENOENT)
                        _exit(99);

                _exit(EXIT_FAILURE);
        }

        r = wait_for_terminate_and_check("mkfs", pid, 0);
        pid = 0;

        if (r < 0) {
                sd_bus_error_set_errnof(error, r, "Failed to wait for mkfs.btrfs: %m");
                goto fail;
        }
        if (r == 99) {
                r = sd_bus_error_set_errnof(error, ENOENT, "Cannot set up /var/lib/machines, mkfs.btrfs is missing");
                goto fail;
        }
        if (r != EXIT_SUCCESS) {
                r = sd_bus_error_setf(error, SD_BUS_ERROR_FAILED, "mkfs.btrfs failed with error code %i", r);
                goto fail;
        }

        r = rename_noreplace(AT_FDCWD, tmp, AT_FDCWD, "/var/lib/machines.raw");
        if (r < 0) {
                sd_bus_error_set_errnof(error, r, "Failed to move /var/lib/machines.raw into place: %m");
                goto fail;
        }

        return TAKE_FD(fd);

fail:
        unlink_noerrno(tmp);

        if (pid > 1)
                kill_and_sigcont(pid, SIGKILL);

        return r;
}
Example #18
0
void daemon_main() {
	chdir("/home/pi/Pokecan/display");
	execlp("/usr/bin/python", "python", "display.py");
}
Example #19
0
void THandler::verifyInterpolantWithExternalTool( vector< Enode * > & expl
                                                , Enode * interp_list )
{
  uint64_t mask = 0xFFFFFFFFFFFFFFFEULL;
  for ( unsigned in = 1 ; in < core_solver.getNofPartitions( ) ; in ++ )
  {
    Enode * args = interp_list;
    // Advance in the interpolants list
    for ( unsigned i = 0 ; i < in - 1 ; i ++ )
      args = args->getCdr( );
    Enode * interp = args->getCar( );
    mask &= ~SETBIT( in );
    // Check A -> I, i.e., A & !I
    // First stage: print declarations
    const char * name = "/tmp/verifyinterp.smt2";
    std::ofstream dump_out( name );
    core_solver.dumpHeaderToFile( dump_out );
    // Print only A atoms
    dump_out << "(assert " << endl;
    dump_out << "(and" << endl;
    for ( size_t j = 0 ; j < expl.size( ) ; j ++ )
    {
      Enode * e = expl[ j ];
      assert( e->isTAtom( ) );
      assert( e->getPolarity( ) != l_Undef );
      assert( (core_solver.getIPartitions( e ) &  mask) != 0
           || (core_solver.getIPartitions( e ) & ~mask) != 0 );
      if ( (core_solver.getIPartitions( e ) & ~mask) != 0 )
      {
        bool negated = e->getPolarity( ) == l_False;
        if ( negated )
          dump_out << "(not ";
        e->print( dump_out );
        if ( negated )
          dump_out << ")";
        dump_out << endl;
      }
    }

    dump_out << "(not " << interp << ")" << endl;
    dump_out << "))" << endl;
    dump_out << "(check-sat)" << endl;
    dump_out << "(exit)" << endl;
    dump_out.close( );
    // Check !
    bool tool_res;
    if ( int pid = fork() )
    {
      int status;
      waitpid(pid, &status, 0);
      switch ( WEXITSTATUS( status ) )
      {
        case 0:
          tool_res = false;
          break;
        case 1:
          tool_res = true;
          break;
        default:
          perror( "Tool" );
          exit( EXIT_FAILURE );
      }
    }
    else
    {
      execlp( "tool_wrapper.sh", "tool_wrapper.sh", name, 0 );
      perror( "Tool" );
      exit( 1 );
    }

    if ( tool_res == true )
      opensmt_error2( config.certifying_solver, " says A -> I does not hold" );
    // Now check B & I
    dump_out.open( name );
    core_solver.dumpHeaderToFile( dump_out );
    // Print only B atoms
    dump_out << "(assert " << endl;
    dump_out << "(and" << endl;
    for ( size_t j = 0 ; j < expl.size( ) ; j ++ )
    {
      Enode * e = expl[ j ];
      assert( e->isTAtom( ) );
      assert( e->getPolarity( ) != l_Undef );
      assert( (core_solver.getIPartitions( e ) &  mask) != 0
           || (core_solver.getIPartitions( e ) & ~mask) != 0 );
      if ( (core_solver.getIPartitions( e ) & mask) != 0 )
      {
        bool negated = e->getPolarity( ) == l_False;
        if ( negated )
          dump_out << "(not ";
        e->print( dump_out );
        if ( negated )
          dump_out << ")";
        dump_out << endl;
      }
    }
    dump_out << interp << endl;
    dump_out << "))" << endl;
    dump_out << "(check-sat)" << endl;
    dump_out << "(exit)" << endl;
    dump_out.close( );
    // Check !
    tool_res;
    if ( int pid = fork() )
    {
      int status;
      waitpid(pid, &status, 0);
      switch ( WEXITSTATUS( status ) )
      {
        case 0:
          tool_res = false;
          break;
        case 1:
          tool_res = true;
          break;
        default:
          perror( "Tool" );
          exit( EXIT_FAILURE );
      }
    }
    else
    {
      execlp( "tool_wrapper.sh", "tool_wrapper.sh", name, 0 );
      perror( "Tool" );
      exit( 1 );
    }
    if ( tool_res == true )
      opensmt_error2( config.certifying_solver, " says B & I does not hold" );
  }
}
Example #20
0
int main()
{
	// remove all bad files
	int _ = system("rm -f frame*jpg");

	signal(SIGINT, stopme);
	// start the gstreamer thingy
	int pid;
	if ((pid = fork()) == 0)
	{
		execlp("./twovid_fuuu.sh", "./twovid_fuuu.sh", NULL);
		perror("Broken dreams");
	}

	cv::Mat file;
	// grab and display the frame
	cv::namedWindow("hud");
	double offset = 0.15;
	gcube limg, rimg, combined;
	cv::Mat out;
	limg.create(640, 480, 3);
	rimg.create(640, 480, 3);

	char buf[256];
	char buf2[256];

	for (size_t i = 0; !stopsig; i++)
	{
		sprintf(buf, "frame%zu.jpg", i);
		sprintf(buf2, "frame%zu.jpg", i+4);

		while (access(buf, F_OK) == -1) ; // detect for delays on the gst side
		while (access(buf2, F_OK) != -1)
		{ // detect for delays on this side
			strcpy(buf, buf2);
			i += 4;
			sprintf(buf2, "frame%zu.jpg", i+4);
		}

		file = cv::imread(buf);
		// statically mapped numbers - assumption is that the frame is going to be 480x640 big
		limg.create(file, 0, 640, 0, 480, false);
		rimg.create(file, 0, 640, 480, 960, false);
		combined = ovr_image(limg, rimg, offset); // waste copy
		out = combined.cv_img();
		cv::imshow("hud", out);
		if (cv::waitKey(DELAY) >= 0)
		{
			break;
		}
	}

	kill(pid, SIGINT);
	sleep(1);
	kill(pid, SIGKILL);
	waitpid(pid, NULL, 0);

	_ = system("rm -f frame*jpg");

	return 0;
}
Example #21
0
int
main(int argc, char **argv)
{
	static const char	*outfile = "tags";	/* output file */
	int	aflag;				/* -a: append to tags */
	int	uflag;				/* -u: update tags */
	int	exit_val;			/* exit value */
	int	step;				/* step through args */
	int	ch;				/* getopts char */

	setlocale(LC_ALL, "");

	aflag = uflag = NO;
	tflag = YES;
	while ((ch = getopt(argc, argv, "BFTadf:tuwvx")) != -1)
		switch(ch) {
		case 'B':
			searchar = '?';
			break;
		case 'F':
			searchar = '/';
			break;
		case 'T':
			tflag = NO;
			break;
		case 'a':
			aflag++;
			break;
		case 'd':
			dflag++;
			break;
		case 'f':
			outfile = optarg;
			break;
		case 't':
			tflag = YES;
			break;
		case 'u':
			uflag++;
			break;
		case 'w':
			wflag++;
			break;
		case 'v':
			vflag++;
		case 'x':
			xflag++;
			break;
		case '?':
		default:
			usage();
		}
	argv += optind;
	argc -= optind;
	if (!argc)
		usage();

	if (!xflag)
		setlocale(LC_COLLATE, "C");

	init();

	for (exit_val = step = 0; step < argc; ++step)
		if (!(inf = fopen(argv[step], "r"))) {
			warn("%s", argv[step]);
			exit_val = 1;
		}
		else {
			curfile = argv[step];
			find_entries(argv[step]);
			(void)fclose(inf);
		}

	if (head) {
		if (xflag)
			put_entries(head);
		else {
			if (uflag) {
				FILE *oldf;
				regex_t *regx;

				if ((oldf = fopen(outfile, "r")) == NULL)
					err(1, "opening %s", outfile);
				if (unlink(outfile))
					err(1, "unlinking %s", outfile);
				if ((outf = fopen(outfile, "w")) == NULL)
					err(1, "recreating %s", outfile);
				if ((regx = calloc(argc, sizeof(regex_t))) == NULL)
					err(1, "RE alloc");
				for (step = 0; step < argc; step++) {
					(void)strcpy(lbuf, "\t");
					(void)strlcat(lbuf, argv[step], LINE_MAX);
					(void)strlcat(lbuf, "\t", LINE_MAX);
					if (regcomp(regx + step, lbuf,
					    REG_NOSPEC))
						warn("RE compilation failed");
				}
nextline:
				while (fgets(lbuf, LINE_MAX, oldf)) {
					for (step = 0; step < argc; step++)
						if (regexec(regx + step,
						    lbuf, 0, NULL, 0) == 0)
							goto nextline;
					fputs(lbuf, outf);
				}
				for (step = 0; step < argc; step++)
					regfree(regx + step);
				free(regx);
				fclose(oldf);
				fclose(outf);
				++aflag;
			}
			if (!(outf = fopen(outfile, aflag ? "a" : "w")))
				err(1, "%s", outfile);
			put_entries(head);
			(void)fclose(outf);
			if (uflag) {
				pid_t pid;

				if ((pid = fork()) == -1)
					err(1, "fork failed");
				else if (pid == 0) {
					execlp("sort", "sort", "-o", outfile,
					    outfile, NULL);
					err(1, "exec of sort failed");
				}
				/* Just assume the sort went OK. The old code
				   did not do any checks either. */
				(void)wait(NULL);
			}
		}
	}
	exit(exit_val);
}
Example #22
0
/* cvs_ext_connect
 *
 * connect to the cvs :ext: server as further described in the cvsfs_config
 * configuration structure
 */
error_t
cvs_ext_connect(FILE **send, FILE **recv)
{
  char port[10];
  int fd_to_rsh[2], fd_from_rsh[2];
  pid_t pid;

  if(pipe(fd_to_rsh))
    return errno;
  if(pipe(fd_from_rsh))
    return errno;

  if((pid = fork()) < 0)
    {
      perror(PACKAGE ": cannot fork remote shell client");
      return pid;
    }

  if(! pid)
    {
      /* okay, child process, fork to remote shell client */
      close(fd_to_rsh[1]);   /* close writing end */
      close(fd_from_rsh[0]); /* close reading end */

      if(dup2(fd_to_rsh[0], 0) < 0 || dup2(fd_from_rsh[1], 1) < 0)
	{
	  perror(PACKAGE ": unable to dup2 pipe to stdin/stdout");
	  exit(1);
	}

      if(config.cvs_mode == EXT) 
	{
	  snprintf(port, sizeof(port), "%d",
		   config.cvs_port ? config.cvs_port : 22);

	  execlp(config.cvs_shell_client, config.cvs_shell_client,
		 "-p", port,
		 "-l", config.cvs_username, config.cvs_hostname,
		 "--", "cvs", "server", NULL);
	}
      else if(config.cvs_mode == LOCAL)
	{
	  execlp("cvs", "cvs", "server", NULL);
	}
      else
	{
	  fprintf(stderr, PACKAGE ": damn, this line was not reached.\n");
	  abort();
	}

      exit(1);
    }

  close(fd_to_rsh[0]);
  close(fd_from_rsh[1]);

  if(! ((*send = fdopen(fd_to_rsh[1], "w"))
	&& (*recv = fdopen(fd_from_rsh[0], "r"))))
    {
      perror(PACKAGE ": unable to convert pipe's fds to file streams");

      if(send)
	fclose(*send);
      else
	close(fd_to_rsh[1]);

      if(recv)
	fclose(*recv);
      else
	close(fd_from_rsh[0]);

      kill(pid, SIGTERM);
      return EIO;
    }

  if(setvbuf(*send, NULL, _IOLBF, 0) || setvbuf(*recv, NULL, _IOLBF, 0))
    {
      perror(PACKAGE ": cannot force streams to be linebuffered");
      fclose(*send);
      fclose(*recv);
      return EIO;
    }

  return 0;
}
Example #23
0
int
main(int argc, char **argv)
{
    int rc = 0;
    int flag;
    int argerr = 0;
    static int command = '?';
    const char *validation = NULL;
    char *shadow = NULL;
    char *shadow_file = NULL;
    gboolean full_upload = FALSE;
    gboolean dangerous_cmd = FALSE;
    struct stat buf;
    int option_index = 0;

    crm_log_cli_init("crm_shadow");
    crm_set_options(NULL, "(query|command) [modifiers]", long_options,
                    "Perform configuration changes in a sandbox before updating the live cluster."
                    "\n\nSets up an environment in which configuration tools (cibadmin, crm_resource, etc) work"
                    " offline instead of against a live cluster, allowing changes to be previewed and tested"
                    " for side-effects.\n");

    if (argc < 2) {
        crm_help('?', EX_USAGE);
    }

    while (1) {
        flag = crm_get_option(argc, argv, &option_index);
        if (flag == -1 || flag == 0)
            break;

        switch (flag) {
            case 'a':
                full_upload = TRUE;
                break;
            case 'd':
            case 'E':
            case 'p':
            case 'w':
            case 'F':
                command = flag;
                free(shadow);
                shadow = NULL;
                {
                    const char *env = getenv("CIB_shadow");
                    if(env) {
                        shadow = strdup(env);
                    } else {
                        fprintf(stderr, "No active shadow configuration defined\n");
                        crm_exit(ENOENT);
                    }
                }
                break;
            case 'v':
                validation = optarg;
                break;
            case 'e':
            case 'c':
            case 's':
            case 'r':
                command = flag;
                free(shadow);
                shadow = strdup(optarg);
                break;
            case 'C':
            case 'D':
                command = flag;
                dangerous_cmd = TRUE;
                free(shadow);
                shadow = strdup(optarg);
                break;
            case 'V':
                command_options = command_options | cib_verbose;
                crm_bump_log_level(argc, argv);
                break;
            case '$':
            case '?':
                crm_help(flag, EX_OK);
                break;
            case 'f':
                command_options |= cib_quorum_override;
                force_flag = 1;
                break;
            case 'b':
                batch_flag = 1;
                break;
            default:
                printf("Argument code 0%o (%c)" " is not (?yet?) supported\n", flag, flag);
                ++argerr;
                break;
        }
    }

    if (optind < argc) {
        printf("non-option ARGV-elements: ");
        while (optind < argc)
            printf("%s ", argv[optind++]);
        printf("\n");
        crm_help('?', EX_USAGE);
    }

    if (optind > argc) {
        ++argerr;
    }

    if (argerr) {
        crm_help('?', EX_USAGE);
    }

    if (command == 'w') {
        /* which shadow instance is active? */
        const char *local = getenv("CIB_shadow");

        if (local == NULL) {
            fprintf(stderr, "No shadow instance provided\n");
            rc = -ENXIO;
            goto done;
        }
        fprintf(stdout, "%s\n", local);
        rc = 0;
        goto done;
    }

    if (shadow == NULL) {
        fprintf(stderr, "No shadow instance provided\n");
        fflush(stderr);
        rc = -EINVAL;
        goto done;

    } else if (command != 's' && command != 'c') {
        const char *local = getenv("CIB_shadow");

        if (local != NULL && safe_str_neq(local, shadow) && force_flag == FALSE) {
            fprintf(stderr,
                    "The supplied shadow instance (%s) is not the same as the active one (%s).\n"
                    "  To prevent accidental destruction of the cluster,"
                    " the --force flag is required in order to proceed.\n", shadow, local);
            fflush(stderr);
            rc = EX_USAGE;
            goto done;
        }
    }

    if (dangerous_cmd && force_flag == FALSE) {
        fprintf(stderr, "The supplied command is considered dangerous."
                "  To prevent accidental destruction of the cluster,"
                " the --force flag is required in order to proceed.\n");
        fflush(stderr);
        rc = EX_USAGE;
        goto done;
    }

    shadow_file = get_shadow_file(shadow);
    if (command == 'D') {
        /* delete the file */
        rc = stat(shadow_file, &buf);
        if (rc == 0) {
            rc = unlink(shadow_file);
            if (rc != 0) {
                fprintf(stderr, "Could not remove shadow instance '%s': %s\n", shadow,
                        strerror(errno));
                goto done;
            }
        }

        shadow_teardown(shadow);
        goto done;

    } else if (command == 'F') {
        printf("%s\n", shadow_file);
        rc = 0;
        goto done;
    }

    if (command == 'd' || command == 'r' || command == 'c' || command == 'C') {
        real_cib = cib_new_no_shadow();
        rc = real_cib->cmds->signon(real_cib, crm_system_name, cib_command);
        if (rc != pcmk_ok) {
            fprintf(stderr, "Signon to CIB failed: %s\n", pcmk_strerror(rc));
            goto done;
        }
    }

    rc = stat(shadow_file, &buf);

    if (command == 'e' || command == 'c') {
        if (rc == 0 && force_flag == FALSE) {
            fprintf(stderr, "A shadow instance '%s' already exists.\n"
                    "  To prevent accidental destruction of the cluster,"
                    " the --force flag is required in order to proceed.\n", shadow);
            rc = -ENOTUNIQ;
            goto done;
        }

    } else if (rc != 0) {
        fprintf(stderr, "Could not access shadow instance '%s': %s\n", shadow, strerror(errno));
        rc = -ENXIO;
        goto done;
    }

    rc = pcmk_ok;
    if (command == 'c' || command == 'e' || command == 'r') {
        xmlNode *output = NULL;

        /* create a shadow instance based on the current cluster config */
        if (command == 'c' || command == 'r') {
            rc = real_cib->cmds->query(real_cib, NULL, &output, command_options);
            if (rc != pcmk_ok) {
                fprintf(stderr, "Could not connect to the CIB: %s\n", pcmk_strerror(rc));
                goto done;
            }

        } else {
            output = createEmptyCib(0);
            if(validation) {
                crm_xml_add(output, XML_ATTR_VALIDATION, validation);
            }
            printf("Created new %s configuration\n",
                   crm_element_value(output, XML_ATTR_VALIDATION));
        }

        rc = write_xml_file(output, shadow_file, FALSE);
        free_xml(output);

        if (rc < 0) {
            fprintf(stderr, "Could not %s the shadow instance '%s': %s\n",
                    command == 'r' ? "reset" : "create",
                    shadow, strerror(errno));
            goto done;
        }
        shadow_setup(shadow, FALSE);
        rc = pcmk_ok;

    } else if (command == 'E') {
        const char *err = NULL;
        char *editor = getenv("EDITOR");

        if (editor == NULL) {
            fprintf(stderr, "No value for $EDITOR defined\n");
            rc = -EINVAL;
            goto done;
        }

        execlp(editor, "--", shadow_file, NULL);
        err = strerror(errno);
        fprintf(stderr, "Could not invoke $EDITOR (%s %s): %s\n", editor, shadow_file, err);
        rc = -EINVAL;
        goto done;

    } else if (command == 's') {
        shadow_setup(shadow, TRUE);
        rc = 0;
        goto done;

    } else if (command == 'P') {
        /* display the current contents */
        char *output_s = NULL;
        xmlNode *output = filename2xml(shadow_file);

        output_s = dump_xml_formatted(output);
        printf("%s", output_s);

        free(output_s);
        free_xml(output);

    } else if (command == 'd') {
        /* diff against cluster */
        xmlNode *diff = NULL;
        xmlNode *old_config = NULL;
        xmlNode *new_config = filename2xml(shadow_file);

        rc = real_cib->cmds->query(real_cib, NULL, &old_config, command_options);

        if (rc != pcmk_ok) {
            fprintf(stderr, "Could not query the CIB: %s\n", pcmk_strerror(rc));
            goto done;
        }

        xml_track_changes(new_config, NULL, new_config, FALSE);
        xml_calculate_changes(old_config, new_config);

        diff = xml_create_patchset(0, old_config, new_config, NULL, FALSE);

        xml_log_changes(LOG_INFO, __FUNCTION__, new_config);
        xml_accept_changes(new_config);

        if (diff != NULL) {
            xml_log_patchset(0, "  ", diff);
            rc = 1;
            goto done;
        }
        rc = 0;
        goto done;

    } else if (command == 'C') {
        /* commit to the cluster */
        xmlNode *input = filename2xml(shadow_file);

        if (full_upload) {
            rc = real_cib->cmds->replace(real_cib, NULL, input, command_options);
        } else {
            xmlNode *config = first_named_child(input, XML_CIB_TAG_CONFIGURATION);

            rc = real_cib->cmds->replace(real_cib, XML_CIB_TAG_CONFIGURATION, config,
                                         command_options);
        }

        if (rc != pcmk_ok) {
            fprintf(stderr, "Could not commit shadow instance '%s' to the CIB: %s\n",
                    shadow, pcmk_strerror(rc));
            goto done;
        }
        shadow_teardown(shadow);
        free_xml(input);
    }
  done:
    free(shadow_file);
    free(shadow);
    return crm_exit(rc);
}
Example #24
0
int
t_edit(struct t_tune *tune)
{
	FILE *fp = NULL;
	struct t_taglist *tlist = NULL;
	char *tmp = NULL, *fmtdata = NULL;
	const char *editor, *tmpdir;
	pid_t editpid; /* child process */
	int status, success = 0;
	struct stat before, after;
	extern const struct t_format *Fflag;

	assert(tune != NULL);

	/* convert the tags into the requested format */
	tlist = t_tune_tags(tune);
	if (tlist == NULL)
		goto out;
	fmtdata = Fflag->tags2fmt(tlist, t_tune_path(tune));
	t_taglist_delete(tlist);
	tlist = NULL;
	if (fmtdata == NULL)
		goto out;

	tmpdir = getenv("TMPDIR");
	if (tmpdir == NULL)
		tmpdir = "/tmp";
	/* print the format data into a temp file */
	if (asprintf(&tmp, "%s/%s-XXXXXX.%s", tmpdir, getprogname(),
	    Fflag->fileext) < 0) {
		goto out;
	}
	if (mkstemps(tmp, strlen(Fflag->fileext) + 1) == -1) {
		warn("mkstemps");
		goto out;
	}
	fp = fopen(tmp, "w");
	if (fp == NULL) {
		warn("%s: fopen", tmp);
		goto out;
	}
	if (fprintf(fp, "%s", fmtdata) < 0) {
		warn("%s: fprintf", tmp);
		goto out;
	}
	if (fclose(fp) != 0) {
		warn("%s: fclose", tmp);
		goto out;
	}
	fp = NULL;

	/* call the user's editor to edit the temp file */
	editor = getenv("EDITOR");
	if (editor == NULL) {
		warnx("please set the $EDITOR environment variable.");
		goto out;
	}

	/* save the current mtime so we know later if the file has been
	   modified */
	if (stat(tmp, &before) != 0)
		goto out;

	/* launch the editor */
	switch (editpid = fork()) {
	case -1: /* error */
		warn("fork");
		goto out;
		/* NOTREACHED */
	case 0: /* child (edit process) */
		execlp(editor, /* argv[0] */editor, /* argv[1] */tmp, NULL);
		/* if we reach here, execlp(3) has failed */
		err(EXIT_FAILURE, "execlp");
		/* NOTREACHED */
	default: /* parent (tagutil process) */
		waitpid(editpid, &status, 0);
	}

	/* get the mtime now that the editor has been run */
	if (stat(tmp, &after) != 0)
		goto out;

	int modified = (after.st_mtim.tv_sec  > before.st_mtim.tv_sec ||
		        after.st_mtim.tv_nsec > before.st_mtim.tv_nsec);

	/* we perform the load iff the file has been modified by the edit
	   process and that process exited with success */
	if (modified && WIFEXITED(status) && WEXITSTATUS(status) == 0) {
		if (t_load(tune, tmp) == -1)
			goto out;
	}

	success = 1;
	/* FALLTHROUGH */
out:
	if (fp != NULL)
		(void)fclose(fp);
	if (tmp != NULL)
		(void)unlink(tmp);
	free(tmp);
	free(fmtdata);
	return (success ? 0 : -1);
}
Example #25
0
File: ToONP.c Project: agaX/OS
int main(int argc, char* argv[]) {
  if (argc != 2) {
    printf("Wywołaj program z jednym argumentem.\n");
    exit(0);
  }

  int pipe_dsc[2][2];
  if (pipe(pipe_dsc[0]) == -1) syserr("Error in pipe\n");
  if (pipe(pipe_dsc[1]) == -1) syserr("Error in pipe\n");

  // Utworzenie procesu potomnego W(1)
  switch (fork()) {
    case -1:
      syserr("Error in fork\n");

    // proces potomny
    case 0:
      if (close(0) == -1) syserr("W, close(0)");
      if (close(1) == -1) syserr("W, close(1)");
      if (dup(pipe_dsc[0][0]) == -1) syserr("W, dup(pipe_dsc[0][0])");
      if (dup(pipe_dsc[1][1]) == -1) syserr("W, dup(pipe_dsc[1][1])");
      if (close(pipe_dsc[0][0]) == -1) syserr("W, close(pipe_dsc[0][0])");
      if (close(pipe_dsc[0][1]) == -1) syserr("W, close(pipe_dsc[0][1])");
      if (close(pipe_dsc[1][0]) == -1) syserr("W, close(pipe_dsc[1][0])");
      if (close(pipe_dsc[1][1]) == -1) syserr("W, close(pipe_dsc[1][1])");
      execlp("./W", "./W", NULL);
      syserr("Error in execlp\n");
      exit(0);

    // proces macierzysty
    default:
      if (close(pipe_dsc[1][1]) == -1) syserr("ToONP, close(pipe_dsc[1][1])");
      if (close(pipe_dsc[0][0]) == -1) syserr("ToONP, close(pipe_dsc[0][0])");

      // Wysyłanie danych do procesu w(1).
      for (int i = 0; i < strlen(argv[1]); i++)
        if (write(pipe_dsc[0][1], &argv[1][i], sizeof(char)) == -1)
          syserr("ToONP, write(pipe_dsc[0][1])");

      // "Dodanie" trzech '#', które oddzielają poszczególne części napisu
      char c = '#';
      for (int i = 0; i < 3; i++)
        if (write(pipe_dsc[0][1], &c, sizeof(char)) == -1)
          syserr("ToONP, write(pipe_dsc[0][1])#");

      // Odczytanie wyniku.
      if (read(pipe_dsc[1][0], &c, sizeof(char)) == -1)
        syserr("ToONP, read(pipe_dsc[1][0])");

      // Wypisywanie wyniku konwersji wyrażenia na standardowe wyjście
      while (c != '#') {
        write(1, &c, sizeof(char));
        if (read(pipe_dsc[1][0], &c, sizeof(char)) == -1)
          syserr("ToONP, read(pipe_dsc[1][0])");
      }
      printf("\n");

      // Oczekiwanie za zakończenie procesów potomnych.
      if (wait(0) == -1) syserr("wait");
      if (close(pipe_dsc[1][0]) == -1) syserr("ToONP, close(pipe_dsc[1][0])");
      if (close(pipe_dsc[0][1]) == -1) syserr("ToONP, close(pipe_dsc[0][1])");
      exit(0);
  }
}
Example #26
0
/**
 * g_process_perform_supervise:
 *
 * Supervise process, returns only in the context of the daemon process, the
 * supervisor process exits here.
 **/
static void
g_process_perform_supervise(void)
{
  pid_t pid;
  gboolean first = TRUE, exited = FALSE;
  gchar proc_title[PROC_TITLE_SPACE];
  struct sigaction sa;

  g_snprintf(proc_title, PROC_TITLE_SPACE, "supervising %s", process_opts.name);
  g_process_setproctitle(proc_title);
  
  memset(&sa, 0, sizeof(sa));
  sa.sa_handler = SIG_IGN;
  sigaction(SIGHUP, &sa, NULL);

  while (1)
    {
      if (pipe(init_result_pipe) != 0)
        {
          g_process_message("Error daemonizing process, cannot open pipe; error='%s'", g_strerror(errno));
          g_process_startup_failed(1, TRUE);
        }
        
      /* fork off a child process */
      if ((pid = fork()) < 0)
        {
          g_process_message("Error forking child process; error='%s'", g_strerror(errno));
          g_process_startup_failed(1, TRUE);
        }
      else if (pid != 0)
        {
          gint rc;
          gboolean deadlock = FALSE;
          
          /* this is the supervisor process */

          /* shut down init_result_pipe write side */
          close(init_result_pipe[1]);
          init_result_pipe[1] = -1;
          
          rc = g_process_recv_result();
          if (first)
            {
              /* first time encounter, we have a chance to report back, do it */
              g_process_send_result(rc);
              if (rc != 0)
                break;
              g_process_detach_stdio();
            }
          first = FALSE;
          if (rc != 0)
            {
              gint i = 0;
              /* initialization failed in daemon, it will probably exit soon, wait and restart */
              
              while (i < 6 && waitpid(pid, &rc, WNOHANG) == 0)
                {
                  if (i > 3)
                    kill(pid, i > 4 ? SIGKILL : SIGTERM);
                  sleep(1);
                  i++;
                }
              if (i == 6)
                g_process_message("Initialization failed but the daemon did not exit, even when forced to, trying to recover; pid='%d'", pid);
              continue;
            }
          
          if (process_opts.check_fn && (process_opts.check_period >= 0))
            {
              gint i = 1;
              while (!(exited = waitpid(pid, &rc, WNOHANG)))
                {
                  if (i >= process_opts.check_period)
                    {
                      if (!process_opts.check_fn())
                        break;
                      i = 0;
                    }
                  sleep(1);
                  i++;
                }

              if (!exited)
                {
                  gint j = 0;
                  g_process_message("Daemon deadlock detected, killing process;");
                  deadlock = TRUE;
              
                  while (j < 6 && waitpid(pid, &rc, WNOHANG) == 0)
                    {
                      if (j > 3)
                        kill(pid, j > 4 ? SIGKILL : SIGABRT);
                      sleep(1);
                      j++;
                    }
                  if (j == 6)
                    g_process_message("The daemon did not exit after deadlock, even when forced to, trying to recover; pid='%d'", pid);
                }
            }
          else
            {
              waitpid(pid, &rc, 0);
            }

          if (deadlock || WIFSIGNALED(rc) || (WIFEXITED(rc) && WEXITSTATUS(rc) != 0))
            {
              gchar argbuf[64];

              if (!access(G_PROCESS_FAILURE_NOTIFICATION, R_OK | X_OK)) 
                {
                  const gchar *notify_reason;
                  pid_t npid = fork();
                  gint nrc;
                  switch (npid)
                    {
                    case -1:
                      g_process_message("Could not fork for external notification; reason='%s'", strerror(errno));
                      break;
    
                    case 0:
                      switch(fork())
                        {
                        case -1:
                          g_process_message("Could not fork for external notification; reason='%s'", strerror(errno));
                          exit(1);
                          break;
                        case 0: 
			  if (deadlock)
			    {
			      notify_reason = "deadlock detected";
			      argbuf[0] = 0;
			    }
			  else 
			    {
			      snprintf(argbuf, sizeof(argbuf), "%d", WIFSIGNALED(rc) ? WTERMSIG(rc) : WEXITSTATUS(rc));
			      if (WIFSIGNALED(rc))
				notify_reason = "signalled";
			      else
				notify_reason = "non-zero exit code";
			    }
			  execlp(G_PROCESS_FAILURE_NOTIFICATION, G_PROCESS_FAILURE_NOTIFICATION, 
				 SAFE_STRING(process_opts.name),
				 SAFE_STRING(process_opts.chroot_dir),
				 SAFE_STRING(process_opts.pidfile_dir),
				 SAFE_STRING(process_opts.pidfile),
				 SAFE_STRING(process_opts.cwd),
				 SAFE_STRING(process_opts.caps),
				 notify_reason,
				 argbuf,
				 (deadlock || !WIFSIGNALED(rc) || WTERMSIG(rc) != SIGKILL) ? "restarting" : "not-restarting",
				 (gchar*) NULL);
			  g_process_message("Could not execute external notification; reason='%s'", strerror(errno));
			  break;
			  
			default:
			  exit(0);
			  break;
			} /* child process */
                    default:
                      waitpid(npid, &nrc, 0);
                      break;
                    }
                }
              if (deadlock || !WIFSIGNALED(rc) || WTERMSIG(rc) != SIGKILL)
                {
                  g_process_message("Daemon exited due to a deadlock/signal/failure, restarting; exitcode='%d'", rc);
                  sleep(1);
                }
              else
                {
                  g_process_message("Daemon was killed, not restarting; exitcode='%d'", rc);
                  break;
                }
            }
          else
            {
              g_process_message("Daemon exited gracefully, not restarting; exitcode='%d'", rc);
              break;
            }
        }
      else
        {
          /* this is the daemon process, thus we should return to the caller of g_process_start() */
          /* shut down init_result_pipe read side */
          process_kind = G_PK_DAEMON;
          close(init_result_pipe[0]);
          init_result_pipe[0] = -1;

          /* update systemd socket activation pid */
          inherit_systemd_activation();

          memcpy(process_opts.argv_start, process_opts.argv_orig, process_opts.argv_env_len);
          return;
        }
    }
  exit(0);
}
Example #27
0
int
main(int argc, char **argv)
{
	struct group *gr;
	struct stat st;
	int retries, backoff;
	int ask, ch, cnt, quietlog, rootlogin, rval;
	uid_t uid, euid;
	gid_t egid;
	char *term;
	char *p, *ttyn;
	char tname[sizeof(_PATH_TTY) + 10];
	char *arg0;
	const char *tp;
	const char *shell = NULL;
	login_cap_t *lc = NULL;
	login_cap_t *lc_user = NULL;
	pid_t pid;
#ifdef USE_BSM_AUDIT
	char auditsuccess = 1;
#endif

	signal(SIGQUIT, SIG_IGN);
	signal(SIGINT, SIG_IGN);
	signal(SIGHUP, SIG_IGN);
	if (setjmp(timeout_buf)) {
		if (failures)
			badlogin(username);
		fprintf(stderr, "Login timed out after %d seconds\n",
		    timeout);
		bail(NO_SLEEP_EXIT, 0);
	}
	signal(SIGALRM, timedout);
	alarm(timeout);
	setpriority(PRIO_PROCESS, 0, 0);

	openlog("login", LOG_ODELAY, LOG_AUTH);

	uid = getuid();
	euid = geteuid();
	egid = getegid();

	while ((ch = getopt(argc, argv, "fh:p")) != -1)
		switch (ch) {
		case 'f':
			fflag = 1;
			break;
		case 'h':
			if (uid != 0)
				errx(1, "-h option: %s", strerror(EPERM));
			if (strlen(optarg) >= MAXHOSTNAMELEN)
				errx(1, "-h option: %s: exceeds maximum "
				    "hostname size", optarg);
			hflag = 1;
			hostname = optarg;
			break;
		case 'p':
			pflag = 1;
			break;
		case '?':
		default:
			if (uid == 0)
				syslog(LOG_ERR, "invalid flag %c", ch);
			usage();
		}
	argc -= optind;
	argv += optind;

	if (argc > 0) {
		username = strdup(*argv);
		if (username == NULL)
			err(1, "strdup()");
		ask = 0;
	} else {
		ask = 1;
	}

	setproctitle("-%s", getprogname());

	for (cnt = getdtablesize(); cnt > 2; cnt--)
		close(cnt);

	/*
	 * Get current TTY
	 */
	ttyn = ttyname(STDIN_FILENO);
	if (ttyn == NULL || *ttyn == '\0') {
		snprintf(tname, sizeof(tname), "%s??", _PATH_TTY);
		ttyn = tname;
	}
	if (strncmp(ttyn, _PATH_DEV, sizeof(_PATH_DEV) -1) == 0)
		tty = ttyn + sizeof(_PATH_DEV) -1;
	else
		tty = ttyn;

	/*
	 * Get "login-retries" & "login-backoff" from default class
	 */
	lc = login_getclass(NULL);
	prompt = login_getcapstr(lc, "login_prompt",
	    default_prompt, default_prompt);
	passwd_prompt = login_getcapstr(lc, "passwd_prompt",
	    default_passwd_prompt, default_passwd_prompt);
	retries = login_getcapnum(lc, "login-retries",
	    DEFAULT_RETRIES, DEFAULT_RETRIES);
	backoff = login_getcapnum(lc, "login-backoff",
	    DEFAULT_BACKOFF, DEFAULT_BACKOFF);
	login_close(lc);
	lc = NULL;

	/*
	 * Try to authenticate the user until we succeed or time out.
	 */
	for (cnt = 0;; ask = 1) {
		if (ask) {
			fflag = 0;
			if (olduser != NULL)
				free(olduser);
			olduser = username;
			username = getloginname();
		}
		rootlogin = 0;

		/*
		 * Note if trying multiple user names; log failures for
		 * previous user name, but don't bother logging one failure
		 * for nonexistent name (mistyped username).
		 */
		if (failures && strcmp(olduser, username) != 0) {
			if (failures > (pwd ? 0 : 1))
				badlogin(olduser);
		}

		/*
		 * Load the PAM policy and set some variables
		 */
		pam_err = pam_start("login", username, &pamc, &pamh);
		if (pam_err != PAM_SUCCESS) {
			pam_syslog("pam_start()");
#ifdef USE_BSM_AUDIT
			au_login_fail("PAM Error", 1);
#endif
			bail(NO_SLEEP_EXIT, 1);
		}
		pam_err = pam_set_item(pamh, PAM_TTY, tty);
		if (pam_err != PAM_SUCCESS) {
			pam_syslog("pam_set_item(PAM_TTY)");
#ifdef USE_BSM_AUDIT
			au_login_fail("PAM Error", 1);
#endif
			bail(NO_SLEEP_EXIT, 1);
		}
		pam_err = pam_set_item(pamh, PAM_RHOST, hostname);
		if (pam_err != PAM_SUCCESS) {
			pam_syslog("pam_set_item(PAM_RHOST)");
#ifdef USE_BSM_AUDIT
			au_login_fail("PAM Error", 1);
#endif
			bail(NO_SLEEP_EXIT, 1);
		}

		pwd = getpwnam(username);
		if (pwd != NULL && pwd->pw_uid == 0)
			rootlogin = 1;

		/*
		 * If the -f option was specified and the caller is
		 * root or the caller isn't changing their uid, don't
		 * authenticate.
		 */
		if (pwd != NULL && fflag &&
		    (uid == (uid_t)0 || uid == (uid_t)pwd->pw_uid)) {
			/* already authenticated */
			rval = 0;
#ifdef USE_BSM_AUDIT
			auditsuccess = 0; /* opened a terminal window only */
#endif
		} else {
			fflag = 0;
			setpriority(PRIO_PROCESS, 0, -4);
			rval = auth_pam();
			setpriority(PRIO_PROCESS, 0, 0);
		}

		if (pwd && rval == 0)
			break;

		pam_cleanup();

		/*
		 * We are not exiting here, but this corresponds to a failed
		 * login event, so set exitstatus to 1.
		 */
#ifdef USE_BSM_AUDIT
		au_login_fail("Login incorrect", 1);
#endif

		printf("Login incorrect\n");
		failures++;

		pwd = NULL;

		/*
		 * Allow up to 'retry' (10) attempts, but start
		 * backing off after 'backoff' (3) attempts.
		 */
		if (++cnt > backoff) {
			if (cnt >= retries) {
				badlogin(username);
				bail(SLEEP_EXIT, 1);
			}
			sleep((u_int)((cnt - backoff) * 5));
		}
	}

	/* committed to login -- turn off timeout */
	alarm((u_int)0);
	signal(SIGHUP, SIG_DFL);

	endpwent();

#ifdef USE_BSM_AUDIT
	/* Audit successful login. */
	if (auditsuccess)
		au_login_success();
#endif

	/*
	 * Establish the login class.
	 */
	lc = login_getpwclass(pwd);
	lc_user = login_getuserclass(pwd);

	if (!(quietlog = login_getcapbool(lc_user, "hushlogin", 0)))
		quietlog = login_getcapbool(lc, "hushlogin", 0);

	/*
	 * Switching needed for NFS with root access disabled.
	 *
	 * XXX: This change fails to modify the additional groups for the
	 * process, and as such, may restrict rights normally granted
	 * through those groups.
	 */
	setegid(pwd->pw_gid);
	seteuid(rootlogin ? 0 : pwd->pw_uid);
	if (!*pwd->pw_dir || chdir(pwd->pw_dir) < 0) {
		if (login_getcapbool(lc, "requirehome", 0))
			refused("Home directory not available", "HOMEDIR", 1);
		if (chdir("/") < 0)
			refused("Cannot find root directory", "ROOTDIR", 1);
		if (!quietlog || *pwd->pw_dir)
			printf("No home directory.\nLogging in with home = \"/\".\n");
		pwd->pw_dir = strdup("/");
		if (pwd->pw_dir == NULL) {
			syslog(LOG_NOTICE, "strdup(): %m");
			bail(SLEEP_EXIT, 1);
		}
	}
	seteuid(euid);
	setegid(egid);
	if (!quietlog) {
		quietlog = access(_PATH_HUSHLOGIN, F_OK) == 0;
		if (!quietlog)
			pam_silent = 0;
	}

	shell = login_getcapstr(lc, "shell", pwd->pw_shell, pwd->pw_shell);
	if (*pwd->pw_shell == '\0')
		pwd->pw_shell = strdup(_PATH_BSHELL);
	if (pwd->pw_shell == NULL) {
		syslog(LOG_NOTICE, "strdup(): %m");
		bail(SLEEP_EXIT, 1);
	}
	if (*shell == '\0')   /* Not overridden */
		shell = pwd->pw_shell;
	if ((shell = strdup(shell)) == NULL) {
		syslog(LOG_NOTICE, "strdup(): %m");
		bail(SLEEP_EXIT, 1);
	}

	/*
	 * Set device protections, depending on what terminal the
	 * user is logged in. This feature is used on Suns to give
	 * console users better privacy.
	 */
	login_fbtab(tty, pwd->pw_uid, pwd->pw_gid);

	/*
	 * Clear flags of the tty.  None should be set, and when the
	 * user sets them otherwise, this can cause the chown to fail.
	 * Since it isn't clear that flags are useful on character
	 * devices, we just clear them.
	 *
	 * We don't log in the case of EOPNOTSUPP because dev might be
	 * on NFS, which doesn't support chflags.
	 *
	 * We don't log in the EROFS because that means that /dev is on
	 * a read only file system and we assume that the permissions there
	 * are sane.
	 */
	if (ttyn != tname && chflags(ttyn, 0))
		if (errno != EOPNOTSUPP && errno != EROFS)
			syslog(LOG_ERR, "chflags(%s): %m", ttyn);
	if (ttyn != tname && chown(ttyn, pwd->pw_uid,
	    (gr = getgrnam(TTYGRPNAME)) ? gr->gr_gid : pwd->pw_gid))
		if (errno != EROFS)
			syslog(LOG_ERR, "chown(%s): %m", ttyn);

	/*
	 * Exclude cons/vt/ptys only, assume dialup otherwise
	 * TODO: Make dialup tty determination a library call
	 * for consistency (finger etc.)
	 */
	if (hflag && isdialuptty(tty))
		syslog(LOG_INFO, "DIALUP %s, %s", tty, pwd->pw_name);

#ifdef LOGALL
	/*
	 * Syslog each successful login, so we don't have to watch
	 * hundreds of wtmp or lastlogin files.
	 */
	if (hflag)
		syslog(LOG_INFO, "login from %s on %s as %s",
		       hostname, tty, pwd->pw_name);
	else
		syslog(LOG_INFO, "login on %s as %s",
		       tty, pwd->pw_name);
#endif

	/*
	 * If fflag is on, assume caller/authenticator has logged root
	 * login.
	 */
	if (rootlogin && fflag == 0) {
		if (hflag)
			syslog(LOG_NOTICE, "ROOT LOGIN (%s) ON %s FROM %s",
			    username, tty, hostname);
		else
			syslog(LOG_NOTICE, "ROOT LOGIN (%s) ON %s",
			    username, tty);
	}

	/*
	 * Destroy environment unless user has requested its
	 * preservation - but preserve TERM in all cases
	 */
	term = getenv("TERM");
	if (!pflag)
		environ = envinit;
	if (term != NULL) {
		if (setenv("TERM", term, 0) == -1)
			err(1, "setenv: cannot set TERM=%s", term);
	}

	/*
	 * PAM modules might add supplementary groups during pam_setcred().
	 */
	if (setusercontext(lc, pwd, pwd->pw_uid, LOGIN_SETGROUP) != 0) {
		syslog(LOG_ERR, "setusercontext() failed - exiting");
		bail(NO_SLEEP_EXIT, 1);
	}

	pam_err = pam_setcred(pamh, pam_silent|PAM_ESTABLISH_CRED);
	if (pam_err != PAM_SUCCESS) {
		pam_syslog("pam_setcred()");
		bail(NO_SLEEP_EXIT, 1);
	}
	pam_cred_established = 1;

	pam_err = pam_open_session(pamh, pam_silent);
	if (pam_err != PAM_SUCCESS) {
		pam_syslog("pam_open_session()");
		bail(NO_SLEEP_EXIT, 1);
	}
	pam_session_established = 1;

	/*
	 * We must fork() before setuid() because we need to call
	 * pam_close_session() as root.
	 */
	pid = fork();
	if (pid < 0) {
		err(1, "fork");
	} else if (pid != 0) {
		/*
		 * Parent: wait for child to finish, then clean up
		 * session.
		 */
		int status;
		setproctitle("-%s [pam]", getprogname());
		waitpid(pid, &status, 0);
		bail(NO_SLEEP_EXIT, 0);
	}

	/*
	 * NOTICE: We are now in the child process!
	 */

	/*
	 * Add any environment variables the PAM modules may have set.
	 */
	export_pam_environment();

	/*
	 * We're done with PAM now; our parent will deal with the rest.
	 */
	pam_end(pamh, 0);
	pamh = NULL;

	/*
	 * We don't need to be root anymore, so set the login name and
	 * the UID.
	 */
	if (setlogin(username) != 0) {
		syslog(LOG_ERR, "setlogin(%s): %m - exiting", username);
		bail(NO_SLEEP_EXIT, 1);
	}
	if (setusercontext(lc, pwd, pwd->pw_uid,
	    LOGIN_SETALL & ~(LOGIN_SETLOGIN|LOGIN_SETGROUP)) != 0) {
		syslog(LOG_ERR, "setusercontext() failed - exiting");
		exit(1);
	}

	if (setenv("SHELL", pwd->pw_shell, 1) == -1)
		err(1, "setenv: cannot set SHELL=%s", pwd->pw_shell);
	if (setenv("HOME", pwd->pw_dir, 1) == -1)
		err(1, "setenv: cannot set HOME=%s", pwd->pw_dir);
	/* Overwrite "term" from login.conf(5) for any known TERM */
	if (term == NULL && (tp = stypeof(tty)) != NULL) {
		if (setenv("TERM", tp, 1) == -1)
			err(1, "setenv: cannot set TERM=%s", tp);
	} else {
		if (setenv("TERM", TERM_UNKNOWN, 0) == -1)
			err(1, "setenv: cannot set TERM=%s", TERM_UNKNOWN);
	}

	if (setenv("LOGNAME", username, 1) == -1)
		err(1, "setenv: cannot set LOGNAME=%s", username);
	if (setenv("USER", username, 1) == -1)
		err(1, "setenv: cannot set USER=%s", username);
	if (setenv("PATH",
	    rootlogin ? _PATH_STDPATH : _PATH_DEFPATH, 0) == -1) {
		err(1, "setenv: cannot set PATH=%s",
		    rootlogin ? _PATH_STDPATH : _PATH_DEFPATH);
	}

	if (!quietlog) {
		const char *cw;

		cw = login_getcapstr(lc, "copyright", NULL, NULL);
		if (cw == NULL || motd(cw) == -1)
			printf("%s", copyright);

		printf("\n");

		cw = login_getcapstr(lc, "welcome", NULL, NULL);
		if (cw != NULL && access(cw, F_OK) == 0)
			motd(cw);
		else
			motd(_PATH_MOTDFILE);

		if (login_getcapbool(lc_user, "nocheckmail", 0) == 0 &&
		    login_getcapbool(lc, "nocheckmail", 0) == 0) {
			char *cx;

			/* $MAIL may have been set by class. */
			cx = getenv("MAIL");
			if (cx == NULL) {
				asprintf(&cx, "%s/%s",
				    _PATH_MAILDIR, pwd->pw_name);
			}
			if (cx && stat(cx, &st) == 0 && st.st_size != 0)
				printf("You have %smail.\n",
				    (st.st_mtime > st.st_atime) ? "new " : "");
			if (getenv("MAIL") == NULL)
				free(cx);
		}
	}

	login_close(lc_user);
	login_close(lc);

	signal(SIGALRM, SIG_DFL);
	signal(SIGQUIT, SIG_DFL);
	signal(SIGINT, SIG_DFL);
	signal(SIGTSTP, SIG_IGN);

	/*
	 * Login shells have a leading '-' in front of argv[0]
	 */
	p = strrchr(pwd->pw_shell, '/');
	if (asprintf(&arg0, "-%s", p ? p + 1 : pwd->pw_shell) >= MAXPATHLEN) {
		syslog(LOG_ERR, "user: %s: shell exceeds maximum pathname size",
		    username);
		errx(1, "shell exceeds maximum pathname size");
	} else if (arg0 == NULL) {
		err(1, "asprintf()");
	}

	execlp(shell, arg0, NULL);
	err(1, "%s", shell);

	/*
	 * That's it, folks!
	 */
}
Example #28
0
void main(int argc,char* argv[])
{
	signal(SIGKILL,wrapup);
	signal(SIGINT,wrapup);
	signal(SIGTERM,wrapup);
	signal(SIGQUIT,wrapup);

	int num_ATMs,i;

	if(argc!=2)
	{
		printf("Please enter : %s <number_of_ATMs>\n", argv[0]);
		exit(0);
	}
	else
		sscanf(argv[1],"%d",&num_ATMs);

	createLocatorFile();

	semID = semget((key_t)SEMAPHORE_KEY,num_ATMs,IPC_CREAT|0666);
	if(semID==-1) perror("Error in semget !\n");

	mssgQ_ID=msgget((key_t)MASTER_MSSG_Q_KEY,IPC_CREAT|0666);
	if(mssgQ_ID==-1) perror("Error in msgget !\n");

	globl_shmID = shmget((key_t)GLOBAL_SHARED_MEMORY_KEY,MAX_CLIENTS*sizeof(struct balance_record),IPC_CREAT|0666);
	if(globl_shmID==-1) perror("Error in shmget !\n");

	globl_shm_ptr = shmat(globl_shmID,NULL,0);
	globl_shm_end_record = globl_shm_ptr; // initially NO client record

	initializeAllSubSemaphoreValues(num_ATMs);

	for(i=0;i<num_ATMs;i++)
	{
		int index,KEY; // the same KEY will be used for both the ATM - Client Message Queue as well as the shared memory of the ATM process

		int pid = fork();
		if(pid == 0)
			{			
				// ATM (forked child) process
				index = getpid() - getppid();
				KEY = 10*index;

				char buf[10];
				sprintf(buf,"%d",KEY);

				//int retv = execlp("atm.c","./atm",buf,NULL);
				int retv = execlp("./atm","./atm",buf,NULL);	
				if(retv == -1) {perror("Error in execlp ! \n"); exit(1);}
			}
		else
		{
			// master(parent) process
			index = pid - getpid();
			KEY = 10*index;

			appendToLocatorFile(index,KEY,index-1,KEY);
			
		}

		//sleep(1);	// sleep for 1 second before generating another process
	}

	while(1)
	{
		int pid;
		int atm_pid;

		struct mssg buffer;
		struct msqid_ds qstat;

		msgrcv(mssgQ_ID,&buffer,sizeof(buffer),getpid(),0);
		msgctl(mssgQ_ID,IPC_STAT,&qstat);

		printf("Master Process received message %s from ATM%d\n\n",buffer.mtext,qstat.msg_lspid-getpid());

		if(sscanf(buffer.mtext,"CHCK_ACCOUNT %d",&pid)==1)
			checkClientAccount(pid);
		else if(strcmp(buffer.mtext,"GLOBAL_CONSISTENCY_CHECK_REQUEST")==0)
		{
			performGlobalConsistencyCheck();

			buffer.mtype=qstat.msg_lspid;
			strcpy(buffer.mtext,"GLOBAL CONSISTENCY CHECK COMPLETION CONFIRMATION ");
			msgsnd(mssgQ_ID,&buffer,sizeof(buffer),0);

		}
		else printf("Invalid Message !\n\n");

	}

	wrapup();
}
Example #29
0
int
main(int argc, char **argv)
{
  int verbose;
  int ca_racket;
  int showtime;
  int setclock;
  const char *host;
  const char *port;
  const char *protocol;
  const char *ca_cert_container;
  int timewarp;
  int leap;
  const char *proxy;

  host = DEFAULT_HOST;
  port = DEFAULT_PORT;
  protocol = DEFAULT_PROTOCOL;
  ca_cert_container = DEFAULT_CERTFILE;
  verbose = 0;
  ca_racket = 1;
  showtime = 0;
  setclock = 1;
  timewarp = 0;
  leap = 0;
  proxy = NULL;

  while (1) {
    int option_index = 0;
    int c;

    static struct option long_options[] =
      {
        {"verbose", 0, 0, 'v'},
        {"showtime", 2, 0, 'V'},
        {"skip-verification", 0, 0, 's'},
        {"help", 0, 0, 'h'},
        {"host", 0, 0, 'H'},
        {"port", 0, 0, 'p'},
        {"protocol", 0, 0, 'P'},
        {"dont-set-clock", 0, 0, 'n'},
        {"certcontainer", 0, 0, 'C'},
        {"timewarp", 0, 0, 't'},
        {"leap", 0, 0, 'l'},
        {"proxy", 0, 0, 'x'},
        {0, 0, 0, 0}
      };

    c = getopt_long(argc, argv, "vV::shH:p:P:nC:tlx:",
                    long_options, &option_index);
    if (c == -1)
      break;

    switch (c) {
      case 'v': verbose = 1; break;
      case 'V': showtime = (optarg && 0 == strcmp("raw", optarg) ? 2:1); break;
      case 's': ca_racket = 0; break;
      case 'h': usage(); exit(1); break;
      case 'H': host = optarg; break;
      case 'p': port = optarg; break;
      case 'P': protocol = optarg; break;
      case 'n': setclock = 0; break;
      case 'C': ca_cert_container = optarg; break;
      case 't': timewarp = 1; break;
      case 'l': leap = 1; break;
      case 'x': proxy = optarg; break;
      case '?': break;
      default : fprintf(stderr, "Unknown option!\n"); usage(); exit(1);
    }
  }

  if (verbose) {
    fprintf(stderr,
      "V: tlsdate version %s\n"
            "V: We were called with the following arguments:\n"
            "V: %s host = %s:%s\n",
            PACKAGE_VERSION,
      ca_racket ? "validate SSL certificates" : "disable SSL certificate check",
            host, port);
    if (0 == ca_racket)
      fprintf(stderr, "WARNING: Skipping certificate verification!\n");
  }

  execlp (TLSDATE_HELPER,
    "tlsdate",
    host,
    port,
    protocol,
    (ca_racket ? "racket" : "unchecked"),
    (verbose ? "verbose" : "quiet"),
    ca_cert_container,
    (setclock ? "setclock" : "dont-set-clock"),
    (showtime ? (showtime == 2 ? "showtime=raw" : "showtime") : "no-showtime"),
    (timewarp ? "timewarp" : "no-fun"),
    (leap ? "leapaway" : "holdfast"),
    (proxy ? proxy : "none"),
    NULL);
  perror("Failed to run tlsdate-helper");
  return 1;
}
Example #30
0
leave()
{
  close_all();
  execlp("syscomm", "syscomm", 0);
  krash("leave", "syscomm load", 1);
}