示例#1
0
/*
 * Display the contents of a uio structure on a terminal.  Used by wall(1),
 * syslogd(8), and talkd(8).  Forks and finishes in child if write would block,
 * waiting up to tmout seconds.  Returns pointer to error string on unexpected
 * error; string is not newline-terminated.  Various "normal" errors are
 * ignored (exclusive-use, lack of permission, etc.).
 */
char *
ttymsg(struct iovec *iov, int iovcnt, char *line, int tmout) {
	static char device[MAXNAMLEN];
	static char errbuf[MAXNAMLEN+1024];
	register int cnt, fd, left, wret;
	struct iovec localiov[6];
	int forked = 0, errsv;

	if (iovcnt > sizeof(localiov) / sizeof(localiov[0]))
		return (_("too many iov's (change code in wall/ttymsg.c)"));

	/* The old code here rejected the line argument when it contained a '/',
	   saying: "A slash may be an attempt to break security...".
	   However, if a user can control the line argument here
	   then he can make this routine write to /dev/hda or /dev/sda
	   already. So, this test was worthless, and these days it is
	   also wrong since people use /dev/pts/xxx. */

	if (strlen(line) + sizeof(_PATH_DEV) + 1 > sizeof(device)) {
		(void) sprintf(errbuf, _("excessively long line arg"));
		return (errbuf);
	}
	(void) sprintf(device, "%s%s", _PATH_DEV, line);

	/*
	 * open will fail on slip lines or exclusive-use lines
	 * if not running as root; not an error.
	 */
	if ((fd = open(device, O_WRONLY|O_NONBLOCK, 0)) < 0) {
		if (errno == EBUSY || errno == EACCES)
			return (NULL);
		if (strlen(strerror(errno)) > 1000)
			return (NULL);
		(void) sprintf(errbuf, "%s: %s", device, strerror(errno));
		errbuf[1024] = 0;
		return (errbuf);
	}

	for (cnt = left = 0; cnt < iovcnt; ++cnt)
		left += iov[cnt].iov_len;

	for (;;) {
		wret = writev(fd, iov, iovcnt);
		if (wret >= left)
			break;
		if (wret >= 0) {
			left -= wret;
			if (iov != localiov) {
				bcopy(iov, localiov,
				    iovcnt * sizeof(struct iovec));
				iov = localiov;
			}
			for (cnt = 0; wret >= iov->iov_len; ++cnt) {
				wret -= iov->iov_len;
				++iov;
				--iovcnt;
			}
			if (wret) {
				iov->iov_base += wret;
				iov->iov_len -= wret;
			}
			continue;
		}
		if (errno == EWOULDBLOCK) {
			int cpid, off = 0;

			if (forked) {
				(void) close(fd);
				_exit(1);
			}
			cpid = fork();
			if (cpid < 0) {
				if (strlen(strerror(errno)) > 1000)
					(void) sprintf(errbuf, _("cannot fork"));
				else {
					errsv = errno;
					(void) sprintf(errbuf,
						 _("fork: %s"), strerror(errsv));
				}
				(void) close(fd);
				return (errbuf);
			}
			if (cpid) {	/* parent */
				(void) close(fd);
				return (NULL);
			}
			forked++;
			/* wait at most tmout seconds */
			(void) signal(SIGALRM, SIG_DFL);
			(void) signal(SIGTERM, SIG_DFL); /* XXX */
			(void) sigsetmask(0);
			(void) alarm((u_int)tmout);
			(void) fcntl(fd, O_NONBLOCK, &off);
			continue;
		}
		/*
		 * We get ENODEV on a slip line if we're running as root,
		 * and EIO if the line just went away.
		 */
		if (errno == ENODEV || errno == EIO)
			break;
		(void) close(fd);
		if (forked)
			_exit(1);
		if (strlen(strerror(errno)) > 1000)
			(void) sprintf(errbuf, _("%s: BAD ERROR"), device);
		else {
			errsv = errno;
			(void) sprintf(errbuf, "%s: %s", device,
				       strerror(errsv));
		}
		errbuf[1024] = 0;
		return (errbuf);
	}

	(void) close(fd);
	if (forked)
		_exit(0);
	return (NULL);
}
示例#2
0
void alarmHandler(int s) {
	alarm(1);
	alarmSignal = true;
	return;
}
示例#3
0
int
main(int argc, char **argv)
{
	gzFile	       *infp;
	char		buf[BUFSIZ], *bp, **aliases;
	struct hostent  *he;
	int		ch, errors = 0;
	int		backcount = 0;

	progname = argv[0];

	while ((ch = getopt(argc, argv, "a:")) != -1)
		switch(ch) {
		case 'a':
			backcount = atoi(optarg);
			break;
			
		case 'h':
		case '?':
		default:
			usage();
		}
	argc -= optind;
	argv += optind;

	if (argc)
		usage();

	openlog("genlastlog", LOG_PID, LOG_TESTBED);
	syslog(LOG_NOTICE, "genlastlog starting");

	if (!dbinit()) {
		syslog(LOG_ERR, "Could not connect to DB!");
		exit(1);
	}

	/*
	 * We need the canonical hostname for the usersnode so that we can
	 * put those logins in another table.
	 */
	if ((he = gethostbyname(USERNODE)) == NULL) {
		syslog(LOG_ERR, "gethostname %s: %s",
		       USERNODE, hstrerror(h_errno));
		exit(-1);
	}
	strncpy(opshostname, he->h_name, sizeof(opshostname));

	if (bp = strchr(opshostname, '.')) 
		*bp = 0;

	while (backcount) {
		sprintf(buf, "%s/%s.%d.gz", USERSVAR, LOGINS, backcount);

		/*
		 * Use setjmp and timer to prevent NFS lockup.
		 */
		if (setjmp(deadline) == 0) {
			alarm(15);

			if ((infp = gzopen(buf, "r")) == NULL) {
				syslog(LOG_ERR, "Opening %s: %m", buf);
				errors++;
			}
			else {
				doit(infp);
				gzclose(infp);
			}
		}
		backcount--;
		alarm(0);
	}
	
	sprintf(buf, "%s/%s", USERSVAR, LOGINS);

	if (setjmp(deadline) == 0) {
		alarm(15);

		if ((infp = gzopen(buf, "r")) == NULL) {
			syslog(LOG_ERR, "Opening %s: %m", buf);
			errors++;
		}
		else {
			doit(infp);
			gzclose(infp);
		}
	}
	alarm(0);

	syslog(LOG_NOTICE, "genlastlog ending");
	exit(errors);
	
}
示例#4
0
文件: signal.c 项目: AlexSteel/wine
void start_watchdog(void)
{
    alarm( 3 );
    watchdog = 0;
}
示例#5
0
文件: fuse.c 项目: LuaAndC/luafuse
static xmp_main(lua_State *L)
{
    /*
     * called in lua as fuse.main(dispatch_table, fuse_table)
     */

    L_VM = L;
    int argc = lua_objlen(L, 2);
    char *argv[256];
    int i;
    
    if (argc < 2) luaL_error(L, "check parameter fusemount parameter table");

    #if 0
    lua_pushstring(L, "pulse_freq");
    lua_gettable(L, 1);
    pulse_freq = lua_tointeger(L,-1);
    lua_pop(L,1);
    if (pulse_freq == 0) pulse_freq = 10;
    #endif

    /*
     * save dispatch table for future reference by C program
     */
    lua_pushvalue(L, 1);
    dispatch_table = luaL_ref(L_VM, LUA_REGISTRYINDEX);

    /*
     * turn fuse option table(effectively cmdline) to argv style
     */
    for (i=0; i < argc && i < 255; i++) {
        lua_rawgeti(L, 2, i + 1);
        argv[i]=lua_tostring(L, -1); 
    }
    argv[i] = NULL;

#if 0
    if (pulse_freq > 0) {
        signal(SIGALRM,l_signal);
        alarm(pulse_freq);
    }
#endif
    
    /*
     * hand over to fuse loop
     */

    fuse_main(argc, argv, &xmp_oper);

    /*
     * remove argv strings from L stack
     */
    lua_pop(L, i);
    
    /*
     * discard reference to dispatch_table
     */
    luaL_unref(L, LUA_REGISTRYINDEX, dispatch_table);

    #if 0
    signal(SIGALRM, SIG_DFL);
    #endif

    return 0;
}
示例#6
0
int	main(int argc, char **argv)
{
	char		ch;
	int		task = ZBX_TASK_START;
	char		*TEST_METRIC = NULL;
	zbx_sock_t	s_in;
	zbx_sock_t	s_out;

	int		ret;
	char		**value, *command;

	AGENT_RESULT	result;

	memset(&result, 0, sizeof(AGENT_RESULT));

	progname = get_program_name(argv[0]);

/* Parse the command-line. */
	while ((ch = (char)zbx_getopt_long(argc, argv, "c:hVpt:", longopts, NULL)) != (char)EOF)
		switch (ch)
		{
			case 'c':
				CONFIG_FILE = strdup(zbx_optarg);
				break;
			case 'h':
				help();
				exit(-1);
				break;
			case 'V':
				version();
#ifdef _AIX
				tl_version();
#endif /* _AIX */
				exit(-1);
				break;
			case 'p':
				if (task == ZBX_TASK_START)
					task = ZBX_TASK_PRINT_SUPPORTED;
				break;
			case 't':
				if (task == ZBX_TASK_START)
				{
					task = ZBX_TASK_TEST_METRIC;
					TEST_METRIC = strdup(zbx_optarg);
				}
				break;
			default:
				task = ZBX_TASK_SHOW_USAGE;
				break;
		}

	if (CONFIG_FILE == NULL)
		CONFIG_FILE = DEFAULT_CONFIG_FILE;

	init_metrics();

	if (ZBX_TASK_START == task)
	{
		load_config();
		load_user_parameters(0);
	}

	/* Do not create debug files */
	zabbix_open_log(LOG_TYPE_SYSLOG, LOG_LEVEL_EMPTY, NULL);

	switch (task)
	{
		case ZBX_TASK_PRINT_SUPPORTED:
			load_user_parameters(1);
			test_parameters();
			exit(-1);
			break;
		case ZBX_TASK_TEST_METRIC:
			load_user_parameters(1);
			test_parameter(TEST_METRIC, PROCESS_TEST);
			exit(-1);
			break;
		case ZBX_TASK_SHOW_USAGE:
			usage();
			exit(-1);
			break;
	}

	signal(SIGINT,  child_signal_handler);
	signal(SIGTERM, child_signal_handler);
	signal(SIGQUIT, child_signal_handler);
	signal(SIGALRM, child_signal_handler);

	alarm(CONFIG_TIMEOUT);

	zbx_tcp_init(&s_in, (ZBX_SOCKET)fileno(stdin));
	zbx_tcp_init(&s_out, (ZBX_SOCKET)fileno(stdout));

	if( SUCCEED == (ret = zbx_tcp_check_security(&s_in, CONFIG_HOSTS_ALLOWED, 0)) )
	{
		if( SUCCEED == (ret = zbx_tcp_recv(&s_in, &command)) )
		{
			zbx_rtrim(command, "\r\n");

			zabbix_log(LOG_LEVEL_DEBUG, "Requested [%s]", command);

			init_result(&result);

			process(command, 0, &result);

			if( NULL == (value = GET_TEXT_RESULT(&result)) )
				value = GET_MSG_RESULT(&result);

			if(value)
			{
				zabbix_log(LOG_LEVEL_DEBUG, "Sending back [%s]", *value);

				ret = zbx_tcp_send(&s_out, *value);
			}

			free_result(&result);
		}

		if( FAIL == ret )
		{
			zabbix_log(LOG_LEVEL_DEBUG, "Processing error: %s", zbx_tcp_strerror());
		}
	}

	fflush(stdout);

	free_metrics();
	alias_list_free();

	alarm(0);

	zabbix_close_log();

	return SUCCEED;
}
示例#7
0
文件: courier.c 项目: ryo/netbsd-src
static int
cour_connect(void)
{
	char c;
	int volatile nc;
	int volatile nl;
	int n;
	char dialer_buf[64];
	struct baud_msg *bm;
	sig_t f;

	if (cour_swallow("\r\n") == 0)
		return (0);
	f = signal(SIGALRM, sigALRM);
again:
	(void)memset(dialer_buf, 0, sizeof(dialer_buf));
	timeout = 0;
	for (nc = 0, nl = sizeof(dialer_buf) - 1 ; nl > 0 ; nc++, nl--) {
		if (setjmp(timeoutbuf))
			break;
		(void)alarm((unsigned)number(value(DIALTIMEOUT)));
		n = read(FD, &c, 1);
		(void)alarm(0);
		if (n <= 0)
			break;
		c &= 0x7f;
		if (c == '\r') {
			if (cour_swallow("\n") == 0)
				break;
			if (!dialer_buf[0])
				goto again;
			if (strcmp(dialer_buf, "RINGING") == 0 &&
			    boolean(value(VERBOSE))) {
#ifdef DEBUG
				(void)printf("%s\r\n", dialer_buf);
#endif
				goto again;
			}
			if (strncmp(dialer_buf, "CONNECT",
				    sizeof("CONNECT")-1) != 0)
				break;
			for (bm = baud_msg ; bm->msg ; bm++)
				if (strcmp(bm->msg,
				    dialer_buf+sizeof("CONNECT")-1) == 0) {
					struct termios	cntrl;

					(void)tcgetattr(FD, &cntrl);
					(void)cfsetospeed(&cntrl, bm->baud);
					(void)cfsetispeed(&cntrl, bm->baud);
					(void)tcsetattr(FD, TCSAFLUSH, &cntrl);
					(void)signal(SIGALRM, f);
#ifdef DEBUG
					if (boolean(value(VERBOSE)))
						(void)printf("%s\r\n", dialer_buf);
#endif
					return (1);
				}
			break;
		}
		dialer_buf[nc] = c;
#ifdef notdef
		if (boolean(value(VERBOSE)))
			(void)putchar(c);
#endif
	}
	(void)printf("%s\r\n", dialer_buf);
	(void)signal(SIGALRM, f);
	return (0);
}
示例#8
0
文件: 6pack.c 项目: morisson/code
int
collect (char *iface, u_long seq)
{
  struct libnet_tcp_hdr *tcp;
  pid_t pid;
  struct pcap_pkthdr hdr;
  pcap_t *desc;
  char errbuf[PCAP_ERRBUF_SIZE];
  u_char *in_pkt;
  struct bpf_program bp;
  char *filter = "ip6 and tcp";
  struct timeval timenow, timethen;
  int hdr_size;

  desc = pcap_open_live (iface, 1500, 1, 0, errbuf);
  if (desc == NULL)
    {
      fprintf (stderr, "error opening device for capture: %s", errbuf);
      return 0;
    }
  pcap_compile (desc, &bp, filter, 1, 65535);
  pcap_setfilter (desc, &bp);
  switch (pcap_datalink (desc))
    {
    case DLT_RAW:
      hdr_size = 40;
      if (verbose)
	printf ("Datalink: Raw\n");
      break;
    case DLT_EN10MB:
      hdr_size = 54;
      if (verbose)
	printf ("Datalink: Ethernet\n");
      break;
    default:
      fprintf (stderr, "Datalink type not supported\n");
      return 0;

    }

  if ((pid = fork ()))
    {				/*chld */
      setsid ();
      signal (SIGALRM, (void *) (finish));
      if (verbose)
	gettimeofday (&timethen, NULL);
      do
	{
	  alarm (timeout);
	  in_pkt = (u_char *) pcap_next (desc, &hdr);
	  if (in_pkt != NULL)
	    { /* we should check for extra headers...someday */
	      tcp = ((struct libnet_tcp_hdr *) (in_pkt + hdr_size));
	      if (ntohl (tcp->th_ack) == seq + 1)
		{
		  alarm (0);
		  if ((tcp->th_flags & TH_SYN) && (tcp->th_flags & TH_ACK))
		    {
		      if (verbose)
			gettimeofday (&timenow, NULL);
		      !verbose ? printf ("Open: %d\n",
					 ntohs (tcp->
						th_sport)) :
			printf ("Open: %d  %u.%.4us\n",
				ntohs (tcp->th_sport),
				timenow.tv_sec - timethen.tv_sec,
				timenow.tv_usec - timethen.tv_usec);
		    }
		}
	    }
	}
      while (1);
    }
  return 1;
}
示例#9
0
文件: fileio.c 项目: Difrex/OpenSAN2
int start(int argc, char **argv)
{
	int res = 0;
	int fd;
	int i, rc;
	void *rc1;
	static struct scst_user_dev_desc desc;
	pthread_t thread[MAX_VDEVS][threads];

	memset(thread, 0, sizeof(thread));

	i = 0;
	optind -= 2;
	while (1) {
		int j;

		optind += 2;
		if (optind > (argc-2))
			break;

		devs[i].block_size = block_size;
		devs[i].block_shift = block_shift;
		devs[i].alloc_fn = alloc_fn;

		devs[i].rd_only_flag = rd_only_flag;
		devs[i].wt_flag = wt_flag;
		devs[i].nv_cache = nv_cache;
		devs[i].o_direct_flag = o_direct_flag;
		devs[i].nullio = nullio;
		devs[i].non_blocking = non_blocking;
#if defined(DEBUG_TM_IGNORE) || defined(DEBUG_TM_IGNORE_ALL)
		devs[i].debug_tm_ignore = debug_tm_ignore;
#endif
		devs[i].type = TYPE_DISK;
		devs[i].name = argv[optind];
		devs[i].file_name = argv[optind+1];

		TRACE_DBG("Opening file %s", devs[i].file_name);
		fd = open(devs[i].file_name, O_RDONLY|O_LARGEFILE);
		if (fd < 0) {
			res = -errno;
			PRINT_ERROR("Unable to open file %s (%s)", devs[i].file_name,
				strerror(-res));
			continue;
		}

		devs[i].file_size = lseek64(fd, 0, SEEK_END);
		devs[i].nblocks = devs[i].file_size >> devs[i].block_shift;

		close(fd);

		PRINT_INFO("%s", " ");
		PRINT_INFO("Virtual device \"%s\", path \"%s\", size %"PRId64"MB, "
			"block size %d, nblocks %"PRId64", options:", devs[i].name,
			devs[i].file_name, (uint64_t)devs[i].file_size/1024/1024,
			devs[i].block_size, (uint64_t)devs[i].nblocks);

		snprintf(devs[i].usn, sizeof(devs[i].usn), "%"PRIx64,
			gen_dev_id_num(&devs[i]));
		TRACE_DBG("usn %s", devs[i].usn);

		devs[i].scst_usr_fd = open(DEV_USER_PATH DEV_USER_NAME, O_RDWR |
					(devs[i].non_blocking ? O_NONBLOCK : 0));
		if (devs[i].scst_usr_fd < 0) {
			res = -errno;
			PRINT_ERROR("Unable to open SCST device %s (%s)",
				DEV_USER_PATH DEV_USER_NAME, strerror(-res));
			goto out_unreg;
		}

		memset(&desc, 0, sizeof(desc));
		desc.license_str = (unsigned long)"GPL";
		desc.version_str = (unsigned long)DEV_USER_VERSION;
		strncpy(desc.name, devs[i].name, sizeof(desc.name)-1);
		desc.name[sizeof(desc.name)-1] = '\0';
		if (sgv_shared) {
			desc.sgv_shared = 1;
			strncpy(desc.sgv_name, devs[0].name, sizeof(desc.sgv_name)-1);
			desc.sgv_name[sizeof(desc.sgv_name)-1] = '\0';
		}
		desc.sgv_single_alloc_pages = sgv_single_alloc_pages;
		desc.sgv_purge_interval = sgv_purge_interval;
		desc.sgv_disable_clustered_pool = sgv_disable_clustered_pool;
		desc.type = devs[i].type;
		desc.block_size = devs[i].block_size;

		desc.opt.parse_type = parse_type;
		desc.opt.on_free_cmd_type = on_free_cmd_type;
		desc.opt.memory_reuse_type = memory_reuse_type;

		desc.opt.tst = SCST_CONTR_MODE_SEP_TASK_SETS;
		desc.opt.queue_alg = SCST_CONTR_MODE_QUEUE_ALG_UNRESTRICTED_REORDER;
		desc.opt.d_sense = SCST_CONTR_MODE_FIXED_SENSE;

		res = ioctl(devs[i].scst_usr_fd, SCST_USER_REGISTER_DEVICE, &desc);
		if (res != 0) {
			res = errno;
			PRINT_ERROR("Unable to register device: %s", strerror(res));
			goto out_unreg;
		}

		if ((prealloc_buffers_num > 0) && (prealloc_buffer_size > 0)) {
			res = prealloc_buffers(&devs[i]);
			if (res != 0)
				goto out_unreg;
		}

#if 1
		{
			/* Not needed, added here only as a test */
			struct scst_user_opt opt;

			res = ioctl(devs[i].scst_usr_fd, SCST_USER_GET_OPTIONS, &opt);
			if (res != 0) {
				res = errno;
				PRINT_ERROR("Unable to get options: %s", strerror(res));
				goto out_unreg;
			}

			opt.parse_type = parse_type;
			opt.on_free_cmd_type = on_free_cmd_type;
			opt.memory_reuse_type = memory_reuse_type;

			res = ioctl(devs[i].scst_usr_fd, SCST_USER_SET_OPTIONS, &opt);
			if (res != 0) {
				res = errno;
				PRINT_ERROR("Unable to set options: %s", strerror(res));
				goto out_unreg;
			}
		}
#endif

		res = pthread_mutex_init(&devs[i].dev_mutex, NULL);
		if (res != 0) {
			res = errno;
			PRINT_ERROR("pthread_mutex_init() failed: %s", strerror(res));
			goto out_unreg;
		}

		for (j = 0; j < threads; j++) {
			rc = pthread_create(&thread[i][j], NULL, main_loop, &devs[i]);
			if (rc != 0) {
				res = errno;
				PRINT_ERROR("pthread_create() failed: %s",
					strerror(res));
				break;
			}
		}

		i++;
		num_devs++;
		if (num_devs >= MAX_VDEVS) {
			PRINT_INFO("Max devices limit %d reached", i);
			break;
		}
	}

	for (i = 0; i < num_devs; i++) {
		int j = 0;
		while (thread[i][j] != 0) {
			rc = pthread_join(thread[i][j], &rc1);
			if (rc != 0) {
				res = errno;
				PRINT_ERROR("pthread_join() failed: %s",
					strerror(res));
			} else if (rc1 != NULL) {
				res = (long)rc1;
				PRINT_INFO("Thread %d exited (dev %s), res %lx", j,
					devs[i].name, (long)rc1);
			} else
				PRINT_INFO("Thread %d exited (dev %s)", j,
					devs[i].name);
			j++;
		}
		pthread_mutex_destroy(&devs[i].dev_mutex);
	}

out_unreg:
	alarm(0);
	for (i = 0; i < num_devs; i++) {
		if (unreg_before_close) {
			res = ioctl(devs[i].scst_usr_fd, SCST_USER_UNREGISTER_DEVICE, NULL);
			if (res != 0) {
				res = errno;
				PRINT_ERROR("Unable to unregister device: %s",
					strerror(res));
				/* go through */
			}
		}
		close(devs[i].scst_usr_fd);
	}

	return res;
}
示例#10
0
int
simple_eval(char *const argv[], char *path, int timeout, int *ppid)
{
	pid_t pid;
	int status;
	int fd;
	int flags;
	int sig;
	int i;

	switch (pid = fork()) {
	case -1:	// error
		perror("fork");
		return errno;
	case 0:		// child
		// Reset signal handlers set for parent process
		for (sig = 0; sig < (_NSIG-1); sig++)
			signal(sig, SIG_DFL);

		// Clean up
		//ioctl(0, TIOCNOTTY, 0);
		//close(STDIN_FILENO);
		setsid();

		for (i=3; i<256; ++i)    // close un-needed fd
			close(i);

		// Redirect stdout to <path>
		if (path) {
			flags = O_WRONLY | O_CREAT;
			if (!strncmp(path, ">>", 2)) {
				// append to <path>
				flags |= O_APPEND;
				path += 2;
			} else if (!strncmp(path, ">", 1)) {
				// overwrite <path>
				flags |= O_TRUNC;
				path += 1;
			}
			if ((fd = open(path, flags, 0644)) < 0)
				perror(path);
			else {
				dup2(fd, STDOUT_FILENO);
				dup2(fd, STDERR_FILENO);
				close(fd);
			}
		}

		// execute command 
		dprintf("%s\n", argv[0]);
		setenv("PATH", "/sbin:/bin:/usr/sbin:/usr/bin", 1);
		alarm(timeout);
		execvp(argv[0], argv);
		perror(argv[0]);
		exit(errno);
	default:	// parent
		if (ppid) {
			*ppid = pid;
			return 0;
		} else {
			if (waitpid(pid, &status, 0) == -1) {
				perror("waitpid");
				return errno;
			}
			if (WIFEXITED(status))
				return WEXITSTATUS(status);
			else
				return status;
		}
	}
}
示例#11
0
int
_eval(char *const argv[], char *path, int timeout, int *ppid)
{
	sigset_t set;
	pid_t pid, ret;
	int status;
	int fd;
	int flags;
	int sig, i;

	switch (pid = fork()) {
	case -1:	/* error */
		perror("fork");
		return errno;
	case 0:	 /* child */
		/* Reset signal handlers set for parent process */
		for (sig = 0; sig < (_NSIG-1); sig++)
			signal(sig, SIG_DFL);

		/* Unblock signals if called from signal handler */
		sigemptyset(&set);
		sigprocmask(SIG_SETMASK, &set, NULL);

		/* Clean up */
		for (i=3; i<256; i++)    // close un-needed fd
			close(i);
		ioctl(0, TIOCNOTTY, 0);	// detach from current process
		setsid();
		
		/* Redirect stdout to <path> */
		if (path) {
			flags = O_WRONLY | O_CREAT;
			if (!strncmp(path, ">>", 2)) {
				/* append to <path> */
				flags |= O_APPEND;
				path += 2;
			} else if (!strncmp(path, ">", 1)) {
				/* overwrite <path> */
				flags |= O_TRUNC;
				path += 1;
			}
			if ((fd = open(path, flags, 0644)) < 0)
				perror(path);
			else {
				dup2(fd, STDOUT_FILENO);
				dup2(fd, STDERR_FILENO);
				close(fd);
			}
		}
		
		/* execute command */
		dprintf("%s\n", argv[0]);
		setenv("PATH", "/sbin:/bin:/usr/sbin:/usr/bin", 1);
		alarm(timeout);
		execvp(argv[0], argv);
		perror(argv[0]);
		exit(errno);
	default:	/* parent */
		if (ppid) {
			*ppid = pid;
			return 0;
		} else {
			do
				ret = waitpid(pid, &status, 0);
			while ((ret == -1) && (errno == EINTR));
			
			if (ret != pid) {
				perror("waitpid");
				return errno;
			}
			if (WIFEXITED(status))
				return WEXITSTATUS(status);
			else
				return status;
		}
	}
}
示例#12
0
int main(int argc, char *argv[]) {
    
    ///////////////*****SETUP****/////////////////
    int sock, port, nbytes, size, base;
    struct sockaddr_in serv_addr, client_addr;

    //initialize the alarm signal
    signal(SIGALRM, catch_alarm);
    
    if (argc < 5) {
         fprintf(stderr,"usage %s port CWind Pl Pc\n", argv[0]);
         exit(1);
    }

    int windowSize = atoi(argv[2]);
    struct packet packets[windowSize];
    int acks[windowSize];
    char fileName[DATA_SIZE];   
    int packetsSent = 0;

    int pCorrupt = atoi(argv[3]);
    int pLoss= atoi(argv[4]);

    sock = socket(AF_INET, SOCK_DGRAM, 0);

    //set socket to not block and set the buffer size
    int flags = fcntl(sock, F_GETFL);
    fcntl(sock, F_SETFL, flags | O_NONBLOCK);

    if (sock < 0) 
    error("ERROR opening socket");

    bzero((char *) &serv_addr, sizeof(serv_addr));
    port = atoi(argv[1]);
    serv_addr.sin_family = AF_INET;
    serv_addr.sin_addr.s_addr = INADDR_ANY;
    serv_addr.sin_port = htons(port);

    //bind the socket
    size = sizeof(serv_addr);
    if ( bind(sock, (struct sockaddr*) &serv_addr, (socklen_t) size) < 0) {
        error("bind error");
    }

    ///////////////*****HANDSHAKE****/////////////////
    //wait for connections
    struct packet handshake;

    fprintf (stderr, "waiting for message \n");

    size = sizeof(client_addr);
    while(1) {
        if( nbytes = recvfrom(sock, &handshake, DATAGRAM_SIZE, 0, 
                                (struct sockaddr *) &client_addr,
                                 &size) < 0)
        {
            if( errno == EWOULDBLOCK ) {
                continue;
            }
            error("recvfrom failed");
        }
        break;
    }

    //print diagnostic to console
    char addr[256];
    inet_ntop(AF_INET, &(client_addr.sin_addr), addr, INET_ADDRSTRLEN);

    fprintf (stderr, "Sender: got message: %s From: %s : %d\n", handshake.data, addr, client_addr.sin_port);
    dump(&handshake);

    //get the requested filename
    strcpy(fileName, handshake.data);
    
    //init connection by sending an ack   
    //seq stays the same 
    handshake.ack = 1;  
 
    size = sizeof(client_addr);
    while(1) {
        if( nbytes = sendto (sock, &handshake, DATAGRAM_SIZE, 0,
                        (struct sockaddr *) &client_addr , size) < 0)
        {
                if( errno == EWOULDBLOCK ) {
                    continue;
                }
                printf("error: %d\n", errno);
                error("sendto failed");

        }    
        break;
    }


    //print diagnostic to console
    inet_ntop(AF_INET, &(client_addr.sin_addr), addr, INET_ADDRSTRLEN); 
    printf ("Sender: Sent ack for : %d To: %s : %d  ", handshake.seq, addr, client_addr.sin_port);
    dump(&handshake);

    /////// FILE IO /////////
    // open file
    FILE * fd = fopen(fileName,"r");

    if (fd == NULL) // open failed 
    {
        error("failed open file"); 
    }

    ////////////initial window of packets////////////
    base = 1;
    int k;
    for(k = 0; k < windowSize; k++) {

        // get the next chunk of the file
        struct packet p;
        initPacket(&p);

        p.seq = k+1;
        p.size = fread(p.data, 1, DATA_SIZE, fd);
        printf ("Sender: size is %d\n", p.size);
        packets[k] = p;

        //send the packet
        size = sizeof(client_addr);
        while(1) {
            if( nbytes = sendto (sock, &packets[k], DATAGRAM_SIZE, 0,
                (struct sockaddr *) &client_addr , size) < 0)
            {
                if( errno == EWOULDBLOCK ) {
                    continue;
                }
                error("sendto failed");
            }
            break;
        }
        packetsSent++;

        //print diagnostic to console
        inet_ntop(AF_INET, &(client_addr.sin_addr), addr, INET_ADDRSTRLEN); 
        printf ("Sender: Sent datagram to: %s : %d :\n", addr, client_addr.sin_port);
        dump(&packets[k]);

        if(feof(fd) || ferror(fd) ) {
            //done reading file
            break;
        }

   }
   //start the timer
   setTimeout(TIMEOUT);


    ////////****** MAIN LOOP *********///////////
    // wait for acks
    // when we receive an ack, update the packet window and send out the new packets
    while(1) {
        if(timeout) {
            //we timed out, retransmit the window
            printf("packet timed out Seq: \n");
            int k;
            for(k = 0; k < windowSize; k++) {
                //send the packet
                size = sizeof(client_addr);
                while(1) {
                    if( nbytes = sendto (sock, &packets[k], DATAGRAM_SIZE, 0,
                        (struct sockaddr *) &client_addr , size) < 0)
                    {
                        if( errno == EWOULDBLOCK ) {
                            continue;
                        }
                        error("sendto failed");
                    }
                    break;
                }
            }
            setTimeout(TIMEOUT);
        }

        //if file is empty or done reading, terminate connection
        if(feof(fd)) {
        }

        struct packet ack;
        initPacket(&ack);

        //wait for packet
        size = sizeof(client_addr);
        if( nbytes = recvfrom(sock, &ack, DATAGRAM_SIZE, 0, 
                             (struct sockaddr *) &client_addr,
                             &size) < 0)
        {
            if( errno == EWOULDBLOCK ) {
                continue;
            }
            error("recvfrom failed");
        }

        if (prob(pCorrupt) || prob(pLoss)) {
            fprintf(stderr, "packet was corrupted or lost\n");
            continue;
        }

        char addr[256];
        inet_ntop(AF_INET, &(client_addr.sin_addr), addr, INET_ADDRSTRLEN);
        
        /////********* PACKET IS ACK *********////
        if( ack.ack == 1)
        {
            fprintf (stderr, "Sender: got ack From: %s : %d\n", addr, client_addr.sin_port);
            dump(&ack);
            
            if( feof(fd) && ack.seq == packetsSent) {
                fclose(fd);
                struct packet terminate;
                initPacket(&terminate);
                terminate.fin = 1;
                //send the packet
                size = sizeof(client_addr);
                while(1) {    
                    if( nbytes = sendto (sock, &terminate, DATAGRAM_SIZE, 0,
                            (struct sockaddr *) &client_addr , size) < 0)
                    {
                        if( errno == EWOULDBLOCK ) {
                            continue;
                        }
                        error("sendto failed");
                    }
                    break;
                }
                //print diagnostic to console
                inet_ntop(AF_INET, &(client_addr.sin_addr), addr, INET_ADDRSTRLEN); 
                printf ("Sender: Sent termination: To: %s : %d \n", addr, client_addr.sin_port);
                dump(&terminate);
                break;
            }        

            // update the packets in the window and send new packets
            if(base <= ack.seq) {
                //stop the timeout alarm
                alarm(0);

                for(k=0; k < windowSize; k++) {
                    if(packets[k].seq <= ack.seq ) {
                        if(feof(fd) || ferror(fd) ) {
                            //done reading file
                            printf("done reading file\n");
                            break;
                        }

                        //get the next packet
                        struct packet p;
                        p.seq = base + windowSize;
                        //read the next chunk from the file
                        p.size = fread(p.data, 1, DATA_SIZE, fd);
                        packets[k] = p;

                        //send the packet
                        size = sizeof(client_addr);
                        while(1) {
                            if( nbytes = sendto (sock, &packets[k], DATAGRAM_SIZE, 0, (struct sockaddr *) &client_addr , size) < 0)
                            {
                                if( errno == EWOULDBLOCK ) {
                                    continue;
                                }
                                error("sendto failed");
                            }
                            break;
                        }
                        packetsSent++;

                        //print diagnostic to console
                        inet_ntop(AF_INET, &(client_addr.sin_addr), addr, INET_ADDRSTRLEN); 
                        printf ("Sender: Sent datagram To: %s : %d \n", addr, client_addr.sin_port);
                        dump(&packets[k]);

                        base++;
                    }
                }
                //reset the timer
                setTimeout(TIMEOUT);
            }


        }
        else
        {
            fprintf (stderr, "Sender: message wasn't an ack From: %s : %d\n", addr, client_addr.sin_port);
            dump(&ack);
        }
    
    }

}
示例#13
0
int main(int argc, char **argv)
{
    long count;
    static unsigned char buf[BUFSIZE];
    static DES_cblock key = {0x12,0x34,0x56,0x78,0x9a,0xbc,0xde,0xf0};
    static DES_cblock key2= {0x34,0x56,0x78,0x9a,0xbc,0xde,0xf0,0x12};
    static DES_cblock key3= {0x56,0x78,0x9a,0xbc,0xde,0xf0,0x12,0x34};
    DES_key_schedule sch,sch2,sch3;
    double d,tm[16],max=0;
    int rank[16];
    char *str[16];
    int max_idx=0,i,num=0,j;
#ifndef SIGALARM
    long ca,cb,cc,cd,ce;
#endif

    for (i=0; i<12; i++)
    {
        tm[i]=0.0;
        rank[i]=0;
    }

#ifndef TIMES
    fprintf(stderr,"To get the most accurate results, try to run this\n");
    fprintf(stderr,"program when this computer is idle.\n");
#endif

    DES_set_key_unchecked(&key,&sch);
    DES_set_key_unchecked(&key2,&sch2);
    DES_set_key_unchecked(&key3,&sch3);

#ifndef SIGALRM
    fprintf(stderr,"First we calculate the approximate speed ...\n");
    DES_set_key_unchecked(&key,sch);
    count=10;
    do	{
        long i;
        unsigned long data[2];

        count*=2;
        Time_F(START);
        for (i=count; i; i--)
            DES_encrypt1(data,&(sch[0]),DES_ENCRYPT);
        d=Time_F(STOP);
    } while (d < 3.0);
    ca=count;
    cb=count*3;
    cc=count*3*8/BUFSIZE+1;
    cd=count*8/BUFSIZE+1;

    ce=count/20+1;
#define COND(d) (count != (d))
#define COUNT(d) (d)
#else
#define COND(c) (run)
#define COUNT(d) (count)
    signal(SIGALRM,sig_done);
    alarm(10);
#endif

#ifdef PART1
    time_it(des_encrypt_u4_cisc_idx,  "des_encrypt_u4_cisc_idx  ", 0);
    time_it(des_encrypt_u16_cisc_idx, "des_encrypt_u16_cisc_idx ", 1);
    time_it(des_encrypt_u4_risc1_idx, "des_encrypt_u4_risc1_idx ", 2);
    num+=3;
#endif
#ifdef PART2
    time_it(des_encrypt_u16_risc1_idx,"des_encrypt_u16_risc1_idx", 3);
    time_it(des_encrypt_u4_risc2_idx, "des_encrypt_u4_risc2_idx ", 4);
    time_it(des_encrypt_u16_risc2_idx,"des_encrypt_u16_risc2_idx", 5);
    num+=3;
#endif
#ifdef PART3
    time_it(des_encrypt_u4_cisc_ptr,  "des_encrypt_u4_cisc_ptr  ", 6);
    time_it(des_encrypt_u16_cisc_ptr, "des_encrypt_u16_cisc_ptr ", 7);
    time_it(des_encrypt_u4_risc1_ptr, "des_encrypt_u4_risc1_ptr ", 8);
    num+=3;
#endif
#ifdef PART4
    time_it(des_encrypt_u16_risc1_ptr,"des_encrypt_u16_risc1_ptr", 9);
    time_it(des_encrypt_u4_risc2_ptr, "des_encrypt_u4_risc2_ptr ",10);
    time_it(des_encrypt_u16_risc2_ptr,"des_encrypt_u16_risc2_ptr",11);
    num+=3;
#endif

#ifdef PART1
    str[0]=" 4  c i";
    print_it("des_encrypt_u4_cisc_idx  ",0);
    max=tm[0];
    max_idx=0;
    str[1]="16  c i";
    print_it("des_encrypt_u16_cisc_idx ",1);
    if (max < tm[1]) {
        max=tm[1];
        max_idx=1;
    }
    str[2]=" 4 r1 i";
    print_it("des_encrypt_u4_risc1_idx ",2);
    if (max < tm[2]) {
        max=tm[2];
        max_idx=2;
    }
#endif
#ifdef PART2
    str[3]="16 r1 i";
    print_it("des_encrypt_u16_risc1_idx",3);
    if (max < tm[3]) {
        max=tm[3];
        max_idx=3;
    }
    str[4]=" 4 r2 i";
    print_it("des_encrypt_u4_risc2_idx ",4);
    if (max < tm[4]) {
        max=tm[4];
        max_idx=4;
    }
    str[5]="16 r2 i";
    print_it("des_encrypt_u16_risc2_idx",5);
    if (max < tm[5]) {
        max=tm[5];
        max_idx=5;
    }
#endif
#ifdef PART3
    str[6]=" 4  c p";
    print_it("des_encrypt_u4_cisc_ptr  ",6);
    if (max < tm[6]) {
        max=tm[6];
        max_idx=6;
    }
    str[7]="16  c p";
    print_it("des_encrypt_u16_cisc_ptr ",7);
    if (max < tm[7]) {
        max=tm[7];
        max_idx=7;
    }
    str[8]=" 4 r1 p";
    print_it("des_encrypt_u4_risc1_ptr ",8);
    if (max < tm[8]) {
        max=tm[8];
        max_idx=8;
    }
#endif
#ifdef PART4
    str[9]="16 r1 p";
    print_it("des_encrypt_u16_risc1_ptr",9);
    if (max < tm[9]) {
        max=tm[9];
        max_idx=9;
    }
    str[10]=" 4 r2 p";
    print_it("des_encrypt_u4_risc2_ptr ",10);
    if (max < tm[10]) {
        max=tm[10];
        max_idx=10;
    }
    str[11]="16 r2 p";
    print_it("des_encrypt_u16_risc2_ptr",11);
    if (max < tm[11]) {
        max=tm[11];
        max_idx=11;
    }
#endif
    printf("options    des ecb/s\n");
    printf("%s %12.2f 100.0%%\n",str[max_idx],tm[max_idx]);
    d=tm[max_idx];
    tm[max_idx]= -2.0;
    max= -1.0;
    for (;;)
    {
        for (i=0; i<12; i++)
        {
            if (max < tm[i]) {
                max=tm[i];
                j=i;
            }
        }
        if (max < 0.0) break;
        printf("%s %12.2f  %4.1f%%\n",str[j],tm[j],tm[j]/d*100.0);
        tm[j]= -2.0;
        max= -1.0;
    }

    switch (max_idx)
    {
    case 0:
        printf("-DDES_DEFAULT_OPTIONS\n");
        break;
    case 1:
        printf("-DDES_UNROLL\n");
        break;
    case 2:
        printf("-DDES_RISC1\n");
        break;
    case 3:
        printf("-DDES_UNROLL -DDES_RISC1\n");
        break;
    case 4:
        printf("-DDES_RISC2\n");
        break;
    case 5:
        printf("-DDES_UNROLL -DDES_RISC2\n");
        break;
    case 6:
        printf("-DDES_PTR\n");
        break;
    case 7:
        printf("-DDES_UNROLL -DDES_PTR\n");
        break;
    case 8:
        printf("-DDES_RISC1 -DDES_PTR\n");
        break;
    case 9:
        printf("-DDES_UNROLL -DDES_RISC1 -DDES_PTR\n");
        break;
    case 10:
        printf("-DDES_RISC2 -DDES_PTR\n");
        break;
    case 11:
        printf("-DDES_UNROLL -DDES_RISC2 -DDES_PTR\n");
        break;
    }
    exit(0);
#if defined(LINT) || defined(OPENSSL_SYS_MSDOS)
    return(0);
#endif
}
void daemonize()
{
    pid_t pid, sid, parent;

    char *lockfile;

    lockfile = "/var/lock/subsys/" DAEMON_NAME;

    openlog(DAEMON_NAME, LOG_PID, LOG_LOCAL5);

    /* already a daemon */
    if ( getppid() == 1 ) return;

    /* Create the lock file as the current user */
/*
    if ( lockfile && lockfile[0] ) {
        lfp = open(lockfile,O_RDWR|O_CREAT,0660);
        if ( lfp < 0 ) {
            fprintf(stderr,"Unable to create lock file %s\n", lockfile);
            syslog( LOG_ERR, "unable to create lock file %s, code=%d (%s)",
                    lockfile, errno, strerror(errno) );
            exit(EXIT_FAILURE);
        }
    }
*/

    /* Drop user if there is one, and we were run as root */
    if ( getuid() == 0 || geteuid() == 0 ) {
        struct passwd *pw = getpwnam(RUN_AS_USER);
        if ( pw ) {
            syslog( LOG_NOTICE, "setting user to " RUN_AS_USER );
            setuid( pw->pw_uid );
        }
    }

    /* Trap signals that we expect to recieve */
    signal(SIGCHLD,child_handler);
    signal(SIGUSR1,child_handler);
    signal(SIGALRM,child_handler);

    /* Fork off the parent process */
    pid = fork();
    if (pid < 0) {
        syslog( LOG_ERR, "unable to fork daemon, code=%d (%s)",
                errno, strerror(errno) );
        exit(EXIT_FAILURE);
    }
    /* If we got a good PID, then we can exit the parent process. */
    if (pid > 0) {

        /* Wait for confirmation from the child via SIGTERM or SIGCHLD, or
           for two seconds to elapse (SIGALRM).  pause() should not return. */
        alarm(2);
        pause();

        exit(EXIT_FAILURE);
    }

    /* At this point we are executing as the child process */
    parent = getppid();

    syslog(LOG_INFO, "Starting daemon " DAEMON_NAME);

    /* Cancel certain signals */
    signal(SIGCHLD,SIG_DFL); /* A child process dies */
    signal(SIGTSTP,SIG_IGN); /* Various TTY signals */
    signal(SIGTTOU,SIG_IGN);
    signal(SIGTTIN,SIG_IGN);
    signal(SIGHUP, SIG_IGN); /* Ignore hangup signal */
    signal(SIGTERM,sigterm_handler); /* Die on SIGTERM */

    /* Change the file mode mask */
    umask(0);

    /* Create a new SID for the child process */
    sid = setsid();
    if (sid < 0) {
        syslog( LOG_ERR, "unable to create a new session, code %d (%s)",
                errno, strerror(errno) );
        exit(EXIT_FAILURE);
    }

    /* Change the current working directory.  This prevents the current
       directory from being locked; hence not being able to remove it. */
    if ((chdir("/")) < 0) {
        syslog( LOG_ERR, "unable to change directory to %s, code %d (%s)",
                "/", errno, strerror(errno) );
        exit(EXIT_FAILURE);
    }

/*
    // write our pid to /var/run/DAEMON_NAME.pid 
    pid_filename = "/var/run/" DAEMON_NAME ".pid";
    pid_file = fopen(pid_filename, "w");
    if (pid_file != NULL)
    {
      fprintf(pid_file, "%d\n", getpid());
    } else {
      syslog (LOG_ERR, "Unable to create pid file %s %d %s", pid_filename,
                errno, strerror(errno));
    }
*/

    /* Redirect standard files to /dev/null */
    freopen( "/dev/null", "r", stdin);
    freopen( "/dev/null", "w", stdout);
    freopen( "/var/tmp/" DAEMON_NAME, "w", stderr);
    chmod( "/var/tmp/" DAEMON_NAME, 0660);

    /* Tell the parent process that we are A-okay */
    kill( parent, SIGUSR1 );
} // daemonize()
示例#15
0
文件: types.c 项目: 4144/sxhkd
hotkey_t *find_hotkey(xcb_keysym_t keysym, xcb_button_t button, uint16_t modfield, uint8_t event_type, bool *replay_event)
{
	int num_active = 0;
	hotkey_t *result = NULL;

	for (hotkey_t *hk = hotkeys_head; hk != NULL; hk = hk->next) {
		chain_t *c = hk->chain;
		if (chained && c->state == c->head)
			continue;
		if (match_chord(c->state, event_type, keysym, button, modfield)) {
			if (status_fifo != NULL && num_active == 0) {
				if (!chained) {
					snprintf(progress, sizeof(progress), "%s", c->state->repr);
				} else {
					strncat(progress, LNK_SEP, sizeof(progress) - strlen(progress) - 1);
					strncat(progress, c->state->repr, sizeof(progress) - strlen(progress) - 1);
				}
				put_status(HOTKEY_PREFIX, progress);
			}
			if (replay_event != NULL && c->state->replay_event)
				*replay_event = true;
			if (!locked && c->state->lock_chain) {
				locked = true;
				if (timeout > 0)
					alarm(0);
			}
			if (c->state == c->tail) {
				if (hk->cycle != NULL) {
					unsigned char delay = hk->cycle->delay;
					hk->cycle->delay = (delay == 0 ? hk->cycle->period - 1 : delay - 1);
					if (delay == 0)
						result = hk;
					continue;
				}
				if (chained && !locked)
					abort_chain();
				return hk;
			} else {
				c->state = c->state->next;
				num_active++;
				grab_chord(c->state);
			}
		} else if (chained) {
			if (!locked && c->state->event_type == event_type)
				c->state = c->head;
			else
				num_active++;
		}
	}

	if (result != NULL)
		return result;

	if (!chained) {
		if (num_active > 0) {
			chained = true;
			grab_chord(escape_chord);
		}
	} else if (num_active == 0 || match_chord(escape_chord, event_type, keysym, button, modfield)) {
		abort_chain();
		return find_hotkey(keysym, button, modfield, event_type, replay_event);
	}
	if (chained && !locked && timeout > 0)
		alarm(timeout);
	PRINTF("num active %i\n", num_active);

	return NULL;
}
示例#16
0
文件: fileio.c 项目: Difrex/OpenSAN2
int main(int argc, char **argv)
{
	int res = 0;
	int ch, longindex;
	struct sigaction act;

	setlinebuf(stdout);

	res = debug_init();
	if (res != 0)
		goto out;

	app_name = argv[0];

	memset(devs, 0, sizeof(devs));

	while ((ch = getopt_long(argc, argv, "+b:e:trongluF:I:cp:f:m:d:vsS:P:hDR:Z:",
			long_options, &longindex)) >= 0) {
		switch (ch) {
		case 'b':
			block_size = atoi(optarg);
			PRINT_INFO("block_size %x (%s)", block_size, optarg);
			block_shift = scst_calc_block_shift(block_size);
			if (block_shift < 9) {
				res = -EINVAL;
				goto out_usage;
			}
			break;
		case 'e':
			threads = strtol(optarg, (char **)NULL, 0);
			break;
		case 't':
			wt_flag = 1;
			break;
#if defined(DEBUG) || defined(TRACING)
		case 'd':
			trace_flag = strtol(optarg, (char **)NULL, 0);
			break;
#endif
		case 'r':
			rd_only_flag = 1;
			break;
		case 'o':
			o_direct_flag = 1;
			break;
		case 'n':
			nullio = 1;
			break;
		case 'c':
			nv_cache = 1;
			break;
		case 'p':
			if (strncmp(optarg, "std", 3) == 0)
				parse_type = SCST_USER_PARSE_STANDARD;
			else if (strncmp(optarg, "call", 3) == 0)
				parse_type = SCST_USER_PARSE_CALL;
			else if (strncmp(optarg, "excpt", 5) == 0)
				parse_type = SCST_USER_PARSE_EXCEPTION;
			else
				goto out_usage;
			break;
		case 'f':
			on_free_cmd_type_set = 1;
			if (strncmp(optarg, "ignore", 6) == 0)
				on_free_cmd_type = SCST_USER_ON_FREE_CMD_IGNORE;
			else if (strncmp(optarg, "call", 3) == 0)
				on_free_cmd_type = SCST_USER_ON_FREE_CMD_CALL;
			else
				goto out_usage;
			break;
		case 's':
			sgv_shared = 1;
			break;
		case 'S':
			sgv_single_alloc_pages = atoi(optarg);
			break;
		case 'P':
			sgv_purge_interval = atoi(optarg);
			break;
		case 'D':
			sgv_disable_clustered_pool = 1;
			break;
		case 'R':
			prealloc_buffers_num = atoi(optarg);
			break;
		case 'Z':
			prealloc_buffer_size = atoi(optarg) * 1024;
			break;
		case 'm':
			if (strncmp(optarg, "all", 3) == 0)
				memory_reuse_type = SCST_USER_MEM_REUSE_ALL;
			else if (strncmp(optarg, "read", 4) == 0)
				memory_reuse_type = SCST_USER_MEM_REUSE_READ;
			else if (strncmp(optarg, "write", 5) == 0)
				memory_reuse_type = SCST_USER_MEM_REUSE_WRITE;
			else if (strncmp(optarg, "none", 4) == 0)
				memory_reuse_type = SCST_USER_MEM_NO_REUSE;
			else
				goto out_usage;
			break;
		case 'l':
			non_blocking = 1;
			break;
		case 'I':
			vdisk_ID = strtol(optarg, (char **)NULL, 0);
			break;
		case 'F':
			flush_interval = strtol(optarg, (char **)NULL, 0);
			if (flush_interval < 0) {
				PRINT_ERROR("Wrong flush interval %d",
					flush_interval);
				flush_interval = 0;
			}
			break;
		case 'u':
			unreg_before_close = 1;
			break;
#if defined(DEBUG_TM_IGNORE) || defined(DEBUG_TM_IGNORE_ALL)
		case 'g':
			debug_tm_ignore = 1;
			break;
#endif
		case 'v':
			printf("%s version %s\n", app_name, VERSION_STR);
			goto out_done;
		default:
			goto out_usage;
		}
	}

	if (optind > (argc-2))
		goto out_usage;

	if (!on_free_cmd_type_set &&
	    (memory_reuse_type != SCST_USER_MEM_REUSE_ALL))
		on_free_cmd_type = SCST_USER_ON_FREE_CMD_CALL;

	PRINT_INFO("%s", "Options:");

	if (rd_only_flag)
		PRINT_INFO("	%s", "READ ONLY");
	if (wt_flag)
		PRINT_INFO("	%s", "WRITE THROUGH");
	if (nv_cache)
		PRINT_INFO("	%s", "NV_CACHE");
	if (o_direct_flag)
		PRINT_INFO("	%s", "O_DIRECT");
	if (nullio)
		PRINT_INFO("	%s", "NULLIO");
	if (non_blocking)
		PRINT_INFO("	%s", "NON-BLOCKING");

	switch(parse_type) {
	case SCST_USER_PARSE_STANDARD:
		PRINT_INFO("	%s", "Standard parse");
		break;
	case SCST_USER_PARSE_CALL:
		PRINT_INFO("	%s", "Call parse");
		break;
	case SCST_USER_PARSE_EXCEPTION:
		PRINT_INFO("	%s", "Exception parse");
		break;
	default:
		sBUG();
	}

	switch(on_free_cmd_type) {
	case SCST_USER_ON_FREE_CMD_IGNORE:
		PRINT_INFO("	%s", "Ignore on_free_cmd");
		break;
	case SCST_USER_ON_FREE_CMD_CALL:
		PRINT_INFO("	%s", "Call on_free_cmd");
		break;
	default:
		sBUG();
	}

	switch(memory_reuse_type) {
	case SCST_USER_MEM_REUSE_ALL:
		PRINT_INFO("	%s", "Full memory reuse enabled");
		break;
	case SCST_USER_MEM_REUSE_READ:
		PRINT_INFO("	%s", "READ memory reuse enabled");
		break;
	case SCST_USER_MEM_REUSE_WRITE:
		PRINT_INFO("	%s", "WRITE memory reuse enabled");
		break;
	case SCST_USER_MEM_NO_REUSE:
		PRINT_INFO("	%s", "Memory reuse disabled");
		break;
	default:
		sBUG();
	}

	if (sgv_shared)
		PRINT_INFO("	%s", "SGV shared");

	if (sgv_single_alloc_pages != 0)
		PRINT_INFO("	Use single entry SGV cache with %d pages/entry",
			sgv_single_alloc_pages);

	if (sgv_purge_interval != 0) {
		if (sgv_purge_interval > 0)
			PRINT_INFO("	Use SGV cache purge interval %d seconds",
				sgv_purge_interval);
		else
			PRINT_INFO("	%s", "SGV cache purging disabled");
	}

	if (sgv_disable_clustered_pool)
		PRINT_INFO("	%s", "Disable clustered SGV pool");

	if ((prealloc_buffers_num > 0) && (prealloc_buffer_size > 0))
		PRINT_INFO("	Prealloc %d buffers of %dKB",
			prealloc_buffers_num, prealloc_buffer_size / 1024);

	if (!o_direct_flag && (memory_reuse_type == SCST_USER_MEM_NO_REUSE)) {
		PRINT_INFO("	%s", "Using unaligned buffers");
		alloc_fn = malloc;
	}

#if defined(DEBUG_TM_IGNORE) || defined(DEBUG_TM_IGNORE_ALL)
	if (debug_tm_ignore)
		PRINT_INFO("	%s", "DEBUG_TM_IGNORE");
#endif

#ifdef DEBUG
	PRINT_INFO("trace_flag %lx", trace_flag);
#endif

	memset(&act, 0, sizeof(act));
	act.sa_handler = sigusr1_handler;
	act.sa_flags = SA_RESTART;
	sigemptyset(&act.sa_mask);
	res = sigaction(SIGUSR1, &act, NULL);
	if (res != 0) {
		res = errno;
		PRINT_ERROR("sigaction() failed: %s",
			strerror(res));
		/* don't do anything */
	}

	if (flush_interval != 0) {
		memset(&act, 0, sizeof(act));
		act.sa_handler = sigalrm_handler;
		act.sa_flags = SA_RESTART;
		sigemptyset(&act.sa_mask);
		res = sigaction(SIGALRM, &act, NULL);
		if (res != 0) {
			res = errno;
			PRINT_ERROR("sigaction() failed: %s",
				strerror(res));
			goto out_done;
		}       

		res = alarm(flush_interval);
		if (res != 0) {
			res = errno;
			PRINT_ERROR("alarm() failed: %s",
				strerror(res));
			goto out_done;
		}
	}

	res = start(argc, argv);

out_done:
	debug_done();

out:
	return res;

out_usage:
	usage();
	goto out_done;
}
示例#17
0
文件: 1-1.c 项目: Mellanox/arc_ltp
int main()
{
	int cnt = 0;
	int rc;
	pthread_t child_thread;
	struct sigaction act;

	/* Set up main thread to handle SIGALRM */
	act.sa_flags = 0;
	act.sa_handler = sig_handler;
	sigfillset(&act.sa_mask);
	sigaction(SIGALRM, &act, 0);

	printf("Initialize barrier with count = 2\n");
	if (pthread_barrier_init(&barrier, NULL, 2) != 0)
	{
		printf("main: Error at pthread_barrier_init()\n");
		return PTS_UNRESOLVED;
	}

	printf("main: create child thread\n");
	thread_state = NOT_CREATED_THREAD;
	if (pthread_create(&child_thread, NULL, fn_chld, NULL) != 0)
	{
		printf("main: Error at pthread_create()\n");
		return PTS_UNRESOLVED;
	}

	/* Expect the child to block*/
	cnt = 0;
	do{
		sleep(1);
	}while (thread_state !=EXITING_THREAD && cnt++ < 2);

	if (thread_state == EXITING_THREAD)
	{
		/* child thread did not block */
		printf("Test FAILED: child thread did not block on "
			"pthread_barrier_wait()\n");
		exit(PTS_FAIL);
	}
	else if (thread_state != ENTERED_THREAD)
	{
		printf("Unexpected thread state: %d\n", thread_state);
		exit(PTS_UNRESOLVED);
	}

	printf("main: call barrier wait\n");

	/* we should not block here, but just in case we do */
	alarm(2);

	rc = pthread_barrier_wait(&barrier);

	if (rc != 0 && rc != PTHREAD_BARRIER_SERIAL_THREAD)
	{
		printf("Test FAILED: main: pthread_barrier_wait() get unexpected "
			"return code : %d\n" , rc);
		exit(PTS_FAIL);
	}
	else if (rc == PTHREAD_BARRIER_SERIAL_THREAD)
	{
		printf("main: got PTHREAD_BARRIER_SERIAL_THREAD\n");
	}

	/* We expected the child returned from barrier wait */
	cnt = 1;
	do{
		sleep(1);
	}while (thread_state != EXITING_THREAD && cnt++ < 3);

	if (thread_state == ENTERED_THREAD)
	{
		printf("Test FAILED: child thread still blocked on "
			"barrier wait\n");
		return PTS_FAIL;
	}
	else if (thread_state != EXITING_THREAD)
	{
		printf("main: Unexpected thread state: %d\n", thread_state);
		return PTS_UNRESOLVED;
	}

	if (pthread_join(child_thread, NULL) != 0)
	{
		printf("main: Error at pthread_join()\n");
		exit(PTS_UNRESOLVED);
	}

	if (pthread_barrier_destroy(&barrier) != 0)
	{
		printf("Error at pthread_barrier_destroy()");
		return PTS_UNRESOLVED;
	}

	printf("Test PASSED\n");
	return PTS_PASS;
}
int main (int argc, char **argv) {
    /* Local Vars */
    int status;
    char *clustername = NULL;
    long int clusterstatus = 255;
    char *clusterstatusdesc = NULL;
    long int clustervotes = 0;
    long int clusterquorum = 0;
    long int clusternodes = 0;
    netsnmp_session *ss;

    /* OIDs to query */
    mp_snmp_query_cmd snmpcmd[] = {
        {{1,3,6,1,4,1,2312,8,2,1,0}, 11,
            ASN_OCTET_STR, (void *)&clustername, 0},
        {{1,3,6,1,4,1,2312,8,2,2,0}, 11,
            ASN_INTEGER, (void *)&clusterstatus, sizeof(long int)},
        {{1,3,6,1,4,1,2312,8,2,3,0}, 11,
            ASN_OCTET_STR, (void *)&clusterstatusdesc, 0},
        {{1,3,6,1,4,1,2312,8,2,5,0}, 11,
            ASN_INTEGER, (void *)&clustervotes, sizeof(long int)},
        {{1,3,6,1,4,1,2312,8,2,4,0}, 11,
            ASN_INTEGER, (void *)&clusterquorum, sizeof(long int)},
        {{1,3,6,1,4,1,2312,8,2,7,0}, 11,
            ASN_INTEGER, (void *)&clusternodes, sizeof(long int)},
        {{0}, 0, 0, 0},
    };

    /* Set signal handling and alarm */
    if (signal(SIGALRM, timeout_alarm_handler) == SIG_ERR)
        critical("Setup SIGALRM trap failed!");

    /* Process check arguments */
    if (process_arguments(argc, argv) != OK)
        unknown("Parsing arguments failed!");

    /* Start plugin timeout */
    alarm(mp_timeout);

    /* Init Net-SNMP */
    ss = mp_snmp_init();

    /* Query target agent */
    status = mp_snmp_query(ss, snmpcmd);
    switch (status) {
        case STAT_ERROR:
            unknown("Error in libnetsnmp");
            break;
        case STAT_TIMEOUT:
            critical("Timeout in libnetsnmp");
            break;
    }

    /* Finish Net-SNMP */
    mp_snmp_deinit();

    if (!clustername || clusterstatus == 255)
        unknown("No Cluster Status found");

    /* Perfdata */
    if (mp_showperfdata)
        mp_perfdata_int3("votes", clustervotes, "", 1, clusterquorum, 1,
                         clusterquorum-1, 1, 0, 1, clusternodes);

    /* Output and return */
    if (clusterstatus < 2)
        ok("%s [%s]", clustername, clusterstatusdesc);
    if (clusterstatus < 16)
        warning("%s [%s]", clustername, clusterstatusdesc);
    critical("%s [%s]", clustername, clusterstatusdesc);
}
示例#19
0
static cairo_test_status_t
cairo_test_for_target (cairo_test_context_t		 *ctx,
		       const cairo_boilerplate_target_t	 *target,
		       int				  dev_offset,
		       int				  dev_scale,
		       cairo_bool_t                       similar)
{
    cairo_test_status_t status;
    cairo_surface_t *surface = NULL;
    cairo_t *cr;
    const char *empty_str = "";
    char *offset_str;
    char *scale_str;
    char *base_name, *base_path;
    char *out_png_path;
    char *ref_path = NULL, *ref_png_path, *cmp_png_path = NULL;
    char *new_path = NULL, *new_png_path;
    char *xfail_path = NULL, *xfail_png_path;
    char *base_ref_png_path;
    char *base_new_png_path;
    char *base_xfail_png_path;
    char *diff_png_path;
    char *test_filename = NULL, *pass_filename = NULL, *fail_filename = NULL;
    cairo_test_status_t ret;
    cairo_content_t expected_content;
    cairo_font_options_t *font_options;
    const char *format;
    cairo_bool_t have_output = FALSE;
    cairo_bool_t have_result = FALSE;
    void *closure;
    double width, height;
    cairo_bool_t have_output_dir;
#if HAVE_MEMFAULT
    int malloc_failure_iterations = ctx->malloc_failure;
    int last_fault_count = 0;
#endif

    /* Get the strings ready that we'll need. */
    format = cairo_boilerplate_content_name (target->content);
    if (dev_offset)
	xasprintf (&offset_str, ".%d", dev_offset);
    else
	offset_str = (char *) empty_str;

    if (dev_scale != 1)
	xasprintf (&scale_str, ".x%d", dev_scale);
    else
	scale_str = (char *) empty_str;

    xasprintf (&base_name, "%s.%s.%s%s%s%s",
	       ctx->test_name,
	       target->name,
	       format,
	       similar ? ".similar" : "",
	       offset_str,
               scale_str);

    if (offset_str != empty_str)
      free (offset_str);
    if (scale_str != empty_str)
      free (scale_str);

    ref_png_path = cairo_test_reference_filename (ctx,
						  base_name,
						  ctx->test_name,
						  target->name,
						  target->basename,
						  format,
						  CAIRO_TEST_REF_SUFFIX,
						  CAIRO_TEST_PNG_EXTENSION);
    new_png_path = cairo_test_reference_filename (ctx,
						  base_name,
						  ctx->test_name,
						  target->name,
						  target->basename,
						  format,
						  CAIRO_TEST_NEW_SUFFIX,
						  CAIRO_TEST_PNG_EXTENSION);
    xfail_png_path = cairo_test_reference_filename (ctx,
						    base_name,
						    ctx->test_name,
						    target->name,
						    target->basename,
						    format,
						    CAIRO_TEST_XFAIL_SUFFIX,
						    CAIRO_TEST_PNG_EXTENSION);

    base_ref_png_path = cairo_test_reference_filename (ctx,
						  base_name,
						  ctx->test_name,
						  NULL, NULL,
						  format,
						  CAIRO_TEST_REF_SUFFIX,
						  CAIRO_TEST_PNG_EXTENSION);
    base_new_png_path = cairo_test_reference_filename (ctx,
						  base_name,
						  ctx->test_name,
						  NULL, NULL,
						  format,
						  CAIRO_TEST_NEW_SUFFIX,
						  CAIRO_TEST_PNG_EXTENSION);
    base_xfail_png_path = cairo_test_reference_filename (ctx,
						    base_name,
						    ctx->test_name,
						    NULL, NULL,
						    format,
						    CAIRO_TEST_XFAIL_SUFFIX,
						    CAIRO_TEST_PNG_EXTENSION);

    if (target->file_extension != NULL) {
	ref_path = cairo_test_reference_filename (ctx,
						  base_name,
						  ctx->test_name,
						  target->name,
						  target->basename,
						  format,
						  CAIRO_TEST_REF_SUFFIX,
						  target->file_extension);
	new_path = cairo_test_reference_filename (ctx,
						  base_name,
						  ctx->test_name,
						  target->name,
						  target->basename,
						  format,
						  CAIRO_TEST_NEW_SUFFIX,
						  target->file_extension);
	xfail_path = cairo_test_reference_filename (ctx,
						    base_name,
						    ctx->test_name,
						    target->name,
						    target->basename,
						    format,
						    CAIRO_TEST_XFAIL_SUFFIX,
						    target->file_extension);
    }

    have_output_dir = cairo_test_mkdir (ctx->output);
    xasprintf (&base_path, "%s/%s",
	       have_output_dir ? ctx->output : ".",
	       base_name);
    xasprintf (&out_png_path, "%s" CAIRO_TEST_OUT_PNG, base_path);
    xasprintf (&diff_png_path, "%s" CAIRO_TEST_DIFF_PNG, base_path);

    if (ctx->test->requirements != NULL) {
	const char *required;

	required = target->is_vector ? "target=raster" : "target=vector";
	if (strstr (ctx->test->requirements, required) != NULL) {
	    cairo_test_log (ctx, "Error: Skipping for %s target %s\n",
			    target->is_vector ? "vector" : "raster",
			    target->name);
	    ret = CAIRO_TEST_UNTESTED;
	    goto UNWIND_STRINGS;
	}

	required = target->is_recording ? "target=!recording" : "target=recording";
	if (strstr (ctx->test->requirements, required) != NULL) {
	    cairo_test_log (ctx, "Error: Skipping for %s target %s\n",
			    target->is_recording ? "recording" : "non-recording",
			    target->name);
	    ret = CAIRO_TEST_UNTESTED;
	    goto UNWIND_STRINGS;
	}
    }

    width = ctx->test->width;
    height = ctx->test->height;
    if (width && height) {
	width *= dev_scale;
	height *= dev_scale;
	width += dev_offset;
	height += dev_offset;
    }

#if HAVE_MEMFAULT
REPEAT:
    MEMFAULT_CLEAR_FAULTS ();
    MEMFAULT_RESET_LEAKS ();
    ctx->last_fault_count = 0;
    last_fault_count = MEMFAULT_COUNT_FAULTS ();

    /* Pre-initialise fontconfig so that the configuration is loaded without
     * malloc failures (our primary goal is to test cairo fault tolerance).
     */
#if HAVE_FCINIT
    FcInit ();
#endif

    MEMFAULT_ENABLE_FAULTS ();
#endif
    have_output = FALSE;
    have_result = FALSE;

    /* Run the actual drawing code. */
    ret = CAIRO_TEST_SUCCESS;
    surface = (target->create_surface) (base_path,
					target->content,
					width, height,
					ctx->test->width * NUM_DEVICE_SCALE + 25 * NUM_DEVICE_OFFSETS,
					ctx->test->height * NUM_DEVICE_SCALE + 25 * NUM_DEVICE_OFFSETS,
					CAIRO_BOILERPLATE_MODE_TEST,
					&closure);
    if (surface == NULL) {
	cairo_test_log (ctx, "Error: Failed to set %s target\n", target->name);
	ret = CAIRO_TEST_UNTESTED;
	goto UNWIND_STRINGS;
    }

#if HAVE_MEMFAULT
    if (ctx->malloc_failure &&
	MEMFAULT_COUNT_FAULTS () - last_fault_count > 0 &&
	cairo_surface_status (surface) == CAIRO_STATUS_NO_MEMORY)
    {
	goto REPEAT;
    }
#endif

    if (cairo_surface_status (surface)) {
	MF (MEMFAULT_PRINT_FAULTS ());
	cairo_test_log (ctx, "Error: Created an error surface: %s\n",
			cairo_status_to_string (cairo_surface_status (surface)));
	ret = CAIRO_TEST_FAILURE;
	goto UNWIND_STRINGS;
    }

    /* Check that we created a surface of the expected type. */
    if (cairo_surface_get_type (surface) != target->expected_type) {
	MF (MEMFAULT_PRINT_FAULTS ());
	cairo_test_log (ctx, "Error: Created surface is of type %d (expected %d)\n",
			cairo_surface_get_type (surface), target->expected_type);
	ret = CAIRO_TEST_UNTESTED;
	goto UNWIND_SURFACE;
    }

    /* Check that we created a surface of the expected content,
     * (ignore the artificial CAIRO_TEST_CONTENT_COLOR_ALPHA_FLATTENED value).
     */
    expected_content = cairo_boilerplate_content (target->content);

    if (cairo_surface_get_content (surface) != expected_content) {
	MF (MEMFAULT_PRINT_FAULTS ());
	cairo_test_log (ctx, "Error: Created surface has content %d (expected %d)\n",
			cairo_surface_get_content (surface), expected_content);
	ret = CAIRO_TEST_FAILURE;
	goto UNWIND_SURFACE;
    }

    if (cairo_surface_set_user_data (surface,
				     &cairo_boilerplate_output_basename_key,
				     base_path,
				     NULL))
    {
#if HAVE_MEMFAULT
	cairo_surface_destroy (surface);

	if (target->cleanup)
	    target->cleanup (closure);

	goto REPEAT;
#else
	ret = CAIRO_TEST_FAILURE;
	goto UNWIND_SURFACE;
#endif
    }

    cairo_surface_set_device_offset (surface, dev_offset, dev_offset);
    cairo_surface_set_device_scale (surface, dev_scale, dev_scale);

    cr = cairo_create (surface);
    if (cairo_set_user_data (cr, &_cairo_test_context_key, (void*) ctx, NULL)) {
#if HAVE_MEMFAULT
	cairo_destroy (cr);
	cairo_surface_destroy (surface);

	if (target->cleanup)
	    target->cleanup (closure);

	goto REPEAT;
#else
	ret = CAIRO_TEST_FAILURE;
	goto UNWIND_CAIRO;
#endif
    }

    if (similar)
	cairo_push_group_with_content (cr, expected_content);

    /* Clear to transparent (or black) depending on whether the target
     * surface supports alpha. */
    cairo_save (cr);
    cairo_set_operator (cr, CAIRO_OPERATOR_CLEAR);
    cairo_paint (cr);
    cairo_restore (cr);

    /* Set all components of font_options to avoid backend differences
     * and reduce number of needed reference images. */
    font_options = cairo_font_options_create ();
    cairo_font_options_set_hint_style (font_options, CAIRO_HINT_STYLE_NONE);
    cairo_font_options_set_hint_metrics (font_options, CAIRO_HINT_METRICS_ON);
    cairo_font_options_set_antialias (font_options, CAIRO_ANTIALIAS_GRAY);
    cairo_set_font_options (cr, font_options);
    cairo_font_options_destroy (font_options);

    cairo_save (cr);
    alarm (ctx->timeout);
    status = (ctx->test->draw) (cr, ctx->test->width, ctx->test->height);
    alarm (0);
    cairo_restore (cr);

    if (similar) {
	cairo_pop_group_to_source (cr);
	cairo_set_operator (cr, CAIRO_OPERATOR_SOURCE);
	cairo_paint (cr);
    }

#if HAVE_MEMFAULT
    MEMFAULT_DISABLE_FAULTS ();

    /* repeat test after malloc failure injection */
    if (ctx->malloc_failure &&
	MEMFAULT_COUNT_FAULTS () - last_fault_count > 0 &&
	(status == CAIRO_TEST_NO_MEMORY ||
	 cairo_status (cr) == CAIRO_STATUS_NO_MEMORY ||
	 cairo_surface_status (surface) == CAIRO_STATUS_NO_MEMORY))
    {
	cairo_destroy (cr);
	cairo_surface_destroy (surface);
	if (target->cleanup)
	    target->cleanup (closure);
	cairo_debug_reset_static_data ();
#if HAVE_FCFINI
	FcFini ();
#endif
	if (MEMFAULT_COUNT_LEAKS () > 0) {
	    MEMFAULT_PRINT_FAULTS ();
	    MEMFAULT_PRINT_LEAKS ();
	}

	goto REPEAT;
    }
#endif

    /* Then, check all the different ways it could fail. */
    if (status) {
	cairo_test_log (ctx, "Error: Function under test failed\n");
	ret = status;
	goto UNWIND_CAIRO;
    }

#if HAVE_MEMFAULT
    if (MEMFAULT_COUNT_FAULTS () - last_fault_count > 0 &&
	MEMFAULT_HAS_FAULTS ())
    {
	VALGRIND_PRINTF ("Unreported memfaults...");
	MEMFAULT_PRINT_FAULTS ();
    }
#endif

    if (target->finish_surface != NULL) {
#if HAVE_MEMFAULT
	/* We need to re-enable faults as most recording-surface processing
	 * is done during cairo_surface_finish().
	 */
	MEMFAULT_CLEAR_FAULTS ();
	last_fault_count = MEMFAULT_COUNT_FAULTS ();
	MEMFAULT_ENABLE_FAULTS ();
#endif

	/* also check for infinite loops whilst replaying */
	alarm (ctx->timeout);
	status = target->finish_surface (surface);
	alarm (0);

#if HAVE_MEMFAULT
	MEMFAULT_DISABLE_FAULTS ();

	if (ctx->malloc_failure &&
	    MEMFAULT_COUNT_FAULTS () - last_fault_count > 0 &&
	    status == CAIRO_STATUS_NO_MEMORY)
	{
	    cairo_destroy (cr);
	    cairo_surface_destroy (surface);
	    if (target->cleanup)
		target->cleanup (closure);
	    cairo_debug_reset_static_data ();
#if HAVE_FCFINI
	    FcFini ();
#endif
	    if (MEMFAULT_COUNT_LEAKS () > 0) {
		MEMFAULT_PRINT_FAULTS ();
		MEMFAULT_PRINT_LEAKS ();
	    }

	    goto REPEAT;
	}
#endif
	if (status) {
	    cairo_test_log (ctx, "Error: Failed to finish surface: %s\n",
			    cairo_status_to_string (status));
	    ret = CAIRO_TEST_FAILURE;
	    goto UNWIND_CAIRO;
	}
    }

    /* Skip image check for tests with no image (width,height == 0,0) */
    if (ctx->test->width != 0 && ctx->test->height != 0) {
	cairo_surface_t *ref_image;
	cairo_surface_t *test_image;
	cairo_surface_t *diff_image;
	buffer_diff_result_t result;
	cairo_status_t diff_status;

	if (ref_png_path == NULL) {
	    cairo_test_log (ctx, "Error: Cannot find reference image for %s\n",
			    base_name);

	    /* we may be running this test to generate reference images */
	    _xunlink (ctx, out_png_path);
	    /* be more generous as we may need to use external renderers */
	    alarm (4 * ctx->timeout);
	    test_image = target->get_image_surface (surface, 0,
		                                    ctx->test->width,
						    ctx->test->height);
	    alarm (0);
	    diff_status = cairo_surface_write_to_png (test_image, out_png_path);
	    cairo_surface_destroy (test_image);
	    if (diff_status) {
		if (cairo_surface_status (test_image) == CAIRO_STATUS_INVALID_STATUS)
		    ret = CAIRO_TEST_CRASHED;
		else
		    ret = CAIRO_TEST_FAILURE;
		cairo_test_log (ctx,
			        "Error: Failed to write output image: %s\n",
			        cairo_status_to_string (diff_status));
	    }
	    have_output = TRUE;

	    ret = CAIRO_TEST_XFAILURE;
	    goto UNWIND_CAIRO;
	}

	if (target->file_extension != NULL) { /* compare vector surfaces */
	    char *filenames[] = {
		ref_png_path,
		ref_path,
		new_png_path,
		new_path,
		xfail_png_path,
		xfail_path,
		base_ref_png_path,
		base_new_png_path,
		base_xfail_png_path,
	    };

	    xasprintf (&test_filename, "%s.out%s",
		       base_path, target->file_extension);
	    xasprintf (&pass_filename, "%s.pass%s",
		       base_path, target->file_extension);
	    xasprintf (&fail_filename, "%s.fail%s",
		       base_path, target->file_extension);

	    if (cairo_test_file_is_older (pass_filename,
					  filenames,
					  ARRAY_LENGTH (filenames)))
	    {
		_xunlink (ctx, pass_filename);
	    }
	    if (cairo_test_file_is_older (fail_filename,
					  filenames,
					  ARRAY_LENGTH (filenames)))
	    {
		_xunlink (ctx, fail_filename);
	    }

	    if (cairo_test_files_equal (out_png_path, ref_path)) {
		cairo_test_log (ctx, "Vector surface matches reference.\n");
		have_output = FALSE;
		ret = CAIRO_TEST_SUCCESS;
		goto UNWIND_CAIRO;
	    }
	    if (cairo_test_files_equal (out_png_path, new_path)) {
		cairo_test_log (ctx, "Vector surface matches current failure.\n");
		have_output = FALSE;
		ret = CAIRO_TEST_NEW;
		goto UNWIND_CAIRO;
	    }
	    if (cairo_test_files_equal (out_png_path, xfail_path)) {
		cairo_test_log (ctx, "Vector surface matches known failure.\n");
		have_output = FALSE;
		ret = CAIRO_TEST_XFAILURE;
		goto UNWIND_CAIRO;
	    }

	    if (cairo_test_files_equal (test_filename, pass_filename)) {
		/* identical output as last known PASS */
		cairo_test_log (ctx, "Vector surface matches last pass.\n");
		have_output = TRUE;
		ret = CAIRO_TEST_SUCCESS;
		goto UNWIND_CAIRO;
	    }
	    if (cairo_test_files_equal (test_filename, fail_filename)) {
		/* identical output as last known FAIL, fail */
		cairo_test_log (ctx, "Vector surface matches last fail.\n");
		have_result = TRUE; /* presume these were kept around as well */
		have_output = TRUE;
		ret = CAIRO_TEST_FAILURE;
		goto UNWIND_CAIRO;
	    }
	}

	/* be more generous as we may need to use external renderers */
	alarm (4 * ctx->timeout);
	test_image = target->get_image_surface (surface, 0,
					        ctx->test->width,
						ctx->test->height);
	alarm (0);
	if (cairo_surface_status (test_image)) {
	    cairo_test_log (ctx, "Error: Failed to extract image: %s\n",
			    cairo_status_to_string (cairo_surface_status (test_image)));
	    if (cairo_surface_status (test_image) == CAIRO_STATUS_INVALID_STATUS)
		ret = CAIRO_TEST_CRASHED;
	    else
		ret = CAIRO_TEST_FAILURE;
	    cairo_surface_destroy (test_image);
	    goto UNWIND_CAIRO;
	}

	_xunlink (ctx, out_png_path);
	diff_status = cairo_surface_write_to_png (test_image, out_png_path);
	if (diff_status) {
	    cairo_test_log (ctx, "Error: Failed to write output image: %s\n",
			    cairo_status_to_string (diff_status));
	    cairo_surface_destroy (test_image);
	    ret = CAIRO_TEST_FAILURE;
	    goto UNWIND_CAIRO;
	}
	have_output = TRUE;

	/* binary compare png files (no decompression) */
	if (target->file_extension == NULL) {
	    char *filenames[] = {
		ref_png_path,
		new_png_path,
		xfail_png_path,
		base_ref_png_path,
		base_new_png_path,
		base_xfail_png_path,
	    };

	    xasprintf (&test_filename, "%s", out_png_path);
	    xasprintf (&pass_filename, "%s.pass.png", base_path);
	    xasprintf (&fail_filename, "%s.fail.png", base_path);

	    if (cairo_test_file_is_older (pass_filename,
					  filenames,
					  ARRAY_LENGTH (filenames)))
	    {
		_xunlink (ctx, pass_filename);
	    }
	    if (cairo_test_file_is_older (fail_filename,
					  filenames,
					  ARRAY_LENGTH (filenames)))
	    {
		_xunlink (ctx, fail_filename);
	    }

	    if (cairo_test_files_equal (test_filename, pass_filename)) {
		cairo_test_log (ctx, "PNG file exactly matches last pass.\n");
                have_result = TRUE;
		cairo_surface_destroy (test_image);
		ret = CAIRO_TEST_SUCCESS;
		goto UNWIND_CAIRO;
	    }
	    if (cairo_test_files_equal (out_png_path, ref_png_path)) {
		cairo_test_log (ctx, "PNG file exactly matches reference image.\n");
                have_result = TRUE;
		cairo_surface_destroy (test_image);
		ret = CAIRO_TEST_SUCCESS;
		goto UNWIND_CAIRO;
	    }
	    if (cairo_test_files_equal (out_png_path, new_png_path)) {
		cairo_test_log (ctx, "PNG file exactly matches current failure image.\n");
                have_result = TRUE;
		cairo_surface_destroy (test_image);
		ret = CAIRO_TEST_NEW;
		goto UNWIND_CAIRO;
	    }
	    if (cairo_test_files_equal (out_png_path, xfail_png_path)) {
		cairo_test_log (ctx, "PNG file exactly matches known failure image.\n");
                have_result = TRUE;
		cairo_surface_destroy (test_image);
		ret = CAIRO_TEST_XFAILURE;
		goto UNWIND_CAIRO;
	    }
	    if (cairo_test_files_equal (test_filename, fail_filename)) {
		cairo_test_log (ctx, "PNG file exactly matches last fail.\n");
		have_result = TRUE; /* presume these were kept around as well */
		cairo_surface_destroy (test_image);
		ret = CAIRO_TEST_FAILURE;
		goto UNWIND_CAIRO;
	    }
	} else {
	    if (cairo_test_files_equal (out_png_path, ref_png_path)) {
		cairo_test_log (ctx, "PNG file exactly matches reference image.\n");
		have_result = TRUE;
		cairo_surface_destroy (test_image);
		ret = CAIRO_TEST_SUCCESS;
		goto UNWIND_CAIRO;
	    }
	    if (cairo_test_files_equal (out_png_path, new_png_path)) {
		cairo_test_log (ctx, "PNG file exactly matches current failure image.\n");
		have_result = TRUE;
		cairo_surface_destroy (test_image);
		ret = CAIRO_TEST_NEW;
		goto UNWIND_CAIRO;
	    }
	    if (cairo_test_files_equal (out_png_path, xfail_png_path)) {
		cairo_test_log (ctx, "PNG file exactly matches known failure image.\n");
		have_result = TRUE;
		cairo_surface_destroy (test_image);
		ret = CAIRO_TEST_XFAILURE;
		goto UNWIND_CAIRO;
	    }
	}

	if (cairo_test_files_equal (out_png_path, base_ref_png_path)) {
	    cairo_test_log (ctx, "PNG file exactly reference image.\n");
	    have_result = TRUE;
	    cairo_surface_destroy (test_image);
	    ret = CAIRO_TEST_SUCCESS;
	    goto UNWIND_CAIRO;
	}
	if (cairo_test_files_equal (out_png_path, base_new_png_path)) {
	    cairo_test_log (ctx, "PNG file exactly current failure image.\n");
	    have_result = TRUE;
	    cairo_surface_destroy (test_image);
	    ret = CAIRO_TEST_NEW;
	    goto UNWIND_CAIRO;
	}
	if (cairo_test_files_equal (out_png_path, base_xfail_png_path)) {
	    cairo_test_log (ctx, "PNG file exactly known failure image.\n");
	    have_result = TRUE;
	    cairo_surface_destroy (test_image);
	    ret = CAIRO_TEST_XFAILURE;
	    goto UNWIND_CAIRO;
	}

	/* first compare against the ideal reference */
	ref_image = cairo_test_get_reference_image (ctx, base_ref_png_path,
						    target->content == CAIRO_TEST_CONTENT_COLOR_ALPHA_FLATTENED);
	if (cairo_surface_status (ref_image)) {
	    cairo_test_log (ctx, "Error: Cannot open reference image for %s: %s\n",
			    base_ref_png_path,
			    cairo_status_to_string (cairo_surface_status (ref_image)));
	    cairo_surface_destroy (test_image);
	    ret = CAIRO_TEST_FAILURE;
	    goto UNWIND_CAIRO;
	}

	diff_image = cairo_image_surface_create (CAIRO_FORMAT_ARGB32,
						 ctx->test->width,
						 ctx->test->height);

	cmp_png_path = base_ref_png_path;
	diff_status = image_diff (ctx,
				  test_image, ref_image, diff_image,
				  &result);
	_xunlink (ctx, diff_png_path);
	if (diff_status ||
            image_diff_is_failure (&result, target->error_tolerance))
	{
	    /* that failed, so check against the specific backend */
	    ref_image = cairo_test_get_reference_image (ctx, ref_png_path,
							target->content == CAIRO_TEST_CONTENT_COLOR_ALPHA_FLATTENED);
	    if (cairo_surface_status (ref_image)) {
		cairo_test_log (ctx, "Error: Cannot open reference image for %s: %s\n",
				ref_png_path,
				cairo_status_to_string (cairo_surface_status (ref_image)));
		cairo_surface_destroy (test_image);
		ret = CAIRO_TEST_FAILURE;
		goto UNWIND_CAIRO;
	    }

	    cmp_png_path = ref_png_path;
	    diff_status = image_diff (ctx,
				      test_image, ref_image,
				      diff_image,
				      &result);
	    if (diff_status)
	    {
		cairo_test_log (ctx, "Error: Failed to compare images: %s\n",
				cairo_status_to_string (diff_status));
		ret = CAIRO_TEST_FAILURE;
	    }
	    else if (image_diff_is_failure (&result, target->error_tolerance))
	    {
		ret = CAIRO_TEST_FAILURE;

		diff_status = cairo_surface_write_to_png (diff_image,
							  diff_png_path);
		if (diff_status) {
		    cairo_test_log (ctx, "Error: Failed to write differences image: %s\n",
				    cairo_status_to_string (diff_status));
		} else {
		    have_result = TRUE;
		}

		cairo_test_copy_file (test_filename, fail_filename);
	    }
	    else
	    { /* success */
		cairo_test_copy_file (test_filename, pass_filename);
	    }
	}
	else
	{ /* success */
	    cairo_test_copy_file (test_filename, pass_filename);
	}

	/* If failed, compare against the current image output,
	 * and attempt to detect systematic failures.
	 */
	if (ret == CAIRO_TEST_FAILURE) {
	    char *image_out_path;

	    image_out_path =
		cairo_test_reference_filename (ctx,
					       base_name,
					       ctx->test_name,
					       "image",
					       "image",
					       format,
					       CAIRO_TEST_OUT_SUFFIX,
					       CAIRO_TEST_PNG_EXTENSION);
	    if (image_out_path != NULL) {
		if (cairo_test_files_equal (out_png_path,
					    image_out_path))
		{
		    ret = CAIRO_TEST_XFAILURE;
		}
		else
		{
		    ref_image =
			cairo_image_surface_create_from_png (image_out_path);
		    if (cairo_surface_status (ref_image) == CAIRO_STATUS_SUCCESS)
		    {
			diff_status = image_diff (ctx,
						  test_image, ref_image,
						  diff_image,
						  &result);
			if (diff_status == CAIRO_STATUS_SUCCESS &&
			    !image_diff_is_failure (&result, target->error_tolerance))
			{
			    ret = CAIRO_TEST_XFAILURE;
			}

			cairo_surface_destroy (ref_image);
		    }
		}

		free (image_out_path);
	    }
	}

	cairo_surface_destroy (test_image);
	cairo_surface_destroy (diff_image);
    }

    if (cairo_status (cr) != CAIRO_STATUS_SUCCESS) {
	cairo_test_log (ctx, "Error: Function under test left cairo status in an error state: %s\n",
			cairo_status_to_string (cairo_status (cr)));
	ret = CAIRO_TEST_ERROR;
	goto UNWIND_CAIRO;
    }

UNWIND_CAIRO:
    free (test_filename);
    free (fail_filename);
    free (pass_filename);

    test_filename = fail_filename = pass_filename = NULL;

#if HAVE_MEMFAULT
    if (ret == CAIRO_TEST_FAILURE)
	MEMFAULT_PRINT_FAULTS ();
#endif
    cairo_destroy (cr);
UNWIND_SURFACE:
    cairo_surface_destroy (surface);

    if (target->cleanup)
	target->cleanup (closure);

#if HAVE_MEMFAULT
    cairo_debug_reset_static_data ();

#if HAVE_FCFINI
    FcFini ();
#endif

    if (MEMFAULT_COUNT_LEAKS () > 0) {
	if (ret != CAIRO_TEST_FAILURE)
	    MEMFAULT_PRINT_FAULTS ();
	MEMFAULT_PRINT_LEAKS ();
    }

    if (ret == CAIRO_TEST_SUCCESS && --malloc_failure_iterations > 0)
	goto REPEAT;
#endif

    if (have_output)
	cairo_test_log (ctx, "OUTPUT: %s\n", out_png_path);

    if (have_result) {
	if (cmp_png_path == NULL) {
	    /* XXX presume we matched the normal ref last time */
	    cmp_png_path = ref_png_path;
	}
	cairo_test_log (ctx,
			"REFERENCE: %s\nDIFFERENCE: %s\n",
			cmp_png_path, diff_png_path);
    }

UNWIND_STRINGS:
    free (out_png_path);
    free (ref_png_path);
    free (base_ref_png_path);
    free (ref_path);
    free (new_png_path);
    free (base_new_png_path);
    free (new_path);
    free (xfail_png_path);
    free (base_xfail_png_path);
    free (xfail_path);
    free (diff_png_path);
    free (base_path);
    free (base_name);

    return ret;
}
示例#20
0
文件: csapp.c 项目: zhanjindong/csapp
unsigned int Alarm(unsigned int seconds)
{
    return alarm(seconds);
}
示例#21
0
int
main (int argc, char *argv[])
{

	LDAP *ld;
	LDAPMessage *result;

	/* should be 	int result = STATE_UNKNOWN; */

	int status = STATE_UNKNOWN;
	long microsec;
	double elapsed_time;

	/* for ldap tls */

	int tls;
	int version=3;

	setlocale (LC_ALL, "");
	bindtextdomain (PACKAGE, LOCALEDIR);
	textdomain (PACKAGE);

	if (strstr(argv[0],"check_ldaps")) {
		xasprintf (&progname, "check_ldaps");
 	}

	/* Parse extra opts if any */
	argv=np_extra_opts (&argc, argv, progname);

	if (process_arguments (argc, argv) == ERROR)
		usage4 (_("Could not parse arguments"));

	if (strstr(argv[0],"check_ldaps") && ! starttls && ! ssl_on_connect)
		starttls = TRUE;

	/* initialize alarm signal handling */
	signal (SIGALRM, socket_timeout_alarm_handler);

	/* set socket timeout */
	alarm (socket_timeout);

	/* get the start time */
	gettimeofday (&tv, NULL);

	/* initialize ldap */
#ifdef HAVE_LDAP_INIT
	if (!(ld = ldap_init (ld_host, ld_port))) {
		printf ("Could not connect to the server at port %i\n", ld_port);
		return STATE_CRITICAL;
	}
#else
	if (!(ld = ldap_open (ld_host, ld_port))) {
		if (verbose)
			ldap_perror(ld, "ldap_open");
		printf (_("Could not connect to the server at port %i\n"), ld_port);
		return STATE_CRITICAL;
	}
#endif /* HAVE_LDAP_INIT */

#ifdef HAVE_LDAP_SET_OPTION
	/* set ldap options */
	if (ldap_set_option (ld, LDAP_OPT_PROTOCOL_VERSION, &ld_protocol) !=
			LDAP_OPT_SUCCESS ) {
		printf(_("Could not set protocol version %d\n"), ld_protocol);
		return STATE_CRITICAL;
	}
#endif

	if (ld_port == LDAPS_PORT || ssl_on_connect) {
		xasprintf (&SERVICE, "LDAPS");
#if defined(HAVE_LDAP_SET_OPTION) && defined(LDAP_OPT_X_TLS)
		/* ldaps: set option tls */
		tls = LDAP_OPT_X_TLS_HARD;

		if (ldap_set_option (ld, LDAP_OPT_X_TLS, &tls) != LDAP_SUCCESS)
		{
			if (verbose)
				ldap_perror(ld, "ldaps_option");
			printf (_("Could not init TLS at port %i!\n"), ld_port);
			return STATE_CRITICAL;
		}
#else
		printf (_("TLS not supported by the libraries!\n"));
		return STATE_CRITICAL;
#endif /* LDAP_OPT_X_TLS */
	} else if (starttls) {
		xasprintf (&SERVICE, "LDAP-TLS");
#if defined(HAVE_LDAP_SET_OPTION) && defined(HAVE_LDAP_START_TLS_S)
		/* ldap with startTLS: set option version */
		if (ldap_get_option(ld,LDAP_OPT_PROTOCOL_VERSION, &version) == LDAP_OPT_SUCCESS )
		{
			if (version < LDAP_VERSION3)
			{
				version = LDAP_VERSION3;
				ldap_set_option(ld, LDAP_OPT_PROTOCOL_VERSION, &version);
			}
		}
		/* call start_tls */
		if (ldap_start_tls_s(ld, NULL, NULL) != LDAP_SUCCESS)
		{
			if (verbose)
				ldap_perror(ld, "ldap_start_tls");
			printf (_("Could not init startTLS at port %i!\n"), ld_port);
			return STATE_CRITICAL;
		}
#else
		printf (_("startTLS not supported by the library, needs LDAPv3!\n"));
		return STATE_CRITICAL;
#endif /* HAVE_LDAP_START_TLS_S */
	}

	/* bind to the ldap server */
	if (ldap_bind_s (ld, ld_binddn, ld_passwd, LDAP_AUTH_SIMPLE) !=
			LDAP_SUCCESS) {
		if (verbose)
			ldap_perror(ld, "ldap_bind");
		printf (_("Could not bind to the LDAP server\n"));
		return STATE_CRITICAL;
	}

	/* do a search of all objectclasses in the base dn */
	if (ldap_search_s (ld, ld_base, LDAP_SCOPE_BASE, ld_attr, NULL, 0, &result)
			!= LDAP_SUCCESS) {
		if (verbose)
			ldap_perror(ld, "ldap_search");
		printf (_("Could not search/find objectclasses in %s\n"), ld_base);
		return STATE_CRITICAL;
	}

	/* unbind from the ldap server */
	ldap_unbind (ld);

	/* reset the alarm handler */
	alarm (0);

	/* calcutate the elapsed time and compare to thresholds */

	microsec = deltime (tv);
	elapsed_time = (double)microsec / 1.0e6;

	if (crit_time!=UNDEFINED && elapsed_time>crit_time)
		status = STATE_CRITICAL;
	else if (warn_time!=UNDEFINED && elapsed_time>warn_time)
		status = STATE_WARNING;
	else
		status = STATE_OK;

	/* print out the result */
	printf (_("LDAP %s - %.3f seconds response time|%s\n"),
	        state_text (status),
	        elapsed_time,
	        fperfdata ("time", elapsed_time, "s",
	                  (int)warn_time, warn_time,
	                  (int)crit_time, crit_time,
	                  TRUE, 0, FALSE, 0));

	return status;
}
示例#22
0
/*
 * Receive a file.
 */
void
recvfile (int fd, char *name, char *mode)
{
  register struct tftphdr *ap;
  struct tftphdr *dp, *w_init ();
  register int n;
  volatile int block, size, firsttrip;
  volatile unsigned long amount;
  struct sockaddr_in from;
  socklen_t fromlen;
  FILE *file;
  volatile int convert;		/* true if converting crlf -> lf */

  startclock ();
  dp = w_init ();
  ap = (struct tftphdr *) ackbuf;
  file = fdopen (fd, "w");
  convert = !strcmp (mode, "netascii");
  block = 1;
  firsttrip = 1;
  amount = 0;

  signal (SIGALRM, timer);
  do
    {
      if (firsttrip)
	{
	  size = makerequest (RRQ, name, ap, mode);
	  firsttrip = 0;
	}
      else
	{
	  ap->th_opcode = htons ((u_short) ACK);
	  ap->th_block = htons ((u_short) (block));
	  size = 4;
	  block++;
	}
      timeout = 0;
      setjmp (timeoutbuf);

    send_ack:
      if (trace)
	tpacket ("sent", ap, size);
      if (sendto (f, ackbuf, size, 0, (struct sockaddr *) &peeraddr,
		  sizeof (peeraddr)) != size)
	{
	  alarm (0);
	  perror ("tftp: sendto");
	  goto abort;
	}
      write_behind (file, convert);

      for (;;)
	{
	  alarm (rexmtval);
	  do
	    {
	      fromlen = sizeof (from);
	      n = recvfrom (f, (char *) dp, PKTSIZE, 0,
			    (struct sockaddr *) &from, &fromlen);
	    }
	  while (n <= 0);

	  alarm (0);
	  if (n < 0)
	    {
	      perror ("tftp: recvfrom");
	      goto abort;
	    }
	  peeraddr.sin_port = from.sin_port;	/* added */
	  if (trace)
	    tpacket ("received", dp, n);
	  /* should verify client address */
	  dp->th_opcode = ntohs (dp->th_opcode);
	  dp->th_block = ntohs (dp->th_block);
	  if (dp->th_opcode == ERROR)
	    {
	      printf ("Error code %d: %s\n", dp->th_code, dp->th_msg);
	      goto abort;
	    }
	  if (dp->th_opcode == DATA)
	    {
	      int j;

	      if (dp->th_block == block)
		break;		/* have next packet */

	      /* On an error, try to synchronize
	       * both sides.
	       */
	      j = synchnet (f);
	      if (j && trace)
		printf ("discarded %d packets\n", j);

	      if (dp->th_block == (block - 1))
		goto send_ack;	/* resend ack */
	    }
	}
      /*      size = write(fd, dp->th_data, n - 4); */
      size = writeit (file, &dp, n - 4, convert);
      if (size < 0)
	{
	  nak (errno + 100);
	  break;
	}
      amount += size;
    }
  while (size == SEGSIZE);

abort:				/* ok to ack, since user */
  ap->th_opcode = htons ((u_short) ACK);	/* has seen err msg */
  ap->th_block = htons ((u_short) block);
  sendto (f, ackbuf, 4, 0, (struct sockaddr *) &peeraddr, sizeof (peeraddr));
  write_behind (file, convert);	/* flush last buffer */
  fclose (file);
  stopclock ();
  if (amount > 0)
    printstats ("Received", amount);
}
示例#23
0
文件: signal.c 项目: AlexSteel/wine
void stop_watchdog(void)
{
    alarm( 0 );
    watchdog = 0;
}
示例#24
0
文件: ip.c 项目: AsherBond/cf22cf3
int RemoteConnect(char *host,char forceipv4,short oldport, char *newport) 

{ int err;

#if defined(HAVE_GETADDRINFO)
 
if (forceipv4 == 'n')
   {
   struct addrinfo query, *response, *ap;
   struct addrinfo query2, *response2, *ap2;
   int err,connected = false;
   
   memset(&query,0,sizeof(struct addrinfo));   

   query.ai_family = AF_UNSPEC;
   query.ai_socktype = SOCK_STREAM;

   if ((err = getaddrinfo(host,newport,&query,&response)) != 0)
      {
      snprintf(OUTPUT,CF_BUFSIZE,"Unable to find hostname or cfengine service: (%s/%s) %s",host,STR_CFENGINEPORT,gai_strerror(err));
      CfLog(cfinform,OUTPUT,"");
      return false;
      }
   
   for (ap = response; ap != NULL; ap = ap->ai_next)
      {
      Verbose("Connect to %s = %s on port %s\n",host,sockaddr_ntop(ap->ai_addr),newport);
      
      if ((CONN->sd = socket(ap->ai_family,ap->ai_socktype,ap->ai_protocol)) == -1)
         {
         CfLog(cfinform,"Couldn't open a socket","socket");      
         continue;
         }
      
      if (BINDINTERFACE[0] != '\0')
         {
         memset(&query2,0,sizeof(struct addrinfo));   
         
         query.ai_family = AF_UNSPEC;
         query.ai_socktype = SOCK_STREAM;
         
         if ((err = getaddrinfo(BINDINTERFACE,NULL,&query2,&response2)) != 0)
            {
            snprintf(OUTPUT,CF_BUFSIZE,"Unable to lookup hostname or cfengine service: %s",gai_strerror(err));
            CfLog(cferror,OUTPUT,"");
            return false;
            }
         
         for (ap2 = response2; ap2 != NULL; ap2 = ap2->ai_next)
            {
            if (bind(CONN->sd, ap2->ai_addr, ap2->ai_addrlen) == 0)
               {
               freeaddrinfo(response2);
               response2 = NULL;
               break;
               }
            }
         
         if (response2)
            {
            freeaddrinfo(response2);
            }
         }
      
      signal(SIGALRM,(void *)TimeOut);
      alarm(CF_TIMEOUT);
      
      if (connect(CONN->sd,ap->ai_addr,ap->ai_addrlen) >= 0)
         {
         connected = true;
         alarm(0);
         signal(SIGALRM,SIG_DFL);
         break;
         }
      
      alarm(0);
      signal(SIGALRM,SIG_DFL);
      }
   
   if (connected)
      {
      CONN->family = ap->ai_family;
      snprintf(CONN->remoteip,CF_MAX_IP_LEN-1,"%s",sockaddr_ntop(ap->ai_addr));
      }
   else
      {
      close(CONN->sd);
      snprintf(OUTPUT,CF_BUFSIZE*2,"Couldn't connect to host %s\n",host);
      CONN->sd = CF_NOT_CONNECTED;
      }
   
   if (response != NULL)
      {
      freeaddrinfo(response);
      }
   
   if (!connected)
      {
      return false;
      }
   }
 
 else
     
#endif /* ---------------------- only have ipv4 ---------------------------------*/ 

   {
   struct hostent *hp;
   struct sockaddr_in cin;
   memset(&cin,0,sizeof(cin));
   
   if ((hp = gethostbyname(host)) == NULL)
      {
      snprintf(OUTPUT,CF_BUFSIZE,"Unable to look up IP address of %s",host);
      CfLog(cferror,OUTPUT,"gethostbyname");
      return false;
      }
   
   cin.sin_port = oldport;
   cin.sin_addr.s_addr = ((struct in_addr *)(hp->h_addr))->s_addr;
   cin.sin_family = AF_INET; 
   
   Verbose("Connect to %s = %s, port =%u\n",host,inet_ntoa(cin.sin_addr),SHORT_CFENGINEPORT);
    
   if ((CONN->sd = socket(AF_INET,SOCK_STREAM,0)) == -1)
      {
      CfLog(cferror,"Couldn't open a socket","socket");
      return false;
      }

   if (BINDINTERFACE[0] != '\0')
      {
      Verbose("Cannot bind interface with this OS.\n");
      /* Could fix this - any point? */
      }
   
   CONN->family = AF_INET;
   snprintf(CONN->remoteip,CF_MAX_IP_LEN-1,"%s",inet_ntoa(cin.sin_addr));
    
   signal(SIGALRM,(void *)TimeOut);
   alarm(CF_TIMEOUT);
    
   if (err=connect(CONN->sd,(void *)&cin,sizeof(cin)) == -1)
      {
      snprintf(OUTPUT,CF_BUFSIZE*2,"Couldn't connect to host %s\n",host);
      CfLog(cfinform,OUTPUT,"connect");
      return false;
      }
   
   alarm(0);
   signal(SIGALRM,SIG_DFL);
   }

LastSeen(host,cf_connect);
return true; 
}
示例#25
0
文件: stress.c 项目: jreybert/power
int
main (int argc, char **argv)
{
  int i, pid, children = 0, retval = 0;
  long starttime, stoptime, runtime, forks;

  /* Variables that indicate which options have been selected.  */
  int do_dryrun = 0;
  long long do_backoff = 3000;
  long long do_timeout = 0;
  long long do_cpu = 0;
  long long do_io = 0;
  long long do_vm = 0;
  long long do_vm_bytes = 256 * 1024 * 1024;
  long long do_vm_stride = 4096;
  long long do_vm_hang = -1;
  int do_vm_keep = 0;
  long long do_hdd = 0;
  int do_hdd_clean = 2;
  long long do_hdd_bytes = 1024 * 1024 * 1024;

  /* Record our start time.  */
  if ((starttime = time (NULL)) == -1)
    {
      err (stderr, "failed to acquire current time: %s\n", strerror (errno));
      exit (1);
    }

  /* SuSv3 does not define any error conditions for this function.  */
  global_progname = basename (argv[0]);

  /* For portability, parse command line options without getopt_long.  */
  for (i = 1; i < argc; i++)
    {
      char *arg = argv[i];

      if (strcmp (arg, "--help") == 0 || strcmp (arg, "-?") == 0)
        {
          usage (0);
        }
      else if (strcmp (arg, "--version") == 0)
        {
          version (0);
        }
      else if (strcmp (arg, "--verbose") == 0 || strcmp (arg, "-v") == 0)
        {
          global_debug = 3;
        }
      else if (strcmp (arg, "--quiet") == 0 || strcmp (arg, "-q") == 0)
        {
          global_debug = 0;
        }
      else if (strcmp (arg, "--dry-run") == 0 || strcmp (arg, "-n") == 0)
        {
          do_dryrun = 1;
        }
      else if (strcmp (arg, "--backoff") == 0)
        {
          assert_arg ("--backoff");
          if (sscanf (arg, "%lli", &do_backoff) != 1)
            {
              err (stderr, "invalid number: %s\n", arg);
              exit (1);
            }
          if (do_backoff < 0)
            {
              err (stderr, "invalid backoff factor: %lli\n", do_backoff);
              exit (1);
            }
          dbg (stdout, "setting backoff coeffient to %llius\n", do_backoff);
        }
      else if (strcmp (arg, "--timeout") == 0 || strcmp (arg, "-t") == 0)
        {
          assert_arg ("--timeout");
          do_timeout = atoll_s (arg);
          if (do_timeout <= 0)
            {
              err (stderr, "invalid timeout value: %llis\n", do_timeout);
              exit (1);
            }
        }
      else if (strcmp (arg, "--cpu") == 0 || strcmp (arg, "-c") == 0)
        {
          assert_arg ("--cpu");
          do_cpu = atoll_b (arg);
          if (do_cpu <= 0)
            {
              err (stderr, "invalid number of cpu hogs: %lli\n", do_cpu);
              exit (1);
            }
        }
      else if (strcmp (arg, "--io") == 0 || strcmp (arg, "-i") == 0)
        {
          assert_arg ("--io");
          do_io = atoll_b (arg);
          if (do_io <= 0)
            {
              err (stderr, "invalid number of io hogs: %lli\n", do_io);
              exit (1);
            }
        }
      else if (strcmp (arg, "--vm") == 0 || strcmp (arg, "-m") == 0)
        {
          assert_arg ("--vm");
          do_vm = atoll_b (arg);
          if (do_vm <= 0)
            {
              err (stderr, "invalid number of vm hogs: %lli\n", do_vm);
              exit (1);
            }
        }
      else if (strcmp (arg, "--vm-bytes") == 0)
        {
          assert_arg ("--vm-bytes");
          do_vm_bytes = atoll_b (arg);
          if (do_vm_bytes <= 0)
            {
              err (stderr, "invalid vm byte value: %lli\n", do_vm_bytes);
              exit (1);
            }
        }
      else if (strcmp (arg, "--vm-stride") == 0)
        {
          assert_arg ("--vm-stride");
          do_vm_stride = atoll_b (arg);
          if (do_vm_stride <= 0)
            {
              err (stderr, "invalid stride value: %lli\n", do_vm_stride);
              exit (1);
            }
        }
      else if (strcmp (arg, "--vm-hang") == 0)
        {
          assert_arg ("--vm-hang");
          do_vm_hang = atoll_b (arg);
          if (do_vm_hang < 0)
            {
              err (stderr, "invalid value: %lli\n", do_vm_hang);
              exit (1);
            }
        }
      else if (strcmp (arg, "--vm-keep") == 0)
        {
          do_vm_keep = 1;
        }
      else if (strcmp (arg, "--hdd") == 0 || strcmp (arg, "-d") == 0)
        {
          assert_arg ("--hdd");
          do_hdd = atoll_b (arg);
          if (do_hdd <= 0)
            {
              err (stderr, "invalid number of hdd hogs: %lli\n", do_hdd);
              exit (1);
            }
        }
      else if (strcmp (arg, "--hdd-noclean") == 0)
        {
          do_hdd_clean = 0;
        }
      else if (strcmp (arg, "--hdd-bytes") == 0)
        {
          assert_arg ("--hdd-bytes");
          do_hdd_bytes = atoll_b (arg);
          if (do_hdd_bytes <= 0)
            {
              err (stderr, "invalid hdd byte value: %lli\n", do_hdd_bytes);
              exit (1);
            }
        }
      else
        {
          err (stderr, "unrecognized option: %s\n", arg);
          exit (1);
        }
    }

  /* Print startup message if we have work to do, bail otherwise.  */
  if (do_cpu + do_io + do_vm + do_hdd)
    {
      out (stdout, "dispatching hogs: %lli cpu, %lli io, %lli vm, %lli hdd\n",
           do_cpu, do_io, do_vm, do_hdd);
    }
  else
    usage (0);

  /* Round robin dispatch our worker processes.  */
  while ((forks = (do_cpu + do_io + do_vm + do_hdd)))
    {
      long long backoff, timeout = 0;

      /* Calculate the backoff value so we get good fork throughput.  */
      backoff = do_backoff * forks;
      dbg (stdout, "using backoff sleep of %llius\n", backoff);

      /* If we are supposed to respect a timeout, calculate it.  */
      if (do_timeout)
        {
          long long currenttime;

          /* Acquire current time.  */
          if ((currenttime = time (NULL)) == -1)
            {
              perror ("error acquiring current time");
              exit (1);
            }

          /* Calculate timeout based on current time.  */
          timeout = do_timeout - (currenttime - starttime);

          if (timeout > 0)
            {
              dbg (stdout, "setting timeout to %llis\n", timeout);
            }
          else
            {
              wrn (stderr, "used up time before all workers dispatched\n");
              break;
            }
        }

      if (do_cpu)
        {
          switch (pid = fork ())
            {
            case 0:            /* child */
              alarm (timeout);
              usleep (backoff);
              if (do_dryrun)
                exit (0);
              exit (hogcpu ());
            case -1:           /* error */
              err (stderr, "fork failed: %s\n", strerror (errno));
              break;
            default:           /* parent */
              dbg (stdout, "--> hogcpu worker %lli [%i] forked\n",
                   do_cpu, pid);
              ++children;
            }
          --do_cpu;
        }

      if (do_io)
        {
          switch (pid = fork ())
            {
            case 0:            /* child */
              alarm (timeout);
              usleep (backoff);
              if (do_dryrun)
                exit (0);
              exit (hogio ());
            case -1:           /* error */
              err (stderr, "fork failed: %s\n", strerror (errno));
              break;
            default:           /* parent */
              dbg (stdout, "--> hogio worker %lli [%i] forked\n", do_io, pid);
              ++children;
            }
          --do_io;
        }

      if (do_vm)
        {
          switch (pid = fork ())
            {
            case 0:            /* child */
              alarm (timeout);
              usleep (backoff);
              if (do_dryrun)
                exit (0);
              exit (hogvm
                    (do_vm_bytes, do_vm_stride, do_vm_hang, do_vm_keep));
            case -1:           /* error */
              err (stderr, "fork failed: %s\n", strerror (errno));
              break;
            default:           /* parent */
              dbg (stdout, "--> hogvm worker %lli [%i] forked\n", do_vm, pid);
              ++children;
            }
          --do_vm;
        }

      if (do_hdd)
        {
          switch (pid = fork ())
            {
            case 0:            /* child */
              alarm (timeout);
              usleep (backoff);
              if (do_dryrun)
                exit (0);
              exit (hoghdd (do_hdd_bytes, do_hdd_clean));
            case -1:           /* error */
              err (stderr, "fork failed: %s\n", strerror (errno));
              break;
            default:           /* parent */
              dbg (stdout, "--> hoghdd worker %lli [%i] forked\n",
                   do_hdd, pid);
              ++children;
            }
          --do_hdd;
        }
    }

  /* Wait for our children to exit.  */
  while (children)
    {
      int status, ret;

      if ((pid = wait (&status)) > 0)
        {
          --children;

          if (WIFEXITED (status))
            {
              if ((ret = WEXITSTATUS (status)) == 0)
                {
                  dbg (stdout, "<-- worker %i returned normally\n", pid);
                }
              else
                {
                  err (stderr, "<-- worker %i returned error %i\n", pid, ret);
                  ++retval;
                  wrn (stderr, "now reaping child worker processes\n");
                  if (signal (SIGUSR1, SIG_IGN) == SIG_ERR)
                    err (stderr, "handler error: %s\n", strerror (errno));
                  if (kill (-1 * getpid (), SIGUSR1) == -1)
                    err (stderr, "kill error: %s\n", strerror (errno));
                }
            }
          else if (WIFSIGNALED (status))
            {
              if ((ret = WTERMSIG (status)) == SIGALRM)
                {
                  dbg (stdout, "<-- worker %i signalled normally\n", pid);
                }
              else if ((ret = WTERMSIG (status)) == SIGUSR1)
                {
                  dbg (stdout, "<-- worker %i reaped\n", pid);
                }
              else
                {
                  err (stderr, "<-- worker %i got signal %i\n", pid, ret);
                  ++retval;
                  wrn (stderr, "now reaping child worker processes\n");
                  if (signal (SIGUSR1, SIG_IGN) == SIG_ERR)
                    err (stderr, "handler error: %s\n", strerror (errno));
                  if (kill (-1 * getpid (), SIGUSR1) == -1)
                    err (stderr, "kill error: %s\n", strerror (errno));
                }
            }
          else
            {
              err (stderr, "<-- worker %i exited abnormally\n", pid);
              ++retval;
            }
        }
      else
        {
          err (stderr, "error waiting for worker: %s\n", strerror (errno));
          ++retval;
          break;
        }
    }

  /* Record our stop time.  */
  if ((stoptime = time (NULL)) == -1)
    {
      err (stderr, "failed to acquire current time\n");
      exit (1);
    }

  /* Calculate our runtime.  */
  runtime = stoptime - starttime;

  /* Print final status message.  */
  if (retval)
    {
      err (stderr, "failed run completed in %lis\n", runtime);
    }
  else
    {
      out (stdout, "successful run completed in %lis\n", runtime);
    }

  exit (retval);
}
示例#26
0
static void
writefile(time_t runtimer, char queue)
{
    /* This does most of the work if at or batch are invoked for writing a job.
     */
    long jobno;
    char *ap, *ppos, *mailname;
    struct passwd *pass_entry;
    struct stat statbuf;
    int fdes, lockdes, fd2;
    FILE *fp, *fpin;
    struct sigaction act;
    char **atenv;
    int ch;
    mode_t cmask;
    struct flock lock;

#ifdef __FreeBSD__
    (void) setlocale(LC_TIME, "");
#endif

    /* Install the signal handler for SIGINT; terminate after removing the
     * spool file if necessary
     */
    act.sa_handler = sigc;
    sigemptyset(&(act.sa_mask));
    act.sa_flags = 0;

    sigaction(SIGINT, &act, NULL);

    ppos = atfile + strlen(ATJOB_DIR);

    /* Loop over all possible file names for running something at this
     * particular time, see if a file is there; the first empty slot at any
     * particular time is used.  Lock the file LFILE first to make sure
     * we're alone when doing this.
     */

    PRIV_START

    if ((lockdes = open(LFILE, O_WRONLY | O_CREAT, S_IWUSR | S_IRUSR)) < 0)
        perr("cannot open lockfile " LFILE);

    lock.l_type = F_WRLCK;
    lock.l_whence = SEEK_SET;
    lock.l_start = 0;
    lock.l_len = 0;

    act.sa_handler = alarmc;
    sigemptyset(&(act.sa_mask));
    act.sa_flags = 0;

    /* Set an alarm so a timeout occurs after ALARMC seconds, in case
     * something is seriously broken.
     */
    sigaction(SIGALRM, &act, NULL);
    alarm(ALARMC);
    fcntl(lockdes, F_SETLKW, &lock);
    alarm(0);

    if ((jobno = nextjob()) == EOF)
        perr("cannot generate job number");

    sprintf(ppos, "%c%5lx%8lx", queue,
            jobno, (unsigned long) (runtimer/60));

    for(ap=ppos; *ap != '\0'; ap ++)
        if (*ap == ' ')
            *ap = '0';

    if (stat(atfile, &statbuf) != 0)
        if (errno != ENOENT)
            perr("cannot access " ATJOB_DIR);

    /* Create the file. The x bit is only going to be set after it has
     * been completely written out, to make sure it is not executed in the
     * meantime.  To make sure they do not get deleted, turn off their r
     * bit.  Yes, this is a kluge.
     */
    cmask = umask(S_IRUSR | S_IWUSR | S_IXUSR);
    if ((fdes = creat(atfile, O_WRONLY)) == -1)
        perr("cannot create atjob file");

    if ((fd2 = dup(fdes)) <0)
        perr("error in dup() of job file");

    if(fchown(fd2, real_uid, real_gid) != 0)
        perr("cannot give away file");

    PRIV_END

    /* We no longer need suid root; now we just need to be able to write
     * to the directory, if necessary.
     */

    REDUCE_PRIV(DAEMON_UID, DAEMON_GID)

    /* We've successfully created the file; let's set the flag so it
     * gets removed in case of an interrupt or error.
     */
    fcreated = 1;

    /* Now we can release the lock, so other people can access it
     */
    lock.l_type = F_UNLCK;
    lock.l_whence = SEEK_SET;
    lock.l_start = 0;
    lock.l_len = 0;
    fcntl(lockdes, F_SETLKW, &lock);
    close(lockdes);

    if((fp = fdopen(fdes, "w")) == NULL)
        panic("cannot reopen atjob file");

    /* Get the userid to mail to, first by trying getlogin(),
     * then from LOGNAME, finally from getpwuid().
     */
    mailname = getlogin();
    if (mailname == NULL)
        mailname = getenv("LOGNAME");

    if ((mailname == NULL) || (mailname[0] == '\0')
            || (strlen(mailname) >= MAXLOGNAME) || (getpwnam(mailname)==NULL))
    {
        pass_entry = getpwuid(real_uid);
        if (pass_entry != NULL)
            mailname = pass_entry->pw_name;
    }

    if (atinput != (char *) NULL)
    {
        fpin = freopen(atinput, "r", stdin);
        if (fpin == NULL)
            perr("cannot open input file");
    }
    fprintf(fp, "#!/bin/sh\n# atrun uid=%ld gid=%ld\n# mail %*s %d\n",
            (long) real_uid, (long) real_gid, MAXLOGNAME - 1, mailname,
            send_mail);

    /* Write out the umask at the time of invocation
     */
    fprintf(fp, "umask %lo\n", (unsigned long) cmask);

    /* Write out the environment. Anything that may look like a
     * special character to the shell is quoted, except for \n, which is
     * done with a pair of "'s.  Don't export the no_export list (such
     * as TERM or DISPLAY) because we don't want these.
     */
    for (atenv= environ; *atenv != NULL; atenv++)
    {
        int export = 1;
        char *eqp;

        eqp = strchr(*atenv, '=');
        if (ap == NULL)
            eqp = *atenv;
        else
        {
            size_t i;
            for (i=0; i<sizeof(no_export)/sizeof(no_export[0]); i++)
            {
                export = export
                         && (strncmp(*atenv, no_export[i],
                                     (size_t) (eqp-*atenv)) != 0);
            }
            eqp++;
        }

        if (export)
        {
            (void)fputs("export ", fp);
            fwrite(*atenv, sizeof(char), eqp-*atenv, fp);
            for(ap = eqp; *ap != '\0'; ap++)
            {
                if (*ap == '\n')
                    fprintf(fp, "\"\n\"");
                else
                {
                    if (!isalnum(*ap)) {
                        switch (*ap) {
                        case '%':
                        case '/':
                        case '{':
                        case '[':
                        case ']':
                        case '=':
                        case '}':
                        case '@':
                        case '+':
                        case '#':
                        case ',':
                        case '.':
                        case ':':
                        case '-':
                        case '_':
                            break;
                        default:
                            fputc('\\', fp);
                            break;
                        }
                    }
                    fputc(*ap, fp);
                }
            }
            fputc('\n', fp);

        }
    }
示例#27
0
static int	process_trap(zbx_sock_t	*sock, char *s, int max_len)
{
	char	*pl, *pr, *data, value_dec[MAX_BUFFER_LEN];
	char	lastlogsize[11], timestamp[11], source[HISTORY_LOG_SOURCE_LEN_MAX], severity[11];
	int	sender_nodeid, nodeid;
	char	*answer;

	int	ret = SUCCEED, res;
	size_t	datalen;

	struct 		zbx_json_parse jp;
	char		value[MAX_STRING_LEN];
	AGENT_VALUE	av;

	memset(&av, 0, sizeof(AGENT_VALUE));
	
	zbx_rtrim(s, " \r\n");

	datalen = strlen(s);
	zabbix_log(LOG_LEVEL_DEBUG, "Trapper got [%s] len %zd", s, datalen);

	if (0 == strncmp(s, "stats", 5))        /* Request performance stats */
	{
		ret = send_perf_stats(sock, s);
		return ret;
	}
	else if (0 == strncmp(s, "ZBX_GET_ACTIVE_CHECKS", 21)) /* Request for list of active checks */
	{
		ret = send_list_of_active_checks(sock, s, zbx_process);
	}
	else if (strncmp(s, "ZBX_GET_HISTORY_LAST_ID", 23) == 0) /* Request for last ids */
	{
		send_history_last_id(sock, s);
		return ret;
	}
	else	/* Process information sent by zabbix_sender */
	{
		/* Node data exchange? */
		if (strncmp(s, "Data", 4) == 0)
		{
			node_sync_lock(0);

			res = node_sync(s, &sender_nodeid, &nodeid);
			if (FAIL == res)
			{
				alarm(CONFIG_TIMEOUT);
				send_data_to_node(sender_nodeid, sock, "FAIL");
				alarm(0);
			}
			else
			{
				res = calculate_checksums(nodeid, NULL, 0);
				if (SUCCEED == res && NULL != (data = get_config_data(nodeid, ZBX_NODE_SLAVE)))
				{
					zabbix_log( LOG_LEVEL_WARNING, "NODE %d: Sending configuration changes"
							" to slave node %d for node %d datalen %d",
							CONFIG_NODEID,
							sender_nodeid,
							nodeid,
							strlen(data));
					alarm(CONFIG_TRAPPER_TIMEOUT);
					res = send_data_to_node(sender_nodeid, sock, data);
					zbx_free(data);
					if (SUCCEED == res)
						res = recv_data_from_node(sender_nodeid, sock, &answer);
					if (SUCCEED == res && 0 == strcmp(answer, "OK"))
						res = update_checksums(nodeid, ZBX_NODE_SLAVE, SUCCEED, NULL, 0, NULL);
					alarm(0);
				}
			}

			node_sync_unlock(0);

			return ret;
		}
		/* Slave node history ? */
		if (strncmp(s, "History", 7) == 0)
		{
			const char	*reply;

			reply = (SUCCEED == node_history(s, datalen) ? "OK" : "FAIL");

			alarm(CONFIG_TIMEOUT);
			if (SUCCEED != zbx_tcp_send_raw(sock, reply))
			{
				zabbix_log(LOG_LEVEL_WARNING, "Error sending %s to node", reply);
				zabbix_syslog("Trapper: error sending %s to node", reply);
			}
			alarm(0);

			return ret;
		}
		/* JSON protocol? */
		else if (SUCCEED == zbx_json_open(s, &jp))
		{
			if (SUCCEED == zbx_json_value_by_name(&jp, ZBX_PROTO_TAG_REQUEST, value, sizeof(value)))
			{
				if (0 == strcmp(value, ZBX_PROTO_VALUE_PROXY_CONFIG))
				{
					if (0 != (zbx_process & ZBX_PROCESS_SERVER))
						send_proxyconfig(sock, &jp);
					else if (0 != (zbx_process & ZBX_PROCESS_PROXY_PASSIVE))
						recv_proxyconfig(sock, &jp);
				}
				else if (0 == strcmp(value, ZBX_PROTO_VALUE_AGENT_DATA) ||
					0 == strcmp(value, ZBX_PROTO_VALUE_SENDER_DATA))
				{
					recv_agenthistory(sock, &jp);
				}
				else if (0 == strcmp(value, ZBX_PROTO_VALUE_HISTORY_DATA))
				{
					if (0 != (zbx_process & ZBX_PROCESS_SERVER))
						recv_proxyhistory(sock, &jp);
					else if (0 != (zbx_process & ZBX_PROCESS_PROXY_PASSIVE))
						send_proxyhistory(sock);
				}
				else if (0 == strcmp(value, ZBX_PROTO_VALUE_DISCOVERY_DATA))
				{
					if (0 != (zbx_process & ZBX_PROCESS_SERVER))
						recv_discovery_data(sock, &jp);
					else if (0 != (zbx_process & ZBX_PROCESS_PROXY_PASSIVE))
						send_discovery_data(sock);
				}
				else if (0 == strcmp(value, ZBX_PROTO_VALUE_AUTO_REGISTRATION_DATA))
				{
					if (0 != (zbx_process & ZBX_PROCESS_SERVER))
						recv_areg_data(sock, &jp);
					else if (0 != (zbx_process & ZBX_PROCESS_PROXY_PASSIVE))
						send_areg_data(sock);
				}
				else if (0 == strcmp(value, ZBX_PROTO_VALUE_PROXY_HEARTBEAT))
				{
					if (0 != (zbx_process & ZBX_PROCESS_SERVER))
						recv_proxy_heartbeat(sock, &jp);
				}
				else if (0 == strcmp(value, ZBX_PROTO_VALUE_GET_ACTIVE_CHECKS))
				{
					ret = send_list_of_active_checks_json(sock, &jp, zbx_process);
				}
				else if (0 == strcmp(value, ZBX_PROTO_VALUE_HOST_AVAILABILITY))
				{
					if (0 != (zbx_process & ZBX_PROCESS_SERVER))
						recv_host_availability(sock, &jp);
					else if (0 != (zbx_process & ZBX_PROCESS_PROXY_PASSIVE))
						send_host_availability(sock);
				}
				else if (0 == strcmp(value, ZBX_PROTO_VALUE_COMMAND))
				{
					ret = node_process_command(sock, s, &jp);
				}
				else
				{
					zabbix_log(LOG_LEVEL_WARNING, "Unknown request received [%s]",
							value);
				}
			}
			return ret;
		}
		/* XML protocol? */
		else if (*s == '<')
		{
			comms_parse_response(s, av.host_name, sizeof(av.host_name), av.key, sizeof(av.key), value_dec, sizeof(value_dec),
					lastlogsize, sizeof(lastlogsize), timestamp, sizeof(timestamp),
					source, sizeof(source),	severity, sizeof(severity));

			av.value	= value_dec;
			av.lastlogsize	= atoi(lastlogsize);
			av.timestamp	= atoi(timestamp);
			av.source	= source;
			av.severity	= atoi(severity);
		}
		else
		{
			pl = s;
			if (NULL == (pr = strchr(pl, ':')))
				return FAIL;

			*pr = '\0';
			zbx_strlcpy(av.host_name, pl, sizeof(av.host_name));
			*pr = ':';

			pl = pr + 1;
			if (NULL == (pr = strchr(pl, ':')))
				return FAIL;

			*pr = '\0';
			zbx_strlcpy(av.key, pl, sizeof(av.key));
			*pr = ':';

			av.value	= pr + 1;
			av.severity	= 0;
		}

		av.clock = time(NULL);

		process_mass_data(sock, 0, &av, 1, NULL);

		alarm(CONFIG_TIMEOUT);
		if (SUCCEED != zbx_tcp_send_raw(sock, SUCCEED == ret ? "OK" : "NOT OK"))
		{
			zabbix_log(LOG_LEVEL_WARNING, "Error sending result back");
			zabbix_syslog("Trapper: error sending result back");
		}
		alarm(0);
	}
	return ret;
}
示例#28
0
int64_t HHVM_FUNCTION(pcntl_alarm,
                      int seconds) {
  return alarm(seconds);
}
示例#29
0
/*
 * Send the requested file.
 */
void
send_file(int fd, char *name, char *mode)
{
	register struct tftphdr *ap;	   /* data and ack packets */
	struct tftphdr *r_init(), *dp;
	register int n;
	volatile int block, size, convert;
	volatile unsigned long amount;
	struct sockaddr_in from;
	int fromlen;
	FILE *file;

	startclock();		/* start stat's clock */
	dp = r_init();		/* reset fillbuf/read-ahead code */
	ap = (struct tftphdr *)ackbuf;
	file = fdopen(fd, "r");
	convert = !strcmp(mode, "netascii");
	block = 0;
	amount = 0;

	signal(SIGALRM, timer);
	do {
		if (block == 0)
			size = makerequest(WRQ, name, dp, mode) - 4;
		else {
		/*	size = read(fd, dp->th_data, SEGSIZE);	 */
			size = readit(file, &dp, convert);
			if (size < 0) {
				nak(errno + 100);
				break;
			}
			dp->th_opcode = htons((u_short)DATA);
			dp->th_block = htons((u_short)block);
		}
		timeout = 0;
		(void) setjmp(timeoutbuf);
send_data:
		if (trace)
			tpacket("sent", dp, size + 4);
		n = sendto(f, (const char *)dp, size + 4, 0,
		    (struct sockaddr *)&peeraddr, sizeof(peeraddr));
		if (n != size + 4) {
			perror("tftp: sendto");
			goto abort;
		}
		read_ahead(file, convert);
		for ( ; ; ) {
			alarm(rexmtval);
			do {
				fromlen = sizeof(from);
				n = recvfrom(f, ackbuf, sizeof(ackbuf), 0,
				    (struct sockaddr *)&from, &fromlen);
			} while (n <= 0);
			alarm(0);
			if (n < 0) {
				perror("tftp: recvfrom");
				goto abort;
			}
			peeraddr.sin_port = from.sin_port;	/* added */
			if (trace)
				tpacket("received", ap, n);
			/* should verify packet came from server */
			ap->th_opcode = ntohs(ap->th_opcode);
			ap->th_block = ntohs(ap->th_block);
			if (ap->th_opcode == ERROR) {
				printf("Error code %d: %s\n", ap->th_code,
					ap->th_msg);
				goto abort;
			}
			if (ap->th_opcode == ACK) {
				int j;

				if (ap->th_block == block) {
					break;
				}
				/* On an error, try to synchronize
				 * both sides.
				 */
				j = synchnet(f);
				if (j && trace) {
					printf("discarded %d packets\n",
							j);
				}
				if (ap->th_block == (block-1)) {
					goto send_data;
				}
			}
		}
		if (block > 0)
			amount += size;
		block++;
	} while (size == SEGSIZE || block == 1);
abort:
	fclose(file);
	stopclock();
	if (amount > 0)
		printstats("Sent", amount);
}
示例#30
-1
/* helper processes start here via fork()/exec() in the parent  */
void DCC_NORET
helper_child(DCC_SOCKET s, int fd, int total_helpers)
{
	sigset_t sigs;
	socklen_t soc_len;
	DNSBL_REQ req;
	int req_len;
	DNSBL_RESP resp;
	DCC_SOCKU req_su;
	socklen_t su_len;
	struct timeval now;
	u_char wake_buf;
	int secs, i;

	/* this process inherits via exec() by dccm or dccifd odd signal
	 * blocking from some pthreads implementations including FreeBSD 5.* */
	signal(SIGHUP, SIG_IGN);
	signal(SIGINT, SIG_IGN);
	signal(SIGTERM, SIG_IGN);
	sigemptyset(&sigs);
	sigaddset(&sigs, SIGALRM);
	sigprocmask(SIG_UNBLOCK, &sigs, 0);

	helper_init(0);
	if (have_helpers)
		dcc_logbad(EX_SOFTWARE, "no threads for DNSBL helpers");

	helper.total_helpers = total_helpers;

	helper.pipe_read = fd;
	helper.soc = s;
	soc_len = sizeof(helper.su);
	if (0 > getsockname(helper.soc, &helper.su.sa, &soc_len))
		dcc_logbad(EX_IOERR, "DNSBL helper getsockname(%d): %s",
			   helper.soc, ERROR_STR());

	if (helper.debug > 1)
		dcc_trace_msg("DNSBL helper process starting on %s",
			      dcc_su2str_err(&helper.su));

	for (;;) {
		/* Use read() and SIGALRM to watch for a wake-up byte
		 * from the parent, the parent ending and closing the pipe,
		 * or enough idle time to require our retirement.  This
		 * tactic awakens a single child for each wake-up call
		 * from the parent.  Using select() or poll() on the main
		 * socket awakens a thundering herd of children */
		secs = HELPER_IDLE_STOP_SECS+1;
		if (helper.total_helpers > 0)
			secs /= helper.total_helpers+1;
		if (secs < 5)
			secs = 5;
		signal(SIGALRM, helper_alarm);
#ifdef HAVE_SIGINTERRUPT
		siginterrupt(SIGALRM, 1);
#endif
		helper_alarm_hit = 0;
		alarm(secs);
		for (;;) {
			su_len = sizeof(req_su);
			req_len = recvfrom(helper.soc, &req, ISZ(req), 0,
					   &req_su.sa, &su_len);

			/* sleep until awakened if no work is ready */
			if (req_len <= 0) {
				if (req_len == 0)
					dcc_logbad(EX_IOERR,
						   "DNSBL helper recvfrom()=0");
				if (!DCC_BLOCK_ERROR())
					dcc_logbad(EX_IOERR,
						   "DNSBL helper recvfrom():"
						   " %s",
						   ERROR_STR());
				if (helper_alarm_hit)
					helper_exit("idle helper exit");

				i = read(helper.pipe_read, &wake_buf, 1);

				/* The other end of the pipe can be marked
				 * non-blocking by some pthreads
				 * implementations.  That makes read() on this
				 * end fail with EAGAIN.  When that happens,
				 * fall back on select() or poll().
				 * Even on such pthread implementations,
				 * it rarely happens. */
				if (i < 0 && DCC_BLOCK_ERROR()) {
					DCC_POLLFD pollfd;
					DCC_EMSG emsg;

					pollfd.fd = helper.pipe_read;
					i = select_poll(emsg, &pollfd, 1,
							0, -1);
					if (i < 0)
					    dcc_logbad(EX_IOERR,
						       "dnsbl HELPER %s", emsg);
				}

				/* loof for work after a wake-up call */
				if (i > 0)
					continue;

				if (helper_alarm_hit)
					continue;
				if (i == 0)
					helper_exit("shutdown");
				if (i < 0) {
					dcc_logbad(EX_OSERR,
						   "DNSBL read(terminate): %s",
						   ERROR_STR());
				}
			}
			if (req_len != helper.req_len) {
				if (helper.debug)
					dcc_trace_msg("DNSBL helper"
						      " recvfrom(parent %s)=%d"
						      " instead of %d",
						      dcc_su2str_err(&req_su),
						      req_len,
						      helper.req_len);
				continue;
			}

			/* we might get stray packets because we cannot
			 * connect to a single port */
			if (!DCC_SUnP_EQ(&helper.su, &req_su)) {
				if (helper.debug)
					dcc_trace_msg("DNSBL helper"
						    " request from"
						    " %s instead of %s",
						    dcc_su2str_err(&req_su),
						    dcc_su2str_err(&helper.su));
				continue;
			}

			if (req.hdr.magic != HELPER_MAGIC_REQ
			    || req.hdr.version != HELPER_VERSION) {
				if (helper.debug)
					dcc_trace_msg("DNSBL helper"
						      " recvfrom(parent %s)"
						      " magic=%#08x",
						      dcc_su2str_err(&req_su),
						      req.hdr.magic);
				continue;
			}
			break;
		}
		gettimeofday(&now, 0);
		alarm(0);

		/* do not bother working if it is already too late to answer,
		 * perhaps because a previous helper died */
		i = tv_diff2us(&now, &req.hdr.start);
		if (i >= req.hdr.avail_us) {
			if (helper.debug > 1)
				dcc_trace_msg("%s DNSBL helper"
					      " already too late to start;"
					      " used %.1f of %.1f seconds",
					      req.hdr.id, i / (DCC_US*1.0),
					      req.hdr.avail_us / (DCC_US*1.0));
			continue;
		}

		memset(&resp, 0, sizeof(resp));
		resp.hdr.magic = HELPER_MAGIC_RESP;
		resp.hdr.version = HELPER_VERSION;
		resp.hdr.sn = req.hdr.sn;

		/* do the work and send an answer if we have one */
		if (!dnsbl_work(&req, &resp))
			continue;

		/* do not answer if it is too late */
		gettimeofday(&now, 0);
		i = tv_diff2us(&now, &req.hdr.start);
		if (i > (req.hdr.avail_us + DCC_US/2)) {
			if (helper.debug > 1)
				dcc_trace_msg("%s DNSBL helper"
					      " too late to answer;"
					      " used %.1f of %.1f seconds",
					      req.hdr.id, i / (DCC_US*1.0),
					      req.hdr.avail_us / (DCC_US*1.0));
			continue;
		}

		i = sendto(helper.soc, &resp, sizeof(resp), 0,
			   &req_su.sa, DCC_SU_LEN(&req_su));
		if (i != sizeof(resp)) {
			if (i < 0)
				dcc_error_msg("%s helper sendto(%s): %s",
					      req.hdr.id,
					      dcc_su2str_err(&req_su),
					      ERROR_STR());
			else
				dcc_error_msg("%s helper sendto(%s)=%d",
					      req.hdr.id,
					      dcc_su2str_err(&req_su), i);
		}
	}
}