コード例 #1
0
ファイル: trap.c プロジェクト: AgamAgarwal/minix
/*
 * Clear traps on a fork.
 */
void
clear_traps(void)
{
	char *volatile *tp;

	for (tp = trap ; tp <= &trap[_NSIG - 1] ; tp++) {
		if (*tp && **tp) {	/* trap not NULL or SIG_IGN */
			INTOFF;
			ckfree(*tp);
			*tp = NULL;
			if (tp != &trap[0])
				setsignal(tp - trap);
			INTON;
		}
	}
}
コード例 #2
0
ファイル: trap.c プロジェクト: alimon/dash
void
clear_traps(void)
{
    char **tp;

    INTOFF;
    for (tp = trap ; tp < &trap[NSIG] ; tp++) {
        if (*tp && **tp) {	/* trap not NULL or SIG_IGN */
            ckfree(*tp);
            *tp = NULL;
            if (tp != &trap[0])
                setsignal(tp - trap);
        }
    }
    trapcnt = 0;
    INTON;
}
コード例 #3
0
ファイル: jobs.c プロジェクト: saltstar/smartnix
void
setjobctl(int on)
{
	int fd;
	int pgrp;

	if (on == jobctl || rootshell == 0)
		return;
	if (on) {
		int ofd;
		ofd = fd = open(_PATH_TTY, O_RDWR);
		if (fd < 0) {
			fd += 3;
			while (!isatty(fd))
				if (--fd < 0)
					goto out;
		}
		fd = savefd(fd, ofd);
		do { /* while we are in the background */
			if ((pgrp = tcgetpgrp(fd)) < 0) {
out:
				sh_warnx("can't access tty; job control turned off");
				mflag = on = 0;
				goto close;
			}
			if (pgrp == getpgrp())
				break;
			killpg(0, SIGTTIN);
		} while (1);
		initialpgrp = pgrp;

		setsignal(SIGTSTP);
		setsignal(SIGTTOU);
		setsignal(SIGTTIN);
		pgrp = rootpid;
		setpgid(0, pgrp);
		xtcsetpgrp(fd, pgrp);
	} else {
		/* turning job control off */
		fd = ttyfd;
		pgrp = initialpgrp;
		xtcsetpgrp(fd, pgrp);
		setpgid(0, pgrp);
		setsignal(SIGTSTP);
		setsignal(SIGTTOU);
		setsignal(SIGTTIN);
close:
		close(fd);
		fd = -1;
	}
	ttyfd = fd;
	jobctl = on;
}
コード例 #4
0
ファイル: trap.c プロジェクト: 2fast4u88/oxygen_system_core
void
clear_traps(int vforked)
{
	char **tp;

	for (tp = trap ; tp <= &trap[NSIG] ; tp++) {
		if (*tp && **tp) {	/* trap not NULL or SIG_IGN */
			INTOFF;
			if (!vforked) {
				ckfree(*tp);
				*tp = NULL;
			}
			if (tp != &trap[0])
				setsignal(tp - trap, vforked);
			INTON;
		}
	}
}
コード例 #5
0
ファイル: trap.c プロジェクト: dezelin/kBuild
void
clear_traps(shinstance *psh, int vforked)
{
	char **tp;

	for (tp = psh->trap ; tp <= &psh->trap[NSIG] ; tp++) {
		if (*tp && **tp) {	/* trap not NULL or SIG_IGN */
			INTOFF;
			if (!vforked) {
				ckfree(psh, *tp);
				*tp = NULL;
			}
			if (tp != &psh->trap[0])
				setsignal(psh, (int)(tp - psh->trap), vforked);
			INTON;
		}
	}
}
コード例 #6
0
ファイル: trap.c プロジェクト: ozaki-r/netbsd-src
/*
 * Clear traps on a fork or vfork.
 * Takes one arg vfork, to tell it to not be destructive of
 * the parents variables.
 */
void
clear_traps(int vforked)
{
	char * volatile *tp;

	VTRACE(DBG_TRAP, ("clear_traps(%d)\n", vforked));
	if (!vforked)
		traps_invalid = 1;

	for (tp = &trap[1] ; tp < &trap[NSIG] ; tp++) {
		if (*tp && **tp) {	/* trap not NULL or SIG_IGN */
			INTOFF;
			setsignal(tp - trap, vforked == 1);
			INTON;
		}
	}
	if (vforked == 2)
		free_traps();
}
コード例 #7
0
ファイル: ssh.c プロジェクト: caidongyun/ssh-proxy
static void shell(ssh_session_t *session)
{
    ssh_channel_t *channel;
    struct termios terminal_local;
    int interactive=isatty(0);
    channel = ssh_channel_new(session);
    if(interactive)
    {
        tcgetattr(0,&terminal_local);
        memcpy(&terminal,&terminal_local,sizeof(struct termios));
    }
    if(ssh_channel_open_session(channel))
    {
        printf("error opening channel : %s\n",ssh_get_error(session));
        return;
    }
    chan = channel;
    if(interactive)
    {
        ssh_channel_request_pty(channel);
        sizechanged();
    }
    if(ssh_channel_request_shell(channel))
    {
        printf("Requesting shell : %s\n", ssh_get_error(session));
        return;
    }
    if(interactive)
    {
        cfmakeraw(&terminal_local);
        tcsetattr(0,TCSANOW,&terminal_local);
        setsignal();
    }
    signal(SIGTERM,do_cleanup);
    select_loop(session,channel);
    if(interactive) {
        do_cleanup(0);
    }
}
コード例 #8
0
ファイル: jobs.c プロジェクト: Stephen8554/4.4BSD-Lite
void
setjobctl(on) {
#ifdef OLD_TTY_DRIVER
	int ldisc;
#endif

	if (on == jobctl || rootshell == 0)
		return;
	if (on) {
		do { /* while we are in the background */
			if (ioctl(2, TIOCGPGRP, (char *)&initialpgrp) < 0) {
				out2str("sh: can't access tty; job control turned off\n");
				mflag = 0;
				return;
			}
			if (initialpgrp == -1)
				initialpgrp = getpgrp(0);
			else if (initialpgrp != getpgrp(0)) {
				killpg(initialpgrp, SIGTTIN);
				continue;
			}
		} while (0);
#ifdef OLD_TTY_DRIVER
		if (ioctl(2, TIOCGETD, (char *)&ldisc) < 0 || ldisc != NTTYDISC) {
			out2str("sh: need new tty driver to run job control; job control turned off\n");
			mflag = 0;
			return;
		}
#endif
		setsignal(SIGTSTP);
		setsignal(SIGTTOU);
		setsignal(SIGTTIN);
		setpgrp(0, rootpid);
		ioctl(2, TIOCSPGRP, (char *)&rootpid);
	} else { /* turning job control off */
		setpgrp(0, initialpgrp);
		ioctl(2, TIOCSPGRP, (char *)&initialpgrp);
		setsignal(SIGTSTP);
		setsignal(SIGTTOU);
		setsignal(SIGTTIN);
	}
	jobctl = on;
}
コード例 #9
0
ファイル: jobs.c プロジェクト: VargMon/netbsd-cvs-mirror
void
forkchild(struct job *jp, union node *n, int mode, int vforked)
{
	int wasroot;
	int pgrp;
	const char *devnull = _PATH_DEVNULL;
	const char *nullerr = "Can't open %s";

	wasroot = rootshell;
	TRACE(("Child shell %d\n", getpid()));
	if (!vforked)
		rootshell = 0;

	closescript(vforked);
	clear_traps(vforked);
#if JOBS
	if (!vforked)
		jobctl = 0;		/* do job control only in root shell */
	if (wasroot && mode != FORK_NOJOB && mflag) {
		if (jp == NULL || jp->nprocs == 0)
			pgrp = getpid();
		else
			pgrp = jp->ps[0].pid;
		/* This can fail because we are doing it in the parent also */
		(void)setpgid(0, pgrp);
		if (mode == FORK_FG) {
			if (tcsetpgrp(ttyfd, pgrp) == -1)
				error("Cannot set tty process group (%s) at %d",
				    strerror(errno), __LINE__);
		}
		setsignal(SIGTSTP, vforked);
		setsignal(SIGTTOU, vforked);
	} else if (mode == FORK_BG) {
		ignoresig(SIGINT, vforked);
		ignoresig(SIGQUIT, vforked);
		if ((jp == NULL || jp->nprocs == 0) &&
		    ! fd0_redirected_p ()) {
			close(0);
			if (open(devnull, O_RDONLY) != 0)
				error(nullerr, devnull);
		}
	}
#else
	if (mode == FORK_BG) {
		ignoresig(SIGINT, vforked);
		ignoresig(SIGQUIT, vforked);
		if ((jp == NULL || jp->nprocs == 0) &&
		    ! fd0_redirected_p ()) {
			close(0);
			if (open(devnull, O_RDONLY) != 0)
				error(nullerr, devnull);
		}
	}
#endif
	if (wasroot && iflag) {
		setsignal(SIGINT, vforked);
		setsignal(SIGQUIT, vforked);
		setsignal(SIGTERM, vforked);
	}

	if (!vforked)
		jobs_invalid = 1;
}
コード例 #10
0
ファイル: jobs.c プロジェクト: VargMon/netbsd-cvs-mirror
void
setjobctl(int on)
{
#ifdef OLD_TTY_DRIVER
	int ldisc;
#endif

	if (on == jobctl || rootshell == 0)
		return;
	if (on) {
#if defined(FIOCLEX) || defined(FD_CLOEXEC)
		int err;
		int i;
		if (ttyfd != -1)
			close(ttyfd);
		if ((ttyfd = open("/dev/tty", O_RDWR)) == -1) {
			for (i = 0; i < 3; i++) {
				if (isatty(i) && (ttyfd = dup(i)) != -1)
					break;
			}
			if (i == 3)
				goto out;
		}
		/* Move to a high fd */
		for (i = 10; i > 2; i--) {
			if ((err = fcntl(ttyfd, F_DUPFD, (1 << i) - 1)) != -1)
				break;
		}
		if (err != -1) {
			close(ttyfd);
			ttyfd = err;
		}
#ifdef FIOCLEX
		err = ioctl(ttyfd, FIOCLEX, 0);
#elif FD_CLOEXEC
		err = fcntl(ttyfd, F_SETFD,
		    fcntl(ttyfd, F_GETFD, 0) | FD_CLOEXEC);
#endif
		if (err == -1) {
			close(ttyfd);
			ttyfd = -1;
			goto out;
		}
#else
		out2str("sh: Need FIOCLEX or FD_CLOEXEC to support job control");
		goto out;
#endif
		do { /* while we are in the background */
			if ((initialpgrp = tcgetpgrp(ttyfd)) < 0) {
out:
				out2str("sh: can't access tty; job control turned off\n");
				mflag = 0;
				return;
			}
			if (initialpgrp == -1)
				initialpgrp = getpgrp();
			else if (initialpgrp != getpgrp()) {
				killpg(0, SIGTTIN);
				continue;
			}
		} while (0);

#ifdef OLD_TTY_DRIVER
		if (ioctl(ttyfd, TIOCGETD, (char *)&ldisc) < 0
		    || ldisc != NTTYDISC) {
			out2str("sh: need new tty driver to run job control; job control turned off\n");
			mflag = 0;
			return;
		}
#endif
		setsignal(SIGTSTP, 0);
		setsignal(SIGTTOU, 0);
		setsignal(SIGTTIN, 0);
		if (getpgrp() != rootpid && setpgid(0, rootpid) == -1)
			error("Cannot set process group (%s) at %d",
			    strerror(errno), __LINE__);
		if (tcsetpgrp(ttyfd, rootpid) == -1)
			error("Cannot set tty process group (%s) at %d",
			    strerror(errno), __LINE__);
	} else { /* turning job control off */
		if (getpgrp() != initialpgrp && setpgid(0, initialpgrp) == -1)
			error("Cannot set process group (%s) at %d",
			    strerror(errno), __LINE__);
		if (tcsetpgrp(ttyfd, initialpgrp) == -1)
			error("Cannot set tty process group (%s) at %d",
			    strerror(errno), __LINE__);
		close(ttyfd);
		ttyfd = -1;
		setsignal(SIGTSTP, 0);
		setsignal(SIGTTOU, 0);
		setsignal(SIGTTIN, 0);
	}
	jobctl = on;
}
コード例 #11
0
ファイル: relay.c プロジェクト: csmuc/iProxy
int serv_loop()
{
  int    cs, ss = 0;
  struct sockaddr_storage cl;
  fd_set readable;
  int    i, n, len;
  char   cl_addr[NI_MAXHOST];
  char   cl_name[NI_MAXHOST];
  int    error;
  pid_t  pid;

#ifdef USE_THREAD
  if (threading) {
    blocksignal(SIGHUP);
    blocksignal(SIGINT);
    blocksignal(SIGUSR1);
  }
#endif

  for (;;) {
    readable = allsock;

    MUTEX_LOCK(mutex_select);
    n = select(maxsock+1, &readable, 0, 0, 0);
    if (n <= 0) {
      if (n < 0 && errno != EINTR) {
        msg_out(warn, "select: %m");
      }
      MUTEX_UNLOCK(mutex_select);
      continue;
    }

#ifdef USE_THREAD
    if ( ! threading ) {
#endif
      /* handle any queued signal flags */
      if (FD_ISSET(sig_queue[0], &readable)) {
        if (ioctl(sig_queue[0], FIONREAD, &i) != 0) {
          msg_out(crit, "ioctl: %m");
          exit(-1);
        }
        while (--i >= 0) {
          char c;
          if (read(sig_queue[0], &c, 1) != 1) {
            msg_out(crit, "read: %m");
            exit(-1);
          }
          switch(c) {
          case 'H': /* sighup */
            reload();
            break;
          case 'C': /* sigchld */
            reapchild();
            break;
          case 'T': /* sigterm */
            cleanup();
            break;
          default:
            break;
          }
        }
      }
#ifdef USE_THREAD
    }
#endif

    for ( i = 0; i < serv_sock_ind; i++ ) {
      if (FD_ISSET(serv_sock[i], &readable)) {
	n--;
	break;
      }
    }
    if ( n < 0 || i >= serv_sock_ind ) {
      MUTEX_UNLOCK(mutex_select);
      continue;
    }

    len = sizeof(struct sockaddr_storage);
    cs = accept(serv_sock[i], (struct sockaddr *)&cl, (socklen_t *)&len);
    if (cs < 0) {
      if (errno == EINTR
#ifdef SOLARIS
	  || errno == EPROTO
#endif
	  || errno == EWOULDBLOCK
	  || errno == ECONNABORTED) {
	; /* ignore */
      } else {
	/* real accept error */
	msg_out(warn, "accept: %m");
      }
      MUTEX_UNLOCK(mutex_select);
      continue;
    }
    MUTEX_UNLOCK(mutex_select);

#ifdef USE_THREAD
    if ( !threading ) {
#endif
      if (max_child > 0 && cur_child >= max_child) {
	msg_out(warn, "child: cur %d; exeedeing max(%d)",
		          cur_child, max_child);
	close(cs);
	continue;
      }
#ifdef USE_THREAD
    }
#endif

    error = getnameinfo((struct sockaddr *)&cl, len,
			cl_addr, sizeof(cl_addr),
			NULL, 0,
			NI_NUMERICHOST);
    if (resolv_client) {
      error = getnameinfo((struct sockaddr *)&cl, len,
			  cl_name, sizeof(cl_name),
			  NULL, 0, 0);
      msg_out(norm, "%s[%s] connected", cl_name, cl_addr);
    } else {
      msg_out(norm, "%s connected", cl_addr);
      strncpy(cl_name, cl_addr, sizeof(cl_name));
    }

    i = validate_access(cl_addr, cl_name);
    if (i < 1) {
      /* access denied */
      close(cs);
      continue;
    }

    set_blocking(cs);

#ifdef USE_THREAD
    if (!threading ) {
#endif
      blocksignal(SIGHUP);
      blocksignal(SIGCHLD);
      pid = fork();
      switch (pid) {
        case -1:  /* fork child failed */
            printf("\nfork failed\n");
            break;
        case 0:   /* i am child */
            for ( i = 0; i < serv_sock_ind; i++ ) {
              close(serv_sock[i]);
            }
            setsignal(SIGCHLD, SIG_DFL);
                setsignal(SIGHUP, SIG_DFL);
                releasesignal(SIGCHLD);
                releasesignal(SIGHUP);
            ss = proto_socks(cs);
            if ( ss == -1 ) {
              close(cs);  /* may already be closed */
              exit(1);
            }
            printf("\nrelaying\n");
            relay(cs, ss);
            exit(0);
      default: /* may be parent */
            printf("\nadding proc\n");
            proclist_add(pid);
            break;
      }
      close(cs);
      releasesignal(SIGHUP);
      releasesignal(SIGCHLD);
#ifdef USE_THREAD
    } else {
      ss = proto_socks(cs);
      if ( ss == -1 ) {
        close(cs);  /* may already be closed */
        continue;
      }
      relay(cs, ss);
    }
#endif
  }
}
コード例 #12
0
ファイル: arpwatch.c プロジェクト: einyx/arpwatch
int
main(int argc, char **argv)
{
	register char *cp;
	register int op, pid, snaplen, timeout, linktype, status;
#ifdef TIOCNOTTY
	register int fd;
#endif
	register pcap_t *pd;
	register char *interface, *rfilename;
	struct bpf_program code;
	char errbuf[PCAP_ERRBUF_SIZE];

	if (argv[0] == NULL)
		prog = "arpwatch";
	else if ((cp = strrchr(argv[0], '/')) != NULL)
		prog = cp + 1;
	else
		prog = argv[0];

	if (abort_on_misalignment(errbuf) < 0) {
		(void)fprintf(stderr, "%s: %s\n", prog, errbuf);
		exit(1);
	}

	opterr = 0;
	interface = NULL;
	rfilename = NULL;
	pd = NULL;
	while ((op = getopt(argc, argv, "df:i:n:Nr:")) != EOF)
		switch (op) {

		case 'd':
			++debug;
#ifndef DEBUG
			(void)fprintf(stderr,
			    "%s: Warning: Not compiled with -DDEBUG\n", prog);
#endif
			break;

		case 'f':
			arpfile = optarg;
			break;

		case 'i':
			interface = optarg;
			break;

		case 'n':
			if (!addnet(optarg))
				usage();
			break;

		case 'N':
			++nobogons;
			break;

		case 'r':
			rfilename = optarg;
			break;

		default:
			usage();
		}

	if (optind != argc)
		usage();

	if (rfilename != NULL) {
		net = 0;
		netmask = 0;
	} else {
		/* Determine interface if not specified */
		if (interface == NULL &&
		    (interface = pcap_lookupdev(errbuf)) == NULL) {
			(void)fprintf(stderr, "%s: lookup_device: %s\n",
			    prog, errbuf);
			exit(1);
		}

		/* Determine network and netmask */
		if (pcap_lookupnet(interface, &net, &netmask, errbuf) < 0) {
			(void)fprintf(stderr, "%s: bad interface %s: %s\n",
			    prog, interface, errbuf);
			exit(1);
		}

		/* Drop into the background if not debugging */
		if (!debug) {
			pid = fork();
			if (pid < 0) {
				syslog(LOG_ERR, "main fork(): %m");
				exit(1);
			} else if (pid != 0)
				exit(0);
			(void)close(fileno(stdin));
			(void)close(fileno(stdout));
			(void)close(fileno(stderr));
#ifdef TIOCNOTTY
			fd = open("/dev/tty", O_RDWR);
			if (fd >= 0) {
				(void)ioctl(fd, TIOCNOTTY, 0);
				(void)close(fd);
			}
#else
			(void) setsid();
#endif
		}
	}

	openlog(prog, 0, LOG_DAEMON);

	if (chdir(arpdir) < 0) {
		syslog(LOG_ERR, "chdir(%s): %m", arpdir);
		syslog(LOG_ERR, "(using current working directory)");
	}

	if (rfilename != NULL) {
		pd = pcap_open_offline(rfilename, errbuf);
		if (pd == NULL) {
			syslog(LOG_ERR, "pcap open %s: %s", rfilename,  errbuf);
			exit(1);
		}
		swapped = pcap_is_swapped(pd);
	} else {
		snaplen = max(sizeof(struct ether_header),
		    sizeof(struct fddi_header)) + sizeof(struct ether_arp);
		timeout = 1000;
		pd = pcap_open_live(interface, snaplen, 1, timeout, errbuf);
		if (pd == NULL) {
			syslog(LOG_ERR, "pcap open %s: %s", interface, errbuf);
			exit(1);
		}
#ifdef WORDS_BIGENDIAN
		swapped = 1;
#endif
	}

	/*
	 * Revert to non-privileged user after opening sockets
	 * (not needed on most systems).
	 */
	setgid(getgid());
	setuid(getuid());

	/* Must be ethernet or fddi */
	linktype = pcap_datalink(pd);
	if (linktype != DLT_EN10MB && linktype != DLT_FDDI) {
		syslog(LOG_ERR, "Link layer type %d not ethernet or fddi",
		    linktype);
		exit(1);
	}

	/* Compile and install filter */
	if (pcap_compile(pd, &code, "arp or rarp", 1, netmask) < 0) {
		syslog(LOG_ERR, "pcap_compile: %s", pcap_geterr(pd));
		exit(1);
	}
	if (pcap_setfilter(pd, &code) < 0) {
		syslog(LOG_ERR, "pcap_setfilter: %s", pcap_geterr(pd));
		exit(1);
	}
	if (rfilename == NULL)
		syslog(LOG_INFO, "listening on %s", interface);

	/* Read in database */
	initializing = 1;
	if (!readdata())
		exit(1);
	sorteinfo();
#ifdef DEBUG
	if (debug > 2) {
		debugdump();
		exit(0);
	}
#endif
	initializing = 0;

	(void)setsignal(SIGINT, die);
	(void)setsignal(SIGTERM, die);
	(void)setsignal(SIGHUP, die);
	if (rfilename == NULL) {
		(void)setsignal(SIGQUIT, checkpoint);
		(void)setsignal(SIGALRM, checkpoint);
		(void)alarm(CHECKPOINT);
	}

	switch (linktype) {

	case DLT_EN10MB:
		status = pcap_loop(pd, 0, process_ether, NULL);
		break;

	case DLT_FDDI:
		status = pcap_loop(pd, 0, process_fddi, NULL);
		break;

	default:
		syslog(LOG_ERR, "bad linktype %d (can't happen)", linktype);
		exit(1);
	}
	if (status < 0) {
		syslog(LOG_ERR, "pcap_loop: %s", pcap_geterr(pd));
		exit(1);
	}
	pcap_close(pd);
	if (!dump())
		exit(1);
	exit(0);
}
コード例 #13
0
ファイル: multithread.c プロジェクト: caidongyun/backup
int main(int argc, char **argv)
{
    memset(&global_info, 0, sizeof(global_info_t));
    char *url = http_url;
    global_info.round = 1;

    int opt;
    while ((opt = getopt(argc, argv, "w:t:r:hs")) != -1) {
        switch (opt) {
            case 'w':
                global_info.work_num = atoi(optarg);
                break;

            case 't':
                global_info.thread_num = atoi(optarg);
                break;

            case 'r':
                global_info.round = atoi(optarg);
                break;

            case 's':
                url = https_url;
                break;

            case 'h':
            default:
                show_help();
                return EXIT_SUCCESS;
        }
    }

    if (global_info.work_num == 0 || global_info.thread_num == 0) {
        show_help();
        return EXIT_FAILURE;
    }

    setsignal(SIGINT, _sig_int);
    setsignal(SIGTERM, _sig_int);
    printf("get work num: %u, thread num: %u\n", global_info.work_num, global_info.thread_num);
    thread_info_t *thread_list = calloc(global_info.thread_num, sizeof(thread_info_t));

    if (thread_list == NULL) {
        printf("alloc threads error\n");
        return EXIT_FAILURE;
    }

    global_info.work_list = calloc(global_info.work_num, sizeof(work_info_t *));

    if (global_info.work_list == NULL) {
        printf("alloc work_list error\n");
        return EXIT_FAILURE;
    }

    int idx = 0;

    for (idx = 0; idx < global_info.work_num; ++idx) {
        global_info.work_list[idx] = calloc(1, sizeof(work_info_t));

        if (global_info.work_list[idx] == NULL) {
            printf("alloc work_list %u error\n", idx);
            return EXIT_FAILURE;
        }

        global_info.work_list[idx]->url = url;
        global_info.work_list[idx]->idx = idx;
    }

    /* Must initialize libcurl before any threads are started */
    curl_global_init(CURL_GLOBAL_ALL);
    init_locks();
    TS_INIT();
    mutexlock_init(global_info.rmtx);
    mutexlock_init(global_info.wmtx);
    TS_DECLARE(perf);

    for (idx = 0; idx < global_info.thread_num; ++idx) {
        thread_list[idx].global_info = &global_info;
        thread_list[idx].curl = curl_easy_init();
        thread_list[idx].multi_handle = curl_multi_init();

        if (thread_list[idx].curl == NULL || thread_list[idx].multi_handle == NULL) {
            printf("error when curl init\n");
            return EXIT_FAILURE;
        }

        //curl_easy_setopt(thread_list[idx].curl, CURLOPT_FORBID_REUSE, 1L);
        curl_easy_setopt(thread_list[idx].curl, CURLOPT_NOSIGNAL, 1L);

        if (url == https_url) {
            curl_easy_setopt(thread_list[idx].curl, CURLOPT_SSL_VERIFYPEER, 0L);
            curl_easy_setopt(thread_list[idx].curl, CURLOPT_SSL_VERIFYHOST, 0L);
        }

        thread_list[idx].idx = idx;
        set_share_handle(thread_list[idx].curl);
    }

    int error;
    TS_BEGIN(perf);

    for (idx = 0; idx < global_info.thread_num; ++idx) {
        error = pthread_create(&(thread_list[idx].tid),
                               NULL, /* default attributes please */
                               pull_one_url,
                               (void *) & (thread_list[idx]));

        if (0 != error) {
            fprintf(stderr, "Couldn't run thread number %d, errno %d\n", idx, error);
            return EXIT_FAILURE;
        }
    }

    /* now wait for all threads to terminate */
    for (idx = 0; idx < global_info.thread_num; idx++) {
        error = pthread_join(thread_list[idx].tid, NULL);
        //printf("[%u:%lu]Thread %d terminated\n", idx, time(NULL), idx);
    }

    TS_END(perf);

    for (idx = 0; idx < global_info.thread_num; idx++) {
        curl_easy_cleanup(thread_list[idx].curl);
        curl_multi_cleanup(thread_list[idx].multi_handle);
    }

    free(thread_list);
    unsigned long total_length = 0;

    for (idx = 0; idx < global_info.work_num; idx++) {
        if (global_info.work_list[idx]) {
            if (global_info.work_list[idx]->status == STAT_DONE) {
                total_length += global_info.work_list[idx]->data_len;
            }

            free(global_info.work_list[idx]);
        }
    }

    free(global_info.work_list);
    printf("RATE: worknum:%u total_length:%lu total_ms_diff:%lu, %.1fK\n",
           global_info.work_num, total_length, TS_MSDIFF(perf), (double)(total_length) / (double)(TS_MSDIFF(perf)));
    kill_locks();
    curl_global_cleanup();
    return EXIT_SUCCESS;
}
コード例 #14
0
void* ThreadFunction2(void* port)
{
  int secondcounter = 0;
  int outtransition = 0;
  int state = (int)(HASH("de.cau.cs.kieler.simplerailctrl.impl.SetPointImpl@7c26a0ba (initial: true) (point: [POINT_19, POINT_20, POINT_23, POINT_24], direction: BRANCH)"));
  
  if (DEBUGCONTROLLER) printf("Thread 'org.eclipse.internal.xpand2.type.XpandIterator@432dbb4b' started.\n");
  
  while(1) {
      if (DEBUGCONTROLLER) printf("Entering state %d.\n",state);
      
      //escape if railway system is down
      if (!railway_alive(railway)) {
	  	  if (DEBUGCONTROLLER) printf("Railway system down - terminating thread.\n");
     	  exit(EXIT_FAILURE);
	  }//end if
	  
      //all states
      if (state == -1) {}
	  else if (state == ((int)(HASH("de.cau.cs.kieler.simplerailctrl.impl.SetSpeedImpl@73b61aea (initial: false) (track: [IC_JCT_0, IC_LN_0, IC_LN_1, IC_LN_2, IC_LN_3, IC_LN_4, IC_LN_5, IC_ST_0, IC_ST_2, IC_ST_4], speed: 100, direction: FWD)")))) {
	  		  P(2); // GET THE GLOBALLOCK
              if (DEBUGCONTROLLER) printf("State %d (de.cau.cs.kieler.simplerailctrl.impl.SetSpeedImpl@73b61aea (initial: false) (track: [IC_JCT_0, IC_LN_0, IC_LN_1, IC_LN_2, IC_LN_3, IC_LN_4, IC_LN_5, IC_ST_0, IC_ST_2, IC_ST_4], speed: 100, direction: FWD)) entered.\n",(int)(HASH("de.cau.cs.kieler.simplerailctrl.impl.SetSpeedImpl@73b61aea (initial: false) (track: [IC_JCT_0, IC_LN_0, IC_LN_1, IC_LN_2, IC_LN_3, IC_LN_4, IC_LN_5, IC_ST_0, IC_ST_2, IC_ST_4], speed: 100, direction: FWD)")));
	          //state1 entry code (SET SPEED)
			  settrack(railway, IC_JCT_0, FWD, 100);
		      setsignal(railway, IC_JCT_0, FIRST, OFF);
		      setsignal(railway, IC_JCT_0, SECOND, GREEN);
			  settrack(railway, IC_LN_0, FWD, 100);
		      setsignal(railway, IC_LN_0, FIRST, OFF);
		      setsignal(railway, IC_LN_0, SECOND, GREEN);
			  settrack(railway, IC_LN_1, FWD, 100);
		      setsignal(railway, IC_LN_1, FIRST, OFF);
		      setsignal(railway, IC_LN_1, SECOND, GREEN);
			  settrack(railway, IC_LN_2, FWD, 100);
		      setsignal(railway, IC_LN_2, FIRST, OFF);
		      setsignal(railway, IC_LN_2, SECOND, GREEN);
			  settrack(railway, IC_LN_3, FWD, 100);
		      setsignal(railway, IC_LN_3, FIRST, OFF);
		      setsignal(railway, IC_LN_3, SECOND, GREEN);
			  settrack(railway, IC_LN_4, FWD, 100);
		      setsignal(railway, IC_LN_4, FIRST, OFF);
		      setsignal(railway, IC_LN_4, SECOND, GREEN);
			  settrack(railway, IC_LN_5, FWD, 100);
		      setsignal(railway, IC_LN_5, FIRST, OFF);
		      setsignal(railway, IC_LN_5, SECOND, GREEN);
			  settrack(railway, IC_ST_0, FWD, 100);
		      setsignal(railway, IC_ST_0, FIRST, OFF);
		      setsignal(railway, IC_ST_0, SECOND, GREEN);
			  settrack(railway, IC_ST_2, FWD, 100);
		      setsignal(railway, IC_ST_2, FIRST, OFF);
		      setsignal(railway, IC_ST_2, SECOND, GREEN);
			  settrack(railway, IC_ST_4, FWD, 100);
		      setsignal(railway, IC_ST_4, FIRST, OFF);
		      setsignal(railway, IC_ST_4, SECOND, GREEN);
	  		  V(2); // RELEASE THE GLOBALLOCK
	  		  
	          
	          //state1 transitions code
	          secondcounter = 0;
	          while(1) {
		   		    P(2); // GET THE GLOBALLOCK
	                outtransition = 0;
		            if ((DEBUGCONTROLLER)&&(!(secondcounter%10))) printf("Transition wait (%d seconds).\n",secondcounter/10);
			  		outtransition = 1;
	          		//test for contact-events
			  		if ((getcontact_sync(railway,IC_ST_2,FIRST,1) != 0)) {
			  		    V(2); // RELEASE THE GLOBALLOCK
	 	                if (DEBUGCONTROLLER) printf("Event-Transition taken.\n");
			  			state = HASH("de.cau.cs.kieler.simplerailctrl.impl.SetSpeedImpl@2af590c6 (initial: false) (track: [IC_ST_0, IC_ST_2], speed: 30, direction: FWD)");
			  			break;
			  		}
	  		  		V(2); // RELEASE THE GLOBALLOCK
			  			          		
	                //escape if railway system is down
                    if (!railway_alive(railway)) {
	 	                if (DEBUGCONTROLLER) printf("Railway system down - terminating thread.\n");
				    	exit(EXIT_FAILURE);
                    }//end if
                    	          
                    //escape if not outtransitions
                    if (!outtransition) {
	 	                if (DEBUGCONTROLLER) printf("Final state - terminating thread.\n");
						//set localTERMINATED := 1 (so that we not wait on this thread in any next macro-tick any more)
		          		localTERMINATED2 = 1;   
						return (void *)1;
                    }//end if
                    	          
	          		secondcounter++;
				usleep(100000); // sleep for 100ms
					
					//set localLOCK := 1 and wait for its reset
	          		localLOCK2 = 1;   
	          		while (localLOCK2 == 1){
		                    if (!railway_alive(railway)) {
	 			                if (DEBUGCONTROLLER) printf("Railway system down - terminating thread.\n");
						    	exit(EXIT_FAILURE);
                    		}//end if
							usleep(5000); // sleep for 5ms
							//if (DEBUGCONTROLLER) printf("Thread 2 waiting for next tick.\n");
	          		}//end while
	          		
	          }//end while
	      }//end if
	      
	  else if (state == ((int)(HASH("de.cau.cs.kieler.simplerailctrl.impl.SetPointImpl@7c26a0ba (initial: true) (point: [POINT_19, POINT_20, POINT_23, POINT_24], direction: BRANCH)")))) {
	  		  P(2); // GET THE GLOBALLOCK
              if (DEBUGCONTROLLER) printf("State %d (de.cau.cs.kieler.simplerailctrl.impl.SetPointImpl@7c26a0ba (initial: true) (point: [POINT_19, POINT_20, POINT_23, POINT_24], direction: BRANCH)) entered.\n",(int)(HASH("de.cau.cs.kieler.simplerailctrl.impl.SetPointImpl@7c26a0ba (initial: true) (point: [POINT_19, POINT_20, POINT_23, POINT_24], direction: BRANCH)")));
	          //state2 enty code (SET POINT)
			  setpoint(railway,  POINT_19, BRANCH);
			  setpoint(railway,  POINT_20, BRANCH);
			  setpoint(railway,  POINT_23, BRANCH);
			  setpoint(railway,  POINT_24, BRANCH);
	  		  V(2); // RELEASE THE GLOBALLOCK
	  		  
	          
	          //state2 transitions code
	          secondcounter = 0;
	          while(1) {
		   		    P(2); // GET THE GLOBALLOCK
	                outtransition = 0;
		            if ((DEBUGCONTROLLER)&&(!(secondcounter%10))) printf("Transition wait (%d seconds).\n",secondcounter/10);
			  		outtransition = 1;
	          		//test for wait-events
			  		if (secondcounter/10 >= 5) {
			  		    V(2); // RELEASE THE GLOBALLOCK
	 	                if (DEBUGCONTROLLER) printf("Wait-Transition taken.\n");
			  			state = HASH("de.cau.cs.kieler.simplerailctrl.impl.SetSpeedImpl@73b61aea (initial: false) (track: [IC_JCT_0, IC_LN_0, IC_LN_1, IC_LN_2, IC_LN_3, IC_LN_4, IC_LN_5, IC_ST_0, IC_ST_2, IC_ST_4], speed: 100, direction: FWD)");
			  			break;
			  		}
			  		
	  		  		V(2); // RELEASE THE GLOBALLOCK
			  			          		
	                //escape if railway system is down
                    if (!railway_alive(railway)) {
	 	                if (DEBUGCONTROLLER) printf("Railway system down - terminating thread.\n");
				    	exit(EXIT_FAILURE);
                    }//end if
                    	          
                    //escape if not outtransitions
                    if (!outtransition) {
	 	                if (DEBUGCONTROLLER) printf("Final state - terminating thread.\n");
						//set localTERMINATED := 1 (so that we not wait on this thread in any next macro-tick any more)
		          		localTERMINATED2 = 1;   
						return (void *)1;
                    }//end if
                    	          
	          		secondcounter++;
				usleep(100000); // sleep for 100ms
					
					//set localLOCK := 1 and wait for its reset
	          		localLOCK2 = 1;   
	          		while (localLOCK2 == 1){
		                    if (!railway_alive(railway)) {
	 			                if (DEBUGCONTROLLER) printf("Railway system down - terminating thread.\n");
						    	exit(EXIT_FAILURE);
                    		}//end if
							usleep(5000); // sleep for 5ms
							//if (DEBUGCONTROLLER) printf("Thread 2 waiting for next tick.\n");
	          		}//end while
	          		
	          }//end while
	      }//end if
	      
	  else if (state == ((int)(HASH("de.cau.cs.kieler.simplerailctrl.impl.SetSpeedImpl@2af590c6 (initial: false) (track: [IC_ST_0, IC_ST_2], speed: 30, direction: FWD)")))) {
	  		  P(2); // GET THE GLOBALLOCK
              if (DEBUGCONTROLLER) printf("State %d (de.cau.cs.kieler.simplerailctrl.impl.SetSpeedImpl@2af590c6 (initial: false) (track: [IC_ST_0, IC_ST_2], speed: 30, direction: FWD)) entered.\n",(int)(HASH("de.cau.cs.kieler.simplerailctrl.impl.SetSpeedImpl@2af590c6 (initial: false) (track: [IC_ST_0, IC_ST_2], speed: 30, direction: FWD)")));
	          //state3 entry code (SET SPEED)
			  settrack(railway, IC_ST_0, FWD, 30);
		      setsignal(railway, IC_ST_0, FIRST, OFF);
		      setsignal(railway, IC_ST_0, SECOND, YELLOW);
			  settrack(railway, IC_ST_2, FWD, 30);
		      setsignal(railway, IC_ST_2, FIRST, OFF);
		      setsignal(railway, IC_ST_2, SECOND, YELLOW);
	  		  V(2); // RELEASE THE GLOBALLOCK
	  		  
	          
	          //state3 transitions code
	          secondcounter = 0;
	          while(1) {
		   		    P(2); // GET THE GLOBALLOCK
	                outtransition = 0;
		            if ((DEBUGCONTROLLER)&&(!(secondcounter%10))) printf("Transition wait (%d seconds).\n",secondcounter/10);
			  		outtransition = 1;
	          		//test for contact-events
			  		if ((getcontact_sync(railway,IC_ST_2,SECOND,1) != 0)) {
			  		    V(2); // RELEASE THE GLOBALLOCK
	 	                if (DEBUGCONTROLLER) printf("Event-Transition taken.\n");
			  			state = HASH("de.cau.cs.kieler.simplerailctrl.impl.SetSpeedImpl@5ff3cd32 (initial: false) (track: [IC_ST_2], speed: 0, direction: FWD)");
			  			break;
			  		}
	  		  		V(2); // RELEASE THE GLOBALLOCK
			  			          		
	                //escape if railway system is down
                    if (!railway_alive(railway)) {
	 	                if (DEBUGCONTROLLER) printf("Railway system down - terminating thread.\n");
				    	exit(EXIT_FAILURE);
                    }//end if
                    	          
                    //escape if not outtransitions
                    if (!outtransition) {
	 	                if (DEBUGCONTROLLER) printf("Final state - terminating thread.\n");
						//set localTERMINATED := 1 (so that we not wait on this thread in any next macro-tick any more)
		          		localTERMINATED2 = 1;   
						return (void *)1;
                    }//end if
                    	          
	          		secondcounter++;
				usleep(100000); // sleep for 100ms
					
					//set localLOCK := 1 and wait for its reset
	          		localLOCK2 = 1;   
	          		while (localLOCK2 == 1){
		                    if (!railway_alive(railway)) {
	 			                if (DEBUGCONTROLLER) printf("Railway system down - terminating thread.\n");
						    	exit(EXIT_FAILURE);
                    		}//end if
							usleep(5000); // sleep for 5ms
							//if (DEBUGCONTROLLER) printf("Thread 2 waiting for next tick.\n");
	          		}//end while
	          		
	          }//end while
	      }//end if
	      
	  else if (state == ((int)(HASH("de.cau.cs.kieler.simplerailctrl.impl.SetSpeedImpl@5ff3cd32 (initial: false) (track: [IC_ST_2], speed: 0, direction: FWD)")))) {
	  		  P(2); // GET THE GLOBALLOCK
              if (DEBUGCONTROLLER) printf("State %d (de.cau.cs.kieler.simplerailctrl.impl.SetSpeedImpl@5ff3cd32 (initial: false) (track: [IC_ST_2], speed: 0, direction: FWD)) entered.\n",(int)(HASH("de.cau.cs.kieler.simplerailctrl.impl.SetSpeedImpl@5ff3cd32 (initial: false) (track: [IC_ST_2], speed: 0, direction: FWD)")));
	          //state4 entry code (SET SPEED)
			  settrack(railway, IC_ST_2, FWD, 0);
		      setsignal(railway, IC_ST_2, FIRST, OFF);
		      setsignal(railway, IC_ST_2, SECOND, RED);
	  		  V(2); // RELEASE THE GLOBALLOCK
	  		  
	          
	          //state4 transitions code
	          secondcounter = 0;
	          while(1) {
		   		    P(2); // GET THE GLOBALLOCK
	                outtransition = 0;
		            if ((DEBUGCONTROLLER)&&(!(secondcounter%10))) printf("Transition wait (%d seconds).\n",secondcounter/10);
			  		outtransition = 1;
	          		//test for wait-events
			  		if (secondcounter/10 >= 10) {
			  		    V(2); // RELEASE THE GLOBALLOCK
	 	                if (DEBUGCONTROLLER) printf("Wait-Transition taken.\n");
			  			state = HASH("de.cau.cs.kieler.simplerailctrl.impl.SetSpeedImpl@73b61aea (initial: false) (track: [IC_JCT_0, IC_LN_0, IC_LN_1, IC_LN_2, IC_LN_3, IC_LN_4, IC_LN_5, IC_ST_0, IC_ST_2, IC_ST_4], speed: 100, direction: FWD)");
			  			break;
			  		}
			  		
	  		  		V(2); // RELEASE THE GLOBALLOCK
			  			          		
	                //escape if railway system is down
                    if (!railway_alive(railway)) {
	 	                if (DEBUGCONTROLLER) printf("Railway system down - terminating thread.\n");
				    	exit(EXIT_FAILURE);
                    }//end if
                    	          
                    //escape if not outtransitions
                    if (!outtransition) {
	 	                if (DEBUGCONTROLLER) printf("Final state - terminating thread.\n");
						//set localTERMINATED := 1 (so that we not wait on this thread in any next macro-tick any more)
		          		localTERMINATED2 = 1;   
						return (void *)1;
                    }//end if
                    	          
	          		secondcounter++;
				usleep(100000); // sleep for 100ms
					
					//set localLOCK := 1 and wait for its reset
	          		localLOCK2 = 1;   
	          		while (localLOCK2 == 1){
		                    if (!railway_alive(railway)) {
	 			                if (DEBUGCONTROLLER) printf("Railway system down - terminating thread.\n");
						    	exit(EXIT_FAILURE);
                    		}//end if
							usleep(5000); // sleep for 5ms
							//if (DEBUGCONTROLLER) printf("Thread 2 waiting for next tick.\n");
	          		}//end while
	          		
	          }//end while
	      }//end if
	      
  }//end while
}	
コード例 #15
0
/* this is code I used to see if I was getting signaled at one point, and it might be useful*/
int GettingSignaled(void)
{
  char localhost[256]; 
  struct hostent *hep = NULL;
  int i=0;
  /* see if we're getting signaled, damnit!*/
  setsignal(SIGINT, handler);
  /*setsignal(SIGKILL, handler);*/
  /*setsignal(SIGSTOP, handler);*/
  setsignal(SIGTERM, handler);
  setsignal(SIGABRT, handler);

#ifndef WIN32
  setsignal(SIGCHLD, handler);
  setsignal(SIGHUP, SIG_IGN);
  setsignal(SIGPIPE, handler);
  setsignal(SIGQUIT, handler);
  setsignal(SIGTTIN, handler);
#endif

  gethostname(localhost, 256);
  hep = gethostbyname(localhost);
  printf("test host is %s\n", hep->h_name);
  fflush(stdout);

  /*  switch (fork())
      {
      case -1: error
      {
      printf("failed to fork\n");
      }
      case 0: child
      {
  */
  fprintf(stdout, "Child stdout.\n");
  fprintf(stderr, "Child stderr new.\n");    
  /*fclose(stdout);*/
  /*fclose(stderr);*/
  i=30;
  while (i--){
#ifndef WIN32
    int err = usleep (999999);
    if (err) {
      fprintf(stderr, "child sleep err %d\n", err);
      return -1; //TODO: this was exiting with zero changed to -1
    }
#else
    Sleep(999);
#endif
    printf("Child sleeping... (%d) \n", i);
    fflush(stdout);
  }
  /*
    }
    default:
    {
    fprintf(stdout, "parent stdout.");
    fprintf(stderr, "parent stderr x.");
    fclose(stdout);/
    fclose(stderr);/
    return 0;
    }
    }
  */
  return 0;
}
コード例 #16
0
ファイル: jobs.c プロジェクト: KhuramAli/freebsd
void
setjobctl(int on)
{
	int i;

	if (on == jobctl || rootshell == 0)
		return;
	if (on) {
		if (ttyfd != -1)
			close(ttyfd);
		if ((ttyfd = open(_PATH_TTY, O_RDWR | O_CLOEXEC)) < 0) {
			i = 0;
			while (i <= 2 && !isatty(i))
				i++;
			if (i > 2 ||
			    (ttyfd = fcntl(i, F_DUPFD_CLOEXEC, 10)) < 0) {
				jobctl_notty();
				return;
			}
		}
		if (ttyfd < 10) {
			/*
			 * Keep our TTY file descriptor out of the way of
			 * the user's redirections.
			 */
			if ((i = fcntl(ttyfd, F_DUPFD_CLOEXEC, 10)) < 0) {
				jobctl_notty();
				return;
			}
			close(ttyfd);
			ttyfd = i;
		}
		do { /* while we are in the background */
			initialpgrp = tcgetpgrp(ttyfd);
			if (initialpgrp < 0) {
				jobctl_notty();
				return;
			}
			if (initialpgrp != getpgrp()) {
				if (!iflag) {
					initialpgrp = -1;
					jobctl_notty();
					return;
				}
				kill(0, SIGTTIN);
				continue;
			}
		} while (0);
		setsignal(SIGTSTP);
		setsignal(SIGTTOU);
		setsignal(SIGTTIN);
		setpgid(0, rootpid);
		tcsetpgrp(ttyfd, rootpid);
	} else { /* turning job control off */
		setpgid(0, initialpgrp);
		if (ttyfd >= 0) {
			tcsetpgrp(ttyfd, initialpgrp);
			close(ttyfd);
			ttyfd = -1;
		}
		setsignal(SIGTSTP);
		setsignal(SIGTTOU);
		setsignal(SIGTTIN);
	}
	jobctl = on;
}
コード例 #17
0
ファイル: main.c プロジェクト: CRDevOps/srelay
int main(int ac, char **av)
{
  int     ch, i=0;
  pid_t   pid;
  FILE    *fp;
  uid_t   uid;
#ifdef USE_THREAD
  pthread_t tid;
  pthread_attr_t attr;
  struct rlimit rl;
  rlim_t max_fd = (rlim_t)MAX_FD;
  rlim_t save_fd = 0;
#endif

#ifdef USE_THREAD
  threading = 1;
  max_thread = MAX_THREAD;
#endif

  max_child = MAX_CHILD;
  cur_child = 0;

  /* create service socket table (malloc) */
  if (serv_init(NULL) < 0) {
    msg_out(crit, "cannot malloc: %m\n");
    exit(-1);
  }

  proxy_tbl = NULL;
  proxy_tbl_ind = 0;

  method_num = 0;

  uid = getuid();

  openlog(ident, LOG_PID | LOG_NDELAY, SYSLOGFAC);

  while((ch = getopt(ac, av, "a:c:i:J:m:o:p:u:frstbwgIqvh?")) != -1)
    switch (ch) {
    case 'a':
      if (optarg != NULL) {
	for (i=0; i<sizeof method_tab; optarg++) {
	  if (*optarg == '\0')
	    break;
	  switch (*optarg) {
	  case 'p':
	    if ( uid != 0 ) {
	      /* process does not started by root */
	      msg_out(warn, "uid == %d (!=0),"
		      "user/pass auth will not work, ignored.\n",
		      uid);
	      break;
	    }
	    method_tab[i++] = S5AUSRPAS;
	    method_num++;
	    break;
	  case 'n':
	    method_tab[i++] = S5ANOAUTH;
	    method_num++;
	    break;
	  default:
	    break;
	  }
	}
      }
      break;

    case 'b':
      bind_restrict = 0;
      break;

    case 'c':
      if (optarg != NULL) {
        config = strdup(optarg);
      }
      break;

    case 'u':
      if (optarg != NULL) {
        pwdfile = strdup(optarg);
      }
      break;

    case 'i':
      if (optarg != NULL) {
	if (serv_init(optarg) < 0) {
	  msg_out(warn, "cannot init server socket(-i %s): %m\n", optarg);
	  break;
	}
      }
      break;

#ifdef SO_BINDTODEVICE
    case 'J':
      if (optarg != NULL) {
	bindtodevice = strdup(optarg);
      }
      break;
#endif

    case 'o':
      if (optarg != NULL) {
	idle_timeout = atol(optarg);
      }
      break;

    case 'p':
      if (optarg != NULL) {
	pidfile = strdup(optarg);
      }
      break;

    case 'm':
      if (optarg != NULL) {
#ifdef USE_THREAD
	max_thread = atoi(optarg);
#endif
	max_child = atoi(optarg);
      }
      break;

    case 't':
#ifdef USE_THREAD
      threading = 0;    /* threading disabled. */
#endif
      break;

    case 'g':
      same_interface = 1;
      break;

    case 'f':
      fg = 1;
      break;

    case 'r':
      resolv_client = 1;
      break;

    case 's':
      forcesyslog = 1;
      break;

    case 'w':
#ifdef HAVE_LIBWRAP
      use_tcpwrap = 1;
#endif /* HAVE_LIBWRAP */
      break;

    case 'I':
      inetd_mode = 1;
      break;

    case 'q':
      be_quiet = 1;
      break;

    case 'v':
      show_version();
      exit(1);

    case 'h':
    case '?':
    default:
      usage();
    }

  ac -= optind;
  av += optind;

  if ((fp = fopen(config, "r")) != NULL) {
    if (readconf(fp) != 0) {
      /* readconf error */
      exit(1);
    }
    fclose(fp);
  }

  if (inetd_mode) {
    /* close all server socket if opened */
    close_all_serv();
    /* assuming that STDIN_FILENO handles bi-directional
     */
    exit(inetd_service(STDIN_FILENO));
    /* not reached */
  }

  if (serv_sock_ind == 0) {   /* no valid ifs yet */
    if (serv_init(":") < 0) { /* use default */
      /* fatal */
      msg_out(crit, "cannot open server socket\n");
      exit(1);
    }
  }

#ifdef USE_THREAD
  if ( ! threading ) {
#endif
    if (queue_init() != 0) {
      msg_out(crit, "cannot init signal queue\n");
      exit(1);
    }
#ifdef USE_THREAD
  }
#endif

  /* try changing working directory */
  if ( chdir(WORKDIR0) != 0 )
    if ( chdir(WORKDIR1) != 0 )
      msg_out(norm, "giving up chdir to workdir");

  if (!fg) {
    /* force stdin/out/err allocate to /dev/null */
    fclose(stdin);
    fp = fopen("/dev/null", "w+");
    if (fileno(fp) != STDIN_FILENO) {
      msg_out(crit, "fopen: %m");
      exit(1);
    }
    if (dup2(STDIN_FILENO, STDOUT_FILENO) == -1) {
      msg_out(crit, "dup2-1: %m");
      exit(1);
    }
    if (dup2(STDIN_FILENO, STDERR_FILENO) == -1) {
      msg_out(crit, "dup2-2: %m");
      exit(1);
    }

    switch(fork()) {
    case -1:
      msg_out(crit, "fork: %m");
      exit(1);
    case 0:
      /* child */
      pid = setsid();
      if (pid == -1) {
	msg_out(crit, "setsid: %m");
	exit(1);
      }
      break;
    default:
      /* parent */
      exit(0);
    }
  }

  master_pid = getpid();
  umask(S_IWGRP|S_IWOTH);
  if ((fp = fopen(pidfile, "w")) != NULL) {
    fprintf(fp, "%u\n", (unsigned)master_pid);
    fchown(fileno(fp), PROCUID, PROCGID);
    fclose(fp);
  } else {
    msg_out(warn, "cannot open pidfile %s", pidfile);
  }

  setsignal(SIGHUP, reload);
  setsignal(SIGINT, SIG_IGN);
  setsignal(SIGQUIT, SIG_IGN);
  setsignal(SIGILL, SIG_IGN);
  setsignal(SIGTRAP, SIG_IGN);
  setsignal(SIGABRT, SIG_IGN);
#ifdef SIGEMT
  setsignal(SIGEMT, SIG_IGN);
#endif
  setsignal(SIGFPE, SIG_IGN);
  setsignal(SIGBUS, SIG_IGN);
  setsignal(SIGSEGV, SIG_IGN);
  setsignal(SIGSYS, SIG_IGN);
  setsignal(SIGPIPE, SIG_IGN);
  setsignal(SIGALRM, SIG_IGN);
  setsignal(SIGTERM, cleanup);
  setsignal(SIGUSR1, SIG_IGN);
  setsignal(SIGUSR2, SIG_IGN);
#ifdef SIGPOLL
  setsignal(SIGPOLL, SIG_IGN);
#endif
  setsignal(SIGVTALRM, SIG_IGN);
  setsignal(SIGPROF, SIG_IGN);
  setsignal(SIGXCPU, SIG_IGN);
  setsignal(SIGXFSZ, SIG_IGN);

#ifdef USE_THREAD
  if ( threading ) {
    if (max_thread <= 0 || max_thread > THREAD_LIMIT) {
      max_thread = THREAD_LIMIT;
    }
    /* resource limit is problem in threadig (e.g. Solaris:=64)*/
    memset((caddr_t)&rl, 0, sizeof rl);
    if (getrlimit(RLIMIT_NOFILE, &rl) != 0)
      msg_out(warn, "getrlimit: %m");
    else
      save_fd = rl.rlim_cur;
    if (rl.rlim_cur < (rlim_t)max_fd)
      rl.rlim_cur = max_fd;        /* willing to fix to max_fd */
    if ( rl.rlim_cur != save_fd )  /* if rlim_cur is changed   */
      if (setrlimit(RLIMIT_NOFILE, &rl) != 0)
        msg_out(warn, "cannot set rlimit(max_fd)");

    setregid(0, PROCGID);
    setreuid(0, PROCUID);

    pthread_mutex_init(&mutex_select, NULL);
    pthread_attr_init(&attr);
    pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);

    msg_out(norm, "Starting: MAX_TH(%d)", max_thread);
    for (i=0; i<max_thread; i++) {
      if (pthread_create(&tid, &attr,
			 (void *)&serv_loop, (void *)NULL) != 0)
        exit(1);
    }
    main_thread = pthread_self();   /* store main thread ID */
    for (;;) {
      pause();
    }
  } else {
#endif
    setsignal(SIGCHLD, reapchild);
    setregid(0, PROCGID);
    setreuid(0, PROCUID);
    msg_out(norm, "Starting: MAX_CH(%d)", max_child);
    serv_loop();
#ifdef USE_THREAD
  }
#endif
  return(0);
}
コード例 #18
0
ファイル: main.c プロジェクト: CRDevOps/srelay
int serv_loop()
{

  SOCKS_STATE	state;
  SOCK_INFO	si;
  CL_INFO	client;

  int    cs;
  fd_set readable;
  int    i, n, len;
  int    error;
  pid_t  pid;

  memset(&state, 0, sizeof(state));
  memset(&si, 0, sizeof(si));
  memset(&client, 0, sizeof(client));
  state.si = &si;

#ifdef USE_THREAD
  if (threading) {
    blocksignal(SIGHUP);
    blocksignal(SIGINT);
    blocksignal(SIGUSR1);
  }
#endif

  for (;;) {
    readable = allsock;

    MUTEX_LOCK(mutex_select);
    n = select(maxsock+1, &readable, 0, 0, 0);
    if (n <= 0) {
      if (n < 0 && errno != EINTR) {
        msg_out(warn, "select: %m");
      }
      MUTEX_UNLOCK(mutex_select);
      continue;
    }

#ifdef USE_THREAD
    if ( ! threading ) {
#endif
      /* handle any queued signal flags */
      if (FD_ISSET(sig_queue[0], &readable)) {
        if (ioctl(sig_queue[0], FIONREAD, &i) != 0) {
          msg_out(crit, "ioctl: %m");
          exit(-1);
        }
        while (--i >= 0) {
          char c;
          if (read(sig_queue[0], &c, 1) != 1) {
            msg_out(crit, "read: %m");
            exit(-1);
          }
          switch(c) {
          case 'H': /* sighup */
            reload();
            break;
          case 'C': /* sigchld */
            reapchild();
            break;
          case 'T': /* sigterm */
            cleanup();
            break;
          default:
            break;
          }
        }
      }
#ifdef USE_THREAD
    }
#endif

    for ( i = 0; i < serv_sock_ind; i++ ) {
      if (FD_ISSET(serv_sock[i], &readable)) {
	n--;
	break;
      }
    }
    if ( n < 0 || i >= serv_sock_ind ) {
      MUTEX_UNLOCK(mutex_select);
      continue;
    }

    len = SS_LEN;
    cs = accept(serv_sock[i], &si.prc.addr.sa, (socklen_t *)&len);
    si.prc.len = len;
    if (cs < 0) {
      if (errno == EINTR
#ifdef SOLARIS
	  || errno == EPROTO
#endif
	  || errno == EWOULDBLOCK
	  || errno == ECONNABORTED) {
	; /* ignore */
      } else {
	/* real accept error */
	msg_out(warn, "accept: %m");
      }
      MUTEX_UNLOCK(mutex_select);
      continue;
    }
    MUTEX_UNLOCK(mutex_select);

#ifdef USE_THREAD
    if ( !threading ) {
#endif
      if (max_child > 0 && cur_child >= max_child) {
	msg_out(warn, "child: cur %d; exeedeing max(%d)",
		          cur_child, max_child);
	close(cs);
	continue;
      }
#ifdef USE_THREAD
    }
#endif

    /* get downstream-side socket name */
    len = SS_LEN;
    getsockname(cs, &si.myc.addr.sa, (socklen_t *)&len);
    si.myc.len = len;

    error = getnameinfo(&si.prc.addr.sa, si.prc.len,
			client.addr, sizeof(client.addr),
			NULL, 0,
			NI_NUMERICHOST);
    if (resolv_client) {
      error = getnameinfo(&si.prc.addr.sa, si.prc.len,
			  client.name, sizeof(client.name),
			  NULL, 0, 0);
      msg_out(norm, "%s[%s] connected", client.name, client.addr);
    } else {
      msg_out(norm, "%s connected", client.addr);
      strncpy(client.name, client.addr, sizeof(client.name));
    }

    i = validate_access(&client);
    if (i < 1) {
      /* access denied */
      close(cs);
      continue;
    }

    set_blocking(cs);
    state.s = cs;

#ifdef USE_THREAD
    if (!threading ) {
#endif
      blocksignal(SIGHUP);
      blocksignal(SIGCHLD);
      pid = fork();
      switch (pid) {
      case -1:  /* fork child failed */
	break;
      case 0:   /* i am child */
	for ( i = 0; i < serv_sock_ind; i++ ) {
	  close(serv_sock[i]);
	}
	setsignal(SIGCHLD, SIG_DFL);
        setsignal(SIGHUP, SIG_DFL);
        releasesignal(SIGCHLD);
        releasesignal(SIGHUP);
	error = proto_socks(&state);
	if ( error == -1 ) {
	  close(state.s);  /* may already be closed */
	  exit(1);
	}
	relay(&state);
	exit(0);
      default: /* may be parent */
	proclist_add(pid);
	break;
      }
      close(state.s);
      releasesignal(SIGHUP);
      releasesignal(SIGCHLD);
#ifdef USE_THREAD
    } else {
      error = proto_socks(&state);
      if ( error == -1 ) {
	close(state.s);  /* may already be closed */
	/* udp may be dynamically allocated */
	if (state.sr.udp != NULL)
	  free(state.sr.udp);
	continue;
      }
      relay(&state);
    }
#endif
  }
}
コード例 #19
0
ファイル: trap.c プロジェクト: skrll/netbsd-src
int
trapcmd(int argc, char **argv)
{
	char *action;
	char **ap;
	int signo;
	int errs = 0;
	int printonly = 0;

	ap = argv + 1;

	if (argc == 2 && strcmp(*ap, "-l") == 0) {
		printsignals();
		return 0;
	}
	if (argc == 2 && strcmp(*ap, "-") == 0) {
		for (signo = 0; signo < NSIG; signo++) {
			if (trap[signo] == NULL)
				continue;
			INTOFF;
			ckfree(trap[signo]);
			trap[signo] = NULL;
			if (signo != 0)
				setsignal(signo, 0);
			INTON;
		}
		return 0;
	}
	if (argc >= 2 && strcmp(*ap, "-p") == 0) {
		printonly = 1;
		ap++;
		argc--;
	}

	if (argc > 1 && strcmp(*ap, "--") == 0) {
		argc--;
		ap++;
	}

	if (argc <= 1) {
		int count;

		if (printonly) {
			for (count = 0, signo = 0 ; signo < NSIG ; signo++)
				if (trap[signo] == NULL) {
					if (count == 0)
						out1str("trap -- -");
					out1fmt(" %s", trap_signame(signo));
					/* oh! unlucky 13 */
					if (++count >= 13) {
						out1str("\n");
						count = 0;
					}
				}
			if (count)
				out1str("\n");
		}

		for (count = 0, signo = 0 ; signo < NSIG ; signo++)
			if (trap[signo] != NULL && trap[signo][0] == '\0') {
				if (count == 0)
					out1str("trap -- ''");
				out1fmt(" %s", trap_signame(signo));
				/*
				 * the prefix is 10 bytes, with 4 byte
				 * signal names (common) we have room in
				 * the 70 bytes left on a normal line for
				 * 70/(4+1) signals, that's 14, but to
				 * allow for the occasional longer sig name
				 * we output one less...
				 */
				if (++count >= 13) {
					out1str("\n");
					count = 0;
				}
			}
		if (count)
			out1str("\n");

		for (signo = 0 ; signo < NSIG ; signo++)
			if (trap[signo] != NULL && trap[signo][0] != '\0') {
				out1str("trap -- ");
				print_quoted(trap[signo]);
				out1fmt(" %s\n", trap_signame(signo));
			}

		return 0;
	}

	action = NULL;

	if (!printonly && !is_number(*ap)) {
		if ((*ap)[0] == '-' && (*ap)[1] == '\0')
			ap++;			/* reset to default */
		else
			action = *ap++;		/* can be '' for "ignore" */
		argc--;
	}

	if (argc < 2) {		/* there must be at least 1 condition */
		out2str("Usage: trap [-l]\n"
			"       trap -p [condition ...]\n"
			"       trap action condition ...\n"
			"       trap N condition ...\n");
		return 2;
	}


	while (*ap) {
		signo = signame_to_signum(*ap);

		if (signo < 0 || signo >= NSIG) {
			/* This is not a fatal error, so sayeth posix */
			outfmt(out2, "trap: '%s' bad condition\n", *ap);
			errs = 1;
			ap++;
			continue;
		}
		ap++;

		if (printonly) {
			out1str("trap -- ");
			if (trap[signo] == NULL)
				out1str("-");
			else
				print_quoted(trap[signo]);
			out1fmt(" %s\n", trap_signame(signo));
			continue;
		}

		INTOFF;
		if (action)
			action = savestr(action);

		if (trap[signo])
			ckfree(trap[signo]);

		trap[signo] = action;

		if (signo != 0)
			setsignal(signo, 0);
		INTON;
	}
	return errs;
}
コード例 #20
0
ファイル: lem.c プロジェクト: halfd/lem
int
main(int argc, char *argv[])
{
#if EV_MULTIPLICITY
	lem_loop = ev_default_loop(LEM_LOOPFLAGS);
	if (lem_loop == NULL) {
#else
	if (!ev_default_loop(LEM_LOOPFLAGS)) {
#endif
		lem_log_error("lem: error initializing event loop");
		return EXIT_FAILURE;
	}

	if (setsignal(SIGPIPE, SIG_IGN, 0)
#if !EV_CHILD_ENABLE
	    || setsignal(SIGCHLD, SIG_DFL, SA_NOCLDSTOP | SA_NOCLDWAIT)
#endif
	   )
		goto error;

	/* create main Lua state */
	L = luaL_newstate();
	if (L == NULL) {
		lem_log_error("lem: error initializing Lua state");
		goto error;
	}
	luaL_openlibs(L);

	/* push thread table */
	lua_newtable(L);

	/* initialize runqueue */
	ev_idle_init(&rq.w, runqueue_pop);
	ev_idle_start(LEM_ &rq.w);
	rq.queue = lem_xmalloc(LEM_INITIAL_QUEUESIZE
			* sizeof(struct lem_runqueue_slot));
	rq.first = rq.last = 0;
	rq.mask = LEM_INITIAL_QUEUESIZE - 1;

	/* initialize threadpool */
	if (pool_init()) {
		lem_log_error("lem: error initializing threadpool");
		goto error;
	}

	/* load file */
	if (queue_file(argc, argv, 1))
		goto error;

	/* start the mainloop */
	ev_loop(LEM_ 0);
	lem_debug("event loop exited");

	/* if there is an error message left on L print it */
	if (lua_type(L, -1) == LUA_TSTRING)
		lem_log_error("lem: %s", lua_tostring(L, -1));

	/* shutdown Lua */
	lua_close(L);

	/* free runqueue */
	free(rq.queue);

	/* destroy loop */
#if EV_MULTIPLICITY
	ev_loop_destroy(lem_loop);
#else
	ev_default_destroy();
#endif
	lem_debug("Bye %s", exit_status == EXIT_SUCCESS ? "o/" : ":(");
	return exit_status;

error:
	if (L)
		lua_close(L);
	if (rq.queue)
		free(rq.queue);
#if EV_MULTIPLICITY
	ev_loop_destroy(lem_loop);
#else
	ev_default_destroy();
#endif
	return EXIT_FAILURE;
}
コード例 #21
0
ファイル: jobs.c プロジェクト: 0xffea/MINIX3
void
setjobctl(int on)
{
	int i;

	if (on == jobctl || rootshell == 0)
		return;
	if (on) {
		if (ttyfd != -1)
			close(ttyfd);
		if ((ttyfd = open(_PATH_TTY, O_RDWR)) < 0) {
			i = 0;
			while (i <= 2 && !isatty(i))
				i++;
			if (i > 2 || (ttyfd = fcntl(i, F_DUPFD, 10)) < 0)
				goto out;
		}
		if (ttyfd < 10) {
			/*
			 * Keep our TTY file descriptor out of the way of
			 * the user's redirections.
			 */
			if ((i = fcntl(ttyfd, F_DUPFD, 10)) < 0) {
				close(ttyfd);
				ttyfd = -1;
				goto out;
			}
			close(ttyfd);
			ttyfd = i;
		}
		if (fcntl(ttyfd, F_SETFD, FD_CLOEXEC) < 0) {
			close(ttyfd);
			ttyfd = -1;
			goto out;
		}
		do { /* while we are in the background */
			initialpgrp = tcgetpgrp(ttyfd);
			if (initialpgrp < 0) {
out:				out2str("sh: can't access tty; job control turned off\n");
				mflag = 0;
				return;
			}
			if (initialpgrp == -1)
				initialpgrp = getpgrp();
			else if (initialpgrp != getpgrp()) {
				killpg(0, SIGTTIN);
				continue;
			}
		} while (0);
		setsignal(SIGTSTP);
		setsignal(SIGTTOU);
		setsignal(SIGTTIN);
		setpgid(0, rootpid);
		tcsetpgrp(ttyfd, rootpid);
	} else { /* turning job control off */
		setpgid(0, initialpgrp);
		tcsetpgrp(ttyfd, initialpgrp);
		close(ttyfd);
		ttyfd = -1;
		setsignal(SIGTSTP);
		setsignal(SIGTTOU);
		setsignal(SIGTTIN);
	}
	jobctl = on;
}
コード例 #22
0
ファイル: trap.c プロジェクト: dezelin/kBuild
int
trapcmd(shinstance *psh, int argc, char **argv)
{
	char *action;
	char **ap;
	int signo;
#ifndef HAVE_SYS_SIGNAME
	init_sys_signame();
#endif

	if (argc <= 1) {
		for (signo = 0 ; signo <= NSIG ; signo++)
			if (psh->trap[signo] != NULL) {
				out1fmt(psh, "trap -- ");
				print_quoted(psh, psh->trap[signo]);
				out1fmt(psh, " %s\n",
				    (signo) ? sys_signame[signo] : "EXIT");
			}
		return 0;
	}
	ap = argv + 1;

	action = NULL;

	if (strcmp(*ap, "--") == 0)
		if (*++ap == NULL)
			return 0;

	if (signame_to_signum(psh, *ap) == -1) {
		if ((*ap)[0] == '-') {
			if ((*ap)[1] == '\0')
				ap++;
			else if ((*ap)[1] == 'l' && (*ap)[2] == '\0') {
				printsignals(psh);
				return 0;
			}
			else
				error(psh, "bad option %s\n", *ap);
		}
		else
			action = *ap++;
	}

	while (*ap) {
		if (is_number(*ap))
			signo = number(psh, *ap);
		else
			signo = signame_to_signum(psh, *ap);

		if (signo < 0 || signo > NSIG)
			error(psh, "%s: bad trap", *ap);

		INTOFF;
		if (action)
			action = savestr(psh, action);

		if (psh->trap[signo])
			ckfree(psh, psh->trap[signo]);

		psh->trap[signo] = action;

		if (signo != 0)
			setsignal(psh, signo, 0);
		INTON;
		ap++;
	}
	return 0;
}
コード例 #23
0
ファイル: main.c プロジェクト: dezelin/kBuild
SH_NORETURN_1 void
shell_main(shinstance *psh, int argc, char **argv)
{
	struct jmploc jmploc;
	struct stackmark smark;
	volatile int state;
	char *shinit;

	state = 0;
	if (setjmp(jmploc.loc)) {
		/*
		 * When a shell procedure is executed, we raise the
		 * exception EXSHELLPROC to clean up before executing
		 * the shell procedure.
		 */
		switch (psh->exception) {
		case EXSHELLPROC:
			psh->rootpid = /*getpid()*/ psh->pid;
			psh->rootshell = 1;
			psh->minusc = NULL;
			state = 3;
			break;

		case EXEXEC:
			psh->exitstatus = psh->exerrno;
			break;

		case EXERROR:
			psh->exitstatus = 2;
			break;

		default:
			break;
		}

		if (psh->exception != EXSHELLPROC) {
			if (state == 0 || iflag(psh) == 0 || ! psh->rootshell)
				exitshell(psh, psh->exitstatus);
		}
		reset(psh);
		if (psh->exception == EXINT
#if ATTY
		 && (! attyset(psh) || equal(termval(psh), "emacs"))
#endif
		 ) {
			out2c(psh, '\n');
			flushout(&psh->errout);
		}
		popstackmark(psh, &smark);
		FORCEINTON;				/* enable interrupts */
		if (state == 1)
			goto state1;
		else if (state == 2)
			goto state2;
		else if (state == 3)
			goto state3;
		else
			goto state4;
	}
	psh->handler = &jmploc;
	psh->rootpid = /*getpid()*/ psh->pid;
	psh->rootshell = 1;
#ifdef DEBUG
#if DEBUG == 2
	debug(psh) = 1;
#endif
	opentrace(psh);
	trputs(psh, "Shell args:  ");  trargs(psh, argv);
#endif

	init(psh);
	setstackmark(psh, &smark);
	procargs(psh, argc, argv);
	if (argv[0] && argv[0][0] == '-') {
		state = 1;
		read_profile(psh, "/etc/profile");
state1:
		state = 2;
		read_profile(psh, ".profile");
	}
state2:
	state = 3;
	if (sh_getuid(psh) == sh_geteuid(psh) && sh_getgid(psh) == sh_getegid(psh)) {
		if ((shinit = lookupvar(psh, "ENV")) != NULL && *shinit != '\0') {
			state = 3;
			read_profile(psh, shinit);
		}
	}
state3:
	state = 4;
	if (sflag(psh) == 0 || psh->minusc) {
		static int sigs[] =  {
		    SIGINT, SIGQUIT, SIGHUP,
#ifdef SIGTSTP
		    SIGTSTP,
#endif
		    SIGPIPE
		};
#define SIGSSIZE (sizeof(sigs)/sizeof(sigs[0]))
		unsigned i;

		for (i = 0; i < SIGSSIZE; i++)
		    setsignal(psh, sigs[i], 0);
	}

	if (psh->minusc)
		evalstring(psh, psh->minusc, 0);

	if (sflag(psh) || psh->minusc == NULL) {
state4:	/* XXX ??? - why isn't this before the "if" statement */
		cmdloop(psh, 1);
	}
	exitshell(psh, psh->exitstatus);
	/* NOTREACHED */
}
コード例 #24
0
ファイル: relay.c プロジェクト: a2/Soxy
void relay_udp(SOCKS_STATE *state)
{
  fd_set   rfds;
  int      nfds, sfd;
  struct   timeval tv;
  struct   timezone tz;
  ssize_t  wc;
  rlyinfo  ri;
  int      done;
  u_long   max_count = idle_timeout;
  u_long   timeout_count;
  struct sockaddr_storage ss;
  LOGINFO	li;

  memset(&ri, 0, sizeof(ri));
  memset(&li, 0, sizeof(li));
  ri.ss = (struct sockaddr *)&ss;
  ri.flags = 0;
  ri.nr = BUFSIZE-sizeof(UDPH);

  setsignal(SIGALRM, timeout);
  gettimeofday(&li.start, &tz);
  li.bc = li.upl = li.dnl = 0;
  timeout_count = 0;
  for (;;) {
    FD_ZERO(&rfds);
    FD_SET(state->s, &rfds); FD_SET(state->sr.udp->d, &rfds);
    nfds = MAX(state->s, state->sr.udp->d);
    if (state->r >= 0) {
      FD_SET(state->r, &rfds);
      nfds = MAX(nfds, state->r);
    }
    if (state->sr.udp->u >= 0) {
      FD_SET(state->sr.udp->u, &rfds);
      nfds = MAX(nfds, state->sr.udp->u);
    }

    done = 0;
    /* idle timeout related setting. */
    tv.tv_sec = 60; tv.tv_usec = 0;   /* unit = 1 minute. */
    tz.tz_minuteswest = 0; tz.tz_dsttime = 0;
    sfd = select(nfds+1, &rfds, 0, 0, &tv);
    if (sfd > 0) {
      /* UDP channels */
      /* in case of UDP, wc == 0 does not mean EOF (??) */
      if (FD_ISSET(state->sr.udp->d, &rfds)) {
	ri.from = state->sr.udp->d; ri.to = state->sr.udp->u;
	ri.dir = UP;
	if ((wc = forward_udp(&ri, state->sr.udp, state->rtbl.rl_meth)) < 0)
	  done++;
	else
    {
	  li.bc += wc; li.upl += wc;
      if (log_tmp_transfer_callback) log_tmp_transfer_callback(state->si, &li, wc, 0);
    }
	FD_CLR(state->sr.udp->d, &rfds);
      }
      if (state->sr.udp->u >= 0 && FD_ISSET(state->sr.udp->u, &rfds)) {
	ri.from = state->sr.udp->u; ri.to = state->sr.udp->d;
	ri.dir = DOWN;
	if ((wc = forward_udp(&ri, state->sr.udp, state->rtbl.rl_meth)) < 0)
	  done++;
	else
    {
	  li.bc += wc; li.dnl += wc;
      if (log_tmp_transfer_callback) log_tmp_transfer_callback(state->si, &li, wc, 0);
    }
	FD_CLR(state->sr.udp->d, &rfds);
      }
      /* packets on TCP channel may indicate
	 termination of UDP assoc.
      */
      if (FD_ISSET(state->s, &rfds)) {
	ri.from = state->s; ri.to = state->r; ri.flags = 0;
	if ((wc = forward(&ri)) <= 0)
	  done++;
	FD_CLR(state->s, &rfds);
      }
      if (FD_ISSET(state->r >= 0 && state->r, &rfds)) {
	ri.from = state->r; ri.to = state->s; ri.flags = 0;
	if ((wc = forward(&ri)) <= 0)
	  done++;
	FD_CLR(state->r, &rfds);
      }
      if (done > 0)
	break;
    } else if (sfd < 0) {
      if (errno != EINTR)
	break;
    } else { /* sfd == 0 */
      if (max_count != 0) {
	timeout_count++;
	if (timeout_count > max_count)
	  break;
      }
    }
  }

  gettimeofday(&li.end, &tz);
  /* getsockname for logging */
  state->sr.udp->si.myc.len = SS_LEN;
  getsockname(state->sr.udp->d,
	      &state->sr.udp->si.myc.addr.sa,
	      (socklen_t *)&state->sr.udp->si.myc.len);
  if (state->sr.udp->u >= 0) {
    state->sr.udp->si.mys.len = SS_LEN;
    getsockname(state->sr.udp->u,
		&state->sr.udp->si.mys.addr.sa,
		(socklen_t *)&state->sr.udp->si.mys.len);
  }

  log_transfer(&state->sr.udp->si, &li);

  close(state->s);
  if (state->r >= 0)
    close(state->r);
  close(state->sr.udp->d);
  if (state->sr.udp->u >= 0)
    close(state->sr.udp->u);
  if (state->sr.udp != NULL)
    free(state->sr.udp);
}
コード例 #25
0
ファイル: netdump3.c プロジェクト: stringsanbu/CPRE530
int
main(int argc, char **argv)
{
	int cnt, op, i, done = 0;
	bpf_u_int32 localnet, netmask;
	char *cp, *cmdbuf, *device;
	struct bpf_program fcode;
	 void (*oldhandler)(int);
	u_char *pcap_userdata;
	char ebuf[PCAP_ERRBUF_SIZE];

	cnt = -1;
	device = NULL;

	if ((cp = strrchr(argv[0], '/')) != NULL)
		program_name = cp + 1;
	else
		program_name = argv[0];

	opterr = 0;
	while ((i = getopt(argc, argv, "pa")) != -1)
	{
		switch (i)
		{
		case 'p':
			pflag = 1;
		break;
		case 'a':
			aflag = 1;
		break;
		case '?':
		default:
			done = 1;
		break;
		}
		if (done) break;
	}
	if (argc > (optind)) cmdbuf = copy_argv(&argv[optind]);
		else cmdbuf = "";

	if (device == NULL) {
		device = pcap_lookupdev(ebuf);
		if (device == NULL)
			error("%s", ebuf);
	}
	pd = pcap_open_live(device, snaplen,  1, 1000, ebuf);
	if (pd == NULL)
		error("%s", ebuf);
	i = pcap_snapshot(pd);
	if (snaplen < i) {
		warning("snaplen raised from %d to %d", snaplen, i);
		snaplen = i;
	}
	if (pcap_lookupnet(device, &localnet, &netmask, ebuf) < 0) {
		localnet = 0;
		netmask = 0;
		warning("%s", ebuf);
	}
	/*
	 * Let user own process after socket has been opened.
	 */
	setuid(getuid());

	if (pcap_compile(pd, &fcode, cmdbuf, 1, netmask) < 0)
		error("%s", pcap_geterr(pd));

	(void)setsignal(SIGTERM, program_ending);
	(void)setsignal(SIGINT, program_ending);
	/* Cooperate with nohup(1) */
	if ((oldhandler = setsignal(SIGHUP, program_ending)) != SIG_DFL)
		(void)setsignal(SIGHUP, oldhandler);

	if (pcap_setfilter(pd, &fcode) < 0)
		error("%s", pcap_geterr(pd));
	pcap_userdata = 0;
	(void)fprintf(stderr, "%s: listening on %s\n", program_name, device);
	if (pcap_loop(pd, cnt, raw_print, pcap_userdata) < 0) {
		(void)fprintf(stderr, "%s: pcap_loop: %s\n",
		    program_name, pcap_geterr(pd));
		exit(1);
	}
	pcap_close(pd);
	exit(0);
}
コード例 #26
0
ファイル: main.c プロジェクト: dezelin/kBuild
int
main(int argc, char **argv)
{
	struct jmploc jmploc;
	struct stackmark smark;
	volatile int state;
	char *shinit;

	setlocale(LC_ALL, "");

	/* Just a --version for show. */
	if (argc > 1
	 && argv[1][0] == '-'
	 && argv[1][1] == '-') {
		if (!strcmp(&argv[1][2], "version")) {
			printf("kmk_ash - kBuild version %d.%d.%d\n",
				   KBUILD_VERSION_MAJOR, KBUILD_VERSION_MINOR, KBUILD_VERSION_PATCH);
			return 0;
		}
		if (!strcmp(&argv[1][2], "help")) {
			printf("usage: kmk_ash [-aCefnuvxIimqVEb] [+aCefnuvxIimqVEb] [-o option_name]\n"
				   "               [+o option_name] [command_file [argument ...]]\n"
				   "   or: kmk_ash -c [-aCefnuvxIimqVEb] [+aCefnuvxIimqVEb] [-o option_name]\n"
				   "               [+o option_name] command_string [command_name [argument ...]]\n"
				   "   or: kmk_ash -s [-aCefnuvxIimqVEb] [+aCefnuvxIimqVEb] [-o option_name]\n"
				   "               [+o option_name] [argument ...]\n"
				   "   or: kmk_ash --help\n"
				   "   or: kmk_ash --version\n",
				   argv[0], argv[0], argv[0], argv[0], argv[0]);
			return 0;
		}
	}

#if PROFILE
	monitor(4, etext, profile_buf, sizeof profile_buf, 50);
#endif
	state = 0;
	if (setjmp(jmploc.loc)) {
		/*
		 * When a shell procedure is executed, we raise the
		 * exception EXSHELLPROC to clean up before executing
		 * the shell procedure.
		 */
		switch (exception) {
		case EXSHELLPROC:
			rootpid = getpid();
			rootshell = 1;
			minusc = NULL;
			state = 3;
			break;

		case EXEXEC:
			exitstatus = exerrno;
			break;

		case EXERROR:
			exitstatus = 2;
			break;

		default:
			break;
		}

		if (exception != EXSHELLPROC) {
			if (state == 0 || iflag == 0 || ! rootshell)
				exitshell(exitstatus);
		}
		reset();
		if (exception == EXINT
#if ATTY
		 && (! attyset() || equal(termval(), "emacs"))
#endif
		 ) {
			out2c('\n');
			flushout(&errout);
		}
		popstackmark(&smark);
		FORCEINTON;				/* enable interrupts */
		if (state == 1)
			goto state1;
		else if (state == 2)
			goto state2;
		else if (state == 3)
			goto state3;
		else
			goto state4;
	}
	handler = &jmploc;
#ifdef DEBUG
#if DEBUG == 2
	debug = 1;
#endif
	opentrace();
	trputs("Shell args:  ");  trargs(argv);
#endif
	rootpid = getpid();
	rootshell = 1;
#ifdef _MSC_VER
    {
        extern void init_syntax(void);
        init_syntax();
    }
#endif
	init();
	setstackmark(&smark);
	procargs(argc, argv);
	if (argv[0] && argv[0][0] == '-') {
		state = 1;
#ifndef KMK
		read_profile("/etc/profile");
#endif
state1:
		state = 2;
#ifndef KMK
		read_profile(".profile");
#endif
	}
state2:
	state = 3;
#ifndef KMK
	if (getuid() == geteuid() && getgid() == getegid()) {
		if ((shinit = lookupvar("ENV")) != NULL && *shinit != '\0') {
			state = 3;
			read_profile(shinit);
		}
	}
#endif
state3:
	state = 4;
	if (sflag == 0 || minusc) {
		static int sigs[] =  {
		    SIGINT, SIGQUIT, SIGHUP,
#ifdef SIGTSTP
		    SIGTSTP,
#endif
		    SIGPIPE
		};
#define SIGSSIZE (sizeof(sigs)/sizeof(sigs[0]))
		int i;

		for (i = 0; i < SIGSSIZE; i++)
		    setsignal(sigs[i], 0);
	}

	if (minusc)
		evalstring(minusc, 0);

	if (sflag || minusc == NULL) {
state4:	/* XXX ??? - why isn't this before the "if" statement */
		cmdloop(1);
	}
#if PROFILE
	monitor(0);
#endif
	exitshell(exitstatus);
	/* NOTREACHED */
}
コード例 #27
0
ファイル: trap.c プロジェクト: 2fast4u88/oxygen_system_core
int
trapcmd(int argc, char **argv)
{
	char *action;
	char **ap;
	int signo;

	if (argc <= 1) {
		for (signo = 0 ; signo <= NSIG ; signo++)
			if (trap[signo] != NULL) {
				out1fmt("trap -- ");
				print_quoted(trap[signo]);
				out1fmt(" %s\n",
				    (signo) ? sys_signame[signo] : "EXIT");
			}
		return 0;
	}
	ap = argv + 1;

	action = NULL;

	if (strcmp(*ap, "--") == 0)
		if (*++ap == NULL)
			return 0;

	if (signame_to_signum(*ap) == -1) {
		if ((*ap)[0] == '-') {
			if ((*ap)[1] == '\0')
				ap++;
			else if ((*ap)[1] == 'l' && (*ap)[2] == '\0') {
				printsignals();
				return 0;
			}
			else
				error("bad option %s\n", *ap);
		}
		else
			action = *ap++;
	}

	while (*ap) {
		if (is_number(*ap))
			signo = number(*ap);
		else
			signo = signame_to_signum(*ap);

		if (signo < 0 || signo > NSIG)
			error("%s: bad trap", *ap);

		INTOFF;
		if (action)
			action = savestr(action);

		if (trap[signo])
			ckfree(trap[signo]);

		trap[signo] = action;

		if (signo != 0)
			setsignal(signo, 0);
		INTON;
		ap++;
	}
	return 0;
}
コード例 #28
0
ファイル: relay.c プロジェクト: csmuc/iProxy
void relay(int cs, int ss)
{
  fd_set   rfds, xfds;
  int      nfds, sfd;
  struct   timeval tv, ts, ots, elp;
  struct   timezone tz;
  ssize_t  wc;
  rlyinfo  ri;
  int      done;
  u_long   max_count = idle_timeout;
  u_long   timeout_count;
  loginfo  li;

  memset(&ri, 0, sizeof(ri));
  ri.nr = BUFSIZE;

  memset(&li, 0, sizeof(li));
  set_sock_info(&li, cs, ss);

  nfds = (ss > cs ? ss : cs);
  setsignal(SIGALRM, timeout);
  gettimeofday(&ots, &tz);
  li.bc = li.upl = li.dnl = 0; ri.oob = 0; timeout_count = 0;
  for (;;) {
    FD_ZERO(&rfds);
    FD_SET(cs, &rfds); FD_SET(ss, &rfds);
    if (ri.oob == 0) {
      FD_ZERO(&xfds);
      FD_SET(cs, &xfds); FD_SET(ss, &xfds);
    }
    done = 0;
    /* idle timeout related setting. */
    tv.tv_sec = 60; tv.tv_usec = 0;   /* unit = 1 minute. */
    tz.tz_minuteswest = 0; tz.tz_dsttime = 0;
    sfd = select(nfds+1, &rfds, 0, &xfds, &tv);
    if (sfd > 0) {
      if (FD_ISSET(ss, &rfds)) {
	ri.from = ss; ri.to = cs; ri.oob = 0;
	if ((wc = forward(&ri)) <= 0)
	  done++;
	else
	  li.bc += wc; li.dnl += wc;

	FD_CLR(ss, &rfds);
      }
      if (FD_ISSET(ss, &xfds)) {
	ri.from = ss; ri.to = cs; ri.oob = 1;
	if ((wc = forward(&ri)) <= 0)
	  done++;
	else
	  li.bc += wc; li.dnl += wc;
	FD_CLR(ss, &xfds);
      }
      if (FD_ISSET(cs, &rfds)) {
	ri.from = cs; ri.to = ss; ri.oob = 0;
	if ((wc = forward(&ri)) <= 0)
	  done++;
	else
	  li.bc += wc; li.upl += wc;
	FD_CLR(cs, &rfds);
      }
      if (FD_ISSET(cs, &xfds)) {
	ri.from = cs; ri.to = ss; ri.oob = 1;
	if ((wc = forward(&ri)) <= 0)
	  done++;
	else
	  li.bc += wc; li.upl += wc;
	FD_CLR(cs, &xfds);
      }
      if (done > 0)
	break;
    } else if (sfd < 0) {
      if (errno != EINTR)
	break;
    } else { /* sfd == 0 */
      if (max_count != 0) {
	timeout_count++;
	if (timeout_count > max_count)
	  break;
      }
    }
  }
  gettimeofday(&ts, &tz);
  if (ts.tv_usec < ots.tv_usec) {
    ts.tv_sec--; ts.tv_usec += 1000000;
  }
  elp.tv_sec = ts.tv_sec - ots.tv_sec;
  elp.tv_usec = ts.tv_usec - ots.tv_usec;
  li.elp = elp;

  log_transfer(&li);

  close(ss);
  close(cs);
}
コード例 #29
0
ファイル: relay.c プロジェクト: a2/Soxy
void relay_tcp(SOCKS_STATE *state)
{
  fd_set   rfds, xfds;
  int      nfds, sfd;
  struct   timeval tv;
  struct   timezone tz;
  ssize_t  wc;
  rlyinfo  ri;
  int      done;
  u_long   max_count = idle_timeout;
  u_long   timeout_count;
  LOGINFO	li;

  memset(&ri, 0, sizeof(ri));
  memset(&li, 0, sizeof(li));
  ri.ss = (struct sockaddr *)NULL;
  ri.len = 0;
  ri.nr = BUFSIZE;

  nfds = MAX(state->r, state->s);
  setsignal(SIGALRM, timeout);
  gettimeofday(&li.start, &tz);
  li.bc = li.upl = li.dnl = 0;
  ri.flags = 0; timeout_count = 0;
  for (;;) {
    FD_ZERO(&rfds);
    FD_SET(state->s, &rfds); FD_SET(state->r, &rfds);
    if (ri.flags == 0) {
      FD_ZERO(&xfds);
      FD_SET(state->s, &xfds); FD_SET(state->r, &xfds);
    }
    done = 0;
    /* idle timeout related setting. */
    tv.tv_sec = 60; tv.tv_usec = 0;   /* unit = 1 minute. */
    tz.tz_minuteswest = 0; tz.tz_dsttime = 0;
    sfd = select(nfds+1, &rfds, 0, &xfds, &tv);
    if (sfd > 0) {
      if (FD_ISSET(state->r, &rfds)) {
	ri.from = state->r; ri.to = state->s; ri.flags = 0;
	if ((wc = forward(&ri)) <= 0)
	  done++;
	else
    {
	  li.bc += wc; li.dnl += wc;
      if (log_tmp_transfer_callback) log_tmp_transfer_callback(state->si, &li, wc, 0);
    }
	FD_CLR(state->r, &rfds);
      }
      if (FD_ISSET(state->r, &xfds)) {
	ri.from = state->r; ri.to = state->s; ri.flags = MSG_OOB;
	if ((wc = forward(&ri)) <= 0)
	  done++;
	else
    {
	  li.bc += wc; li.dnl += wc;
      if (log_tmp_transfer_callback) log_tmp_transfer_callback(state->si, &li, wc, 0);
    }
	FD_CLR(state->r, &xfds);
      }
      if (FD_ISSET(state->s, &rfds)) {
	ri.from = state->s; ri.to = state->r; ri.flags = 0;
	if ((wc = forward(&ri)) <= 0)
	  done++;
	else
    {
	  li.bc += wc; li.upl += wc;
      if (log_tmp_transfer_callback) log_tmp_transfer_callback(state->si, &li, wc, 0);
    }
	FD_CLR(state->s, &rfds);
      }
      if (FD_ISSET(state->s, &xfds)) {
	ri.from = state->s; ri.to = state->r; ri.flags = MSG_OOB;
	if ((wc = forward(&ri)) <= 0)
	  done++;
	else
    {
	  li.bc += wc; li.upl += wc;
      if (log_tmp_transfer_callback) log_tmp_transfer_callback(state->si, &li, wc, 0);
    }
	FD_CLR(state->s, &xfds);
      }
      if (done > 0)
	break;
    } else if (sfd < 0) {
      if (errno != EINTR)
	break;
    } else { /* sfd == 0 */
      if (max_count != 0) {
	timeout_count++;
	if (timeout_count > max_count)
	  break;
      }
    }
  }
  gettimeofday(&li.end, &tz);
  log_transfer(state->si, &li);

  close(state->r);
  close(state->s);
}
コード例 #30
0
ファイル: main.c プロジェクト: IIJ-NetBSD/netbsd-src
int
main(int argc, char **argv)
{
	struct stackmark smark;
	volatile int state;
	char *shinit;
	uid_t uid;
	gid_t gid;

	uid = getuid();
	gid = getgid();

	max_user_fd = fcntl(0, F_MAXFD);
	if (max_user_fd < 2)
		max_user_fd = 2;

	setlocale(LC_ALL, "");

	posix = getenv("POSIXLY_CORRECT") != NULL;
#if PROFILE
	monitor(4, etext, profile_buf, sizeof profile_buf, 50);
#endif
	state = 0;
	if (setjmp(main_handler.loc)) {
		/*
		 * When a shell procedure is executed, we raise the
		 * exception EXSHELLPROC to clean up before executing
		 * the shell procedure.
		 */
		switch (exception) {
		case EXSHELLPROC:
			rootpid = getpid();
			rootshell = 1;
			minusc = NULL;
			state = 3;
			break;

		case EXEXEC:
			exitstatus = exerrno;
			break;

		case EXERROR:
			exitstatus = 2;
			break;

		default:
			break;
		}

		if (exception != EXSHELLPROC) {
			if (state == 0 || iflag == 0 || ! rootshell ||
			    exception == EXEXIT)
				exitshell(exitstatus);
		}
		reset();
		if (exception == EXINT) {
			out2c('\n');
			flushout(&errout);
		}
		popstackmark(&smark);
		FORCEINTON;				/* enable interrupts */
		if (state == 1)
			goto state1;
		else if (state == 2)
			goto state2;
		else if (state == 3)
			goto state3;
		else
			goto state4;
	}
	handler = &main_handler;
#ifdef DEBUG
#if DEBUG >= 2
	debug = 1;	/* this may be reset by procargs() later */
#endif
	opentrace();
	trputs("Shell args:  ");  trargs(argv);
#if DEBUG >= 3
	set_debug(((DEBUG)==3 ? "_@" : "++"), 1);
#endif
#endif
	rootpid = getpid();
	rootshell = 1;
	init();
	initpwd();
	setstackmark(&smark);
	procargs(argc, argv);

	/*
	 * Limit bogus system(3) or popen(3) calls in setuid binaries,
	 * by requiring the -p flag
	 */
	if (!pflag && (uid != geteuid() || gid != getegid())) {
		setuid(uid);
		setgid(gid);
		/* PS1 might need to be changed accordingly. */
		choose_ps1();
	}

	if (argv[0] && argv[0][0] == '-') {
		state = 1;
		read_profile("/etc/profile");
 state1:
		state = 2;
		read_profile(".profile");
	}
 state2:
	state = 3;
	if ((iflag || !posix) &&
	    getuid() == geteuid() && getgid() == getegid()) {
		struct stackmark env_smark;

		setstackmark(&env_smark);
		if ((shinit = lookupvar("ENV")) != NULL && *shinit != '\0') {
			state = 3;
			read_profile(expandenv(shinit));
		}
		popstackmark(&env_smark);
	}
 state3:
	state = 4;
	line_number = 1;	/* undo anything from profile files */

	if (sflag == 0 || minusc) {
		static int sigs[] =  {
		    SIGINT, SIGQUIT, SIGHUP, 
#ifdef SIGTSTP
		    SIGTSTP,
#endif
		    SIGPIPE
		};
#define SIGSSIZE (sizeof(sigs)/sizeof(sigs[0]))
		size_t i;

		for (i = 0; i < SIGSSIZE; i++)
		    setsignal(sigs[i], 0);
	}

	if (minusc)
		evalstring(minusc, sflag ? 0 : EV_EXIT);

	if (sflag || minusc == NULL) {
 state4:	/* XXX ??? - why isn't this before the "if" statement */
		cmdloop(1);
		if (iflag) {
			out2str("\n");
			flushout(&errout);
		}
	}
#if PROFILE
	monitor(0);
#endif
	line_number = plinno;
	exitshell(exitstatus);
	/* NOTREACHED */
}