void syncmode_gui::tick()
{
	pthread_mutex_lock(&mutex);

	switch(cfg.getsync())
	{
		case SYNC_SYNCED:
			printfounds();
			printstatus(selx,sely);
			break;
		case SYNC_FOUND:
			delwin(popupwin);

			wbkgdset(mainwin,(COLOR_PAIR(1)|A_BOLD));
			wbkgdset(statuswin,(COLOR_PAIR(1)|A_BOLD));
			wbkgdset(msgwin,(COLOR_PAIR(1)|A_BOLD));

			box(mainwin,0,0);
			box(statuswin,0,0);
			box(msgwin,0,0);

			keypad(mainwin,TRUE);

			doupdate();
			cfg.setsync(SYNC_SYNCED);
			break;
		case SYNC_SEARCH:
			break;
	}

	pthread_mutex_unlock(&mutex);
}
Beispiel #2
0
/*
 * This is the function that reads in a # commented file and prints the
 * status report for every url found in it.  The file should be in the
 * format of one url per line, blank lines and lines beginning with # are
 * ignored.
 */
void
dofile(char *filename)
{
    FILE   *f;
    char    line[8192];
    struct status st;

    f = fopen(filename, "r");
    if (!f) {
        perror(filename);
        exit(1);
    }
    while (fgets(line, 8192, f)) {
        /* KILL WHITEY! */
        while (*line && isspace(line[strlen(line) - 1]))
            line[strlen(line) - 1] = NULL;

        /* Ignore blank lines and lines beginning with # */
        if (!(line[0] == NULL || line[0] == '#')) {
            st = getstatus(line);
            printstatus(line, st);
            freestatus(st);
        }
    }

    fclose(f);
}
static int
printwaitn(struct tcb *tcp, void (*const print_rusage)(struct tcb *, long))
{
	if (entering(tcp)) {
		/* On Linux, kernel-side pid_t is typedef'ed to int
		 * on all arches. Also, glibc-2.8 truncates wait3 and wait4
		 * pid argument to int on 64bit arches, producing,
		 * for example, wait4(4294967295, ...) instead of -1
		 * in strace. We have to use int here, not long.
		 */
		int pid = tcp->u_arg[0];
		tprintf("%d, ", pid);
	} else {
		int status;

		/* status */
		if (tcp->u_rval == 0)
			printaddr(tcp->u_arg[1]);
		else if (!umove_or_printaddr(tcp, tcp->u_arg[1], &status))
			printstatus(status);
		/* options */
		tprints(", ");
		printflags(wait4_options, tcp->u_arg[2], "W???");
		if (print_rusage) {
			/* usage */
			tprints(", ");
			if (tcp->u_rval > 0)
				print_rusage(tcp, tcp->u_arg[3]);
			else
				printaddr(tcp->u_arg[3]);
		}
	}
	return 0;
}
Beispiel #4
0
static int
doreadid(int fd, unsigned int numids, unsigned int trackno)
{
	int rv = 0;
	unsigned int i;
	struct fdc_readid info;
	struct fdc_status fdcs;
	struct fd_type fdt;

	if (ioctl(fd, FD_GTYPE, &fdt) == -1)
		err(EX_OSERR, "ioctl(FD_GTYPE) failed -- not a floppy?");

	for (i = 0; i < numids; i++) {
		info.cyl = trackno / fdt.heads;
		info.head = fdt.heads > 1? trackno % fdt.heads: 0;
		if (ioctl(fd, FD_READID, &info) == 0) {
			printf("C = %d, H = %d, R = %d, N = %d\n",
			       info.cyl, info.head, info.sec, info.secshift);
		} else {
			if (errno != EIO) {
				perror("non-IO error");
				return (EX_OSERR);
			}
			if (ioctl(fd, FD_GSTAT, &fdcs) == -1)
				errx(EX_IOERR,
				     "floppy IO error, but no FDC status");
			printstatus(&fdcs, 0);
			putc('\n', stderr);
			rv = EX_IOERR;
		}
	}

	return (rv);
}
Beispiel #5
0
void sigchld() {
 int wstat;
 int pid;

 while ((pid = wait_nohang(&wstat)) > 0) {
  fprintf(stderr, "end: pid %d status %d\n", pid, wstat);
  if (autokill != 0) ptable_remove(pt, limit, pid);
  if (numchildren) --numchildren; printstatus();
 }
}
Beispiel #6
0
void start_test(int role) {
	int sk, pid;
	int i = 0;

	DEBUG_PRINT(DEBUG_NONE, "\nStarting tests...\n");

	repeat_count = repeat;

	DEBUG_PRINT(DEBUG_MIN, "\tsocket(SOCK_STREAM, IPPROTO_SCTP)");

	if ((sk = socket(s_loc.ss_family, SOCK_STREAM, IPPROTO_SCTP)) < 0 ) {
		fprintf(stderr, "\n\n\t\t*** socket: failed to create"
			" socket:  %s ***\n", strerror(errno));
		exit(1);
	}
	DEBUG_PRINT(DEBUG_MIN, "  ->  sk=%d\n", sk);

	bind_r(sk, &s_loc);

	if (role == SERVER) {
		listen_r(sk, 1);
		accept_r(sk);
	} else {
		connect_r(sk, (struct sockaddr *)&s_rem, r_len);
	}

	if ((pid = fork()) == 0) {
		settimerhandle();
		printstatus(gsk);
		while(1);
	} else {
		if (!debug_level) {
			printf("     ");
		}

		for(i = 0; i < repeat_count; i++) {

			if (role == SERVER) {
				DEBUG_PRINT(DEBUG_NONE, "Server: Receiving packets.(%d/%d)\n",
					i+1, repeat_count);
				server(gsk);
			} else {
				DEBUG_PRINT(DEBUG_NONE, "Client: Sending packets.(%d/%d)\n",
					i+1, repeat_count);
				client(sk);
			}

			fflush(stdout);
		}

		if (role == SERVER) close_r(gsk);
		close_r(sk);
	}
} /* start_test() */
Beispiel #7
0
void displayupdate(void)
{
  if (cursorflashdelay >= 6)
  {
    cursorflashdelay %= 6;
    cursorflash++;
    cursorflash &= 3;
  }
  printstatus();
  fliptoscreen();
}
Beispiel #8
0
void sigchld()
{
  int wstat;
  int pid;

  while ((pid = wait_nohang(&wstat)) > 0) {
    if (verbosity >= 2) {
      errlog(0,NOTICE,B("end ",fmtnum(pid)," status ",fmtnum(wstat)));
    }
    if (numchildren) { --numchildren; } printstatus();
  }
}
void sigchld(void) {
  int wstat;
  int pid;
 
  while ((pid = wait_nohang(&wstat)) > 0) {
    if (verbosity >= 2) {
      strnum[fmt_ulong(strnum,pid)] = 0;
      strnum2[fmt_ulong(strnum2,wstat)] = 0;
      strerr_warn4("sslserver: end ",strnum," status ",strnum2,0);
    }
    if (numchildren) --numchildren; printstatus();
  }
}
Beispiel #10
0
int
main ()
{
  int count = 0;
  printf ("Will load in 10 Sec \nLoading ");
  for (count; count < 10; ++count)
    {
      printf (". ");
      fflush (stdout);
      sleep (1);
    }
  printf ("\nDone\n");
  printstatus ();
  return 0;
}
Beispiel #11
0
static int
printwaitn(struct tcb *tcp, int n, int bitness)
{
	int status;

	if (entering(tcp)) {
		/* On Linux, kernel-side pid_t is typedef'ed to int
		 * on all arches. Also, glibc-2.8 truncates wait3 and wait4
		 * pid argument to int on 64bit arches, producing,
		 * for example, wait4(4294967295, ...) instead of -1
		 * in strace. We have to use int here, not long.
		 */
		int pid = tcp->u_arg[0];
		tprintf("%d, ", pid);
	} else {
		/* status */
		if (!tcp->u_arg[1])
			tprints("NULL");
		else if (syserror(tcp) || tcp->u_rval == 0)
			tprintf("%#lx", tcp->u_arg[1]);
		else if (umove(tcp, tcp->u_arg[1], &status) < 0)
			tprints("[?]");
		else
			printstatus(status);
		/* options */
		tprints(", ");
		printflags(wait4_options, tcp->u_arg[2], "W???");
		if (n == 4) {
			tprints(", ");
			/* usage */
			if (!tcp->u_arg[3])
				tprints("NULL");
			else if (tcp->u_rval > 0) {
#ifdef ALPHA
				if (bitness)
					printrusage32(tcp, tcp->u_arg[3]);
				else
#endif
					printrusage(tcp, tcp->u_arg[3]);
			}
			else
				tprintf("%#lx", tcp->u_arg[3]);
		}
	}
	return 0;
}
Beispiel #12
0
void mainloop(void)
{
    gfx_calcpalette(64, 0, 0, 0);
    gfx_setpalette();
    win_getspeed(60);

    for (;;)
    {
        speed = win_getspeed(60);
        key = kbd_getkey();
        getmousemove();
        getmousebuttons();
        if ((key == KEY_ESC) || (win_quitted)) break;
        generalcommands();
        gfx_fillscreen(0);
        printinfo();
        printstatus();
        gfx_drawsprite(mousex, mousey, 0x00010001);
        gfx_updatepage();
    }
}
Beispiel #13
0
/* forkexec -- fork (if necessary) and exec */
extern List *forkexec(char *file, List *list, Boolean inchild) {
	int pid, status;
	Vector *env;
	gcdisable();
	env = mkenv();
	pid = efork(!inchild, FALSE);
	if (pid == 0) {
		execve(file, vectorize(list)->vector, env->vector);
		failexec(file, list);
	}
	gcenable();
	status = ewaitfor(pid);
	if ((status & 0xff) == 0) {
		sigint_newline = FALSE;
		SIGCHK();
		sigint_newline = TRUE;
	} else
		SIGCHK();
	printstatus(0, status);
	return mklist(mkterm(mkstatus(status), NULL), NULL);
}
Beispiel #14
0
int process(FILE *instructions, OrthogonalList **list) {
    /* parse instruction */
    fpos_t *position;    /* store position to print instruction on error */
    position = malloc(sizeof(fpos_t));  /* allocate */
    if (position == NULL) {
        printf("ERROR: insufficient memory.");
        return 0;
    }
    fgetpos(instructions, position);    /* get position */
    char which = fgetc(instructions);   /* route instruction by type */
    switch(which) {
        case 'I':
            ins(instructions, *list, position);
            break;
        case 'D':
            del(instructions, *list, position);
            break;
        case 'S':
            advance(instructions);
            printstatus(*list);
            break;
        case 'Q':
            query(instructions, *list, position);
            break;
        case 'P':
            advance(instructions);
            purge(list);
            break;
        case EOF:
            free(position);
            return 0;
        default:
            printinstruction(instructions, position);
            printf("Undefined instruction: %c\n", which);
    }
    free(position);
    if (feof(instructions))
        return 0;   /* tell main loop to stop */
    return 1;
}
Beispiel #15
0
void
checkpoint_status()
{
  int h, i, k, offset;

  offset = 0;
  for(h = 0; h < 16; h++) {
    for(i = 0; i < 16; i++) {
      if(Status[h][i].changed) {
	if(lseek(status, offset, SEEK_SET) != offset) {
	  fprintf(Log, "%s:  Seek error on status file\n", thedate());
	} else {
	  if(write(status, &Status[h][i], sizeof(STATUS)) != sizeof(STATUS)) {
	    fprintf(Log, "%s:  Write error on status file\n", thedate());
	  }
	}
	Status[h][i].changed = 0;
	for(k = 0; k < MAXMON; k++) {
	  if(Monitor[k].inuse
	     && Monitor[k].house == h && Monitor[k].unit == i) {
	    /*
	     * Arrange to catch SIGPIPE in case client has gone away.
	     */
	    extern int client;
	    extern void clientgone();
	    void (*prev)();

	    client = k;
	    prev = signal(SIGPIPE, clientgone);
	    printstatus(Monitor[k].user, &Status[h][i]);
	    fflush(Monitor[k].user);
	    signal(SIGPIPE, prev);
	  }
	}
      }
      offset += sizeof(STATUS);
    }
  }
}
Beispiel #16
0
printnews()
{
    if (ss_variables) {
	prvarnews();
    }
    if (trcond()) {
	if (ss_lines && curline > 0) {
	    skimsource(srcfilename(pc));
	    printf("trace:  ");
	    printlines(curline, curline);
	}
	if (ss_instructions) {
	    printf("inst trace: ");
	    printinst(pc, pc);
	}
    }
    bpact();
    if (stopcond()) {
	isstopped = TRUE;
	curline = srcline(pc);
	printstatus();
    }
}
			//move the remaining bytes in.
			//the length is cut appropiately
			for(int a = 0; a<bytecount; ++a)
			{
				c <<= 6;
				c |= (getch() & 0x3f);
			}
			a = c;
		}
		return a;
	};

	auto statusthreadloop = [&](){
		while(progrunning)
		{
			printstatus();
			std::this_thread::sleep_for(std::chrono::seconds(1));
		}
	};

	std::thread statusthread (statusthreadloop);
	statusthread.detach();

	nextline();
	doscreen();

	int c = get_widech();
	timerunning = true;
	starttime = std::chrono::high_resolution_clock::now();

	while(progrunning)
int main(int argc,char * const *argv) {
  const char *hostname;
  int opt;
  struct servent *se;
  char *x;
  unsigned long u;
  int s;
  int t;

  io_opt = ssl_io_opt_default;
  io_opt.timeout = 3600;

  while ((opt = getopt(argc,argv,"46dDvqQhHrR1UXx:t:T:u:g:l:b:B:c:Z:pPoO3IiEeSsaAw:nNyYuUjJ")) != opteof)
    switch(opt) {
      case 'b': scan_ulong(optarg,&backlog); break;
      case 'c': scan_ulong(optarg,&limit); break;
      case 'X': flagallownorules = 1; break;
      case 'x': fnrules = optarg; break;
      case 'B': banner = optarg; break;
      case 'd': flagdelay = 1; break;
      case 'D': flagdelay = 0; break;
      case 'v': verbosity = 2; break;
      case 'q': verbosity = 0; break;
      case 'Q': verbosity = 1; break;
      case 'P': flagparanoid = 0; break;
      case 'p': flagparanoid = 1; break;
      case 'O': flagkillopts = 1; break;
      case 'o': flagkillopts = 0; break;
      case 'H': flagremotehost = 0; break;
      case 'h': flagremotehost = 1; break;
      case 'R': flagremoteinfo = 0; break;
      case 'r': flagremoteinfo = 1; break;
      case 't': scan_ulong(optarg,&timeout); break;
      case 'T': scan_ulong(optarg,&ssltimeout); break;
      case 'w': scan_uint(optarg,&io_opt.timeout); break;
      case 'U': x = env_get("UID"); if (x) scan_ulong(x,&uid);
		x = env_get("GID"); if (x) scan_ulong(x,&gid); break;
      case 'u': scan_ulong(optarg,&uid); break;
      case 'g': scan_ulong(optarg,&gid); break;
      case 'Z': netif=socket_getifidx(optarg); break;
      case '1': flag1 = 1; break;
      case '4': noipv6 = 1; break;
      case '6': forcev6 = 1; break;
      case 'l': localhost = optarg; break;
      case '3': flag3 = 1; break;
      case 'I': flagclientcert = 0; break;
      case 'i': flagclientcert = 1; break;
      case 'S': flagsslenv = 0; break;
      case 's': flagsslenv = 1; break;
      case 'E': flagtcpenv = 0; break;
      case 'e': flagtcpenv = 1; break;
      case 'n': case 'y': flagsslwait = 1; break;
      case 'N': case 'Y': flagsslwait = 0; break;
      case 'j': io_opt.just_shutdown = 1; break;
      case 'J': io_opt.just_shutdown = 0; break;
      default: usage();
    }
  argc -= optind;
  argv += optind;

  if (!verbosity)
    buffer_2->fd = -1;
 
  hostname = *argv++;
  if (!hostname) usage();
  if (str_equal(hostname,"")) hostname = "0";

  x = *argv++;
  if (!x) usage();
  prog = argv;
  if (!*argv) usage();
  if (!x[scan_ulong(x,&u)])
    localport = u;
  else {
    se = getservbyname(x,"tcp");
    if (!se)
      strerr_die3x(111,FATAL,"unable to figure out port number for ",x);
    uint16_unpack_big((char*)&se->s_port,&localport);
  }

  if (x = env_get("VERIFYDEPTH")) {
    scan_ulong(x,&u);
    verifydepth = u;
  }

  if (x = env_get("CAFILE")) cafile = x;
  if (cafile && str_equal(cafile,"")) cafile = 0;

  if (x = env_get("CCAFILE")) ccafile = x;
  if (ccafile && str_equal(ccafile,"")) ccafile = 0;
  if (!flagclientcert) ccafile = 0;

  if (x = env_get("CADIR")) cadir = x;
  if (cadir && str_equal(cadir,"")) cadir= 0;

  if (x = env_get("CERTFILE")) certfile = x;
  if (certfile && str_equal(certfile,"")) certfile = 0;

  if (x = env_get("KEYFILE")) keyfile = x;
  if (keyfile && str_equal(keyfile,"")) keyfile = 0;

  if (x = env_get("DHFILE")) dhfile = x;
  if (dhfile && str_equal(dhfile,"")) dhfile = 0;

  if (x = env_get("CIPHERS")) ciphers = x;
  if (ciphers && str_equal(ciphers,"")) ciphers = 0;

  sig_block(sig_child);
  sig_catch(sig_child,sigchld);
  sig_catch(sig_term,sigterm);
  sig_ignore(sig_pipe);
 
  if (str_equal(hostname,"0")) {
    byte_zero(localip,sizeof localip);
  } else {
    if (!stralloc_copys(&tmp,hostname))
      strerr_die2x(111,FATAL,"out of memory");
    if (dns_ip6_qualify(&addresses,&fqdn,&tmp) == -1)
      strerr_die4sys(111,FATAL,"temporarily unable to figure out IP address for ",hostname,": ");
    if (addresses.len < 16)
      strerr_die3x(111,FATAL,"no IP address for ",hostname);
    byte_copy(localip,16,addresses.s);
    if (ip6_isv4mapped(localip))
      noipv6=1;
  }

  s = socket_tcp6();
  if (s == -1)
    strerr_die2sys(111,FATAL,"unable to create socket: ");

  if (socket_bind6_reuse(s,localip,localport,netif) == -1)
    strerr_die2sys(111,FATAL,"unable to bind: ");

  if (socket_local6(s,localip,&localport,&netif) == -1)
    strerr_die2sys(111,FATAL,"unable to get local address: ");
  if (socket_listen(s,backlog) == -1)
    strerr_die2sys(111,FATAL,"unable to listen: ");
  ndelay_off(s);

  localportstr[fmt_ulong(localportstr,localport)] = 0;
  if (flag1) {
    buffer_init(&b,buffer_unixwrite,1,bspace,sizeof bspace);
    buffer_puts(&b,localportstr);
    buffer_puts(&b,"\n");
    buffer_flush(&b);
  }
 
  if (flag3) read_passwd();

  ctx = ssl_server();
  ssl_errstr();
  if (!ctx) strerr_die2x(111,FATAL,"unable to create SSL context");

  switch (ssl_certkey(ctx,certfile,keyfile,passwd_cb)) {
    case -1: strerr_die2x(111,FATAL,"unable to load certificate");
    case -2: strerr_die2x(111,FATAL,"unable to load key");
    case -3: strerr_die2x(111,FATAL,"key does not match certificate");
    default: break;
  }

  if (!ssl_ca(ctx,cafile,cadir,verifydepth))
    strerr_die2x(111,FATAL,"unable to load CA list");

  if (!ssl_cca(ctx,ccafile))
    strerr_die2x(111,FATAL,"unable to load client CA list");

  if (!ssl_params(ctx,dhfile,rsalen))
    strerr_die2x(111,FATAL,"unable to set cipher parameters");

  if (!ssl_ciphers(ctx,ciphers))
    strerr_die2x(111,FATAL,"unable to set cipher list");

  if (verbosity >= 2) {
    strnum[fmt_ulong(strnum,getpid())] = 0;
    strnum2[fmt_ulong(strnum2,rsalen)] = 0;
    strerr_warn4("sslserver: cafile ",strnum," ",cafile,0);
    strerr_warn4("sslserver: ccafile ",strnum," ",ccafile,0);
    strerr_warn4("sslserver: cadir ",strnum," ",cadir,0);
    strerr_warn4("sslserver: cert ",strnum," ",certfile,0);
    strerr_warn4("sslserver: key ",strnum," ",keyfile,0);
    strerr_warn6("sslserver: param ",strnum," ",dhfile," ",strnum2,0);
  }

  close(0); open_read("/dev/null");
  close(1); open_append("/dev/null");

  printstatus();
 
  for (;;) {
    while (numchildren >= limit) sig_pause();

    sig_unblock(sig_child);
    t = socket_accept6(s,remoteip,&remoteport,&netif);
    sig_block(sig_child);

    if (t == -1) continue;
    ++numchildren; printstatus();
 
    switch(fork()) {
      case 0:
        close(s);
        doit(t);
	strerr_die4sys(111,DROP,"unable to run ",*argv,": ");
      case -1:
        strerr_warn2(DROP,"unable to fork: ",&strerr_sys);
        --numchildren; printstatus();
    }
    close(t);
  }
}
Beispiel #19
0
static int
doread(int fd, FILE *of, const char *_devname)
{
	char *trackbuf;
	int rv, fdopts, recoverable, nerrs = 0;
	unsigned int nbytes, tracksize, mediasize, secsize, n;
	struct fdc_status fdcs;
	struct fd_type fdt;

	if (ioctl(fd, FD_GTYPE, &fdt) == -1)
		err(EX_OSERR, "ioctl(FD_GTYPE) failed -- not a floppy?");

	secsize = 128 << fdt.secsize;
	tracksize = fdt.sectrac * secsize;
	mediasize = tracksize * fdt.tracks * fdt.heads;
	if ((trackbuf = malloc(tracksize)) == 0)
		errx(EX_TEMPFAIL, "out of memory");

	if (!quiet)
		fprintf(stderr, "Reading %d * %d * %d * %d medium at %s\n",
			fdt.tracks, fdt.heads, fdt.sectrac, secsize, _devname);

	for (nbytes = 0; nbytes < mediasize;) {
		if (lseek(fd, nbytes, SEEK_SET) != nbytes)
			err(EX_OSERR, "cannot lseek()");
		rv = read(fd, trackbuf, tracksize);
		if (rv == 0) {
			/* EOF? */
			warnx("premature EOF after %u bytes", nbytes);
			return (EX_OK);
		}
		if ((unsigned)rv == tracksize) {
			nbytes += rv;
			if (!quiet)
				fprintf(stderr, "%5d KB\r", nbytes / 1024);
			fwrite(trackbuf, sizeof(unsigned char), rv, of);
			fflush(of);
			continue;
		}
		if (rv == -1) {
			/* fall back reading one sector at a time */
			for (n = 0; n < tracksize; n += secsize) {
				if (lseek(fd, nbytes, SEEK_SET) != nbytes)
					err(EX_OSERR, "cannot lseek()");
				rv = read(fd, trackbuf, secsize);
				if ((unsigned) rv == secsize) {
					nbytes += rv;
					if (!quiet)
						fprintf(stderr, "%5d KB\r",
							nbytes / 1024);
					fwrite(trackbuf, sizeof(unsigned char),
					       rv, of);
					fflush(of);
					continue;
				}
				if (rv == -1) {
					if (errno != EIO) {
						if (!quiet)
							putc('\n', stderr);
						perror("non-IO error");
						return (EX_OSERR);
					}
					if (ioctl(fd, FD_GSTAT, &fdcs) == -1)
						errx(EX_IOERR,
				     "floppy IO error, but no FDC status");
					nerrs++;
					recoverable = fdcs.status[2] &
						NE7_ST2_DD;
					if (!quiet) {
						printstatus(&fdcs, 0);
						fputs(" (", stderr);
						if (!recoverable)
							fputs("not ", stderr);
						fputs("recoverable)", stderr);
					}
					if (!recover) {
						if (!quiet)
							putc('\n', stderr);
						return (EX_IOERR);
					}
					memset(trackbuf, fillbyte, secsize);
					if (recoverable) {
						fdopts |= FDOPT_NOERROR;
						if (ioctl(fd, FD_SOPTS,
							  &fdopts) == -1)
							err(EX_OSERR,
				    "ioctl(fd, FD_SOPTS, FDOPT_NOERROR)");
						rv = read(fd, trackbuf,
							  secsize);
						if ((unsigned)rv != secsize)
							err(EX_IOERR,
				    "read() with FDOPT_NOERROR still fails");
						fdopts &= ~FDOPT_NOERROR;
						(void)ioctl(fd, FD_SOPTS,
							    &fdopts);
					}
					if (!quiet) {
						if (recoverable)
							fprintf(stderr,
								": recovered");
						else
							fprintf(stderr,
								": dummy");
						fprintf(stderr,
							" data @ %#x ... %#x\n",
							nbytes,
							nbytes + secsize - 1);
					}
					nbytes += secsize;
					fwrite(trackbuf, sizeof(unsigned char),
					       secsize, of);
					fflush(of);
					continue;
				}
				errx(EX_OSERR, "unexpected read() result: %d",
				     rv);
			}
		}
		if ((unsigned)rv < tracksize) {
			/* should not happen */
			nbytes += rv;
			if (!quiet)
				fprintf(stderr, "\nshort after %5d KB\r",
					nbytes / 1024);
			fwrite(trackbuf, sizeof(unsigned char), rv, of);
			fflush(of);
			continue;
		}
	}
	if (!quiet) {
		putc('\n', stderr);
		if (nerrs)
			fprintf(stderr, "%d error%s\n",
				nerrs, nerrs > 1? "s": "");
	}

	return (nerrs? EX_IOERR: EX_OK);
}
Beispiel #20
0
int fileselector(char *name, char *path, char *filter, char *title, int filemode)
{
  int c, d, scrrep;
  int color;
  int files;
  int filepos = 0;
  int fileview = 0;
  int lastclick = 0;
  int lastfile = 0;
  int lowest;
  int exitfilesel;

  DIR *dir;
  struct dirent *de;
  struct stat st;
  #ifdef __WIN32__
  char drivestr[] = "A:\\";
  char driveexists[26];
  #endif
  char cmpbuf[MAX_PATHNAME];
  char tempname[MAX_PATHNAME];

  // Set initial path (if any)
  if (strlen(path)) chdir(path);

  // Scan for all existing drives
  #ifdef __WIN32__
  for (c = 0; c < 26; c++)
  {
    drivestr[0] = 'A'+c;
    if (GetDriveType(drivestr) > 1) driveexists[c] = 1;
    else driveexists[c] = 0;
  }
  #endif

  // Read new directory
  NEWPATH:
  getcwd(path, MAX_PATHNAME);
  files = 0;
  // Deallocate old names
  for (c = 0; c < MAX_DIRFILES; c++)
  {
    if (direntry[c].name)
    {
      free(direntry[c].name);
      direntry[c].name = NULL;
    }
  }
  #ifdef __WIN32__
  // Create drive letters
  for (c = 0; c < 26; c++)
  {
    if (driveexists[c])
    {
      drivestr[0] = 'A'+c;
      direntry[files].name = strdup(drivestr);
      direntry[files].attribute = 2;
      files++;
    }
  }
  #endif

  // Process directory
  #ifdef __amigaos__
  dir = opendir("");
  #else
  dir = opendir(".");
  #endif
  if (dir)
  {
    char *filtptr = strstr(filter, "*");
    if (!filtptr) filtptr = filter;
    else filtptr++;
    for (c = 0; c < strlen(filter); c++)
      filter[c] = tolower(filter[c]);

    while ((de = readdir(dir)))
    {
      if ((files < MAX_DIRFILES) && (strlen(de->d_name) < MAX_FILENAME))
      {
        direntry[files].name = strdup(de->d_name);
        direntry[files].attribute = 0;
        stat(de->d_name, &st);
        if (st.st_mode & S_IFDIR)
        {
          direntry[files].attribute = 1;
          files++;
        }
        else
        {
          int c;
          // If a file, must match filter
          strcpy(cmpbuf, de->d_name);
          if ((!strcmp(filtptr, "*")) || (!strcmp(filtptr, ".*")))
            files++;
          else
          {
            for (c = 0; c < strlen(cmpbuf); c++)
              cmpbuf[c] = tolower(cmpbuf[c]);
            if (strstr(cmpbuf, filtptr))
              files++;
            else
            {
              free(direntry[files].name);
              direntry[files].name = NULL;
            }
          }
        }
      }
    }
    closedir(dir);
  }
  // Sort the filelist in a most horrible fashion
  for (c = 0; c < files; c++)
  {
    lowest = c;
    for (d = c+1; d < files; d++)
    {
      if (direntry[d].attribute < direntry[lowest].attribute)
      {
        lowest = d;
      }
      else
      {
        if (direntry[d].attribute == direntry[lowest].attribute)
        {
          if (cmpname(direntry[d].name, direntry[lowest].name) < 0)
          {
            lowest = d;
          }
        }
      }
    }
    if (lowest != c)
    {
      DIRENTRY swaptemp = direntry[c];
      direntry[c] = direntry[lowest];
      direntry[lowest] = swaptemp;
    }
  }

  // Search for the current filename
  fileview = 0;
  filepos = 0;
  for (c = 0; c < files; c++)
  {
    if ((!direntry[c].attribute) && (!cmpname(name, direntry[c].name)))
    {
      filepos = c;
    }
  }

  exitfilesel = -1;
  while (exitfilesel < 0)
  {
    int cc = cursorcolortable[cursorflash];
    if (cursorflashdelay >= 6)
    {
      cursorflashdelay %= 6;
      cursorflash++;
      cursorflash &= 3;
    }
    fliptoscreen();
    getkey();
    if (lastclick) lastclick--;

    if (win_quitted)
    {
      exitprogram = 1;
      for (c = 0; c < MAX_DIRFILES; c++)
      {
        if (direntry[c].name)
        {
          free(direntry[c].name);
          direntry[c].name = NULL;
        }
      }
      return 0;
    }

    if (mouseb)
    {
      // Cancel (click outside)
      if ((mousey < 3) || (mousey > 3+VISIBLEFILES+6) || (mousex <= 4+10) || (mousex >= 75+10))
      {
        if ((!prevmouseb) && (lastclick)) exitfilesel = 0;
      }

      // Select dir,name,filter
      if ((mousey >= 3+VISIBLEFILES+3) && (mousey <= 3+VISIBLEFILES+5) && (mousex >= 14+10) && (mousex <= 73+10))
      {
        filemode = mousey - (3+VISIBLEFILES+3) + 1;
        if ((filemode == 3) && (!prevmouseb) && (lastclick)) goto ENTERFILE;
      }

      // Select file from list
      if ((mousey >= 3) && (mousey <= 3+VISIBLEFILES+2) && (mousex >= 6+10) && (mousex <= 73+10))
      {
        filemode = 0;
        filepos = mousey - 4 - 1 + fileview;
        if (filepos < 0) filepos = 0;
        if (filepos > files-1) filepos = files - 1;

        if (!direntry[filepos].attribute)
          strcpy(name, direntry[filepos].name);

        if ((!prevmouseb) && (lastclick) && (lastfile == filepos)) goto ENTERFILE;
      }
    }

    if (!filemode)
    {
      if (((key >= '0') && (key <= '0')) || ((key >= 'a') && (key <= 'z')) || ((key >= 'A') && (key <= 'Z')))
      {
        char k = tolower(key);
        int oldfilepos = filepos;

        for (filepos = oldfilepos + 1; filepos < files; filepos++)
          if (tolower(direntry[filepos].name[0]) == k) break;
        if (filepos >= files)
        {
          for (filepos = 0; filepos < oldfilepos; filepos++)
             if (tolower(direntry[filepos].name[0]) == k) break;
        }

        if (!direntry[filepos].attribute) strcpy(name, direntry[filepos].name);
      }
    }

    switch(rawkey)
    {
      case KEY_ESC:
      exitfilesel = 0;
      break;

      case KEY_BACKSPACE:
      if (!filemode)
      {
      #ifdef __amigaos__
        chdir("/");
      #else
        chdir("..");
      #endif
        goto NEWPATH;
      }
      break;

      case KEY_HOME:
      if (!filemode)
      {
        filepos = 0;
        if (!direntry[filepos].attribute) strcpy(name, direntry[filepos].name);
      }
      break;

      case KEY_END:
      if (!filemode)
      {
        filepos = files-1;
        if (!direntry[filepos].attribute) strcpy(name, direntry[filepos].name);
      }
      break;

      case KEY_PGUP:
      for (scrrep = PGUPDNREPEAT; scrrep; scrrep--)
      {
        if ((!filemode) && (filepos > 0))
        {
          filepos--;
          if (!direntry[filepos].attribute) strcpy(name, direntry[filepos].name);
        }
      }
      break;

      case KEY_UP:
      if ((!filemode) && (filepos > 0))
      {
        filepos--;
        if (!direntry[filepos].attribute) strcpy(name, direntry[filepos].name);
      }
      break;

      case KEY_PGDN:
      for (scrrep = PGUPDNREPEAT; scrrep; scrrep--)
      {
        if ((!filemode) && (filepos < files-1))
        {
          filepos++;
          if (!direntry[filepos].attribute) strcpy(name, direntry[filepos].name);
        }
      }
      break;

      case KEY_DOWN:
      if ((!filemode) && (filepos < files-1))
      {
        filepos++;
        if (!direntry[filepos].attribute) strcpy(name, direntry[filepos].name);
      }
      break;

      case KEY_TAB:
      if (!shiftpressed)
      {
        filemode++;
        if (filemode > 3) filemode = 0;
      }
      else
      {
        filemode--;
        if (filemode < 0) filemode = 3;
      }
      break;

      case KEY_ENTER:
      ENTERFILE:
      switch(filemode)
      {
        case 0:
        switch (direntry[filepos].attribute)
        {
          case 0:
          strcpy(name, direntry[filepos].name);
          exitfilesel = 1;
          break;

          case 1:
          chdir(direntry[filepos].name);
          goto NEWPATH;

          case 2:
          strcpy(tempname, direntry[filepos].name);
          if (strlen(tempname))
          {
            if (tempname[strlen(tempname)-1] != '\\')
              strcat(tempname, "\\");
          }
          chdir(tempname);
          goto NEWPATH;
        }
        break;

        case 1:
        chdir(path);
        case 2:
        filemode = 0;
        goto NEWPATH;

        case 3:
        exitfilesel = 1;
        break;
      }
      break;
    }

    switch(filemode)
    {
      case 1:
      editstring(path, MAX_PATHNAME);
      break;

      case 2:
      editstring(filter, MAX_FILENAME);
      break;

      case 3:
      editstring(name, MAX_FILENAME);
      break;
    }

    // Validate filelist view
    if (filepos < fileview) fileview = filepos;
    if (filepos - fileview >= VISIBLEFILES) fileview = filepos - VISIBLEFILES + 1;

    // Refresh fileselector display
    if (isplaying()) printstatus();
    for (c = 0; c < VISIBLEFILES+7; c++)
    {
      printblank(50-(MAX_FILENAME+10)/2, 3+c, MAX_FILENAME+10);
    }
    drawbox(50-(MAX_FILENAME+10)/2, 3, 15, MAX_FILENAME+10, VISIBLEFILES+7);
    printblankc(50-(MAX_FILENAME+10)/2+1, 4, 15+16,MAX_FILENAME+8);
    printtext(50-(MAX_FILENAME+10)/2+1, 4, 15+16, title);

    for (c = 0; c < VISIBLEFILES; c++)
    {
      if ((fileview+c >= 0) && (fileview+c < files))
      {
        switch (direntry[fileview+c].attribute)
        {
          case 0:
          sprintf(textbuffer, "%-60s        ", direntry[fileview+c].name);
          break;

          case 1:
          sprintf(textbuffer, "%-60s   <DIR>", direntry[fileview+c].name);
          break;

          case 2:
          sprintf(textbuffer, "%-60s   <DRV>", direntry[fileview+c].name);
          break;
        }
      }
      else
      {
        sprintf(textbuffer, "                                                                    ");
      }
      color = CNORMAL;
      if ((fileview+c) == filepos) color = CEDIT;
      textbuffer[68] = 0;
      printtext(50-(MAX_FILENAME+10)/2+1, 5+c, color, textbuffer);
      if ((!filemode) && ((fileview+c) == filepos)) printbg(50-(MAX_FILENAME+10)/2+1, 5+c, cc, 68);
    }

    printtext(50-(MAX_FILENAME+10)/2+1, 6+VISIBLEFILES, 15, "PATH:   ");
    sprintf(textbuffer, "%-60s", path);
    textbuffer[MAX_FILENAME] = 0;
    color = CNORMAL;
    if (filemode == 1) color = CEDIT;
    printtext(50-(MAX_FILENAME+10)/2+9, 6+VISIBLEFILES, color, textbuffer);
    if ((filemode == 1) && (strlen(path) < MAX_FILENAME)) printbg(50-(MAX_FILENAME+10)/2+9+strlen(path), 6+VISIBLEFILES, cc, 1);

    printtext(50-(MAX_FILENAME+10)/2+1, 7+VISIBLEFILES, 15, "FILTER: ");
    sprintf(textbuffer, "%-60s", filter);
    textbuffer[MAX_FILENAME] = 0;
    color = CNORMAL;
    if (filemode == 2) color = CEDIT;
    printtext(50-(MAX_FILENAME+10)/2+9, 7+VISIBLEFILES, color, textbuffer);
    if (filemode == 2) printbg(50-(MAX_FILENAME+10)/2+9+strlen(filter), 7+VISIBLEFILES, cc, 1);

    printtext(50-(MAX_FILENAME+10)/2+1, 8+VISIBLEFILES, 15, "NAME:   ");
    sprintf(textbuffer, "%-60s", name);
    textbuffer[MAX_FILENAME] = 0;
    color = CNORMAL;
    if (filemode == 3) color = CEDIT;
    printtext(50-(MAX_FILENAME+10)/2+9, 8+VISIBLEFILES, color, textbuffer);
    if (filemode == 3) printbg(50-(MAX_FILENAME+10)/2+9+strlen(name), 8+VISIBLEFILES, cc, 1);

    if (win_quitted) exitfilesel = 0;

    if ((mouseb) && (!prevmouseb))
    {
      lastclick = DOUBLECLICKDELAY;
      lastfile = filepos;
    }
  }

  // Deallocate all used names
  for (c = 0; c < MAX_DIRFILES; c++)
  {
    if (direntry[c].name)
    {
      free(direntry[c].name);
      direntry[c].name = NULL;
    }
  }

  // Restore screen & exit
  printmainscreen();
  return exitfilesel;
}
Beispiel #21
0
void cparse (void)
{
  int result, val;
  
  if (
      !strcmp (stream_->lexeme, "exit")  ||
      !strcmp (stream_->lexeme, "quit")  ||
      !strcmp (stream_->lexeme, "Quit")  ||
      !strcmp (stream_->lexeme, "q")     ||
      !strcmp (stream_->lexeme, "Q")
      )
  {
    printf("Final:\n");
    printstatus ();
    kill(getppid(), SIGQUIT);
    exit(EXIT_SUCCESS);
  }
  else if (!strcmp(stream_->lexeme, "set")) {
    GTNEXT();
    result = p_op ();
    if (stream_->type == T_NUM) {
      val = atoi (stream_->lexeme);
      GTNEXT();
      switch (result) {
        case COM_OP:
          if (val <= 1) {
            pool_->mutate = mutate1;
            printf("Mutate operator now set to: 1\n");
          }
          else {
            pool_->mutate = mutate2;
            printf("Mutate operator now set to: 2\n");
          }
          break;
        case COM_PROB:
          if (val < 0) val = 0;
          else if (val > 100) val = 100;
          pool_->mutateprob = (uint8_t)val;
          printf("Mutate probability now set to %d\n", val);
          break;
        case COM_X:
          if (val <= 1) {
            pool_->cross = uniform_cr;
            printf("Now using uniform crossover\n");
          }
          else {
            pool_->cross = npoint_cr;
            printf("Now using n-point crossover, n = %d\n", CR_N);
          }
          break;
        case COM_SEL:
          if (val <= 1) {
            pool_->select = roulette_sf;
            printf("Now using roulette selection.");
          }
          else if (val == 2) {
            pool_->select = rank_sf;
            printf("Now using rank selection\n");
          }
          else {
            pool_->select = tournament_sf;
            printf("Now using tournament selection\n");
          }
          break;
        case COM_K:
          pool_->k = (uint8_t)val;
          printf ("Now using k value (for tournament selction): %d.\n", val);
          break;
        default:
          break;
      }
    }
    else
      printf ("Command Line Error: Expected number, but got '%s'\n", stream_->lexeme);
  }
  else if (!strcmp(stream_->lexeme, "get")) {
    GTNEXT();
    result = p_op();
    switch (result) {
      case COM_OP:
        if (pool_->mutate == mutate1)
          printf("Currently using mutation operator 1.\n");
        else
          printf("Currently using mutation operator 2.\n");
        break;
      case COM_PROB:
        printf("Current mutation probability is %u%%\n", pool_->mutateprob);
        break;
      case COM_X:
        if (pool_->cross == uniform_cr)
          printf("Currently using uniform crossover.\n");
        else
          printf ("Currently using n-point crossover, n = %d\n", CR_N);
        break;
      case COM_SEL:
        if (pool_->select == roulette_sf)
          printf("Currently using roulette selection.\n");
        else if (pool_->select == rank_sf)
          printf("Currently using rank selection.\n");
        else
          printf("Currently using tournament selection.\n");
        break;
      case COM_K:
        printf("Current k value (for tournament selection): %d.\n", pool_->k);
        break;
      default:
        break;
    }
    
  }
  else if (!strcmp(stream_->lexeme, "show")) {
    GTNEXT();
    p_show();
  }
  else if (!strcmp (stream_->lexeme, "status")) {
    GTNEXT();
    printstatus();
  }
  else
    printf ("Command Line Error: Unrecognized: '%s'\n", stream_->lexeme);
}
Beispiel #22
0
int loadstatus()
{
	printstatus();
	return 0;
}
Beispiel #23
0
int
main(int argc, char **argv)
{
	enum fd_drivetype type;
	struct fd_type fdt, newft, *fdtp;
	struct stat sb;
#define MAXPRINTERRS 10
	struct fdc_status fdcs[MAXPRINTERRS];
	int format, fill, quiet, verify, verify_only, confirm;
	int fd, c, i, track, error, tracks_per_dot, bytes_per_track, errs;
	int flags;
	char *fmtstring, *device;
	const char *name, *descr;

	format = quiet = verify_only = confirm = 0;
	verify = 1;
	fill = 0xf6;
	fmtstring = 0;

	while((c = getopt(argc, argv, "F:f:nqs:vy")) != -1)
		switch(c) {
		case 'F':	/* fill byte */
			if (getnum(optarg, &fill)) {
				fprintf(stderr,
			"Bad argument %s to -F option; must be numeric\n",
					optarg);
				usage();
			}
			break;

		case 'f':	/* format in kilobytes */
			if (getnum(optarg, &format)) {
				fprintf(stderr,
			"Bad argument %s to -f option; must be numeric\n",
					optarg);
				usage();
			}
			break;

		case 'n':	/* don't verify */
			verify = 0;
			break;

		case 'q':	/* quiet */
			quiet = 1;
			break;

		case 's':	/* format string with detailed options */
			fmtstring = optarg;
			break;

		case 'v':	/* verify only */
			verify = 1;
			verify_only = 1;
			break;

		case 'y':	/* confirm */
			confirm = 1;
			break;

		default:
			usage();
		}

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

	if (stat(argv[optind], &sb) == -1 && errno == ENOENT) {
		/* try prepending _PATH_DEV */
		device = malloc(strlen(argv[optind]) + sizeof(_PATH_DEV) + 1);
		if (device == 0)
			errx(EX_UNAVAILABLE, "out of memory");
		strcpy(device, _PATH_DEV);
		strcat(device, argv[optind]);
		if (stat(device, &sb) == -1) {
			free(device);
			device = argv[optind]; /* let it fail below */
		}
	} else {
		device = argv[optind];
	}

	if ((fd = open(device, O_RDWR | O_NONBLOCK)) < 0)
		err(EX_OSERR, "open(%s)", device);

	/*
	 * Device initialization.
	 *
	 * First, get the device type descriptor.  This tells us about
	 * the media geometry data we need to format a medium.  It also
	 * lets us know quickly whether the device name actually points
	 * to a floppy disk drive.
	 *
	 * Then, obtain any drive options.  We're mainly interested to
	 * see whether we're currently working on a device with media
	 * density autoselection (FDOPT_AUTOSEL).  Then, we add the
	 * device option to tell the kernel not to log media errors,
	 * since we can handle them ourselves.  If the device does
	 * media density autoselection, we then need to set the device
	 * type appropriately, since by opening with O_NONBLOCK we
	 * told the driver to bypass media autoselection (otherwise we
	 * wouldn't stand a chance to format an unformatted or damaged
	 * medium).  We do not attempt to set the media type on any
	 * other devices since this is a privileged operation.  For the
	 * same reason, specifying -f and -s options is only possible
	 * for autoselecting devices.
	 *
	 * Finally, we are ready to turn off O_NONBLOCK, and start to
	 * actually format something.
	 */
	if(ioctl(fd, FD_GTYPE, &fdt) < 0)
		errx(EX_OSERR, "not a floppy disk: %s", device);
	if (ioctl(fd, FD_GDTYPE, &type) == -1)
		err(EX_OSERR, "ioctl(FD_GDTYPE)");
	if (format) {
		getname(type, &name, &descr);
		fdtp = get_fmt(format, type);
		if (fdtp == 0)
			errx(EX_USAGE,
			    "unknown format %d KB for drive type %s",
			     format, name);
		fdt = *fdtp;
	}
	if (fmtstring) {
		parse_fmt(fmtstring, type, fdt, &newft);
		fdt = newft;
	}
	if (ioctl(fd, FD_STYPE, &fdt) < 0)
		err(EX_OSERR, "ioctl(FD_STYPE)");
	if ((flags = fcntl(fd, F_GETFL, 0)) == -1)
		err(EX_OSERR, "fcntl(F_GETFL)");
	flags &= ~O_NONBLOCK;
	if (fcntl(fd, F_SETFL, flags) == -1)
		err(EX_OSERR, "fcntl(F_SETFL)");

	bytes_per_track = fdt.sectrac * (128 << fdt.secsize);

	/* XXX  20/40 = 0.5 */
	tracks_per_dot = (fdt.tracks * fdt.heads + 20) / 40;

	if (verify_only) {
		if(!quiet)
			printf("Verify %dK floppy `%s'.\n",
				fdt.tracks * fdt.heads * bytes_per_track / 1024,
				device);
	}
	else if(!quiet && !confirm) {
		printf("Format %dK floppy `%s'? (y/n): ",
			fdt.tracks * fdt.heads * bytes_per_track / 1024,
			device);
		if(!yes()) {
			printf("Not confirmed.\n");
			return (EX_UNAVAILABLE);
		}
	}

	/*
	 * Formatting.
	 */
	if(!quiet) {
		printf("Processing ");
		for (i = 0; i < (fdt.tracks * fdt.heads) / tracks_per_dot; i++)
			putchar('-');
		printf("\rProcessing ");
		fflush(stdout);
	}

	error = errs = 0;

	for (track = 0; track < fdt.tracks * fdt.heads; track++) {
		if (!verify_only) {
			format_track(fd, track / fdt.heads, fdt.sectrac,
				track % fdt.heads, fdt.trans, fdt.f_gap,
				fdt.secsize, fill, fdt.f_inter,
				track % fdt.heads? fdt.offset_side2: 0);
			if(!quiet && !((track + 1) % tracks_per_dot)) {
				putchar('F');
				fflush(stdout);
			}
		}
		if (verify) {
			if (verify_track(fd, track, bytes_per_track) < 0) {
				error = 1;
				if (errs < MAXPRINTERRS && errno == EIO) {
					if (ioctl(fd, FD_GSTAT, fdcs + errs) ==
					    -1)
						errx(EX_IOERR,
					"floppy IO error, but no FDC status");
					errs++;
				}
			}
			if(!quiet && !((track + 1) % tracks_per_dot)) {
				if (!verify_only)
					putchar('\b');
				if (error) {
					putchar('E');
					error = 0;
				}
				else
					putchar('V');
				fflush(stdout);
			}
		}
	}
	if(!quiet)
		printf(" done.\n");

	if (!quiet && errs) {
		fflush(stdout);
		fprintf(stderr, "Errors encountered:\nCyl Head Sect   Error\n");
		for (i = 0; i < errs && i < MAXPRINTERRS; i++) {
			fprintf(stderr, " %2d   %2d   %2d   ",
				fdcs[i].status[3], fdcs[i].status[4],
				fdcs[i].status[5]);
			printstatus(fdcs + i, 1);
			putc('\n', stderr);
		}
		if (errs >= MAXPRINTERRS)
			fprintf(stderr, "(Further errors not printed.)\n");
	}

	return errs != 0;
}
Beispiel #24
0
void sighandler(int signo) {
	DEBUG_PRINT(DEBUG_MAX, "timeout sig\n");
	printstatus(gsk);
}
Beispiel #25
0
int main(int argc,char **argv)
{
  char *hostname;
//  char *portname;
  int opt;
  struct servent *se;
  char *x;
  unsigned long u;
  int s;
  int t;

  while ((opt = getopt(argc,argv,"4dDvqQhHrR1UXx:t:u:g:l:b:B:c:I:pPoO")) != opteof)
    switch(opt) {
      case 'b': scan_ulong(optarg,&backlog); break;
      case 'c': scan_ulong(optarg,&limit); break;
      case 'X': flagallownorules = 1; break;
      case 'x': fnrules = optarg; break;
      case 'B': banner = optarg; break;
      case 'd': flagdelay = 1; break;
      case 'D': flagdelay = 0; break;
      case 'v': verbosity = 2; break;
      case 'q': verbosity = 0; break;
      case 'Q': verbosity = 1; break;
      case 'P': flagparanoid = 0; break;
      case 'p': flagparanoid = 1; break;
      case 'O': flagkillopts = 1; break;
      case 'o': flagkillopts = 0; break;
      case 'H': flagremotehost = 0; break;
      case 'h': flagremotehost = 1; break;
//      case 'R': flagremoteinfo = 0; break;
      case 'r': flagremoteinfo = 1; break;
      case 't': scan_ulong(optarg,&timeout); break;
      case 'U': x = env_get("UID"); if (x) scan_ulong(x,&uid);
        x = env_get("GID"); if (x) scan_ulong(x,&gid); break;
      case 'u': scan_ulong(optarg,&uid); break;
      case 'g': scan_ulong(optarg,&gid); break;
      case 'I': netif=socket_getifidx(optarg); break;
      case '1': flag1 = 1; break;
//      case '4': noipv6 = 1; break;
      case '4': ipv4socket = 1; break;
//      case '6': forcev6 = 1; break;
      case 'l': localhost = optarg; break;
      default: usage();
    }
  argc -= optind;
  argv += optind;

  if (!verbosity)
    buffer_2->fd = -1;

  hostname = *argv++;
  if (!hostname) usage();
  if (str_equal(hostname,"")) hostname = "0";

  x = *argv++;
  if (!x) usage();
  if (!x[scan_ulong(x,&u)])
    localport = u;
  else {
    se = getservbyname(x,"tcp");
    if (!se)
      errint(EHARD,B("unable to figure out port number for ",x));
    uint16_unpack_big((char*)&se->s_port,&localport);
  }

  if (!*argv) usage();

  sig_block(sig_child);
  sig_catch(sig_child,sigchld);
  sig_catch(sig_term,sigterm);
  sig_ignore(sig_pipe);

  if (str_equal(hostname,"0")) {
    byte_zero(localip,sizeof localip);
  } else {
    if (!stralloc_copys(&tmp,hostname)) errmem;
    if (dns_ip6_qualify(&addresses,&fqdn,&tmp) == -1)
      errint(EHARD,B("temporarily unable to figure out IP address for ",hostname,": "));
    if (addresses.len < 16)
	  errint(EHARD,B("no IP address for ",hostname));
    byte_copy(localip,16,addresses.s);
    if (ip6_isv4mapped(localip))
      ipv4socket = 1;
  }

  s = socket_tcp();
  if (s == -1)
    errint(EHARD,"unable to create socket: ");
  if (socket_bind_reuse(s,localip,localport,netif) == -1)
    errint(EHARD,"unable to bind: ");

  if (!ipv4socket) ipv4socket = ip6_isv4mapped(localip);

  if (socket_local(s,localip,&localport,&netif) == -1)
    errint(EHARD,"unable to get local address: ");
  if (socket_listen(s,backlog) == -1)
    errint(EHARD,"unable to listen: ");
  ndelay_off(s);

  if (gid) if (prot_gid(gid) == -1)
    errint(EHARD,"unable to set gid: ");
  if (uid) if (prot_uid(uid) == -1)
    errint(EHARD,"unable to set uid: ");


  localportstr[fmt_ulong(localportstr,localport)] = 0;
  if (flag1) {
    buffer_init(&b,write,1,bspace,sizeof bspace);
    buffer_puts(&b,localportstr);
    buffer_puts(&b,"\n");
    buffer_flush(&b);
  }

  close(0);
  close(1);
  printstatus();

  for (;;) {
    while (numchildren >= limit) sig_pause();

    sig_unblock(sig_child);
    t = socket_accept(s,remoteip,&remoteport,&netif);
    sig_block(sig_child);

    if (t == -1) continue;
    ++numchildren; printstatus();

    switch(fork()) {
      case 0:
        close(s);
        doit(t);
        if ((fd_move(0,t) == -1) || (fd_copy(1,0) == -1))
          errint(EHARD,"unable to set up descriptors: ");
        sig_uncatch(sig_child);
        sig_unblock(sig_child);
        sig_uncatch(sig_term);
        sig_uncatch(sig_pipe);
        pathexec(argv);
        errint(EHARD,B("unable to run ",*argv,": "));
      case -1:
        errlog(ESOFT,NOTICE,"unable to fork: ");
        --numchildren; printstatus();
    }
    close(t);
  }
}
int main(int argc,char * const *argv) {
  const char *hostname;
  int opt;
  char *x;
  unsigned long u;
  int s;
  int t;
  int flagv4 = 1, flagv6 = 1, rc;
  struct addrinfo *localai = NULL, hints = {0}, *ai;
 
  while ((opt = getopt(argc,argv,"dDvqQhHrR1UXx:t:T:u:g:l:b:B:c:pPoO3IiEeSsw:nN46")) != opteof)
    switch(opt) {
      case 'b': scan_ulong(optarg,&backlog); break;
      case 'c': scan_ulong(optarg,&limit); break;
      case 'X': flagallownorules = 1; break;
      case 'x': fnrules = optarg; break;
      case 'B': banner = optarg; break;
      case 'd': flagdelay = 1; break;
      case 'D': flagdelay = 0; break;
      case 'v': verbosity = 2; break;
      case 'q': verbosity = 0; break;
      case 'Q': verbosity = 1; break;
      case 'P': flagparanoid = 0; break;
      case 'p': flagparanoid = 1; break;
      case 'O': flagkillopts = 1; break;
      case 'o': flagkillopts = 0; break;
      case 'H': flagremotehost = 0; break;
      case 'h': flagremotehost = 1; break;
      case 'R': flagremoteinfo = 0; break;
      case 'r': flagremoteinfo = 1; break;
      case 't': scan_ulong(optarg,&timeout); break;
      case 'T': scan_ulong(optarg,&ssltimeout); break;
      case 'w': scan_uint(optarg,&progtimeout); break;
      case 'U': x = env_get("UID"); if (x) scan_ulong(x,&uid);
		x = env_get("GID"); if (x) scan_ulong(x,&gid); break;
      case 'u': scan_ulong(optarg,&uid); break;
      case 'g': scan_ulong(optarg,&gid); break;
      case '1': flag1 = 1; break;
      case 'l': localhost = optarg; break;
      case '3': flag3 = 1; break;
      case 'I': flagclientcert = 0; break;
      case 'i': flagclientcert = 1; break;
      case 'S': flagsslenv = 0; break;
      case 's': flagsslenv = 1; break;
      case 'E': flagtcpenv = 0; break;
      case 'e': flagtcpenv = 1; break;
      case 'n': flagsslwait = 1; break;
      case 'N': flagsslwait = 0; break;
      case '4': flagv6 = 0; break;
      case '6': flagv4 = 0; break;
      default: usage();
    }
  if (flagv4 == flagv6) { flagv4 = flagv6 = 1; }
  argc -= optind;
  argv += optind;

  if (!verbosity)
    buffer_2->fd = -1;
 
  hostname = *argv++;
  if (!hostname) usage();
  if (str_equal(hostname,"")) hostname = NULL;
  if (str_equal(hostname,"0")) hostname = NULL;

  x = *argv++;
  if (!x) usage();
  prog = argv;
  if (!*argv) usage();

  hints.ai_family = flagv4 == flagv6 ? AF_UNSPEC : flagv4 ? AF_INET : AF_INET6;
  hints.ai_socktype = SOCK_STREAM;
  hints.ai_flags = AI_PASSIVE;
  if ((rc = getaddrinfo(hostname, x, &hints, &localai))) {
    strerr_die(111,FATAL "unable to figure out address for ", hostname ? hostname : "0",
		" ",x,": ",gai_strerror(rc),0);
  }
  if (!localai) {
    strerr_die2x(111,FATAL,"address not found");
  }

  if (x = env_get("VERIFYDEPTH")) {
    scan_ulong(x,&u);
    verifydepth = u;
  }

  if (x = env_get("CAFILE")) cafile = x;
  if (cafile && str_equal(cafile,"")) cafile = 0;

  if (x = env_get("CCAFILE")) ccafile = x;
  if (ccafile && str_equal(ccafile,"")) ccafile = 0;
  if (!flagclientcert) ccafile = 0;

  if (x = env_get("CADIR")) cadir = x;
  if (cadir && str_equal(cadir,"")) cadir= 0;

  if (x = env_get("CERTCHAINFILE")) certchainfile = x;
  if (certchainfile && str_equal(certchainfile,"")) certchainfile = 0;

  if (x = env_get("CERTFILE")) certfile = x;
  if (certfile && str_equal(certfile,"")) certfile = 0;

  if (x = env_get("KEYFILE")) keyfile = x;
  if (keyfile && str_equal(keyfile,"")) keyfile = 0;

  if (x = env_get("DHFILE")) dhfile = x;
  if (dhfile && str_equal(dhfile,"")) dhfile = 0;

  if (x = env_get("CIPHERS")) ciphers = x;
  if (ciphers && str_equal(ciphers,"")) ciphers = 0;

  sig_block(sig_child);
  sig_catch(sig_child,sigchld);
  sig_catch(sig_term,sigterm);
  sig_ignore(sig_pipe);

  for (ai = localai; ai; ai = ai->ai_next) { 
    s = socket_tcp(ai->ai_family, ai->ai_protocol);
    if (s == -1)
      strerr_die2sys(111,FATAL,"unable to create socket: ");

    if (socket_bind_reuse(s,ai) == -1)
      strerr_die2sys(111,FATAL,"unable to bind: ");

    if (socket_local(s,&localaddr,&localport) == -1)
      strerr_die2sys(111,FATAL,"unable to get local address: ");
    if (socket_listen(s,backlog) == -1)
      strerr_die2sys(111,FATAL,"unable to listen: ");
    break;
  }
  freeaddrinfo(localai); localai = NULL;
  ndelay_off(s);

  localportstr[fmt_ulong(localportstr,localport)] = 0;
  if (flag1) {
    buffer_init(&b,buffer_unixwrite,1,bspace,sizeof bspace);
    buffer_puts(&b,localportstr);
    buffer_puts(&b,"\n");
    buffer_flush(&b);
  }
 
  if (flag3) read_passwd();

  ctx = ssl_server();
  ssl_errstr();
  if (!ctx) strerr_die2x(111,FATAL,"unable to create SSL context");

  if (certchainfile) {
    switch (ssl_chainfile(ctx,certchainfile,keyfile,passwd_cb)) {
      case -1: strerr_die2x(111,FATAL,"unable to load certificate chain file");
      case -2: strerr_die2x(111,FATAL,"unable to load key");
      case -3: strerr_die2x(111,FATAL,"key does not match certificate");
      default: break;
    }
  } 
  else {  
    switch (ssl_certkey(ctx,certfile,keyfile,passwd_cb)) {
      case -1: strerr_die2x(111,FATAL,"unable to load certificate");
      case -2: strerr_die2x(111,FATAL,"unable to load key");
      case -3: strerr_die2x(111,FATAL,"key does not match certificate");
      default: break;
    }
  }

  if (!ssl_ca(ctx,cafile,cadir,verifydepth))
    strerr_die2x(111,FATAL,"unable to load CA list");

  if (!ssl_cca(ctx,ccafile))
    strerr_die2x(111,FATAL,"unable to load client CA list");

  if (!ssl_params(ctx,dhfile,rsalen))
    strerr_die2x(111,FATAL,"unable to set DH/RSA parameters");

  if (!ssl_ciphers(ctx,ciphers))
    strerr_die2x(111,FATAL,"unable to set cipher list");

  if (verbosity >= 2) {
    strnum[fmt_ulong(strnum,getpid())] = 0;
    strnum2[fmt_ulong(strnum2,rsalen)] = 0;
    strerr_warn4("sslserver: cafile ",strnum," ",cafile,0);
    strerr_warn4("sslserver: ccafile ",strnum," ",ccafile,0);
    strerr_warn4("sslserver: cadir ",strnum," ",cadir,0);
    strerr_warn4("sslserver: chainfile ",strnum," ",certchainfile,0);
    strerr_warn4("sslserver: cert ",strnum," ",certfile,0);
    strerr_warn4("sslserver: key ",strnum," ",keyfile,0);
    strerr_warn6("sslserver: param ",strnum," ",dhfile," ",strnum2,0);
  }

  close(0); open_read("/dev/null");
  close(1); open_append("/dev/null");

  printstatus();
 
  for (;;) {
    while (numchildren >= limit) sig_pause();

    sig_unblock(sig_child);
    t = socket_accept(s,&remoteaddr,&remoteport);
    sig_block(sig_child);

    if (t == -1) continue;
    ++numchildren; printstatus();
 
    switch(fork()) {
      case 0:
        close(s);
        doit(t);
	strerr_die4sys(111,DROP,"unable to run ",*argv,": ");
      case -1:
        strerr_warn2(DROP,"unable to fork: ",&strerr_sys);
        --numchildren; printstatus();
    }
    close(t);
  }
}
Beispiel #27
0
void mainloop(void)
{
    gfx_calcpalette(64, 0, 0, 0);
    gfx_setpalette();

    win_getspeed(60);
    for (;;)
    {
        speed = win_getspeed(60);
        if (speed > 10) speed = 10;
        key = kbd_getkey();
        getmousemove();
        getmousebuttons();
        if ((key == KEY_ESC) || (win_quitted)) break;
        blockediting();
        scrollmap();
        generalcommands();
        gfx_fillscreen(transparent);
        drawalllayers();
        printstatus();
        if (mark)
        {
            int mx, my;
            if (layer[cl].xdivisor) mx = markx1*gfx_blockxsize-xpos/layer[cl].xdivisor;
            else mx = markx1*gfx_blockxsize;
            if (layer[cl].xsize)
            {
                while (mx < 0)
                {
                    mx += layer[cl].xsize*gfx_blockxsize;
                }
                mx %= (layer[cl].xsize*gfx_blockxsize);
            }
            if (layer[cl].ydivisor) my = marky1*gfx_blockysize-ypos/layer[cl].ydivisor;
            else my = marky1*gfx_blockysize;
            if (layer[cl].ysize)
            {
                while (my < 0)
                {
                    my += layer[cl].ysize*gfx_blockysize;
                }
                my %= (layer[cl].ysize*gfx_blockysize);
            }
            gfx_drawsprite(mx,my,0x00010002);
        }
        if (mark==2)
        {
            int mx, my;
            if (layer[cl].xdivisor) mx = markx2*gfx_blockxsize-xpos/layer[cl].xdivisor;
            else mx = markx2*gfx_blockxsize;
            if (layer[cl].xsize)
            {
                while (mx < 0)
                {
                    mx += layer[cl].xsize*gfx_blockxsize;
                }
                mx %= (layer[cl].xsize*gfx_blockxsize);
            }
            if (layer[cl].ydivisor) my = marky2*gfx_blockysize-ypos/layer[cl].ydivisor;
            else my = marky2*gfx_blockysize;
            if (layer[cl].ysize)
            {
                while (my < 0)
                {
                    my += layer[cl].ysize*gfx_blockysize;
                }
                my %= (layer[cl].ysize*gfx_blockysize);
            }
            gfx_drawsprite(mx,my,0x00010003);
        }
        gfx_drawsprite(mousex,mousey,0x00010001);
        gfx_updatepage();

    }
}
Beispiel #28
0
int main(int argc,char **argv)
{
 char *hostname, *x;
 int c, s, t;
 unsigned int u;
 unsigned int cpid = 0;

 opterr = 0;

 while ((c = getopt(argc, argv, "dDoOC:k:c:")) != -1)
  switch (c) {
	case 'c':
	 limit = atoi(optarg);
	 if (limit == 0) usage();
	 break;
	case 'd': flagdelay = 1; break;
	case 'D': flagdelay = 0; break;
	case 'O': flagkillopts = 1; break;
	case 'o': flagkillopts = 0; break;
	case 'C': cacheprogram = 1; break;
	case 'k':
	 autokill = atoi(optarg);
	 if (autokill == 0) usage();
	 break;
	default: abort();
  }
 argc -= optind;
 argv += optind;

 hostname = *argv++;
 if (!hostname) usage();

 x = *argv++;
 if (!x) usage();
 u = 0;
 u = atoi(x);
 if (u != 0) localport = u;
 else usage();

 if (!*argv) usage();

 sig_block(sig_child);
 sig_catch(sig_child,sigchld);
 sig_catch(sig_term,sigterm);
 sig_catch(sig_int,sigint);
 sig_ignore(sig_pipe);

 inet_aton(hostname, (struct in_addr *) &localip);

 if (autokill != 0) pt = ptable_init(limit);

 s = socket_tcp();
 if (s == -1) die(111, "unable to create socket");
 if (socket_bind4_reuse(s,localip,localport) == -1) die(111, "unable to bind");
 if (socket_local4(s,localip,&localport) == -1) die(111, "unable to get local address");
 if (socket_listen(s,20) == -1) die(111, "unable to listen");
 ndelay_off(s);

 fprintf(stderr, "bind: %s:%d\n", hostname, localport);

 close(0);
 close(1);
 printstatus();

 if (cacheprogram) {

   FILE *fp1;
   int fp2;
   char path[1024];
   ssize_t n;

   fp1 = popen(*argv, "r");
   if (fp1 == NULL) {
     fprintf(stderr, "Failed to run command\n");
     exit(1);
   }

   fp2 = open("/var/tmp/tcpd.cache", O_RDWR | O_CREAT, S_IRUSR | S_IWUSR);
   if (fp2 == -1) {
     fprintf(stderr, "Can't open cache file\n");
     exit(1);
   }

   while ((n = fgets(path, sizeof(path)-1, fp1)) != NULL) {
     if (write(fp2, path, n) == n) {
       fprintf(stderr, "Error occured while creating cache\n");
       exit(1);
     }
   }

   /* close */
   pclose(fp1);
   close(fp2);

   // read cache file into memory
   FILE *f = fopen("/var/tmp/tcpd.cache", "rb");
   fseek(f, 0, SEEK_END);
   cachesize = ftell(f);
   fseek(f, 0, SEEK_SET);  //same as rewind(f);
   cache = malloc(cachesize + 1);
   n = fread(cache, cachesize, 1, f);
   fclose(f);
   cache[cachesize] = 0;
 }

 for (;;) {
   while (numchildren >= limit) {
    if (autokill != 0) ptable_autokill(pt, limit, autokill);
    sig_pause();
   }

   sig_unblock(sig_child);
   t = socket_accept4(s,remoteip,&remoteport);
   sig_block(sig_child);

   if (t == -1) continue;
   ++numchildren; printstatus();
   fprintf(stderr, "inbound connection from %d.%d.%d.%d:%d\n", (unsigned char) remoteip[0], (unsigned char) remoteip[1], (unsigned char) remoteip[2], (unsigned char) remoteip[3], remoteport);

   if (autokill != 0) ptable_autokill(pt,limit,autokill);

   cpid = fork();
   switch(cpid) {
	case 0:
	 close(s);
	 if(flagkillopts) socket_ipoptionskill(t);
	 if(!flagdelay) socket_tcpnodelay(t);
	 if((fd_move(0,t) == -1) || (fd_copy(1,0) == -1)) die(111,"unable to setup descriptors");
	 sig_uncatch(sig_child);
	 sig_unblock(sig_child);
	 sig_uncatch(sig_term);
	 sig_uncatch(sig_int);
	 sig_uncatch(sig_pipe);

	 if (cacheprogram) {
	   printf("%s", cache);
	   close(t);
	   exit(0);
	 } else {
	   if(execve(*argv,argv,NULL) == 0) {
	     close(t);
	     exit(0);
	   } else {
	     die(111, "unable to run argv");
	   }
	 }
	 break;
	case -1:
	 // unable to fork
	 eprint(P_WARN,"unable to fork");
	 --numchildren; printstatus();
	 break;
	default:
	 fprintf(stderr, "fork: child pid %d\n", cpid);
	 if (autokill != 0) ptable_set(pt, limit, cpid, time(NULL));
	 break;
   }
   close(t);
 }
}
Beispiel #29
0
int main(int argc, char *argv[]) {

	//User input prompt variables
	char prompt[20] = "308sh>";
	char input[300];
	char *inputArgs[30];
	int nowait;
	char buf[600];
	ProcessList * pList = (ProcessList*) malloc(sizeof(ProcessList));
	pList->size = 0;

	//Scans for argument inputs
	extern char *optarg;
	int ch;
	//Get all optional arguments using the getopt function
	while ((ch = getopt(argc, argv, "p:")) != EOF) {
		switch (ch) {
		//Prompt argument
		case 'p':
			strcpy(prompt, optarg);
			break;
		}

	}

	//Main loop
	while (1) {
		int status = 0;

		//Zero out the input buffer
		memset(&input, '\0', sizeof(input));

		//Display the shell prompt
		printf("%s ", prompt);

		//Grab input from user prompt
		fgets(input, sizeof(input), stdin);

		//Check for status change of background child processes
		pid_t pid = waitpid(-1, &status, WNOHANG);
		if (pid > 0) {
			//Remove from process list
			Process * ended = removeFromList(pList, pid);
			if (ended != NULL) {
				printstatus(status, ended->pid, ended->procname);
			}
		}

		//Split the input line into an array of char arrays (string array)
		int numArgs;
		numArgs = splitArgs(input, inputArgs);

		//Check if a valid number of arguments have been set
		if (numArgs < 0) {
			printf("Invalid Argument(s)\n");
			continue;
		}

		//Prevent execute from attempting to execute nothing (Simply pressing enter)
		if (numArgs == 1 && !strcmp(inputArgs[0], "\0")) {
			continue;
		}

		//Check for ampersand
		if (!(strcmp(inputArgs[numArgs - 1], "&"))) {
			//Set the nowait flag
			nowait = 1;
			//Remove the ampersand from the list of arguments sent to execute
			inputArgs[numArgs - 1] = '\0';
			numArgs--;
		} else {
			nowait = 0;
		}

		int stdout_old = dup(1);
		int fd = 1;
		//Check for file redirect, needs at least 3 arguments:
		// "CMD", the file redirect ">" and the file to redirect to "FILE"
		// CMD > FILE
		if (numArgs > 2 && !(strcmp(inputArgs[numArgs - 2], ">"))) {
			//Open the file
			fd = open(inputArgs[numArgs - 1], O_WRONLY | O_APPEND | O_CREAT,
			S_IWUSR | S_IRUSR | S_IRGRP | S_IROTH);

			//Redirect standard out
			if (dup2(fd, 1) < 0 || fd < 0) {
				exit(-1);
			}
			//Zero these arguments
			memset(&(inputArgs[numArgs - 1]), '\0',
					sizeof(inputArgs[numArgs - 1]));
			memset(&(inputArgs[numArgs - 2]), '\0',
					sizeof(inputArgs[numArgs - 2]));
			numArgs -= 2;
		}

		//All of the checks for user input
		//exit - exit normally
		if (!(strcmp(inputArgs[0], "exit"))) {
			exit(2);
		}
		//pid - print the process ID
		else if (!(strcmp(inputArgs[0], "pid"))) {
			printf("Process id is: [%d]\n", getpid());
		}
		//ppid - print the parent's process ID
		else if (!(strcmp(inputArgs[0], "ppid"))) {
			printf("Parent Process id is: [%d]\n", getppid());
		}
		//pwd - print the parent's process ID
		else if (!(strcmp(inputArgs[0], "pwd"))) {
			printf("Present Wording Directory is: %s\n", getcwd(buf, sizeof(buf)));
		}
		//cd - change current directory
		else if (!(strcmp(inputArgs[0], "cd"))) {
			if (numArgs == 1 || !(strcmp(inputArgs[1], "~"))) {
				chdir(getenv("HOME"));
			} else {
				chdir(inputArgs[1]);
			}
			printf("Present Wording Directory is: %s\n", getcwd(buf, sizeof(buf)));
		}
		//get - get an environment variable
		else if (!(strcmp(inputArgs[0], "get"))) {
			if (numArgs > 1) {
				//Check if variable is set
				if (getenv(inputArgs[1])) {
					//If it is set, print it.
					printf("Environment variable %s has value: %s\n",
							inputArgs[1], getenv(inputArgs[1]));
				} else {
					//If not set, notify user
					printf("Environment variable %s is not set\n",
							inputArgs[1]);
				}
			} else {
				printf("No environment varialbe given\n");
			}
		} else if (!(strcmp(inputArgs[0], "set"))) {
			if (numArgs > 2) {
				//Set environment variable and notify user what has been set to what
				if (!setenv(inputArgs[1], inputArgs[2], 1)) {
					printf(
							"Environment variable %s has been set with value: %s\n",
							inputArgs[1], inputArgs[2]);
				}
			} else if (numArgs == 2) {
				if (!unsetenv(inputArgs[1])) {
					printf("Environment variable %s has been unset\n",
							inputArgs[1]);
				}
			} else {
				printf("No environment varialbe given\n");
			}
		} else if (!(strcmp(inputArgs[0], "jobs"))) {
			printProcesses(pList);
		} else {
			//If none of the built in functions, search the PATH for an executable
			Process * executed = (Process *) malloc(sizeof(Process));
			execute(inputArgs, executed);
			if (!nowait) {
				//If nowait flag is not set, wait until child process completes
				waitpid(executed->pid, &status, 0);
				printstatus(status, executed->pid, executed->procname);
			} else {
				//Put the process in the processList table.
				addToList(pList, executed);
				//Or, if nowait, then process in the background
				printf("Process %s executing in background\n",
						executed->procname);
			}
		}

		//Route stdout to stdout
		//(In case previous command was piped to a file)
		//close previous file descriptor
		close(fd);
		//Flush standard out
		fflush(stdout);
		//Redirect file stream to old standard out
		if (dup2(stdout_old, 1) < 0) {
			exit(-1);
		}
		//Close the saved old standard out file descriptor
		close(stdout_old);

	}
}
Beispiel #30
0
int loadstatus()
{
	char filedest[512];
	FILE *file;
	char c;

	struct dhcp_conn_t dhcpconn;
	struct app_conn_t appconn;

	time_t r_wall, r_rt, r_rtoffset;
	time_t wall, rt, rtoffset;

	has_loaded = 1;

	if (!_options.usestatusfile)
		return 1;

	statedir_file(filedest, sizeof(filedest), _options.usestatusfile, 0);

	log_dbg("Loading file %s", filedest);

	file = fopen(filedest, "r");
	if (!file) {
		log_err(errno, "could not open file %s", filedest);
		return -1;
	}

	while ((c = fgetc(file)) != MARK_START) {
		if (c == EOF) {
			log_err(errno, "end of file");
			fclose(file);
			return -1;
		}
	}

	time(&wall);
	if (fread(&r_wall, sizeof(time_t), 1, file) != 1) {
		log_err(errno, "bad binary file");
		if (c == EOF) {
			fclose(file);
			return -1;
		}
	}

	rt = mainclock_tick();
	if (fread(&r_rt, sizeof(time_t), 1, file) != 1) {
		log_err(errno, "bad binary file");
		if (c == EOF) {
			fclose(file);
			return -1;
		}
	}

	if ((c = fgetc(file)) != MARK_START) {
		log_err(errno, "bad binary file");
		fclose(file);
		return -1;
	}

	rtoffset = wall - rt;
	log_dbg("now: wall = %d, rt = %d, wall at rt=0 %d",
		(int)wall, (int)rt, (int)rtoffset);

	r_rtoffset = r_wall - r_rt;
	log_dbg("file: wall = %d, rt = %d, wall at rt=0 %d",
		(int)r_wall, (int)r_rt, (int)r_rtoffset);

	while (fread(&dhcpconn, sizeof(struct dhcp_conn_t), 1, file) == 1) {
		struct dhcp_conn_t *conn = 0;
		struct ippoolm_t *newipm = 0;
		int n;

		/* todo: read a md5 checksum or magic token */

		if ((c = fgetc(file)) != MARK_NEXT) {
			log_err(errno, "bad binary file");
			fclose(file);
			return -1;
		}

		if (dhcp_hashget(dhcp, &conn, dhcpconn.hismac)) {

			log_info
			    ("Loading dhcp connection %.2X-%.2X-%.2X-%.2X-%.2X-%.2X",
			     dhcpconn.hismac[0], dhcpconn.hismac[1],
			     dhcpconn.hismac[2], dhcpconn.hismac[3],
			     dhcpconn.hismac[4], dhcpconn.hismac[5]);

			/* not already known */
			dhcp_lnkconn(dhcp, &conn);

			/* set/copy all the pointers */
			dhcpconn.nexthash = conn->nexthash;
			dhcpconn.next = conn->next;
			dhcpconn.prev = conn->prev;
			dhcpconn.parent = dhcp;

			dhcpconn.is_reserved = 0;	/* never a reserved ip if added here */

			/*
			 * Fix time_t values:
			 *  lasttime
			 */

#define localizetime(t) \
      /* to it's local real time */ \
      t = r_rtoffset + t; \
      /* now to our local rt offset */ \
      t = t - rtoffset; \
      if (t < 0) t = 0;

			localizetime(dhcpconn.lasttime);

			/* initialize dhcp_conn_t */
			memcpy(conn, &dhcpconn, sizeof(struct dhcp_conn_t));

			for (n = 0; n < DHCP_DNAT_MAX; n++) {
				memset(conn->dnat[n].mac, 0, PKT_ETH_ALEN);
			}

			log_dbg("checking IP %s", inet_ntoa(dhcpconn.hisip));

			/* add into ippool */
			if (ippool_getip(ippool, &newipm, &dhcpconn.hisip)) {
				if (ippool_newip
				    (ippool, &newipm, &dhcpconn.hisip, 1)) {
					if (ippool_newip
					    (ippool, &newipm, &dhcpconn.hisip,
					     0)) {
						log_err(0,
							"Failed to allocate either static or dynamic IP address");
						conn->hisip.s_addr = 0;
					}
				}
			}

			dhcp_hashadd(dhcp, conn);

			if (conn->peer) {
				conn->peer = 0;

				if (fread
				    (&appconn, sizeof(struct app_conn_t), 1,
				     file) == 1) {
					struct app_conn_t *aconn = 0;

					if ((c = fgetc(file)) != MARK_NEXT) {
						log_err(errno,
							"bad binary file");
						fclose(file);
						return -1;
					}

					if (chilli_new_conn(&aconn) == 0) {
						/* set/copy all the pointers/internals */
						appconn.unit = aconn->unit;
						appconn.next = aconn->next;
						appconn.prev = aconn->prev;
						appconn.uplink = newipm;
						appconn.dnlink = conn;

						/*
						 * Fix time_t values:
						 *  start_time, interim_time,
						 *  last_sent_time, last_time,
						 *  uamtime
						 */
						localizetime(appconn.s_state.
							     start_time);
						localizetime(appconn.s_state.
							     interim_time);
						localizetime(appconn.s_state.
							     last_sent_time);
						localizetime(appconn.s_state.
							     last_time);
						localizetime(appconn.s_state.
							     uamtime);

						/* initialize app_conn_t */
						memcpy(aconn, &appconn,
						       sizeof(struct
							      app_conn_t));
						conn->peer = aconn;

						if (newipm) {
							newipm->peer = aconn;

#ifdef ENABLE_UAMANYIP
							if (aconn->natip.s_addr)
								chilli_assign_snat
								    (aconn, 1);
#endif

							dhcp_set_addrs(conn,
								       &newipm->
								       addr,
								       &_options.
								       mask,
								       &aconn->
								       ourip,
								       &aconn->
								       mask,
								       &_options.
								       dns1,
								       &_options.
								       dns2);
						}
#if defined(ENABLE_SESSGARDEN) && defined(HAVE_PATRICIA)
						if (aconn->s_params.
						    pass_through_count) {
							garden_patricia_load_list
							    (&aconn->ptree,
							     aconn->s_params.
							     pass_throughs,
							     aconn->s_params.
							     pass_through_count);
						}
#endif
					}

					/* todo: read a md5 checksum or magic token */
				} else {
					log_err(errno,
						"Problem loading state file %s",
						filedest);
					break;
				}
			}

		} else {

			log_info
			    ("Known dhcp connection %.2X-%.2X-%.2X-%.2X-%.2X-%.2X",
			     dhcpconn.hismac[0], dhcpconn.hismac[1],
			     dhcpconn.hismac[2], dhcpconn.hismac[3],
			     dhcpconn.hismac[4], dhcpconn.hismac[5]);

			conn->authstate = dhcpconn.authstate;

			if (dhcpconn.peer) {

				log_info("Reading appconn (peer)");

				if (fread
				    (&appconn, sizeof(struct app_conn_t), 1,
				     file) == 1) {

					if ((c = fgetc(file)) != MARK_NEXT) {
						log_err(errno,
							"bad binary file");
						fclose(file);
						return -1;
					}

					if (conn->peer) {
						/*
						 * Already have an appconn.
						 */
						struct app_conn_t *aconn =
						    (struct app_conn_t *)conn->
						    peer;

						log_info
						    ("Overwriting existing appconn %d",
						     appconn.s_state.
						     authenticated);

						memcpy(&aconn->s_params,
						       &appconn.s_params,
						       sizeof(struct
							      session_params));
						memcpy(&aconn->s_state,
						       &appconn.s_state,
						       sizeof(struct
							      session_state));

					} else {
						/*
						 * No peer (appconn), then create it just as above.
						 */
						struct app_conn_t *aconn = 0;

						log_info
						    ("Creating new appconn (peer)");

						if (ippool_getip
						    (ippool, &newipm,
						     &conn->hisip)) {
							if (ippool_newip
							    (ippool, &newipm,
							     &conn->hisip, 1)) {
								if (ippool_newip
								    (ippool,
								     &newipm,
								     &conn->
								     hisip,
								     0)) {
									log_err
									    (0,
									     "Failed to allocate either static or dynamic IP address");
									fclose
									    (file);
									return
									    -1;
								}
							}
						}

						if (chilli_new_conn(&aconn) ==
						    0) {
							/* set/copy all the pointers/internals */
							appconn.unit =
							    aconn->unit;
							appconn.next =
							    aconn->next;
							appconn.prev =
							    aconn->prev;
							appconn.uplink = newipm;
							appconn.dnlink = conn;

							/* initialize app_conn_t */
							memcpy(aconn, &appconn,
							       sizeof(struct
								      app_conn_t));
							conn->peer = aconn;
							newipm->peer = aconn;

#ifdef ENABLE_UAMANYIP
							if (appconn.natip.
							    s_addr)
								chilli_assign_snat
								    (aconn, 1);
#endif

							dhcp_set_addrs(conn,
								       &newipm->
								       addr,
								       &_options.
								       mask,
								       &aconn->
								       ourip,
								       &aconn->
								       mask,
								       &_options.
								       dns1,
								       &_options.
								       dns2);
						}
					}
				}
			}
		}
	}

	fclose(file);
	printstatus();
	return 0;
}