Beispiel #1
0
    subprocess_stream::
    subprocess_stream(const char* program_name) : stderr(NULL), iosub(NULL)
    {
        if (access(program_name, F_OK))
            throw dlib::error("Error: '" + std::string(program_name) + "' file does not exist.");
        if (access(program_name, X_OK))
            throw dlib::error("Error: '" + std::string(program_name) + "' file is not executable.");

        child_pid = fork();
        if (child_pid == -1) 
            throw dlib::error("Failed to start child process"); 

        if (child_pid == 0) 
        {   
            // In child process
            dup2(data_pipe.child_fd(), STDIN_FILENO);
            dup2(stdout_pipe.child_fd(), STDOUT_FILENO);
            dup2(stderr_pipe.child_fd(),  STDERR_FILENO);
            data_pipe.close(); 
            stdout_pipe.close();
            stderr_pipe.close();

            char* argv[] = {(char*)program_name, nullptr};
            char* cudadevs = getenv("CUDA_VISIBLE_DEVICES");
            if (cudadevs)
            {
                std::string extra = std::string("CUDA_VISIBLE_DEVICES=") + cudadevs;
                char* envp[] = {(char*)extra.c_str(), nullptr};
                execve(argv[0], argv, envp);
            }
            else
            {
                char* envp[] = {nullptr};
                execve(argv[0], argv, envp);
            }


            // If launching the child didn't work then bail immediately so the parent
            // process has no chance to get tweaked out (*cough* MATLAB *cough*).
            _Exit(1);
        }
        else 
        {
            // In parent process
            close(data_pipe.child_fd());
            close(stdout_pipe.child_fd());
            close(stderr_pipe.child_fd());
            make_fd_non_blocking(data_pipe.parent_fd());
            make_fd_non_blocking(stdout_pipe.parent_fd());
            make_fd_non_blocking(stderr_pipe.parent_fd());
            inout_buf = std::unique_ptr<filestreambuf>(new filestreambuf(data_pipe.parent_fd(), stdout_pipe.parent_fd()));
            err_buf = std::unique_ptr<filestreambuf>(new filestreambuf(stderr_pipe.parent_fd(), stdout_pipe.parent_fd()));
            iosub.rdbuf(inout_buf.get());
            stderr.rdbuf(err_buf.get());
            iosub.tie(&iosub);
            stderr.tie(&iosub);
        }
    }
Beispiel #2
0
void accept_request_socket(http_conf *g) {
	int confd  ;
	struct sockaddr addr;
	struct sockaddr_in addrIn;
	socklen_t addLen = sizeof(struct sockaddr );

	while( (confd =  accept(g->fd, &addr, &addLen)) && confd > 0) {
		pool_t *p = (pool_t *)pool_create();
		http_connect_t * con;
		epoll_extra_data_t *data_ptr;

		addrIn =  *((struct sockaddr_in *) &addr);
		data_ptr = (epoll_extra_data_t *)palloc(p, sizeof(epoll_extra_data_t));
		con = (http_connect_t *) palloc(p, sizeof(http_connect_t));//换成初始化函数,
		con->p= p;
		con->fd = confd;
		con->in = (request *)request_init(p);
		con->out = (response *)response_init(p);
		char *ip  = NULL;
		if(addrIn.sin_addr.s_addr) {
			ip = inet_ntoa(addrIn.sin_addr);
		}

		if(ip) {
			con->in->clientIp = (string *) string_init_from_str(p, ip, strlen(ip));
		}

		make_fd_non_blocking(confd);
		con->next_handle = read_header;
		data_ptr->type = SOCKFD;
		data_ptr->ptr = (void *) con;
		epoll_add_fd(g->epfd, confd, EPOLL_R, (void *)data_ptr);//对epoll data结构指向的结构体重新封装,分websit
		//data struct ,  connect  data struct , file data struct ,
	}
}
Beispiel #3
0
int  open_write_file(http_connect_t *con)
{
    request * in;
    response *out;
    buffer *uri, *tmp, *dir;
    char *ptr ;
    FILE * fp;
    pool_t *p = con->p;
    int count = 0;

    in = con->in;
    out = con->out;


    uri = buffer_init(p);
    uri->ptr = in->uri->ptr;
    uri->used = uri->size = in->uri->len;


    dir = buffer_create_size(con->p, in->uri->len);
    memcpy(dir->ptr, uri->ptr, uri->used);
    ptr = dir->ptr + uri->used;
    dir->used = uri->used;
    while(ptr >= dir->ptr) {
        if(*ptr == '/') {
            *ptr = '\0';
            break;
        }
        ptr--;
        dir->used--;

    }

    uri->ptr[uri->used] = '\0';
    if(dir->used) {
        int ret  = _mkdir(con, dir->ptr, p);
        if(ret == -1) {
            return 0;
        }
    }

    ptr = (char *) palloc(p, sizeof(char)*2048);
    fp = fopen(uri->ptr, "w");

    if(fp) {
        make_fd_non_blocking(fileno(fp));
        con->write_file.fp = fp;
        con->write_file.len = 0;
        con->next_handle = write_file_content;
    } else {
        int logStrLen = strlen(dir) + 30;
        char * logStr = (char *) palloc(p, logStrLen);
        snprintf(logStr, logStrLen, "[access %s Permission denied]", dir );
        ds_log(con, logStr, LOG_LEVEL_ERROR);
        con->next_handle = send_put_forbidden_result;
    }


    return 0;
}
Beispiel #4
0
int start_cgi_server(http_conf *g, execute_cgi_info_manager_t * cgi_info_manager) {
    epoll_extra_data_t *data ;
    int epfd;

    data = (epoll_extra_data_t *) palloc(cgi_info_manager->p, sizeof(epoll_extra_data_t));
    data->type = CGISERVERFD;
    
    make_fd_non_blocking(g->child_pip.in);
    g->fd = g->child_pip.in;
    g->epfd = epoll_init(MAX_CONNECT);

    epoll_add_fd(g->epfd, g->fd, EPOLL_R, data);

    return 0;
}
Beispiel #5
0
int
main (int argc, char *argv[])
{
    int opt, hidfd, sfd = -1;
    int daemonize = 1;
    char *port = "9876";
    char *pid_path = NULL;
    char *hid_path = NULL;
    int pidfd = -1;

    while ((opt = getopt(argc, argv, "fp:P:d:")) != -1) {
	switch (opt) {
	    case 'f':
		daemonize = 0;
		break;
	    case 'p':
		port = optarg;
		break;
	    case 'P':
		pid_path = optarg;
		break;
	    default:
		usage(argv[0]);
		exit(EXIT_FAILURE);
	}
    }

    if (optind >= argc) {
	usage(argv[0]);
	exit(EXIT_FAILURE);
    }
    hid_path = argv[optind];

    if (pid_path) {
	/* open pidfile */
	pidfd = open(pid_path, O_RDWR | O_CREAT, 0644);
	if (pidfd < 0) {
	    perror("open pidfile");
	} else {
	    /* lock it */
	    if (flock(pidfd, LOCK_EX | LOCK_NB) != 0) {
		if (errno == EWOULDBLOCK) {
		    exit(EXIT_SUCCESS);
		} else {
		    perror("lock pidfile");
		}
	    }
	}
    }

    if (daemonize) {
	if (daemon(0, 0) != 0) {
	    perror("daemonize");
	}
    }

    if (pidfd >= 0) {
	/* truncate pidfile at 0 length */
	ftruncate(pidfd, 0);
	dprintf(pidfd, "%u\n", getpid());
	/* unlock the pidfile */
	flock(pidfd, LOCK_UN);
	close(pidfd);
    }

    signal(SIGINT, handle_sigterm);
    signal(SIGTERM, handle_sigterm);

    while (1) {
	int ok = 0;

	hidfd = open(hid_path, O_RDWR);
	if (hidfd < 0 || make_fd_non_blocking(hidfd) < 0) {
	    perror("open hid");
	} else {
	    sfd = create_and_bind_socket(port);
	    if (sfd < 0 || make_fd_non_blocking(sfd) < 0) {
		perror("open socket");
	    } else if (listen(sfd, SOMAXCONN) < 0) {
		perror("listen");
	    } else {
		ok = 1;
	    }
	}

	if (ok) {
	    event_loop(sfd, hidfd);
	}

	if (hidfd >= 0) {
	    close(hidfd);
	}
	if (sfd >= 0) {
	    close(sfd);
	}
	if (g_running) {
	    sleep(10);
	}
	if (!g_running) {
	    break;
	}
    }

    if (pidfd >= 0) {
	unlink(pid_path);
    }

    return 0;
}
Beispiel #6
0
static void
event_loop(int sockfd, int hidfd)
{
    int efd, i, s;
    struct epoll_event events[MAXEVENTS];
    struct timeval last_recv, last_heartbeat;
    int clientfds[MAXCLIENTS];
    int client_count = 0;

    efd = epoll_create1(0);
    if (efd == -1) {
	perror("epoll_create");
	goto out;
    }

    if (add_fd_to_epoll(efd, hidfd) < 0 || add_fd_to_epoll(efd, sockfd) < 0) {
	goto out;
    }

    memset(events, 0, sizeof(events));
    memset(&last_recv, 0, sizeof(last_recv));
    memset(&last_heartbeat, 0, sizeof(last_heartbeat));

    /* The event loop */
    while (1) {
	int n, item;

	n = epoll_wait (efd, events, MAXEVENTS, 2000);
	if (n < 0) {
	    if (errno != EINTR) {
		perror("epoll_wait");
	    }
	    goto out;
	}

	if (client_count > 0) {
	    struct timeval now;

	    gettimeofday(&now, NULL);
	    if (now.tv_sec - last_recv.tv_sec > RESET_TIMEOUT) {
		send_hmr_reset(hidfd);
		last_recv = now;
	    }
	    if (now.tv_sec - last_heartbeat.tv_sec > HEARTBEAT_INTERVAL) {
		send_hmr_heartbeat(hidfd);
		last_heartbeat = now;
	    }
	}

	for (item = 0; item < n; item++) {
	    struct epoll_event *ev = &events[item];

	    if (ev->events & (EPOLLERR | EPOLLHUP)) {
		fprintf (stderr, "epoll error\n");
		if (ev->data.fd == sockfd || ev->data.fd == hidfd) {
		    goto out;
		} else {
		    remove_client(ev->data.fd, clientfds, &client_count);
		    continue;
		}
	    } else if (sockfd == ev->data.fd) {
		/* We have a notification on the listening socket, which
		 * means one or more incoming connections. */
		while (1) {
		    struct sockaddr in_addr;
		    socklen_t in_len;
		    int infd;
		    char hbuf[NI_MAXHOST], sbuf[NI_MAXSERV];

		    in_len = sizeof(in_addr);
		    infd = accept(sockfd, &in_addr, &in_len);
		    if (infd == -1) {
			if (errno == EAGAIN || errno == EWOULDBLOCK) {
			    /* We have processed all incoming
			     * connections. */
			    break;
			} else {
			    perror("accept");
			    break;
			}
		    }

		    s = getnameinfo(&in_addr, in_len, hbuf, sizeof(hbuf),
				    sbuf, sizeof(sbuf), NI_NUMERICHOST | NI_NUMERICSERV);
		    if (s == 0) {
			printf("Accepted connection on descriptor %d "
			       "(host=%s, port=%s)\n", infd, hbuf, sbuf);
		    }

		    /* Make the incoming socket non-blocking and add it to the
		     * list of fds to monitor. */
		    s = make_fd_non_blocking(infd);
		    if (s == -1) {
			close(infd);
			continue;
		    }

		    if (add_fd_to_epoll(efd, infd) < 0) {
			close(infd);
			continue;
		    }
		    if (client_count < MAXCLIENTS) {
			if (client_count == 0) {
			    send_hmr_reset(hidfd);
			    send_hmr_heartbeat(hidfd);
			    gettimeofday(&last_recv, NULL);
			    last_heartbeat = last_recv;
			}
			clientfds[client_count++] = infd;
		    }
		}
	    } else if (hidfd == ev->data.fd) {
		char buf[8];
		ssize_t count = read(hidfd, buf, sizeof(buf));

		gettimeofday(&last_recv, NULL);
		if (count == 8) {
		    int cl, length = buf[0];
		    if (length < 8) {
			for (cl = 0; cl < client_count; ) {
			    if (write_exact(clientfds[cl], buf + 1, length) < 0) {
				remove_client(clientfds[cl], clientfds, &client_count);
				/* keep cl, as remove_client shifted the array */
			    } else {
				cl++;
			    }
			}
		    }
		}
	    } else {
		/* We have data on the fd waiting to be read. Read and
		 * discard it. We must read whatever data is available
		 * completely, as we are running in edge-triggered mode
		 * and won't get a notification again for the same
		 * data. */
		int done = 0;

		while (1) {
		    ssize_t count;
		    char buf[512];

		    count = read (ev->data.fd, buf, sizeof buf);
		    if (count == -1) {
			/* If errno == EAGAIN, that means we have read all
			 * data. So go back to the main loop. */
			if (errno != EAGAIN && errno != EWOULDBLOCK) {
			    perror ("read");
			    done = 1;
			}
			break;
		    } else if (count == 0) {
			/* End of file. The remote has closed the connection */
			done = 1;
			break;
		    }
		}

		if (done) {
		    printf ("Closed connection on descriptor %d\n", ev->data.fd);
		    /* Closing the descriptor will make epoll remove it
		     * from the set of descriptors which are monitored. */
		    remove_client(ev->data.fd, clientfds, &client_count);
		}
	    }
	}
    }

out:
    for (i = 0; i < client_count; i++) {
	close(clientfds[i]);
    }
    if (efd >= 0) {
	close(efd);
    }
}