コード例 #1
0
ファイル: rprimegen.c プロジェクト: GoodiesHQ/RPrimeGen
int16_t main(uint16_t argc, char **argv) {
	if(argc > 4)
		return(_usage(argv, FAILURE));
	setup();
	mpz_set_ui(len1, DEFAULT);
	mpz_set_ui(len2, DEFAULT);
	mpz_set_ui(pair, DEFAULT);
	switch(argc){
		case 4:
			if(mpz_set_str(len1, *(argv+2), 10) == -1 || mpz_set_str(len2, *(argv+3), 10) == -1)
				return _usage(argv, FAILURE);
		case 3:
			if(mpz_set_str(len1, *(argv+2), 10) == -1)
				return _usage(argv, FAILURE);
			if(argc == 3)
				if(mpz_set_str(len2, *(argv+2), 10 == -1))
					return _usage(argv, FAILURE);
		case 2:
			if(mpz_set_str(pair, *(argv+1), 10) == -1)
				return _usage(argv, FAILURE);
	}
	assert(mpz_sgn(len1) > 0);
	assert(mpz_sgn(len2) > 0);
	assert(mpz_sgn(pair) > 0);
	gmp_printf("Generating %Zd relatively prime pairs of lengths %Zd and %Zd:\n\n", pair, len1, len2);
	setlimits();
	setseed();
	while(mpz_sgn(pair)){
		genpair();
		if(!impossible){
			gmp_printf("Pair Found:  %Zd\t%Zd\n", num1, num2);
			mpz_sub_ui(pair, pair, 1);
		}
	}
}
コード例 #2
0
int main(int argc, char ** argv)
{
    DIR * cleandir;
    struct dirent * curfile;
    unsigned long long curval;

	setlimits();
	if(argc!=3)
		usage();
	matchlimit = atoi(argv[1]);
	if(matchlimit == 0)
		usage();

    cleandir = opendir(argv[2]);
    if(cleandir == NULL)
    {
        perror(argv[2]);
        return 3;
    }

    while(curfile = readdir(cleandir))
    {
        if(curfile->d_name[0] == '.')
            continue;
        curval = load_rules(curfile->d_name);
        if(curval < matchlimit)
            printf("%s %lld\n", curfile->d_name, curval);
    }

	return 0;
}
コード例 #3
0
ファイル: safeexec.c プロジェクト: ochko/safeexec
int main (int argc, char **argv, char **envp)
{

  struct rusage usage;

  char **p;
  int status, mem, skipped, memused;
  int tsource, ttarget;
  int v;

  redirect = stderr;
  safe_signal (SIGPIPE, SIG_DFL);

  tsource = time (NULL);
  p = parse (argv);
  if (p == NULL)
    {
      printusage (argv);
      return (EXIT_FAILURE);
    }
  else
    {
      /* Get an unused uid */
      if (profile.minuid != profile.maxuid)
        {
          srand (time (NULL) ^ getpid ());
          profile.minuid += rand () % (profile.maxuid - profile.minuid);
        }

      if (strcmp (usage_file, "/dev/null") != 0)
        {
          redirect = fopen (usage_file, "w");
          chown (usage_file, profile.minuid, getgid());
          chmod (usage_file, 0640);
          if (redirect == NULL)
            error ("Couldn't open usage file\n");
        }

      /* stderr from user program is junk */
      junk = fopen (error_file, "w");
      if (junk == NULL)
        error ("Couldn't open junk file %s\n", error_file);
      if (strcmp (error_file, "/dev/null") != 0)
        {
          chown (error_file, profile.minuid, getgid());
          chmod (error_file, 0640);
        }

      if (setgid (profile.minuid) < 0)
        {
          if (errno == EPERM)
            {
              error ("Couldn't setgid due to permission");
            }
          else
            {
              error (NULL);
            }
        }
      if (setuid (profile.minuid) < 0)
        {
          if (errno == EPERM)
            {
              error ("Couldn't setuid due to permission");
            }
          else
            {
              error (NULL);
            }
        }


      if (getuid () == 0)
        error ("Not changing the uid to an unpriviledged one is a BAD ideia");

      if (signal (SIGALRM, wallclock) == SIG_ERR)
        error ("Couldn't install signal handler");

      if (alarm (profile.clock) != 0)
        error ("Couldn't set alarm");

      /* Fork new process */
      pid = fork ();
      if (pid < 0)
        error (NULL);

      if (pid == 0)
        /* Forked/child process */
        {
          /* Chrooting */
          if (chroot_dir != NULL)
            {
              if (0 != chdir(chroot_dir))
                {
                  kill (getpid (), SIGPIPE);
                  error ("Can not change to chroot dir");
                }
              if (0 != chroot(chroot_dir))
                {
                  kill (getpid (), SIGPIPE);
                  error ("Can not chroot");
                }
            }
          /* Change dir */
          if (run_dir != NULL)
            {
              if (0 != chdir(run_dir))
                {
                  kill (getpid (), SIGPIPE);
                  error ("Cannot change to rundir");
                }
            }

          dup2(fileno(junk), fileno(stderr));

          if (setuid (profile.minuid) < 0)
            error (NULL);

          /* Don't run as root */
          if (getuid () == 0)
            error ("Running as a root is not secure!");

          /* Set priority */
          if (0 != setpriority(PRIO_USER,profile.minuid,NICE_LEVEL))
            {
              kill (getpid (), SIGPIPE);
              error (NULL);
            }

          /* Set resource limits - memory, time etc */
          setlimits(profile);

          /* Execute the program */
          if (execve (*p, p, envp) < 0)
            {
              kill (getpid (), SIGPIPE);
              error (NULL);
            }
        }
      else
        /* Parent process */
        {
          if (setuid (profile.minuid) < 0)
            error (NULL);

          if (getuid () == 0)
            error ("Running as a root is not secure!");

          memusage_init ();

          mark = OK;

          /* Poll every INTERVAL ms and get the maximum   *
           * memory usage, exit when the child terminates */
          mem = 64;
          skipped = 0;
          memused = 0;
          do
            {
              msleep (INTERVAL);
              memused = memusage (pid);
              if (memused > -1)
                {
                  mem = max (mem, memused);
                }
              else
                { /* Can not read memory usage! */
                  skipped++;
                }

              if (skipped > 10)
                { /* process is already finished or something wrong happened */
                  terminate (pid);
                  mark = MLE;
                }

              if (mem > profile.memory)
                {
                  terminate (pid);
                  mark = MLE;
                }

              do
                v = wait4 (pid, &status, WNOHANG | WUNTRACED, &usage);
              //v = wait4 (pid, &status, WNOHANG | WUNTRACED | WCONTINUED | WEXITED, &usage);
              while ((v < 0) && (errno != EINTR));
              if (v < 0)
                error (NULL);
            }
          while (v == 0);

          memusage_close ();

          ttarget = time (NULL);

          if (mark == MLE)
            printstats ("Memory Limit Exceeded\n");
          else if (mark == RTLE)
            printstats ("Time Limit Exceeded\n");
          else
            {
              if (WIFEXITED (status) != 0)
                {
                  if (WEXITSTATUS (status) != 0)
                    printstats ("Command exited with non-zero status (%d)\n",
                                WEXITSTATUS (status));
                  else
                    printstats ("OK\n");
                }
              else
                {
                  if (WIFSIGNALED (status) != 0)
                    {
                      /* Was killed for a TLE (or was it an OLE) */
                      if (WTERMSIG (status) == SIGKILL)
                        mark = TLE;
                      else if (WTERMSIG (status) == SIGXFSZ)
                        mark = OLE;
                      else if (WTERMSIG (status) == SIGHUP)
                        mark = RF;
                      else if (WTERMSIG (status) == SIGPIPE)
                        mark = IE;
                      else
                        printstats ("Command terminated by signal (%d: %s)\n",
                                    WTERMSIG (status),
                                    name (WTERMSIG (status)));
                    }
                  else if (WIFSTOPPED (status) != 0)
                    printstats ("Command terminated by signal (%d: %s)\n",
                                WSTOPSIG (status), name (WSTOPSIG (status)));
                  else
                    printstats ("OK\n");

                  if (mark == TLE)
                    {
                      /* We know the child has terminated at right time(OS did). *
                       * But seing 1.990 as TLE while limit 2.0 is confusing.    *
                       * So here is small adjustment for presentation.           */
                      usage.ru_utime.tv_sec = profile.cpu;
                      usage.ru_utime.tv_usec = 0;
                      printstats ("Time Limit Exceeded\n");
                    }
                  else if (mark == OLE)
                    printstats ("Output Limit Exceeded\n");
                  else if (mark == RTLE)
                    printstats ("Time Limit Exceeded\n");
                  else if (mark == RF)
                    printstats ("Invalid Function\n");
                  else if (mark == IE)
                    printstats ("Internal Error\n");
                }
            }
          printstats ("elapsed time: %d seconds\n", ttarget - tsource);
          printstats ("memory usage: %d kbytes\n", mem);
          printstats ("cpu usage: %0.3f seconds\n",
                      (float) miliseconds (&usage.ru_utime) / 1000.0);
        }
    }
  fclose (redirect);

  return (EXIT_SUCCESS);
}
コード例 #4
0
ファイル: bsd-cray.c プロジェクト: AlfredArouna/illumos-gate
int
cray_setup (uid_t uid, char *username, const char *command)
{
	extern struct udb *getudb();
	extern char *setlimits();

	int err;                      /* error return */
	time_t		system_time;	/* current system clock */
	time_t		expiration_time; /* password expiration time */
	int		maxattempts;	/* maximum no. of failed login attempts */
	int		SecureSys;	/* unicos security flag */
	int		minslevel = 0;	/* system minimum security level */
	int		i, j;
	int		valid_acct = -1; /* flag for reading valid acct */
	char acct_name[MAXACID]  = { "" }; /* used to read acct name */
	struct		jtab jtab;	/* Job table struct */
	struct		udb ue;		/* udb entry for logging-in user */
	struct		udb *up;	/* pointer to UDB entry */
	struct		secstat secinfo; /* file  security attributes */
	struct          servprov init_info; /* used for sesscntl() call */
	int		jid;		/* job ID */
	int		pid;		/* process ID */
	char		*sr;            /* status return from setlimits() */
	char		*ttyn = NULL;	/* ttyname or command name*/
	char		hostname[MAXHOSTNAMELEN];
	passwd_t	pwdacm,
			pwddialup,
			pwdudb,
			pwdwal,
			pwddce;		/* passwd stuff for ia_user */
	ia_user_ret_t	uret;		/* stuff returned from ia_user */
	ia_user_t	usent;		/* ia_user main structure */
	int		ia_rcode;	/* ia_user return code */
	ia_failure_t	fsent;		/* ia_failure structure */
	ia_failure_ret_t fret;		/* ia_failure return stuff */
	ia_success_t	ssent;		/* ia_success structure */
	ia_success_ret_t sret;		/* ia_success return stuff */
	int		ia_mlsrcode;    /* ia_mlsuser return code */
	int		secstatrc;      /* [f]secstat return code */

	if (SecureSys = (int)sysconf(_SC_CRAY_SECURE_SYS)) {
		getsysv(&sysv, sizeof(struct sysv));
		minslevel = sysv.sy_minlvl;
		if (getusrv(&usrv) < 0) {
			debug("getusrv() failed, errno = %d",errno);
			exit(1);
		}
	}
	hostname[0] = '\0';
	strncpy(hostname,
	   (char *)get_canonical_hostname(options.verify_reverse_mapping),
	   MAXHOSTNAMELEN);
        /*
         *  Fetch user's UDB entry.
         */
        getsysudb();
        if ((up = getudbnam(username)) == UDB_NULL) {
                debug("cannot fetch user's UDB entry");
                exit(1);
        }

        /*
         *  Prevent any possible fudging so perform a data
         *  safety check and compare the supplied uid against
         *  the udb's uid.
         */
        if (up->ue_uid != uid) {
                debug("IA uid missmatch");
                exit(1);
        }
	endudb();

	if ((jid = getjtab (&jtab)) < 0) {
		debug("getjtab");
		return -1;
	}
	pid = getpid();
	ttyn = ttyname(0);
	if (SecureSys) {
		if (ttyn) {
			secstatrc = secstat(ttyn, &secinfo);
		} else {
			secstatrc = fsecstat(1, &secinfo);
		}
		if (secstatrc == 0) {
			debug("[f]secstat() successful");
		} else {
			debug("[f]secstat() error, rc = %d", secstatrc);
			exit(1);
		}
	}
	if ((ttyn == NULL) && ((char *)command != NULL))
		ttyn = (char *)command;
        /*
         *  Initialize all structures to call ia_user
         */
        usent.revision = 0;
        usent.uname    = username;
        usent.host     = hostname;
        usent.ttyn     = ttyn;
        usent.caller   = IA_SSHD; 
        usent.pswdlist = &pwdacm;
        usent.ueptr    = &ue;
        usent.flags    = IA_INTERACTIVE | IA_FFLAG;
        pwdacm.atype   = IA_SECURID;
        pwdacm.pwdp    = NULL;
        pwdacm.next    = &pwdudb;

        pwdudb.atype   = IA_UDB;
        pwdudb.pwdp    = NULL;
        pwdudb.next    = &pwddce;

        pwddce.atype   = IA_DCE;
        pwddce.pwdp    = NULL;
        pwddce.next    = &pwddialup;

        pwddialup.atype = IA_DIALUP;
        pwddialup.pwdp  = NULL;
        /* pwddialup.next  = &pwdwal; */
        pwddialup.next  = NULL;

        pwdwal.atype = IA_WAL;
        pwdwal.pwdp  = NULL;
        pwdwal.next  = NULL;

        uret.revision = 0;
        uret.pswd     = NULL;
        uret.normal   = 0;

        ia_rcode = ia_user(&usent, &uret);

        switch (ia_rcode) {
                /*
                 *  These are acceptable return codes from ia_user()
                 */
                case IA_UDBWEEK:        /* Password Expires in 1 week */
		     expiration_time = ue.ue_pwage.time + ue.ue_pwage.maxage;
		     printf ("WARNING - your current password will expire %s\n",
                     ctime((const time_t *)&expiration_time));
                     break;
                case IA_UDBEXPIRED:
		     if (ttyname(0) != NULL) {
		     /* Force a password change */
		         printf("Your password has expired; Choose a new one.\n");
		         execl("/bin/passwd", "passwd", username, 0);
		         exit(9);
		     }

		     break;
                case IA_NORMAL:         /* Normal Return Code */
                     break;
                case IA_BACKDOOR:
                     strcpy(ue.ue_name, "root");
                     strcpy(ue.ue_passwd, "");
                     strcpy(ue.ue_dir, "/");
                     strcpy(ue.ue_shell, "/bin/sh");
                     strcpy(ue.ue_age, "");
                     strcpy(ue.ue_comment, "");
                     strcpy(ue.ue_loghost, "");
                     strcpy(ue.ue_logline, "");
                     ue.ue_uid=-1;
                     ue.ue_nice[UDBRC_INTER]=0;
                     for (i=0;i<MAXVIDS;i++)
                         ue.ue_gids[i]=0;
                     ue.ue_logfails=0;
                     ue.ue_minlvl=minslevel; 
                     ue.ue_maxlvl=minslevel;
                     ue.ue_deflvl=minslevel;
                     ue.ue_defcomps=0;
                     ue.ue_comparts=0;
                     ue.ue_permits=0;
                     ue.ue_trap=0;
                     ue.ue_disabled=0;
                     ue.ue_logtime=0;
                     break;
                case IA_CONSOLE:        /* Superuser not from Console */
		case IA_TRUSTED:	/* Trusted user */
		     if (options.permit_root_login > PERMIT_NO)
                     	break;		/* Accept root login */
   	        default:
                /*
                 *  These are failed return codes from ia_user()
                 */
		     switch (ia_rcode) 
		       {
		       case IA_BADAUTH:
			 printf ("Bad authorization, access denied.\n");
			 break;
		       case IA_DIALUPERR:
			 break;
		       case IA_DISABLED:
			 printf ("Your login has been disabled. Contact the system ");
			 printf ("administrator for assistance.\n");
			 break;
		       case IA_GETSYSV:
			 printf ("getsysv() failed - errno = %d\n", errno);
			 break;
		       case IA_LOCALHOST:
			 break;
		       case IA_MAXLOGS:
			 printf ("Maximum number of failed login attempts exceeded.\n");
			 printf ("Access denied.\n");
			 break;
		       case IA_NOPASS:
			 break;
		       case IA_PUBLIC:
			 break;
		       case IA_SECURIDERR:
			 break;
		       case IA_CONSOLE:
			 break;
		       case IA_TRUSTED:
			 break;
		       case IA_UDBERR:
			 break;
		       case IA_UDBPWDNULL:
			 /* 
			  * NULL password not allowed on MLS systems
			  */
			 if (SecureSys) {
			   printf("NULL Password not allowed on MLS systems.\n");
			 }
			 break;
		       case IA_UNKNOWN:
			 break;
		       case IA_UNKNOWNYP:
			 break;
		       case IA_WALERR:
			 break;
		       default:
			 /* nothing special */
			 ;
		       }   /* 2. switch  (ia_rcode) */
		     /*
		      *  Authentication failed.
		      */
		     printf("sshd: Login incorrect, (0%o)\n",
			    ia_rcode-IA_ERRORCODE);
		     
		     /*
		      *  Initialize structure for ia_failure
		      *  which will exit.
		      */
		     fsent.revision = 0;
		     fsent.uname    = username;
		     fsent.host     = hostname;
		     fsent.ttyn     = ttyn;
		     fsent.caller   = IA_SSHD;
		     fsent.flags    = IA_INTERACTIVE;
		     fsent.ueptr    = &ue;
		     fsent.jid      = jid;
		     fsent.errcode  = ia_rcode;
		     fsent.pwdp     = uret.pswd;
		     fsent.exitcode = 1;
		     
		     fret.revision  = 0;
		     fret.normal    = 0;
		     
		     /*
		      *  Call ia_failure because of an IA failure.
		      *  There is no return because ia_failure exits.
		      */
	
		     ia_failure(&fsent,&fret);

		     exit(1); 
	}   /* 1. switch  (ia_rcode) */
	ia_mlsrcode = IA_NORMAL;
	if (SecureSys) {
		debug("calling ia_mlsuser()");
		ia_mlsrcode = ia_mlsuser (&ue, &secinfo, &usrv, NULL, 0);
	}
	if (ia_mlsrcode != IA_NORMAL) {
		printf("sshd: Login incorrect, (0%o)\n",
		ia_mlsrcode-IA_ERRORCODE);
		/*
 		 *  Initialize structure for ia_failure
 		 *  which will exit.
		*/
		fsent.revision = 0;
		fsent.uname    = username;
		fsent.host     = hostname;
		fsent.ttyn     = ttyn;
		fsent.caller   = IA_SSHD;
		fsent.flags    = IA_INTERACTIVE;
		fsent.ueptr    = &ue;
		fsent.jid      = jid;
		fsent.errcode  = ia_mlsrcode;
		fsent.pwdp     = uret.pswd;
		fsent.exitcode = 1;
		fret.revision  = 0;
		fret.normal    = 0;

		/*
		*  Call ia_failure because of an IA failure.
		*  There is no return because ia_failure exits.
		*/
		ia_failure(&fsent,&fret);
		exit(1); 
	}

        /* Provide login status information */
        if (options.print_lastlog && ue.ue_logtime != 0) {
            printf("Last successful login was : %.*s ",
                    19, (char *)ctime(&ue.ue_logtime));
  
           if (*ue.ue_loghost != '\0')
                printf("from %.*s\n", sizeof(ue.ue_loghost), ue.ue_loghost);
 
            else printf("on %.*s\n", sizeof(ue.ue_logline), ue.ue_logline);
 
            if ( SecureSys && (ue.ue_logfails != 0)) 
                printf("  followed by %d failed attempts\n", ue.ue_logfails);
        }

	
	/*
	 * Call ia_success to process successful I/A.
	 */
	ssent.revision = 0;
	ssent.uname = username;
	ssent.host = hostname;
	ssent.ttyn = ttyn;
	ssent.caller = IA_SSHD;
	ssent.flags = IA_INTERACTIVE;
	ssent.ueptr = &ue;
	ssent.jid = jid;
	ssent.errcode = ia_rcode;
	ssent.us = NULL;
	ssent.time = 1;      		 /* Set ue_logtime */

	sret.revision = 0;
	sret.normal = 0;

	ia_success(&ssent,&sret);

        /*
         * Query for account, iff > 1 valid acid & askacid permbit
         */
        if (((ue.ue_permbits & PERMBITS_ACCTID) ||
             (ue.ue_acids[0] >= 0) && (ue.ue_acids[1] >= 0)) &&
            ue.ue_permbits & PERMBITS_ASKACID) {
		if (ttyname(0) != NULL) {
		  debug("cray_setup: ttyname true case, %.100s", ttyname);
                  while (valid_acct == -1) {
                        printf("Account (? for available accounts)"
                               " [%s]: ", acid2nam(ue.ue_acids[0]));
                        gets(acct_name);
                        switch (acct_name[0]) {
                        case EOF:
                                exit(0);
                                break;
                        case '\0':
                                valid_acct = ue.ue_acids[0];
                                strcpy(acct_name, acid2nam(valid_acct));
                                break;
                        case '?':
                                /* Print the list 3 wide */
                                for (i = 0, j = 0; i < MAXVIDS; i++) {
                                        if (ue.ue_acids[i] == -1) {
                                                printf("\n");
                                                break;
                                        }
                                        if (++j == 4) {
                                                j = 1;
                                                printf("\n");
                                        }
                                        printf(" %s",
                                               acid2nam(ue.ue_acids[i]));
                                }
                                if (ue.ue_permbits & PERMBITS_ACCTID)
                                        printf("\"acctid\" permbit also allows"
                                               " you to select any valid "
                                               "account name.\n");
                                printf("\n");
                                break;
                        default:
                                if ((valid_acct = nam2acid(acct_name)) == -1)                                        printf("Account id not found for"
                                               " account name \"%s\"\n\n",
                                               acct_name);
                                break;
                        }
                        /*
                         * If an account was given, search the user's
                         * acids array to verify they can use this account.
                         */
                        if ((valid_acct != -1) &&
                            !(ue.ue_permbits & PERMBITS_ACCTID)) {
                                for (i = 0; i < MAXVIDS; i++) {
                                        if (ue.ue_acids[i] == -1)
                                                break;
                                        if (valid_acct == ue.ue_acids[i])
                                                break;
                                }
                                if (i == MAXVIDS ||
                                    ue.ue_acids[i] == -1) {
                                        fprintf(stderr, "Cannot set"
                                                " account name to "
                                                "\"%s\", permission "
                                                "denied\n\n", acct_name);
                                        valid_acct = -1;
                                }
                        }
                  }
		} else {
			/*
			 * The client isn't connected to a terminal and can't
			 * respond to an acid prompt.  Use default acid.
			 */
			debug("cray_setup: ttyname false case, %.100s", ttyname);
			valid_acct = ue.ue_acids[0];
		}
        } else {
                /*
                 * The user doesn't have the askacid permbit set or
                 * only has one valid account to use.
                 */
                valid_acct = ue.ue_acids[0];
        }
        if (acctid(0, valid_acct) < 0) {
                printf ("Bad account id: %d\n", valid_acct);
                exit(1);
        }

/* set up shares and quotas */
/* Now set shares, quotas, limits, including CPU time for the (interactive) 
 * job and process, and set up permissions (for chown etc), etc.
 */
	if (setshares(ue.ue_uid, valid_acct, printf, 0, 0)) {
		printf("Unable to give %d shares to <%s>(%d/%d)\n", ue.ue_shares, ue.ue_name, ue.ue_uid, valid_acct);
		exit(1);
        }

	sr = setlimits(username, C_PROC, pid, UDBRC_INTER);
	if (sr != NULL) {
		debug("%.200s", sr);
		exit(1);
	}
	sr = setlimits(username, C_JOB, jid, UDBRC_INTER);
	if (sr != NULL) {
		debug("%.200s", sr);
		exit(1);
	}
	/*
 	 * Place the service provider information into
	 * the session table (Unicos) or job table (Unicos/mk).
	 * There exist double defines for the job/session table in
	 * unicos/mk (jtab.h) so no need for a compile time switch.
	 */
	bzero((char *)&init_info, sizeof(struct servprov));
	init_info.s_sessinit.si_id  = URM_SPT_LOGIN;
	init_info.s_sessinit.si_pid = getpid();
	init_info.s_sessinit.si_sid = jid;
	init_info.s_routing.seqno = 0;
	init_info.s_routing.iadrs = 0;
	sesscntl(0, S_SETSERVPO, (int)&init_info);

	/*
	 * Set user and controlling tty security attributes.
	 */
	if (SecureSys) {
		if (setusrv(&usrv) == -1) {
			debug("setusrv() failed, errno = %d",errno);
			exit(1);
		}
	}

        return(0);
}
コード例 #5
0
ファイル: ra.c プロジェクト: bartavelle/rulesfinder
int main(int argc, char ** argv)
{
    unsigned int i;
    pthread_t * threads;
    unsigned int * ids;

    double maxval;
    double curval;
    struct s_rule_link * root;
    struct s_rule_link * prevlink;
    struct s_rule_link * curlink;
    struct s_rule_link * tmplink;
    struct s_rule_link * maxlink;
		int maxrulelen = 500;
    avl_tree_t * oldcoverage;
    avl_node_t * scoverage;
    avl_node_t * scoverage2;
    BLOOM_TYPE * bloom;
    uint64_t curindex;
    uint64_t nbleft;
    double wordlistProcessingTime, candidateProcessingTime;
    char * endptr;

    setlimits();
    if(argc<6)
        usage();
    matchlimit = atoi(argv[1]);
    if(matchlimit == 0)
        usage();
    nbthreads = atoi(argv[2]);
    if(nbthreads == 0)
        nbthreads = 1;
    wordlistProcessingTime = strtod(argv[3], &endptr);
    // weak check
    if(endptr == argv[3])
    {
        fprintf(stderr, "Could not parse wordlistProcessingTime\n");
        usage();
    }
    candidateProcessingTime = strtod(argv[4], &endptr);
    if(endptr == argv[4])
    {
        fprintf(stderr, "Could not parse candidateProcessingTime: %s\n", argv[4]);
        usage();
    }

    fprintf(stderr, "Wordlist processing time: %es / Candidate processing time: %es/candidate\n", wordlistProcessingTime, candidateProcessingTime);

    nbfiles = argc-5;
    threads = xmalloc(sizeof(pthread_t)*nbthreads);
    memset(threads, 0, sizeof(pthread_t)*nbthreads);
    ids = xmalloc(sizeof(unsigned int)*nbthreads);
    rulejob = xmalloc(sizeof(struct s_rulejob)*nbfiles);
    bloom = xmalloc(BLOOM_STORAGE);
    for(i=0;i<nbfiles;i++)
    {
        rulejob[i].root = NULL;
        rulejob[i].tail = NULL;
        rulejob[i].done_by = -1;
        rulejob[i].filename = argv[i+5];
    }

    for(i=0;i<nbthreads;i++)
    {
        ids[i] = i;
        if(pthread_create(&threads[i], NULL, load_rules, &ids[i]))
        {
            fprintf(stderr, "error, could not create thread for file %s\n", argv[i+4]);
            perror("pthread_create");
            return 1;
        }
    }

    for(i=0;i<nbthreads;i++)
        pthread_join( threads[i], NULL );

    root = NULL;
    for(i=0;i<nbfiles;i++)
    {
        if(rulejob[i].tail == NULL)
            continue;
        rulejob[i].tail->next = root;
        root = rulejob[i].root;
    }
    free(rulejob);

    fprintf(stderr, "start crunching\n");

    oldcoverage = NULL;
    while(1)
    {
        maxval = 0;
        curlink = root;
        prevlink = NULL;
        maxlink = NULL;
        nbleft = 0;
        while(curlink)
        {
            if(curlink->coverage == NULL)
                curval = 1e50;
            else
            {
                if(oldcoverage)
                {
                    /* coverage cleanup */
                    scoverage = curlink->coverage->head;
                    while(scoverage)
                    {
                        curindex = (uint64_t) scoverage->item;
                        if(GETBIT(bloom, curindex) && avl_search(oldcoverage, (void *) curindex))
                        {
                            scoverage2 = scoverage->next;
                            avl_delete_node(curlink->coverage, scoverage);
                            scoverage = scoverage2;
                        }
                        else
                        {
                            nbleft++;
                            scoverage = scoverage->next;
                        }
                    }
                }
                curval = ((double) avl_count(curlink->coverage)) / ( ((double) curlink->pwtested )*candidateProcessingTime + wordlistProcessingTime) ;
            }
            if( (curlink->coverage == NULL) || (avl_count(curlink->coverage) <matchlimit))
            {
                if(curlink->rule)
                {
                    free(curlink->rule);
                }
                if(curlink->coverage)
                {
                    avl_free_tree(curlink->coverage);
                }
                if(prevlink)
                    prevlink->next = curlink->next;
                else
                    root = curlink->next;
                tmplink = curlink;
                curlink = curlink->next;
                free(tmplink);
                continue;
            }
            if(curval>maxval || (curval == maxval && strlen(curlink->rule) < maxrulelen ) )
            {
								maxrulelen = strlen(curlink->rule);
                maxval = curval;
                maxlink = curlink;
            }
            prevlink = curlink;
            curlink = curlink->next;
        }
        if(maxlink == NULL)
            break;
        if(oldcoverage)
            avl_free_tree(oldcoverage);
        oldcoverage = maxlink->coverage;

        /* build bloom filter */
        memset(bloom, 0, BLOOM_STORAGE);
        scoverage = oldcoverage->head;
        while(scoverage)
        {
            //pcurindex = scoverage->item;
            //curindex = *pcurindex;
            curindex = (uint64_t) scoverage->item;
            SETBIT(bloom, curindex);
            scoverage = scoverage->next;
        }

        maxlink->coverage = NULL;
        printf("%s NBPWD=%d [%f]\n", maxlink->rule, avl_count(oldcoverage), maxval);
        fprintf(stderr, "%s NBPWD=%d [%f] NBRULES=%ld\n", maxlink->rule, avl_count(oldcoverage), maxval, nbleft);
    }
    return 0;
}
コード例 #6
0
ファイル: main.c プロジェクト: jrmithdobbs/netatalk-2-2-0-p6
int main(int ac, char **av)
{
    AFPConfig           *config;
    fd_set              rfds;
    void                *ipc;
    struct sigaction	sv;
    sigset_t            sigs;
    int                 ret;

#ifdef TRU64
    argc = ac;
    argv = av;
    set_auth_parameters( ac, av );
#endif /* TRU64 */

    /* Log SIGBUS/SIGSEGV SBT */
    fault_setup(NULL);

    /* Default log setup: log to syslog */
    setuplog("default log_note");

    afp_options_init(&default_options);
    if (!afp_options_parse(ac, av, &default_options))
        exit(EXITERR_CONF);

    /* Save the user's current umask for use with CNID (and maybe some 
     * other things, too). */
    default_options.save_mask = umask( default_options.umask );

    switch(server_lock("afpd", default_options.pidfile,
                       default_options.flags & OPTION_DEBUG)) {
    case -1: /* error */
        exit(EXITERR_SYS);
    case 0: /* child */
        break;
    default: /* server */
        exit(0);
    }
    atexit(afp_exit);

    /* install child handler for asp and dsi. we do this before afp_goaway
     * as afp_goaway references stuff from here. 
     * XXX: this should really be setup after the initial connections. */
    if (!(server_children = server_child_alloc(default_options.connections,
                            CHILD_NFORKS))) {
        LOG(log_error, logtype_afpd, "main: server_child alloc: %s", strerror(errno) );
        exit(EXITERR_SYS);
    }

    memset(&sv, 0, sizeof(sv));    
    /* linux at least up to 2.4.22 send a SIGXFZ for vfat fs,
       even if the file is open with O_LARGEFILE ! */
#ifdef SIGXFSZ
    sv.sa_handler = SIG_IGN;
    sigemptyset( &sv.sa_mask );
    if (sigaction(SIGXFSZ, &sv, NULL ) < 0 ) {
        LOG(log_error, logtype_afpd, "main: sigaction: %s", strerror(errno) );
        exit(EXITERR_SYS);
    }
#endif
    
    sv.sa_handler = child_handler;
    sigemptyset( &sv.sa_mask );
    sigaddset(&sv.sa_mask, SIGALRM);
    sigaddset(&sv.sa_mask, SIGHUP);
    sigaddset(&sv.sa_mask, SIGTERM);
    sigaddset(&sv.sa_mask, SIGUSR1);
    sigaddset(&sv.sa_mask, SIGQUIT);    
    sv.sa_flags = SA_RESTART;
    if ( sigaction( SIGCHLD, &sv, NULL ) < 0 ) {
        LOG(log_error, logtype_afpd, "main: sigaction: %s", strerror(errno) );
        exit(EXITERR_SYS);
    }

    sv.sa_handler = afp_goaway;
    sigemptyset( &sv.sa_mask );
    sigaddset(&sv.sa_mask, SIGALRM);
    sigaddset(&sv.sa_mask, SIGTERM);
    sigaddset(&sv.sa_mask, SIGHUP);
    sigaddset(&sv.sa_mask, SIGCHLD);
    sigaddset(&sv.sa_mask, SIGQUIT);
    sv.sa_flags = SA_RESTART;
    if ( sigaction( SIGUSR1, &sv, NULL ) < 0 ) {
        LOG(log_error, logtype_afpd, "main: sigaction: %s", strerror(errno) );
        exit(EXITERR_SYS);
    }

    sigemptyset( &sv.sa_mask );
    sigaddset(&sv.sa_mask, SIGALRM);
    sigaddset(&sv.sa_mask, SIGTERM);
    sigaddset(&sv.sa_mask, SIGUSR1);
    sigaddset(&sv.sa_mask, SIGCHLD);
    sigaddset(&sv.sa_mask, SIGQUIT);
    sv.sa_flags = SA_RESTART;
    if ( sigaction( SIGHUP, &sv, NULL ) < 0 ) {
        LOG(log_error, logtype_afpd, "main: sigaction: %s", strerror(errno) );
        exit(EXITERR_SYS);
    }


    sigemptyset( &sv.sa_mask );
    sigaddset(&sv.sa_mask, SIGALRM);
    sigaddset(&sv.sa_mask, SIGHUP);
    sigaddset(&sv.sa_mask, SIGUSR1);
    sigaddset(&sv.sa_mask, SIGCHLD);
    sigaddset(&sv.sa_mask, SIGQUIT);
    sv.sa_flags = SA_RESTART;
    if ( sigaction( SIGTERM, &sv, NULL ) < 0 ) {
        LOG(log_error, logtype_afpd, "main: sigaction: %s", strerror(errno) );
        exit(EXITERR_SYS);
    }

    sigemptyset( &sv.sa_mask );
    sigaddset(&sv.sa_mask, SIGALRM);
    sigaddset(&sv.sa_mask, SIGHUP);
    sigaddset(&sv.sa_mask, SIGUSR1);
    sigaddset(&sv.sa_mask, SIGCHLD);
    sigaddset(&sv.sa_mask, SIGTERM);
    sv.sa_flags = SA_RESTART;
    if (sigaction(SIGQUIT, &sv, NULL ) < 0 ) {
        LOG(log_error, logtype_afpd, "main: sigaction: %s", strerror(errno) );
        exit(EXITERR_SYS);
    }

    /* afpd.conf: not in config file: lockfile, connections, configfile
     *            preference: command-line provides defaults.
     *                        config file over-writes defaults.
     *
     * we also need to make sure that killing afpd during startup
     * won't leave any lingering registered names around.
     */

    sigemptyset(&sigs);
    sigaddset(&sigs, SIGALRM);
    sigaddset(&sigs, SIGHUP);
    sigaddset(&sigs, SIGUSR1);
#if 0
    /* don't block SIGTERM */
    sigaddset(&sigs, SIGTERM);
#endif
    sigaddset(&sigs, SIGCHLD);

    pthread_sigmask(SIG_BLOCK, &sigs, NULL);
    if (!(configs = configinit(&default_options))) {
        LOG(log_error, logtype_afpd, "main: no servers configured");
        exit(EXITERR_CONF);
    }
    pthread_sigmask(SIG_UNBLOCK, &sigs, NULL);

    /* Register CNID  */
    cnid_init();

    /* watch atp, dsi sockets and ipc parent/child file descriptor. */
    disasociated_ipc_fd = ipc_server_uds(_PATH_AFP_IPC);
    fd_set_listening_sockets();

    /* set limits */
    (void)setlimits();

    afp_child_t *child;
    int fd[2];  /* we only use one, but server_child_add expects [2] */
    pid_t pid;

    /* wait for an appleshare connection. parent remains in the loop
     * while the children get handled by afp_over_{asp,dsi}.  this is
     * currently vulnerable to a denial-of-service attack if a
     * connection is made without an actual login attempt being made
     * afterwards. establishing timeouts for logins is a possible 
     * solution. */
    while (1) {
        LOG(log_maxdebug, logtype_afpd, "main: polling %i fds", fdset_used);
        pthread_sigmask(SIG_UNBLOCK, &sigs, NULL);
        ret = poll(fdset, fdset_used, -1);
        pthread_sigmask(SIG_BLOCK, &sigs, NULL);
        int saveerrno = errno;

        if (reloadconfig) {
            nologin++;
            auth_unload();
            fd_reset_listening_sockets();

            LOG(log_info, logtype_afpd, "re-reading configuration file");
            for (config = configs; config; config = config->next)
                if (config->server_cleanup)
                    config->server_cleanup(config);

            /* configfree close atp socket used for DDP tickle, there's an issue
             * with atp tid. */
            configfree(configs, NULL);
            if (!(configs = configinit(&default_options))) {
                LOG(log_error, logtype_afpd, "config re-read: no servers configured");
                exit(EXITERR_CONF);
            }

            fd_set_listening_sockets();

            nologin = 0;
            reloadconfig = 0;
            errno = saveerrno;
            continue;
        }

        if (ret == 0)
            continue;
        
        if (ret < 0) {
            if (errno == EINTR)
                continue;
            LOG(log_error, logtype_afpd, "main: can't wait for input: %s", strerror(errno));
            break;
        }

        for (int i = 0; i < fdset_used; i++) {
            if (fdset[i].revents & (POLLIN | POLLERR | POLLHUP)) {
                switch (polldata[i].fdtype) {

                case LISTEN_FD:
                    config = (AFPConfig *)polldata[i].data;
                    /* config->server_start is afp_config.c:dsi_start() for DSI */
                    if (child = config->server_start(config, configs, server_children)) {
                        /* Add IPC fd to select fd set */
                        fdset_add_fd(&fdset, &polldata, &fdset_used, &fdset_size, child->ipc_fds[0], IPC_FD, child);
                    }
                    break;

                case IPC_FD:
                    child = (afp_child_t *)polldata[i].data;
                    LOG(log_debug, logtype_afpd, "main: IPC request from child[%u]", child->pid);

                    if (ipc_server_read(server_children, child->ipc_fds[0]) != 0) {
                        fdset_del_fd(&fdset, &polldata, &fdset_used, &fdset_size, child->ipc_fds[0]);
                        close(child->ipc_fds[0]);
                        child->ipc_fds[0] = -1;
                        if (child->disasociated) {
                            LOG(log_note, logtype_afpd, "main: removing reattached child[%u]", child->pid);
                            server_child_remove(server_children, CHILD_DSIFORK, child->pid);
                        }
                    }
                    break;

                case DISASOCIATED_IPC_FD:
                    LOG(log_debug, logtype_afpd, "main: IPC reconnect request");
                    if ((fd[0] = accept(disasociated_ipc_fd, NULL, NULL)) == -1) {
                        LOG(log_error, logtype_afpd, "main: accept: %s", strerror(errno));
                        break;
                    }
                    if (readt(fd[0], &pid, sizeof(pid_t), 0, 1) != sizeof(pid_t)) {
                        LOG(log_error, logtype_afpd, "main: readt: %s", strerror(errno));
                        close(fd[0]);
                        break;
                    }
                    LOG(log_note, logtype_afpd, "main: IPC reconnect from pid [%u]", pid);
                    if ((child = server_child_add(server_children, CHILD_DSIFORK, pid, fd)) == NULL) {
                        LOG(log_error, logtype_afpd, "main: server_child_add");
                        close(fd[0]);
                        break;
                    }
                    child->disasociated = 1;
                    fdset_add_fd(&fdset, &polldata, &fdset_used, &fdset_size, fd[0], IPC_FD, child);
                    break;

                default:
                    LOG(log_debug, logtype_afpd, "main: IPC request for unknown type");
                    break;
                } /* switch */
            }  /* if */
        } /* for (i)*/
    } /* while (1) */

    return 0;
}
コード例 #7
0
ファイル: CATCH.CPP プロジェクト: AnkitKSinha/BubbleCatch
void game(int mx,int my)
{
        cleardevice();
        int x,y,cl=0,i,j,ctr=0,points=0,lives=3,dt=100;
        int *ycoord,*bomby;
        int delaytime[20];
        int randomcolor;

        int *xcoord,*bombx,numctr=0,playtime=0;
        int nob=0,bombctr=0,temp,selbomb;

        callmouse();
        setlimits(23,mx-23,23,my-23);
        delay(100);

        // ASSIGN THE SPEED
        for(i=0;i<10;i++){delaytime[i]=i+10;}

        // ALOCATE MEMORY FOR COORDINATES

        if((ycoord=(int *)malloc(10))==NULL||(xcoord=(int *)malloc(10))==NULL||(bomby=(int *)malloc(10))==NULL||(bombx=(int *)malloc(10))==NULL)
        {
                cout<<"\nMEMORY ALLOCATION ERROR!";
                getch();
                exit(0);

        }

        randomize();
        outline(mx,my);

//THE GAME BEGINS

        int start=clock(),end;
        for(i=0;i<lives;i++)
        {
                setcolor(WHITE);
                circle((mx-200)+(i*20),my-10,6);
                setfillstyle(SOLID_FILL,RED);
                floodfill((mx-200)+(i*20),my-10,WHITE);
        }

        for(;;)
        {



        //      ASSIGN COORDINATES TO BOMBS
                selbomb=random(10);
                if( (selbomb%7)==0 && nob<=3)
                {
                        *(bombx+bombctr)=50;
                        *(bomby+bombctr)=random(my-100)+50;
                        bombctr++;
                        nob++;
                }


        //      ASSIGN COORDINATES TO BUBLES
                if(numctr<3)
                {
                        *(xcoord+ctr)=48;
                        *(ycoord+ctr)=random(my-100)+48;
                        numctr++;
                        ctr++;
                }
        //      DROP THE BOMBS
                for(i=0;i<nob;i++)
                {
                        setcolor(WHITE);
                        circle(*(bombx+i),*(bomby+i),22);
                }

        //      CREATE BUBLES
                for(i=0;i<numctr;i++)
                {
                        randomcolor=random(5)+1;
                        setcolor(randomcolor);
                        circle(*(xcoord+i),*(ycoord+i),20);

                }
       //       MOUSE
                altermouse(x,y,cl);
                delay(dt);

       //       CHECK WHAT HAPPENED WITH BUBLES
                temp=numctr;
                for(i=0;i<temp;i++)
                {
                //      CHECK IF BUBLES WERE HIT
                        if(x < *(xcoord+i)+20 && x > *(xcoord+i)-20 && y< *(ycoord+i)+20 && y>*(ycoord+i)-20)
                        {
                                points+=10;
                                numctr--;
                                ctr=i;
                                cleardevice();
                                outline(mx,my);
                                for(j=0;j<lives;j++)
                                {
                                        setcolor(WHITE);
                                        circle((mx-200)+(j*20),my-10,6);
                                        setfillstyle(SOLID_FILL,RED);
                                        floodfill((mx-200)+(j*20),my-10,WHITE);
                                }

                        }
                //      DE-CREATE THE BUBLES
                        setcolor(BLACK);
                        circle(*(xcoord+i),*(ycoord+i),20);

                //      LET THE BUBLES MOVE
                        *(xcoord+i)+=delaytime[i];

                //      CHECK FOR PLAYER'S DEATH
                        if(xcoord[i]>=mx-48)
                        {
                                numctr--;
                                lives--;

                                if(lives==0){goto again;}
                                for(j=0;j<lives+1;j++)
                                {
                                        setcolor(BLUE);
                                        circle((mx-200)+(i*20),my-10,6);
                                        setfillstyle(SOLID_FILL,BLUE);
                                        floodfill((mx-200)+(j*20),my-10,BLUE);
                                }
                                for(j=0;j<lives;j++)
                                {
                                        setcolor(WHITE);
                                        circle((mx-200)+(j*20),my-10,6);
                                        setfillstyle(SOLID_FILL,RED);
                                        floodfill((mx-200)+(j*20),my-10,WHITE);
                                }
                                ctr=i;
                        }


                }

       //       CHECK WHAT HAPPENED WITH THE BOMB
                temp=nob;
                for(i=0;i<temp;i++)
                {
                //      CHECK FOR PLAYERS DEATH AND THE END OF GAME
                        if(x < *(bombx+i)+22 && x > *(bombx+i)-22 && y< *(bomby+i)+22 && y>*(bomby+i)-22)
                        {
                                goto again;

                        }
                //      DE-CREATE THE BOMBS
                        setcolor(BLACK);
                        circle(*(bombx+i),*(bomby+i),22);
                //      LET THE BOMBS MOVE
                        *(bombx+i)+=delaytime[i];
                //      CHECK FOR THE BOMBS DEATH
                        if(*(bombx+i)>=mx-45)
                        {
                                bombctr=i;
                                nob--;
                                *(bombx+bombctr)=48;
                                *(bomby+bombctr)=random(my-100)+50;
                                nob++;
                        }

                }
                end=clock();
                playtime=ceill((end-start)/CLK_TCK);
                if(playtime>10)
                {
                        dt-=10;
                        start=clock();
                }

        }
//      THIS IS THE END :

        again:
        cleardevice();
        outline(mx,my);
        endgame(points,mx,my);
        readscore(points);
        hidemouse();
        delete ycoord,xcoord;
        menu(mx,my);
}
コード例 #8
0
ファイル: main.c プロジェクト: NTmatter/Netatalk
int main(int ac, char **av)
{
    fd_set              rfds;
    void                *ipc;
    struct sigaction	sv;
    sigset_t            sigs;
    int                 ret;

    /* Parse argv args and initialize default options */
    afp_options_parse_cmdline(&obj, ac, av);

    if (!(obj.cmdlineflags & OPTION_DEBUG) && (daemonize(0, 0) != 0))
        exit(EXITERR_SYS);

    /* Log SIGBUS/SIGSEGV SBT */
    fault_setup(NULL);

    if (afp_config_parse(&obj, "afpd") != 0)
        afp_exit(EXITERR_CONF);

    /* Save the user's current umask */
    obj.options.save_mask = umask(obj.options.umask);

    /* install child handler for asp and dsi. we do this before afp_goaway
     * as afp_goaway references stuff from here. 
     * XXX: this should really be setup after the initial connections. */
    if (!(server_children = server_child_alloc(obj.options.connections, CHILD_NFORKS))) {
        LOG(log_error, logtype_afpd, "main: server_child alloc: %s", strerror(errno) );
        afp_exit(EXITERR_SYS);
    }
    
    sigemptyset(&sigs);
    pthread_sigmask(SIG_SETMASK, &sigs, NULL);

    memset(&sv, 0, sizeof(sv));    
    /* linux at least up to 2.4.22 send a SIGXFZ for vfat fs,
       even if the file is open with O_LARGEFILE ! */
#ifdef SIGXFSZ
    sv.sa_handler = SIG_IGN;
    sigemptyset( &sv.sa_mask );
    if (sigaction(SIGXFSZ, &sv, NULL ) < 0 ) {
        LOG(log_error, logtype_afpd, "main: sigaction: %s", strerror(errno) );
        afp_exit(EXITERR_SYS);
    }
#endif
    
    sv.sa_handler = afp_goaway; /* handler for all sigs */

    sigemptyset( &sv.sa_mask );
    sigaddset(&sv.sa_mask, SIGALRM);
    sigaddset(&sv.sa_mask, SIGHUP);
    sigaddset(&sv.sa_mask, SIGTERM);
    sigaddset(&sv.sa_mask, SIGUSR1);
    sigaddset(&sv.sa_mask, SIGQUIT);    
    sv.sa_flags = SA_RESTART;
    if ( sigaction( SIGCHLD, &sv, NULL ) < 0 ) {
        LOG(log_error, logtype_afpd, "main: sigaction: %s", strerror(errno) );
        afp_exit(EXITERR_SYS);
    }

    sigemptyset( &sv.sa_mask );
    sigaddset(&sv.sa_mask, SIGALRM);
    sigaddset(&sv.sa_mask, SIGTERM);
    sigaddset(&sv.sa_mask, SIGHUP);
    sigaddset(&sv.sa_mask, SIGCHLD);
    sigaddset(&sv.sa_mask, SIGQUIT);
    sv.sa_flags = SA_RESTART;
    if ( sigaction( SIGUSR1, &sv, NULL ) < 0 ) {
        LOG(log_error, logtype_afpd, "main: sigaction: %s", strerror(errno) );
        afp_exit(EXITERR_SYS);
    }

    sigemptyset( &sv.sa_mask );
    sigaddset(&sv.sa_mask, SIGALRM);
    sigaddset(&sv.sa_mask, SIGTERM);
    sigaddset(&sv.sa_mask, SIGUSR1);
    sigaddset(&sv.sa_mask, SIGCHLD);
    sigaddset(&sv.sa_mask, SIGQUIT);
    sv.sa_flags = SA_RESTART;
    if ( sigaction( SIGHUP, &sv, NULL ) < 0 ) {
        LOG(log_error, logtype_afpd, "main: sigaction: %s", strerror(errno) );
        afp_exit(EXITERR_SYS);
    }

    sigemptyset( &sv.sa_mask );
    sigaddset(&sv.sa_mask, SIGALRM);
    sigaddset(&sv.sa_mask, SIGHUP);
    sigaddset(&sv.sa_mask, SIGUSR1);
    sigaddset(&sv.sa_mask, SIGCHLD);
    sigaddset(&sv.sa_mask, SIGQUIT);
    sv.sa_flags = SA_RESTART;
    if ( sigaction( SIGTERM, &sv, NULL ) < 0 ) {
        LOG(log_error, logtype_afpd, "main: sigaction: %s", strerror(errno) );
        afp_exit(EXITERR_SYS);
    }

    sigemptyset( &sv.sa_mask );
    sigaddset(&sv.sa_mask, SIGALRM);
    sigaddset(&sv.sa_mask, SIGHUP);
    sigaddset(&sv.sa_mask, SIGUSR1);
    sigaddset(&sv.sa_mask, SIGCHLD);
    sigaddset(&sv.sa_mask, SIGTERM);
    sv.sa_flags = SA_RESTART;
    if (sigaction(SIGQUIT, &sv, NULL ) < 0 ) {
        LOG(log_error, logtype_afpd, "main: sigaction: %s", strerror(errno) );
        afp_exit(EXITERR_SYS);
    }

    /* afp.conf:  not in config file: lockfile, configfile
     *            preference: command-line provides defaults.
     *                        config file over-writes defaults.
     *
     * we also need to make sure that killing afpd during startup
     * won't leave any lingering registered names around.
     */

    sigemptyset(&sigs);
    sigaddset(&sigs, SIGALRM);
    sigaddset(&sigs, SIGHUP);
    sigaddset(&sigs, SIGUSR1);
#if 0
    /* don't block SIGTERM */
    sigaddset(&sigs, SIGTERM);
#endif
    sigaddset(&sigs, SIGCHLD);

    pthread_sigmask(SIG_BLOCK, &sigs, NULL);
    if (configinit(&obj) != 0) {
        LOG(log_error, logtype_afpd, "main: no servers configured");
        afp_exit(EXITERR_CONF);
    }
    pthread_sigmask(SIG_UNBLOCK, &sigs, NULL);

    /* Initialize */
    cnid_init();
    
    /* watch atp, dsi sockets and ipc parent/child file descriptor. */

    if (obj.options.flags & OPTION_KEEPSESSIONS) {
        LOG(log_note, logtype_afpd, "Activating continous service");
        disasociated_ipc_fd = ipc_server_uds(_PATH_AFP_IPC);
    }

    fd_set_listening_sockets(&obj);

    /* set limits */
    (void)setlimits();

    afp_child_t *child;
    int recon_ipc_fd;
    pid_t pid;
    int saveerrno;

    /* wait for an appleshare connection. parent remains in the loop
     * while the children get handled by afp_over_{asp,dsi}.  this is
     * currently vulnerable to a denial-of-service attack if a
     * connection is made without an actual login attempt being made
     * afterwards. establishing timeouts for logins is a possible 
     * solution. */
    while (1) {
        LOG(log_maxdebug, logtype_afpd, "main: polling %i fds", fdset_used);
        pthread_sigmask(SIG_UNBLOCK, &sigs, NULL);
        ret = poll(fdset, fdset_used, -1);
        pthread_sigmask(SIG_BLOCK, &sigs, NULL);
        saveerrno = errno;

        if (gotsigchld) {
            gotsigchld = 0;
            child_handler();
            continue;
        }

        if (reloadconfig) {
            nologin++;
            auth_unload();
            fd_reset_listening_sockets(&obj);

            LOG(log_info, logtype_afpd, "re-reading configuration file");

            configfree(&obj, NULL);
            if (configinit(&obj) != 0) {
                LOG(log_error, logtype_afpd, "config re-read: no servers configured");
                afp_exit(EXITERR_CONF);
            }

            fd_set_listening_sockets(&obj);

            nologin = 0;
            reloadconfig = 0;
            errno = saveerrno;
            continue;
        }

        if (ret == 0)
            continue;
        
        if (ret < 0) {
            if (errno == EINTR)
                continue;
            LOG(log_error, logtype_afpd, "main: can't wait for input: %s", strerror(errno));
            break;
        }

        for (int i = 0; i < fdset_used; i++) {
            if (fdset[i].revents & (POLLIN | POLLERR | POLLHUP | POLLNVAL)) {
                switch (polldata[i].fdtype) {

                case LISTEN_FD:
                    if (child = dsi_start(&obj, (DSI *)polldata[i].data, server_children)) {
                        /* Add IPC fd to select fd set */
                        fdset_add_fd(obj.options.connections + AFP_LISTENERS + FDSET_SAFETY,
                                     &fdset,
                                     &polldata,
                                     &fdset_used,
                                     &fdset_size,
                                     child->ipc_fd,
                                     IPC_FD,
                                     child);
                    }
                    break;

                case IPC_FD:
                    child = (afp_child_t *)polldata[i].data;
                    LOG(log_debug, logtype_afpd, "main: IPC request from child[%u]", child->pid);

                    if (ipc_server_read(server_children, child->ipc_fd) != 0) {
                        fdset_del_fd(&fdset, &polldata, &fdset_used, &fdset_size, child->ipc_fd);
                        close(child->ipc_fd);
                        child->ipc_fd = -1;
                        if ((obj.options.flags & OPTION_KEEPSESSIONS) && child->disasociated) {
                            LOG(log_note, logtype_afpd, "main: removing reattached child[%u]", child->pid);
                            server_child_remove(server_children, CHILD_DSIFORK, child->pid);
                        }
                    }
                    break;

                case DISASOCIATED_IPC_FD:
                    LOG(log_debug, logtype_afpd, "main: IPC reconnect request");
                    if ((recon_ipc_fd = accept(disasociated_ipc_fd, NULL, NULL)) == -1) {
                        LOG(log_error, logtype_afpd, "main: accept: %s", strerror(errno));
                        break;
                    }
                    if (readt(recon_ipc_fd, &pid, sizeof(pid_t), 0, 1) != sizeof(pid_t)) {
                        LOG(log_error, logtype_afpd, "main: readt: %s", strerror(errno));
                        close(recon_ipc_fd);
                        break;
                    }
                    LOG(log_note, logtype_afpd, "main: IPC reconnect from pid [%u]", pid);

                    if ((child = server_child_add(server_children, CHILD_DSIFORK, pid, recon_ipc_fd)) == NULL) {
                        LOG(log_error, logtype_afpd, "main: server_child_add");
                        close(recon_ipc_fd);
                        break;
                    }
                    child->disasociated = 1;
                    fdset_add_fd(obj.options.connections + AFP_LISTENERS + FDSET_SAFETY,
                                 &fdset,
                                 &polldata,
                                 &fdset_used,
                                 &fdset_size,
                                 recon_ipc_fd,
                                 IPC_FD,
                                 child);
                    break;

                default:
                    LOG(log_debug, logtype_afpd, "main: IPC request for unknown type");
                    break;
                } /* switch */
            }  /* if */
        } /* for (i)*/
    } /* while (1) */

    return 0;
}