Exemplo n.º 1
0
/*
 * Gather the fds read from input processes to a single output.
 */
STATIC void
gather_input_fds(struct dgsh_negotiation *mb)
{
	struct dgsh_conc *this_conc = find_conc(mb, pid);
	if (!this_conc) {
		printf("%s(): Concentrator with pid %d not registered",
				__func__, pid);
		exit(1);	// XXX
	}
	int n_to_write = this_conc->output_fds;
	int *read_fds = (int *)malloc(n_to_write * sizeof(int));
	int i, j, read_index;
	DPRINTF(4, "%s(): fds to write: %d", __func__, n_to_write);

	read_index = 0;
	for (i = STDIN_FILENO; i < nfd; i == STDIN_FILENO ? i = FREE_FILENO : i++) {
		int n_to_read = get_provided_fds_n(mb, pi[i].pid);
		DPRINTF(4, "%s(): fds to read for p[%d].pid %d: %d",
				__func__, i, pi[i].pid, n_to_read);
		for (j = read_index; j < read_index + n_to_read; j++) {
			read_fds[j] = read_fd(i);
			DPRINTF(4, "%s(): Read fd: %d from input channel: %d",
					__func__, read_fds[j], i);
		}
		read_index += n_to_read;
	}
	assert(read_index == n_to_write);

	for (i = 0; i < n_to_write; i++)
		write_fd(STDOUT_FILENO, read_fds[i]);

}
Exemplo n.º 2
0
/*
 * Scatter the fds read from the input process to multiple outputs.
 */
STATIC void
scatter_input_fds(struct dgsh_negotiation *mb)
{
	struct dgsh_conc *this_conc = find_conc(mb, pid);
	if (!this_conc) {
		printf("%s(): Concentrator with pid %d not registered",
				__func__, pid);
		exit(1);	// XXX
	}
	int n_to_read = this_conc->input_fds;
	int *read_fds = (int *)malloc(n_to_read * sizeof(int));
	int i, j, write_index = 0;
	bool ignore = false;
	DPRINTF(4, "%s(): fds to read: %d", __func__, n_to_read);

	for (i = 0; i < n_to_read; i++)
		read_fds[i] = read_fd(STDIN_FILENO);

	for (i = STDOUT_FILENO; i != STDIN_FILENO; i = next_fd(i, &ignore)) {
		int n_to_write = get_expected_fds_n(mb, pi[i].pid);
		DPRINTF(4, "%s(): fds to write for p[%d].pid %d: %d",
				__func__, i, pi[i].pid, n_to_write);
		for (j = write_index; j < write_index + n_to_write; j++) {
			write_fd(i, read_fds[j]);
			DPRINTF(4, "%s(): Write fd: %d to output channel: %d",
					__func__, read_fds[j], i);
		}
		write_index += n_to_write;
	}
	assert(write_index == n_to_read);
}
Exemplo n.º 3
0
Arquivo: log.c Projeto: yhcting/ylib
void
___ylog_write(enum yloglv lv,
	      const char *file, int lineno,
	      const char *fmt, ...) {
	int r, fd;
	struct timespec tm;
	char *buf = get_buffer();
	if (unlikely(!buf))
		return; /* ignore this log */
	if (unlikely(YLOG_VERBOSE > lv
		     || YLOG_FATAL < lv))
		return; /* invalid log level. ignore this log */
	if (unlikely(clock_gettime(CLOCK_MONOTONIC, &tm)))
		memset(&tm, 0, sizeof(tm));
	/* add log prefix */
	r = snprintf(buf, LOG_BUF_SZ, "[%c] %9lu.%9lu %s:%d ",
		     _lvchar[lv], tm.tv_sec, tm.tv_nsec, file, lineno);
	if (likely(r < LOG_BUF_SZ)) {
		int n;
		va_list alist;
		va_start(alist, fmt);
		n = vsnprintf(buf + r, LOG_BUF_SZ - r, fmt, alist);
		va_end(alist);
		r += n;
	}
	if (unlikely(r > LOG_BUF_SZ))
		r = LOG_BUF_SZ;
	fd = (likely(lv < YLOG_ERR))? _cfg.stdfd: _cfg.errfd;
	write_fd(fd, buf, r); /* return value is ignored intentionally */
}
Exemplo n.º 4
0
void 
process_events(int count) 
{
	int idx, res;

	//printf("count of desc %d\n", count);
	for (idx = 1; idx < count; idx++) {
		if (poll_fd[idx].revents & (POLLIN|POLLPRI)) {

			res = read_fd(poll_fd[idx].fd, &peer_ctx[idx]);
			if (res == 0 && peer_ctx[idx].sfd != -1)
				write_fd(poll_fd[idx].fd, &peer_ctx[idx]);
			else if (res == 0 && peer_ctx[idx].sfd == -1) {
				close(poll_fd[idx].fd);
				poll_fd[idx].fd = -1;
				poll_fd[idx].events = 0;
				poll_fd[idx].revents = 0;
				continue;
			} else 
				continue;

			printf("revents %d, Client send: %s\n",
			       poll_fd[idx].revents, peer_ctx[idx].buf);
		}
		if (poll_fd[idx].revents & (POLLERR|POLLNVAL)) {
			printf("we recived %d event from %d desc\n",
			       poll_fd[idx].revents, poll_fd[idx].fd);
			poll_fd[idx].fd = -1;
			poll_fd[idx].events = 0;
			poll_fd[idx].revents = 0;
		}

	}
}
Exemplo n.º 5
0
void
io_service::process_sets(struct pollfd* fds, std::size_t nfds) {
  std::vector<int> fds_to_read;
  std::vector<int> fds_to_write;

  //! Quickly fetch fds that are readable/writeable
  //! This reduce lock time and avoid possible deadlock in callbacks
  {
    std::lock_guard<std::recursive_mutex> lock(m_fds_mutex);

    for (std::size_t i = 0; i < nfds; ++i) {
      if (fds[i].revents & POLLIN && m_fds[fds[i].fd].async_read)
        fds_to_read.push_back(fds[i].fd);

      if (fds[i].revents & POLLOUT && m_fds[fds[i].fd].async_write)
        fds_to_write.push_back(fds[i].fd);
    }
  }

  for (int fd : fds_to_read) { read_fd(fd); }
  for (int fd : fds_to_write) { write_fd(fd); }

  if (fds[0].revents & POLLIN) {
    char buf[1024];
    (void) read(m_notif_pipe_fds[0], buf, 1024);
  }
}
Exemplo n.º 6
0
int main(void)
{

	int sockfd[2];
	socketpair(AF_LOCAL, SOCK_STREAM, 0, sockfd);
	
	int pid;
	int c = 0;
	int sd;
	int status;

	if ((pid = fork()) > 0)
	{
		close(sockfd[1]);
		read_fd(sockfd[0], &c, sizeof(int), &sd);
		fprintf(stderr, "read fd is : %d\n", sd);
		
	}
	close(sockfd[0]);

	int fd = open("/home/orion/codes/test/c/erm/erm_commnu_module.h",O_RDONLY);
	write_fd(sockfd[1], (void *)&c, sizeof(int), fd);
	fprintf(stderr, "write fd is : %d\n", fd);
	if (waitpid(pid, &status, 0) != 0 )
	{
		perror("waitpid");
		exit(1);
	}
	return 0;
}
Exemplo n.º 7
0
ssize_t Write_fd(int fd, void *ptr, size_t nbytes, int sendfd){
	ssize_t n;

	if( (n = write_fd(fd, ptr, nbytes, sendfd)) < 0)
		err_sys("write_fd error");

	return n;
}
/*
 * Class:     info_kghost_android_openvpn_ManagementSocket
 * Method:    write
 * Signature: (ILjava/nio/ByteBuffer;IILinfo/kghost/android/openvpn/FileDescriptorHolder;)I
 */
JNIEXPORT jint JNICALL Java_info_kghost_android_openvpn_ManagementSocket_write__ILjava_nio_ByteBuffer_2IILinfo_kghost_android_openvpn_FileDescriptorHolder_2
  (JNIEnv *env, jclass cls, jint socket, jobject buffer, jint offset, jint length, jobject fd)
{
  if (socket < 0) {
    throwError(env, "java/lang/IllegalArgumentException", "socket");
    return -1;
  }

  jlong cap = (*env)->GetDirectBufferCapacity(env, buffer);
  char* ptr = (*env)->GetDirectBufferAddress(env, buffer);
  int sendfd = jniGetFDFromFileDescriptor(env, fd);

  if (cap-offset < length) {
    throwError(env, "java/lang/IllegalArgumentException", "socket");
    return -1;
  }
  int result = write_fd(socket, ptr+offset, length, sendfd);
  if (result < 0) {
    switch (errno) {
      case EACCES:
      case EBADF:
      case ENOTCONN:
      case ENOTSOCK:
      case EISCONN:
      case ECONNRESET:
      case EDESTADDRREQ:
	throwError(env, "java/lang/IllegalArgumentException", "socket");
	break;
      case EINVAL:
	throwError(env, "java/lang/IllegalArgumentException", "inval");
	break;
      case EFAULT:
	throwError(env, "java/lang/IllegalArgumentException", "buffer");
	break;
      case EMSGSIZE:
	throwError(env, "java/lang/IllegalArgumentException", "msg size");
	break;
      case EINTR:
	throwError(env, "java/lang/InterruptedException", "interrupted");
	break;
      case ENOBUFS:
      case ENOMEM:
	throwError(env, "java/lang/RuntimeException", "oom");
	break;
      case EAGAIN:
	throwError(env, "java/lang/IllegalArgumentException", "non-block socket");
	break;
      default:
	throwError(env, "java/lang/RuntimeException", strerror(errno));
	break;
    }
  }

  return result;
}
Exemplo n.º 9
0
int main(int argc, char **argv)
{
	int fd;
	if(argc != 4)
		err_quit("OpenFile <sockfd#> <filename> <mode>");
	if((fd=open(argv[2],atoi(arg[3]))) < 0)
		exit((errno > 0) ? errno : 255);
	if(write_fd(atoi(argv[1]), " ", 1, fd) < 0)
		exit((errno > 0) ? errno : 255);
	exit(0);
}
Exemplo n.º 10
0
ssize_t
Write_fd(int fd, void *ptr, size_t nbytes, int sendfd)
{
	ssize_t		n;

	if ( (n = write_fd(fd, ptr, nbytes, sendfd)) < 0)
		//err_sys("write_fd error");
		fprintf(stderr, "write_fd error");

	return(n);
}
Exemplo n.º 11
0
static t_client	*write_to_write(t_client *client)
{
  client->to_write = first_node(&client->to_write->node);
  if (client->to_write == NULL)
    return (client);
  if (write_fd(client->to_write->str, client->ca.cfd) == true)
    return (sup_client(client));
  free(client->to_write->str);
  client->to_write = sup_node(&client->to_write->node);
  return (client);
}
Exemplo n.º 12
0
int
main(int argc, char **argv)
{
    int		fd;
    ssize_t	n;

    if (argc != 4)
        perror("openfile <sockfd#> <filename> <mode>");

    if ( (fd = open(argv[2], atoi(argv[3]))) < 0)
        exit( (errno > 0) ? errno : 255 );

    if ( (n = write_fd(atoi(argv[1]), "", 1, fd)) < 0)
        exit( (errno > 0) ? errno : 255 );

    exit(0);
}
Exemplo n.º 13
0
int myopen(char *path, int flag) {

	int sock_fd[2];
	pid_t childpid;
	char *str_socket_fileno;
	char *str_open_flag;
	int fd;
	int wait_state;
	int state;
	
	if(socketpair(PF_LOCAL, SOCK_STREAM, 0, sock_fd) < 0 ) {
		perror("");
		exit(1);
	}

	if ( (childpid = fork()) == 0 ) {
		close(sock_fd[0]);
		
		if( (fd = open(path, flag)) < 0 ) {
			perror("");
			exit(1);
		}

		if ( write_fd(sock_fd[1], fd) < 0 ) {
			perror("");
			exit(1);
		}
		exit(0);
	}

	close(sock_fd[1]);
	if ( waitpid(childpid, &state, 0) == -1 ) {
		perror("");
		exit(1);
	}
	
	if ( ! WIFEXITED(state) ||  WEXITSTATUS(state) != 0 ) {
		printf("child exit failure");
		exit(1);
	}

	fd = read_fd(sock_fd[0]);
	close(sock_fd[0]);

	return fd;
}
Exemplo n.º 14
0
static int _write_fd(ssize_t (*write_fd)(int fd, void *p, size_t count), int fd, void *p, size_t count)
{
	ssize_t ret;
	size_t sent = 0;

	while (sent < count) {
		ret = write_fd(fd, ((uint8_t*)p)+sent, count-sent);
		if (ret < 0) {
			if (errno == EAGAIN || errno == EINTR)
				continue;
			else
				return -1;
		}
		sent += ret;
	}

	return 0;
}
Exemplo n.º 15
0
int
main(int argc, char **argv){
  int fd;
  ssize_t n;
  printf("enter openfile\n");
  if(argc != 4){
    perror("argc != 4");
    exit(1);
  }

  if((fd = open(argv[2], atoi(argv[3]))) < 0){
    perror("open");
    exit(1);
  }
  printf("write fd  fd = %d\n", fd);
  if((n = write_fd(atoi(argv[1]), "", 1, fd)) < 0){
    perror("write fd error");
    exit(1);
  }
  
  exit(0);
}
Exemplo n.º 16
0
void handler()
{
	printf("Handler Called\n");
	if(scnt<tcnt)
	{
		int i;
		for (i = 0; i < 3; ++i)
		{
			if(flag[i]==0)
				break;
		}
		if(i!=3)
		{
			flag[i]=1;
			char *buf=(char*)malloc(255);
			sprintf(buf,"%d",no[scnt]);
			send(queue[scnt],buf,strlen(buf),0);
			write_fd(nusfd[i],queue[scnt]);
			announce(i,no[scnt]);
			scnt++;
		}
	}
}
Exemplo n.º 17
0
void libwrap_auth(CLI *c, char *accepted_address) {
    int result=0; /* deny by default */
#ifdef USE_PTHREAD
    static volatile int num_busy=0, roundrobin=0;
    int retval, my_process;
    static pthread_mutex_t mutex=PTHREAD_MUTEX_INITIALIZER;
    static pthread_cond_t cond=PTHREAD_COND_INITIALIZER;
#endif /* USE_PTHREAD */

    if(!c->opt->option.libwrap) /* libwrap is disabled for this service */
        return; /* allow connection */
#ifdef HAVE_STRUCT_SOCKADDR_UN
    if(c->peer_addr.sa.sa_family==AF_UNIX) {
        s_log(LOG_INFO, "Libwrap is not supported on Unix sockets");
        return;
    }
#endif
#ifdef USE_PTHREAD
    if(num_processes) {
        s_log(LOG_DEBUG, "Waiting for a libwrap process");

        retval=pthread_mutex_lock(&mutex);
        if(retval) {
            errno=retval;
            ioerror("pthread_mutex_lock");
            longjmp(c->err, 1);
        }
        while(num_busy==num_processes) { /* all child processes are busy */
            retval=pthread_cond_wait(&cond, &mutex);
            if(retval) {
                errno=retval;
                ioerror("pthread_cond_wait");
                longjmp(c->err, 1);
            }
        }
        while(busy[roundrobin]) /* find a free child process */
            roundrobin=(roundrobin+1)%num_processes;
        my_process=roundrobin; /* the process allocated by this thread */
        ++num_busy; /* the child process has been allocated */
        busy[my_process]=1; /* mark the child process as busy */
        retval=pthread_mutex_unlock(&mutex);
        if(retval) {
            errno=retval;
            ioerror("pthread_mutex_unlock");
            longjmp(c->err, 1);
        }

        s_log(LOG_DEBUG, "Acquired libwrap process #%d", my_process);
        write_fd(ipc_socket[2*my_process], c->opt->servname,
            strlen(c->opt->servname)+1, c->local_rfd.fd);
        read_blocking(c, ipc_socket[2*my_process],
            (u8 *)&result, sizeof result);
        s_log(LOG_DEBUG, "Releasing libwrap process #%d", my_process);

        retval=pthread_mutex_lock(&mutex);
        if(retval) {
            errno=retval;
            ioerror("pthread_mutex_lock");
            longjmp(c->err, 1);
        }
        busy[my_process]=0; /* mark the child process as free */
        --num_busy; /* the child process has been released */
        if(num_busy==num_processes-1) { /* need to wake up a thread */
            retval=pthread_cond_signal(&cond); /* signal waiting threads */
            if(retval) {
                errno=retval;
                ioerror("pthread_cond_signal");
                longjmp(c->err, 1);
            }
        }
        retval=pthread_mutex_unlock(&mutex);
        if(retval) {
            errno=retval;
            ioerror("pthread_mutex_unlock");
            longjmp(c->err, 1);
        }

        s_log(LOG_DEBUG, "Released libwrap process #%d", my_process);
    } else
#endif /* USE_PTHREAD */
    { /* use original, synchronous libwrap calls */
        enter_critical_section(CRIT_LIBWRAP);
        result=check(c->opt->servname, c->local_rfd.fd);
        leave_critical_section(CRIT_LIBWRAP);
    }
    if(!result) {
        s_log(LOG_WARNING, "Service [%s] REFUSED by libwrap from %s",
            c->opt->servname, accepted_address);
        s_log(LOG_DEBUG, "See hosts_access(5) manual for details");
        longjmp(c->err, 1);
    }
    s_log(LOG_DEBUG, "Service [%s] permitted by libwrap from %s",
        c->opt->servname, accepted_address);
}
Exemplo n.º 18
0
Arquivo: crypt.c Projeto: dkastner/sc
int
cwritefile(char *fname, int r0, int c0, int rn, int cn)
{
    register FILE *f;
    int pipefd[2];
    int fildes;
    int pid;
    char save[PATHLEN];
    char *fn;
    char *busave;

    if (*fname == '\0') fname = &curfile[0];

    fn = fname;
    while (*fn && (*fn == ' '))	/* Skip leading blanks */
	fn++;

    if (*fn == '|') {
	error("Can't have encrypted pipe");
	return (-1);
	}

    (void) strcpy(save, fname);

    busave = findhome(save);
#ifdef DOBACKUPS
    if (!backup_file(busave) &&
	    (yn_ask("Could not create backup copy, Save anyway?: (y,n)") != 1))
	return (0);
#endif
    if ((fildes = open (busave, O_TRUNC|O_WRONLY|O_CREAT, 0600)) < 0) {
	error("Can't create file \"%s\"", save);
	return (-1);
    }

    if (pipe(pipefd) < 0) {
	error("Can't make pipe to child\n");
	return (-1);
    }

    if (KeyWord[0] == '\0') {
	deraw(1);
	(void) strcpy(KeyWord, getpass("Enter key:"));
	goraw();
    }

    if ((pid=fork()) == 0) {			/* if child		 */
	(void) close(0);			/* close stdin		 */
	(void) close(1);			/* close stdout		 */
	(void) close(pipefd[1]);		/* close pipe output	 */
	(void) dup(pipefd[0]);			/* connect to pipe input */
	(void) dup(fildes);			/* standard out to file  */
	(void) fprintf(stderr, " ");
	(void) execl(CRYPT_PATH, "crypt", KeyWord, 0);
	(void) fprintf(stderr, "execl(%s, \"crypt\", %s, 0) in cwritefile() failed",
			CRYPT_PATH, KeyWord);
	exit (-127);
    }
    else {				  /* else parent */
	(void) close(fildes);
	(void) close(pipefd[0]);		  /* close pipe input */
	f = fdopen(pipefd[1], "w");
	if (f == 0) {
	    (void) kill(pid, -9);
	    error("Can't fdopen file \"%s\"", save);
	    (void) close(pipefd[1]);
	    return (-1);
	}
    }

    write_fd(f, r0, c0, rn, cn);

    (void) fclose(f);
    (void) close(pipefd[1]);
    while (pid != wait(&fildes)) /**/;
    (void) strcpy(curfile,save);

    modflg = 0;
    error("File \"%s\" written (encrypted).", curfile);
    return (0);
}
Exemplo n.º 19
0
// Funcion que graba un archivo
// recibe un rango como parametros y un nombre de archivo a generar
int writefile(char * fname, int r0, int c0, int rn, int cn) {
    register FILE *f;
    char save[PATHLEN];
    char tfname[PATHLEN];
    long namelen;
    char *tpp;
    int pid;

    /* find the extension and mapped plugin if exists
    if ((p = strrchr(fname, '.'))) {
    if ((plugin = findplugin(p+1, 'w')) != NULL) {
        if (!plugin_exists(plugin, strlen(plugin), save + 1)) {
        error("plugin not found");
        return -1;
        }
        *save = '|';
        if ((strlen(save) + strlen(fname) + 20) > PATHLEN) {
        error("Path too long");
        return -1;
        }
        sprintf(save + strlen(save), " %s%d:", coltoa(c0), r0);
        sprintf(save + strlen(save), "%s%d \"%s\"", coltoa(cn), rn, fname);
        // pass it to readfile as an advanced macro
        readfile(save, 0);
        return (0);
    }
    }*/

    if (*fname == '\0') {
        if (isatty(STDOUT_FILENO) || *curfile != '\0')
            fname = curfile;
        else {
            write_fd(stdout, r0, c0, rn, cn);
            return 0;
        }
    }

    if ((tpp = strrchr(fname, '/')) == NULL)
        namelen = pathconf(".", _PC_NAME_MAX);
    else {
        *tpp = '\0';
        namelen = pathconf(fname, _PC_NAME_MAX);
        *tpp = '/';
    }

    (void) strcpy(tfname, fname);
    for (tpp = tfname; *tpp != '\0'; tpp++)
        if (*tpp == '\\' && *(tpp + 1) == '"')
            (void) memmove(tpp, tpp + 1, strlen(tpp));

        if (scext != NULL) {
            if (strlen(tfname) > 3 && !strcmp(tfname + strlen(tfname) - 3, ".sc"))
                tfname[strlen(tfname) - 3] = '\0';
            else if (strlen(tfname) > strlen(scext) + 1 &&
            tfname[strlen(tfname) - strlen(scext) - 1] == '.' &&
            ! strcmp(tfname + strlen(tfname) - strlen(scext), scext))
                tfname[strlen(tfname) - strlen(scext) - 1] = '\0';
            tfname[namelen - strlen(scext) - 1] = '\0';
            strcat(tfname, ".");
            strcat(tfname, scext);
        }

    (void) strcpy(save, tfname);
    for (tpp = save; *tpp != '\0'; tpp++)
    if (*tpp == '"') {
        (void) memmove(tpp + 1, tpp, strlen(tpp) + 1);
        *tpp++ = '\\';
    }

    if ((f = openfile(tfname, &pid, NULL)) == NULL) {
        error("Can't create file \"%s\"", save);
        return -1;
    }

    info("Writing file \"%s\"...", save);
    write_fd(f, r0, c0, rn, cn);
    
    closefile(f, pid, 0);

    if (!pid) {
        (void) strcpy(curfile, save);
        modflg = 0;
        info("File \"%s\" written", curfile);
    }

    return 0;
}
Exemplo n.º 20
0
void
dg_cli(FILE *fp, int sockfd, const SA *pservaddr, socklen_t servlen)
{
	int				icmpfd, maxfdp1;
	char			sendline[MAXLINE], recvline[MAXLINE + 1];
	fd_set			rset;
	ssize_t			n;
	struct timeval	tv;
	struct icmpd_err icmpd_err;
	struct sockaddr_un sun;

	if (sock_bind_wild(sockfd, pservaddr->sa_family) < 0) {
		perror("sock_bind_wild error");
		exit(1);
	}

	if ((icmpfd = socket(AF_LOCAL, SOCK_STREAM, 0)) < 0) {
		perror("socket error");
		exit(1);
	}
	sun.sun_family = AF_LOCAL;
	strcpy(sun.sun_path, ICMPD_PATH);
	if (connect(icmpfd, (SA *)&sun, sizeof(sun)) < 0) {
		perror("connect error");
		exit(1);
	}
	if (write_fd(icmpfd, "1", 1, sockfd) < 0) {
		perror("write_fd error");
		exit(1);
	}
	if ((n = read(icmpfd, recvline, 1)) == -1) {
		perror("read error");
		exit(1);
	}
	if (n != 1 || recvline[0] != '1') {
		fprintf(stderr, "error creating icmp socket, n = %d, char = %c\n",
				 n, recvline[0]);
		exit(1);
	}

	FD_ZERO(&rset);
	maxfdp1 = max(sockfd, icmpfd) + 1;
/* end dgcli011 */

/* include dgcli012 */
	while (fgets(sendline, MAXLINE, fp) != NULL) {
		n = strlen(sendline);
		if (sendto(sockfd, sendline, n, 0, pservaddr, servlen) != n) {
			perror("sendto error");
			exit(1);
		}

		tv.tv_sec = 5;
		tv.tv_usec = 0;
		FD_SET(sockfd, &rset);
		FD_SET(icmpfd, &rset);
		if ( (n = select(maxfdp1, &rset, NULL, NULL, &tv)) < 0) {
			perror("select error");
			exit(1); 
		} else if (n == 0) {
			fprintf(stderr, "socket timeout\n");
			continue;
		}

		if (FD_ISSET(sockfd, &rset)) {
			if ((n = recvfrom(sockfd, recvline, MAXLINE, 0, NULL, NULL)) < 0) {
				perror("recvfrom error");
				exit(1);
			}
			recvline[n] = 0;	/* null terminate */
			if (fputs(recvline, stdout) == EOF) {
				perror("fputs error");
				exit(1);
			}
		}

		if (FD_ISSET(icmpfd, &rset)) {
			if ( (n = read(icmpfd, &icmpd_err, sizeof(icmpd_err))) < 0) {
				perror("read error");
				exit(1);
			} else if (n == 0) {
				fprintf(stderr, "ICMP daemon terminated\n");
				exit(1);
			} else if (n != sizeof(icmpd_err)) {
				fprintf(stderr, "n = %d, expected %d\n", n, sizeof(icmpd_err));
				exit(1);
			}
			printf("ICMP error: dest = %s, %s, type = %d, code = %d\n",
				   sock_ntop(&icmpd_err.icmpd_dest, icmpd_err.icmpd_len),
				   strerror(icmpd_err.icmpd_errno),
				   icmpd_err.icmpd_type, icmpd_err.icmpd_code);
		}
	}
}
Exemplo n.º 21
0
static int
zsocket(zoneid_t zoneid, const char *path) {
  char c = 0;
  ctid_t ct = -1;
  int _errno = 0;
  int pid = 0;
  int sock_fd = 0;
  int sockfd[2] = {0};
  int stat = 0;
  int tmpl_fd = 0;
  int flags;
  struct sockaddr_un addr;
  size_t addr_len = 0;

  if (zoneid < 0) {
    return (-1);
  }

  if (path == NULL) {
    return (-1);
  }

  bzero(&addr, sizeof (addr));

  pthread_mutex_lock(&lock);

  if ((tmpl_fd = init_template()) < 0) {
    pthread_mutex_unlock(&lock);
    return (-1);
  }

  if (socketpair(AF_LOCAL, SOCK_STREAM, 0, sockfd) != 0) {
    (void) ct_tmpl_clear(tmpl_fd);
    pthread_mutex_unlock(&lock);
    return (-1);
  }

  pid = fork();
  debug("fork returned: %d\n", pid);
  if (pid < 0) {
    _errno = errno;
    (void) ct_tmpl_clear(tmpl_fd);
    close(sockfd[0]);
    close(sockfd[1]);
    errno = _errno;
    pthread_mutex_unlock(&lock);
    return (-1);
  }

  if (pid == 0) {
    (void) ct_tmpl_clear(tmpl_fd);
    (void) close(tmpl_fd);
    (void) close(sockfd[0]);

    if (zone_enter(zoneid) != 0) {
      debug("CHILD: zone_enter(%d) => %s\n", zoneid, strerror(errno));
      _exit(1);
    }

    debug("CHILD: zone_enter(%d) => %d\n", zoneid, 0);
    (void) unlink(path);
    sock_fd = socket(PF_UNIX, SOCK_STREAM, 0);
    if (sock_fd < 0) {
      debug("CHILD: socket => %d\n", errno);
      _exit(2);
    }
    fcntl(sock_fd, F_SETFL, O_NONBLOCK);
    addr.sun_family = AF_UNIX;
    addr_len = sizeof (addr.sun_family) +
      snprintf(addr.sun_path, sizeof (addr.sun_path), path);

    if (bind(sock_fd, (struct sockaddr *) &addr, addr_len) != 0) {
      debug("CHILD: bind => %d\n", errno);
      _exit(3);
    }

    if (write_fd(sockfd[1], (void *)"", 1, sock_fd) < 0) {
      debug("CHILD: write_fd => %d\n", errno);
      _exit(4);
    }

    debug("CHILD: write_fd => %d\n", errno);
    _exit(0);
  }

  if (contract_latest(&ct) == -1) {
    ct = -1;
  }
  (void) ct_tmpl_clear(tmpl_fd);
  (void) close(tmpl_fd);
  (void) contract_abandon_id(ct);
  (void) close(sockfd[1]);
  debug("PARENT: waitforpid(%d)\n", pid);
  while ((waitpid(pid, &stat, 0) != pid) && errno != ECHILD) {
      /* DO NOTHING */;
  }

  if (WIFEXITED(stat) == 0) {
    debug("PARENT: Child didn't exit\n");
    _errno = ECHILD;
    sock_fd = -1;
  } else {
    stat = WEXITSTATUS(stat);
    debug("PARENT: Child exit status %d\n", stat);
    if (stat == 0) {
      read_fd(sockfd[0], &c, 1, &sock_fd);
    } else {
      _errno = stat;
      sock_fd = -1;
    }
  }

  close(sockfd[0]);
  pthread_mutex_unlock(&lock);
  if (sock_fd < 0) {
    errno = _errno;
  } else {
    if ((flags = fcntl(sock_fd, F_GETFD)) != -1) {
      flags |= FD_CLOEXEC;
      (void) fcntl(sock_fd, F_SETFD, flags);
    }

    errno = 0;
  }
  debug("zsocket returning fd=%d, errno=%d\n", sock_fd, errno);
  return (sock_fd);
}
Exemplo n.º 22
0
/**
 * new connecion comes, copy file descroptor of new connecton to child
 * process , parent process select
 * @return  0
 */
int main(int argc, char **argv)
{

    int res;
    res = register_sig_handler();
    if (res < 0)
        err_sys("register_sig_handler is err");

    my_getopt(argc, argv);

    int pipefd[2];

    int socket_fd;
    res = srv_socket_init(&socket_fd, 50, PORT);
    if (res < 0)
        err_sys("srv_socket_init err");

    fd_set myset;
    FD_ZERO(&myset);
    FD_SET(socket_fd, &myset);
    int max = socket_fd;

    arraychild = (child_t *) malloc(sizeof(child_t) * childnum);
    memset(arraychild, 0, sizeof(child_t) * childnum);
    for (int i = 0 ; i < childnum; i++)
    {

        res = socketpair(AF_LOCAL, SOCK_STREAM, 0, pipefd);
        if (res < 0)
            err_sys("socketpair is err");
        arraychild[i].child_pipefd = pipefd[0];
        FD_SET(pipefd[0], &myset);
        if (pipefd[0] > max)
            max = pipefd[0];

        int pid = fork();
        if (pid < 0)
            err_sys("fork err");

        if (pid == 0)
        {
            srv_socket_destory(&socket_fd);

            int connfd;
            int childpid = getpid();
            while(1)
            {

                char c;
                res = read_fd(pipefd[1], &c, 1, &connfd);
                if (res < 0)
                    err_sys("read_fd err");
                fprintf(stdout, "pid is %d, accept success.\n",childpid);
                child_process(connfd);

                write(pipefd[1], "", 1);

                srv_socket_close(&connfd);
            }
            //exit(0);
        }
        else
        {
            arraychild[i].child_pid = pid;
        }
    }

    struct sigaction myact;
    myact.sa_handler = sig_int_handler;
    if (sigaction(SIGINT, &myact, NULL) < 0)
        err_sys("sigaction err");

    int navail = childnum;
    fd_set rset ;
    int newfd;
    int i = 0;
    while(1)
    {
        rset = myset;
        if (navail <=0 )
            FD_CLR(socket_fd, &rset);


        select(max + 1, &rset, NULL, NULL, NULL);
        if (FD_ISSET(socket_fd, &rset))
        {
            newfd = accept(socket_fd, NULL, NULL);

            for (i = 0; i < childnum; i++)
            {
                if (arraychild[i].child_status == 0)
                    break;
            }

            res = write_fd(arraychild[i].child_pipefd, "", 1, newfd);
            if (res < 0)
            {
                continue;
            }
            srv_socket_close(&newfd);
            arraychild[i].child_status = 1;
            arraychild[i].child_count++;
            navail--;
        }
        for (int i = 0; i < childnum; i++)
        {
            char c;
            if (FD_ISSET(arraychild[i].child_pipefd, &rset))
            {
                read(arraychild[i].child_pipefd, &c, 1);
                arraychild[i].child_status = 0;
                navail++;
            }
        }
    }

    return 0;
}
Exemplo n.º 23
0
int 
main(int argc, char *argv[])
{
	char **argp = ++argv;
	char *fname;
	char *op;
	int max_pages;
	int rest_secs;
	int iteration = 0;

#define NARGS 4
	if(argc < NARGS + 1)
	{
		printf("frw <fname> <op=r/w> <max_pages> <rest_secs>\n");
		printf("op = r - read , w - random, s - fsync write\n");
		return -2;
	}  
	fname = *argp++;
	op = *argp++;
	sscanf(*argp++, "%d", &max_pages);
	sscanf(*argp++, "%d", &rest_secs);
	printf("fname = %s op=%s  max_pages = %d rest_secs = %d\n", fname, op, max_pages, rest_secs);
	
	if(op[0] == 'r')
	{
		slam_fd = open(fname, O_RDWR);
	}
	else
	{
		slam_fd = open(fname, O_WRONLY| O_TRUNC);
		if(slam_fd < 0 )
			slam_fd = creat(fname, 0666);
		
	}
	if(slam_fd < 0)
	{
		perror("open:");
		return -2;
	}

	signal(SIGINT, sigterm_hdlr);
	signal(SIGTERM, sigterm_hdlr);

	while(1)
	{
		timeit(NULL);
		if(op[0] == 'r')
		{
			read_fd(slam_fd, max_pages, op[1]=='r');
			timeit("read");
		}
		else
		{
			write_fd(slam_fd, max_pages, op[1]=='r');
			if(op[0] == 's')
			{
				fsync(slam_fd);
				timeit("write fsync");
			}
			else
			{
				timeit("write");
			}
		}
		printf("%d:iter=%d\n", getpid(), iteration++);
		
		sleep(rest_secs);
	}
	
	return 0;
	 
}
Exemplo n.º 24
0
int main(int argc, char const *argv[])
{
	if (argc!=2)
	{
		printf("Pass the main server Port\n");
		exit(1);
	}
	shm_init();
	int usfd=init_UDSSER();
	init_Raw_Socket();
	
	int i;
	for(i=0;i<3;i++)
	{
		int c=fork();
		if(c==0)
		{
			execl("p","p",NULL);
		}
	}
	accept_UDS(usfd,nusfd,3);
	int train_no=1;
	
	flag[3]=getpid();
	int sfd=socket(AF_INET,SOCK_STREAM,0);
	if (sfd==-1)
	{
		printf("Socket Error : %d\n",errno);
		exit(1);
	}

	struct sockaddr_in saddr;
	memset(&saddr, 0, sizeof(struct sockaddr_in));
	saddr.sin_family=AF_INET;
	saddr.sin_port=htons(atoi(argv[1]));
	saddr.sin_addr.s_addr=inet_addr("127.0.0.1");
	int addr_len=sizeof(struct sockaddr_in);

	int ret=bind(sfd,(struct sockaddr*)&saddr,sizeof(saddr));	
	if (ret==-1)
	{
		printf("Bind Error : %d\n",errno);
		exit(1);
	}

	ret=listen(sfd,10);
	if (ret==-1)
	{
		printf("Listen Error : %d\n", errno);
		exit(1);
	}

	signal(SIGUSR1,handler);
	

	while(1)
	{
		struct timeval tv;
		tv.tv_sec = 1;
	    tv.tv_usec = 0;
	    fd_set tr;
	    FD_ZERO(&tr);
	    FD_SET(sfd,&tr);
	    int res=select(sfd+1,&tr,NULL,NULL,&tv);
	    if(res>0&&FD_ISSET(sfd,&tr))
	    {
	    	struct sockaddr_in caddr;
			memset(&caddr, 0, sizeof(struct sockaddr_in));
			int caddr_len=sizeof(saddr);
			int nsfd=accept(sfd,(struct sockaddr*)&caddr,&caddr_len);
			if(nsfd==-1)
			{
				printf("Accept Error : %d\n", errno);
				exit(1);
			}
			int i;
			for (i = 0; i < 3; ++i)
			{
				if(flag[i]==0)
					break;
			}
			if(i!=3)
			{
				flag[i]=1;
				char *buf=(char*)malloc(255);
				sprintf(buf,"%d",train_no);
				send(nsfd,buf,strlen(buf),0);
				write_fd(nusfd[i],nsfd);
				announce(i,train_no);
			}
			else
			{
				queue[tcnt]=nsfd;
				no[tcnt]=train_no;
				tcnt++;
				printf("%d is waiting ...\n",train_no );
			}
			train_no++;
	    }
	}
}