Exemple #1
0
int destroy_sandbox_reaper(Service*, int pid, int status) {

	// map pid to the SandboxEnt stucture we have recorded
	SandboxMap::iterator i;
	i = sandbox_map.find(pid);
	SandboxEnt e = i->second;

	if(status == 0) {
		const char * res[1] = {
			"NULL"
		};
		enqueue_result(e.request_id, res, 1);
	} else {
		char *err_msg = NULL;
		read_from_pipe( e.error_pipe, &err_msg );
		if ( err_msg == NULL || err_msg[0] == '\0' ) {
			err_msg = strdup( "Worker thread failed" );
		}

		const char * res[1] = {
			err_msg
		};
		enqueue_result(e.request_id, res, 1);

		free( err_msg );
	}

	close( e.error_pipe );

	// remove from the map
	sandbox_map.erase(pid);

	return 0;
}
Exemple #2
0
int main(void)
{
	int fd[2];
	pid_t pid;
	int stat_val;

	if(pipe(fd)) {
		printf("creat pipe failed!\n");
		exit(1);
	}	
	
	pid = fork();
	switch(pid) {
		case -1:
			printf("fork error!\n");
			exit(1);
		case 0:
			//子进程关闭fd0
			close(fd[0]);
			write_to_pipe(fd[1]);
			exit(0);
		default:
			//父进程关闭fd1
			close(fd[1]);
			read_from_pipe(fd[0]);
			wait(&stat_val);
			exit(0);
	}

	return 0;
}
Exemple #3
0
int main(void)
{
    pid_t pid;
    int mypipe[2];

    /* Create the pipe. */
    if (pipe(mypipe)) {
        write(STDOUT_FILENO, ERR_PIPE, sizeof(ERR_PIPE) - 1);
        return -1;
    }

    /* Create the child process. */
    pid = fork();
    if (pid == (pid_t) 0) {
        /* This is the child process.
           Close other end first. */
        close(mypipe[1]);
        read_from_pipe(mypipe[0]);
        return -1;
    } else if (pid < (pid_t) 0) {
        /* The fork failed. */
        write(STDOUT_FILENO, ERR_FORK, sizeof(ERR_FORK) - 1);
        return -1;
    } else {
        /* This is the parent process.
           Close other end first. */
        close(mypipe[0]);
        write_to_pipe(mypipe[1]);
        return -1;
    }
}
Exemple #4
0
static int run_cmd_with_pipes (const char *arg, char **sout, PRN *prn,
			       int flag) 
{ 
    HANDLE hread, hwrite;
    SECURITY_ATTRIBUTES sa; 
    int ok; 
 
    /* set the bInheritHandle flag so pipe handles are inherited */
    sa.nLength = sizeof(SECURITY_ATTRIBUTES); 
    sa.bInheritHandle = TRUE; 
    sa.lpSecurityDescriptor = NULL; 

    /* create pipe for the child process's STDOUT */ 
    ok = CreatePipe(&hread, &hwrite, &sa, 0);

    if (!ok) {
	win_show_last_error();
    } else {
	/* ensure that the read handle to the child process's pipe for 
	   STDOUT is not inherited */
	SetHandleInformation(hread, HANDLE_FLAG_INHERIT, 0);
	ok = run_child_with_pipe(arg, hwrite, hread, flag);
	if (ok) {
	    /* read from child's output pipe */
	    read_from_pipe(hwrite, hread, sout, prn); 
	}
    }
 
    return 0; 
} 
Exemple #5
0
/****************************************************************************
  reply to a read and X

  This code is basically stolen from reply_read_and_X with some
  wrinkles to handle pipes.
****************************************************************************/
int reply_pipe_read_and_X(char *inbuf,char *outbuf,int length,int bufsize)
{
	pipes_struct *p = get_rpc_pipe_p(inbuf,smb_vwv2);
	int smb_maxcnt = SVAL(inbuf,smb_vwv5);
	int smb_mincnt = SVAL(inbuf,smb_vwv6);
	int nread = -1;
	char *data;
	/* we don't use the offset given to use for pipe reads. This
           is deliberate, instead we always return the next lump of
           data on the pipe */
#if 0
	uint32 smb_offs = IVAL(inbuf,smb_vwv3);
#endif

	if (!p)
		return(ERROR(ERRDOS,ERRbadfid));

	set_message(outbuf,12,0,True);
	data = smb_buf(outbuf);

	nread = (int)read_from_pipe(p, data, (size_t)smb_maxcnt);

	if (nread < 0)
		return(UNIXERROR(ERRDOS,ERRnoaccess));
  
	SSVAL(outbuf,smb_vwv5,nread);
	SSVAL(outbuf,smb_vwv6,smb_offset(data,outbuf));
	SSVAL(smb_buf(outbuf),-2,nread);
  
	DEBUG(3,("readX-IPC pnum=%04x min=%d max=%d nread=%d\n",
		 p->pnum, smb_mincnt, smb_maxcnt, nread));

	return chain_reply(inbuf,outbuf,length,bufsize);
}
Exemple #6
0
void
pipeInput(){

	FILE *pfs;
	char *input;
	int result = 1;

	while( result == 1){
		//continue trying to read input
		input = read_from_pipe();
		result = strncmp(input, "\0", 1);	
	}	
	
	if (echo  == 1){
		/*echo FIFO to STDOUT*/	
		printf("%s \n", input);
	}

	//open the command, then send input to command
	//send input to run_file

	//run the command that was input
	pfs = safe_popen(command, "w");

	fputs(input, pfs);
	fputc('\n', pfs);

	//run at end
	pclose(pfs);	
}
std::string pipe_line_reader::real_get_line_from_pipe
(
    ivytime timeout,
    std::string description // passed by reference to called routines to receive an error message when called function returns "false"
)
{
    std::string s;

    if ( next_char_from_slave_buf >= bytes_last_read_from_slave && !last_read_from_pipe )
    {
        std::ostringstream o;
        o << "<Error> pipe_line_reader::get_line_from_pipe(timeout=" << timeout.format_as_duration_HMMSSns() << ") - no characters available in buffer and read_from_pipe() failed - " << description;
        throw std::runtime_error(o.str());
    }

    if ( next_char_from_slave_buf >= bytes_last_read_from_slave )
    {
        last_read_from_pipe = read_from_pipe(timeout);
        if (!last_read_from_pipe)
        {
            std::ostringstream o;
            o << "<Error> pipe_line_reader::get_line_from_pipe(timeout=" << timeout.format_as_duration_HMMSSns() << ") - no characters available in buffer and read_from_pipe() failed - " << description;
            throw std::runtime_error(o.str());
        }
    }

    // We have bytes in the buffer to serve up and from here on we can only return true.

    while(true)
    {
        // we move characters one at a time from the read buffer, stopping when we see a '\n'.

        if (next_char_from_slave_buf>=bytes_last_read_from_slave)
        {
            // if no more characters in buffer
            last_read_from_pipe=read_from_pipe(timeout);
            if (!last_read_from_pipe) break;
        }
        char c;
        c = buffer[next_char_from_slave_buf++];
        if ('\n' == c) break;
        s.push_back(c);
    }

    return s;
}
Exemple #8
0
static enum mad_flow output(
		void * data,
		const struct mad_header * head,
		struct mad_pcm * pcm) {
	struct stream * ptr = (struct stream *) data;

	unsigned nchan = pcm->channels, rate = pcm->samplerate;
	register unsigned nsample = pcm->length;
	mad_fixed_t * left = pcm->samples[0], * right = pcm->samples[1];
	char *stream, *stream_ptr;

	head = NULL;

	if((signed) rate != ptr->fmt.rate || (signed) nchan != ptr->fmt.channels) {
		ptr->fmt.rate = rate;
		ptr->fmt.channels = nchan;
		if(ptr->device != NULL)
			ao_close(ptr->device);
		ptr->device = ao_open_live(ptr->driver_id, & ptr->fmt, NULL);

		if(NULL == ptr->device) {
			fprintf(stderr, "Unable to open device. %s.\n", strerror(errno));
			return MAD_FLOW_BREAK;
		}
	}

	stream_ptr = stream = malloc(pcm->length * (pcm->channels == 2 ? 4 : 2));

	assert(stream != NULL);
	read_from_pipe(ptr->pipefd);
	
	while(nsample--) {
		signed int sample;

		sample = scale(* left++);
		/* to byteswap or not to byteswap? */
#ifdef WORDS_BIGENDIAN
		*stream_ptr++ = (sample >> 8) & 0xFF;
		*stream_ptr++ = (sample & 0xFF);
#else
		*stream_ptr++ = (sample & 0xFF);
		*stream_ptr++ = (sample >> 8) & 0xFF;
#endif

		if(nchan == 2) {
			sample = scale(* right++);
#ifdef WORDS_BIGENDIAN
			*stream_ptr++ = (sample >> 8) & 0xFF;
			*stream_ptr++ = (sample & 0xFF);
#else
			*stream_ptr++ = (sample & 0xFF);
			*stream_ptr++ = (sample >> 8) & 0xFF;
#endif
		}
	}
Exemple #9
0
void Server::consumeData(){
	while(true){
		shm->mutexProcess.wait();

		/* Receve data from parent by PIPE */
		string data = read_from_pipe();
		/* Execute the data */
		execMsg(data);

		shm->mutexSend.post();
		shm->mutexAnswer.wait();
		shm->mutexThread.unlock();
	}
}
Exemple #10
0
void Server::manipulateData(string data, socket_ptr sock){
	shm->mutexThread.lock();

	/* Send data from client to fork by PIPE */
	write_to_pipe(data);

	shm->mutexProcess.post();
	shm->mutexSend.wait();

	string res = read_from_pipe();
	boost::system::error_code error;
	boost::asio::write(*sock, boost::asio::buffer(res), error);
	cout << "Message answered!" << endl;
	shm->mutexAnswer.post();
}
Exemple #11
0
static inline void
get_kbuild_opts(char **kbuild_dir, char **kbuild_include_opts)
{
	int err;

	if (!kbuild_dir || !kbuild_include_opts)
		return;

	*kbuild_dir = NULL;
	*kbuild_include_opts = NULL;

	if (llvm_param.kbuild_dir && !llvm_param.kbuild_dir[0]) {
		pr_debug("[llvm.kbuild-dir] is set to \"\" deliberately.\n");
		pr_debug("Skip kbuild options detection.\n");
		return;
	}

	err = detect_kbuild_dir(kbuild_dir);
	if (err) {
		pr_warning(
"WARNING:\tunable to get correct kernel building directory.\n"
"Hint:\tSet correct kbuild directory using 'kbuild-dir' option in [llvm]\n"
"     \tsection of ~/.perfconfig or set it to \"\" to suppress kbuild\n"
"     \tdetection.\n\n");
		return;
	}

	pr_debug("Kernel build dir is set to %s\n", *kbuild_dir);
	force_set_env("KBUILD_DIR", *kbuild_dir);
	force_set_env("KBUILD_OPTS", llvm_param.kbuild_opts);
	err = read_from_pipe(kinc_fetch_script,
			     (void **)kbuild_include_opts,
			     NULL);
	if (err) {
		pr_warning(
"WARNING:\tunable to get kernel include directories from '%s'\n"
"Hint:\tTry set clang include options using 'clang-bpf-cmd-template'\n"
"     \toption in [llvm] section of ~/.perfconfig and set 'kbuild-dir'\n"
"     \toption in [llvm] to \"\" to suppress this detection.\n\n",
			*kbuild_dir);

		free(*kbuild_dir);
		*kbuild_dir = NULL;
		return;
	}

	pr_debug("include option is set to %s\n", *kbuild_include_opts);
}
Exemple #12
0
void excrate_handle(struct excrate *e)
{
    assert(e->pid != 0);

    if (e->pe == NULL)
        return;

    if (e->pe->revents == 0)
        return;

    if (read_from_pipe(e) != -1)
        return;

    do_wait(e);
    fire(&e->completion, NULL);
    list_del(&e->rig);
    excrate_release(e); /* may invalidate e */
}
Exemple #13
0
int
exec_and_wait_for_output(po_thrd ptr, char *command)
{
  char buf[0x2000];
  int r = 4;

  bzero(buf, 0x2000);

  if ((r = open_pipe_to_executable(command, ptr)))
    {
      return -0xE;
    }

  r = read_from_pipe(buf, ptr->fd_pipe);

  pclose(ptr->fd_pipe);

  return 0;
}
Exemple #14
0
void reply_pipe_read_and_X(struct smb_request *req)
{
	smb_np_struct *p = get_rpc_pipe_p(SVAL(req->inbuf,smb_vwv2));
	int smb_maxcnt = SVAL(req->inbuf,smb_vwv5);
	int smb_mincnt = SVAL(req->inbuf,smb_vwv6);
	int nread = -1;
	char *data;
	bool unused;

	/* we don't use the offset given to use for pipe reads. This
           is deliberate, instead we always return the next lump of
           data on the pipe */
#if 0
	uint32 smb_offs = IVAL(req->inbuf,smb_vwv3);
#endif

	if (!p) {
		reply_doserror(req, ERRDOS, ERRbadfid);
		return;
	}

	reply_outbuf(req, 12, smb_maxcnt);

	data = smb_buf(req->outbuf);

	nread = read_from_pipe(p, data, smb_maxcnt, &unused);

	if (nread < 0) {
		reply_doserror(req, ERRDOS, ERRnoaccess);
		return;
	}

	srv_set_message((char *)req->outbuf, 12, nread, False);
  
	SSVAL(req->outbuf,smb_vwv5,nread);
	SSVAL(req->outbuf,smb_vwv6,smb_offset(data,req->outbuf));
	SSVAL(smb_buf(req->outbuf),-2,nread);
  
	DEBUG(3,("readX-IPC pnum=%04x min=%d max=%d nread=%d\n",
		 p->pnum, smb_mincnt, smb_maxcnt, nread));

	chain_reply(req);
}
Exemple #15
0
int download_sandbox_reaper(Service*, int pid, int status) {

	// map pid to the SandboxEnt stucture we have recorded
	SandboxMap::iterator i;
	i = sandbox_map.find(pid);
	SandboxEnt e = i->second;

	if (status == 0) {
		std::string path;
		define_sandbox_path(e.sandbox_id, path);

		const char * res[2] = {
			"NULL",
			path.c_str()
		};

		enqueue_result(e.request_id, res, 2);
	} else {
		char *err_msg = NULL;
		read_from_pipe( e.error_pipe, &err_msg );
		if ( err_msg == NULL || err_msg[0] == '\0' ) {
			free( err_msg );
			err_msg = strdup( "Worker thread failed" );
		}

		const char * res[2] = {
			err_msg,
			"NULL"
		};
		enqueue_result(e.request_id, res, 2);

		free( err_msg );
	}

	close( e.error_pipe );

	// remove from the map
	sandbox_map.erase(pid);

	return 0;
}
Exemple #16
0
int
main (void)
{
  pid_t pid;
  int mypipe[2];

/*@group*/
  /* Create the pipe.  */
  if (pipe (mypipe))
    {
      fprintf (stderr, "Pipe failed.\n");
      return EXIT_FAILURE;
    }
/*@end group*/

  /* Create the child process.  */
  pid = fork ();
  if (pid == (pid_t) 0)
    {
      /* This is the child process.
	 Close other end first.  */
      close (mypipe[1]);
      read_from_pipe (mypipe[0]);
      return EXIT_SUCCESS;
    }
  else if (pid < (pid_t) 0)
    {
      /* The fork failed.  */
      fprintf (stderr, "Fork failed.\n");
      return EXIT_FAILURE;
    }
  else
    {
      /* This is the parent process.
	 Close other end first.  */
      close (mypipe[0]);
      write_to_pipe (mypipe[1]);
      return EXIT_SUCCESS;
    }
}
Exemple #17
0
int main(int argc, char** argv) {

    pid_t pid;
    int mypipe[2];

    /* Create the pipe. */
    printf("Create Pipe in parent process!\n");
    if (pipe(mypipe)) {
        fprintf(stderr, "Pipe failed.\n");
        return EXIT_FAILURE;
    }

    printf("Fork this process now!\n");
    pid = fork();
    if (pid == (pid_t) 0) { /*child*/
        printf("This is the child process!\n");
        printf("%d\n", pid);

        /* This is the child process.
         Close other end first. */
        close(mypipe[1]);
        printf("Read from Pipe!\n");
        read_from_pipe(mypipe[0]);
        return EXIT_SUCCESS;
    } else if (pid < (pid_t) 0) { 
        /* The fork failed. */
        fprintf(stderr, "Fork failed.\n");
        return EXIT_FAILURE;
    } else {
        printf("This is the parent process!\n");
        printf("%d\n", pid);
        /* This is the parent process.
           Close other end first. */
        close(mypipe[0]);
        printf("Write to Pipe!\n");
        write_to_pipe(mypipe[1]);
        return EXIT_SUCCESS;
    }

}
Exemple #18
0
void process_requests(void)
{
	int retval = 0;
	request *current, *trailer;

	current = request_ready;

	while (current) {
#ifdef CRASHDEBUG
		crashdebug_current = current;
#endif		
		if (current->buffer_end) {
			req_flush(current);
			if (current->status == CLOSE)
				retval = 0;
			else
				retval = 1;
		} else {
			switch (current->status) {
			case READ_HEADER:
			case ONE_CR:
			case ONE_LF:
			case TWO_CR:
				retval = read_header(current);
				break;
			case BODY_READ:
				retval = read_body(current);
				break;
			case BODY_WRITE:
				retval = write_body(current);
				break;
			case WRITE:
				retval = process_get(current);
				break;
			case PIPE_READ:
				retval = read_from_pipe(current);
				break;
			case PIPE_WRITE:
				retval = write_from_pipe(current);
				break;
			default:
				retval = 0;
#if 0
				fprintf(stderr, "Unknown status (%d), closing!\n",
						current->status);
#endif
				break;
			}
		}
		
		if (lame_duck_mode)
			SQUASH_KA(current);

		switch (retval) {
		case -1:				/* request blocked */
			trailer = current;
			current = current->next;
			block_request(trailer);
			break;
		default:			/* everything else means an error, jump ship */
			send_r_error(current);
			/* fall-through */
		case 0:				/* request complete */
			trailer = current;
			current = current->next;
			free_request(&request_ready, trailer);
			break;
		case 1:				/* more to do */
			current->time_last = time_counter;
			current = current->next;
			break;
		}
	}
#ifdef CRASHDEBUG
		crashdebug_current = current;
#endif
}
Exemple #19
0
void reader_func(int child_socket, const std::vector<std::string>& opened_files, std::mutex& mutex)
{
  std::vector<std::string> tortured = read_from_pipe(child_socket);
  std::lock_guard<std::mutex> lk(mutex);
  search_unnecessary_openings(opened_files, tortured);
}
Exemple #20
0
void process_requests(int server_sock)
{
    int retval = 0;
    request *current, *trailer;

    if (pending_requests) {
        get_request(server_sock);
#ifdef ORIGINAL_BEHAVIOR
        pending_requests = 0;
#endif
    }

    current = request_ready;

    while (current) {
        time(&current_time);
        retval = 1;             /* emulate "success" in case we don't have to flush */

        if (current->buffer_end && /* there is data in the buffer */
            current->status < TIMED_OUT) {
            retval = req_flush(current);
            /*
             * retval can be -2=error, -1=blocked, or bytes left
             */
            if (retval == -2) { /* error */
                current->status = DEAD;
                retval = 0;
            } else if (retval >= 0) {
                /* notice the >= which is different from below?
                   Here, we may just be flushing headers.
                   We don't want to return 0 because we are not DONE
                   or DEAD */
                retval = 1;
            }
        }

        if (retval == 1) {
            switch (current->status) {
            case READ_HEADER:
            case ONE_CR:
            case ONE_LF:
            case TWO_CR:
                retval = read_header(current);
                break;
            case BODY_READ:
                retval = read_body(current);
                break;
            case BODY_WRITE:
                retval = write_body(current);
                break;
            case WRITE:
                retval = process_get(current);
                break;
            case PIPE_READ:
                retval = read_from_pipe(current);
                break;
            case PIPE_WRITE:
                retval = write_from_pipe(current);
                break;
            case IOSHUFFLE:
#ifdef HAVE_SENDFILE
                retval = io_shuffle_sendfile(current);
#else
                retval = io_shuffle(current);
#endif
                break;
            case DONE:
                /* a non-status that will terminate the request */
                retval = req_flush(current);
                /*
                 * retval can be -2=error, -1=blocked, or bytes left
                 */
                if (retval == -2) { /* error */
                    current->status = DEAD;
                    retval = 0;
                } else if (retval > 0) {
                    retval = 1;
                }
                break;
            case TIMED_OUT:
            case DEAD:
                retval = 0;
                current->buffer_end = 0;
                SQUASH_KA(current);
                break;
            default:
                retval = 0;
                fprintf(stderr, "Unknown status (%d), "
                        "closing!\n", current->status);
                current->status = DEAD;
                break;
            }

        }

        if (sigterm_flag)
        {
          SQUASH_KA(current);
        }

        /* we put this here instead of after the switch so that
         * if we are on the last request, and get_request is successful,
         * current->next is valid!
         */
        if (pending_requests)
            get_request(server_sock);

        switch (retval) {
        case -1:               /* request blocked */
            trailer = current;
            current = current->next;
            block_request(trailer);
            break;
        case 0:                /* request complete */
            current->time_last = current_time;
            trailer = current;
            current = current->next;
            free_request(trailer);
            break;
        case 1:                /* more to do */
            current->time_last = current_time;
            current = current->next;
            break;
        default:
            log_error_doc(current);
            fprintf(stderr, "Unknown retval in process.c - "
                    "Status: %d, retval: %d\n", current->status, retval);
            current->status = DEAD;
            current = current->next;
            break;
        }
    }
}
Exemple #21
0
void process_requests(int server_s, struct soap *soap)/*by SeanHou*/
{
    /* :TODO:Monday, December 01, 2014 11:17:36 HKT:SeanHou:  */
    int OnvifEN = 0;
    int lookupindex = 0;
    char service_uri[100] = "";

    memset((void*)&soap->peer, 0, sizeof(soap->peer));
    soap->socket = SOAP_INVALID_SOCKET;
    soap->error  = SOAP_OK;
    soap->errmode = 0;
    soap->keep_alive = 0;

    fprintf(stderr, "Warning:" \
            "(==>%s).\n", __func__);

    /* :TODO:End---  */
    int retval = 0;
    request *current, *trailer;

    if (pending_requests) {
        get_request(server_s);
#ifdef ORIGINAL_BEHAVIOR
        pending_requests = 0;
#endif
    }

    current = request_ready;

    while (current) {
        /* :TODO:Monday, December 01, 2014 11:18:42 HKT:SeanHou: juge is onvif */
        OnvifEN = isonvif(current->client_stream, service_uri, &lookupindex);
        if(OnvifEN == 1)
        {
            fprintf(stderr, "[boa:onvif] Warning: is onvif line[%d]remote port[%d]h2ns[%d]remote ip[%s]\n", __LINE__, current->remote_port, htons(current->remote_port), current->remote_ip_addr);
            struct sockaddr_in onvif_client_addr;
            memset(&onvif_client_addr, 0, sizeof(onvif_client_addr));
            onvif_client_addr.sin_family = AF_INET;
            onvif_client_addr.sin_port = htons(current->remote_port);//随机端口
            onvif_client_addr.sin_addr.s_addr = inet_addr(current->remote_ip_addr);//

            soap->socket = current->fd;
            soap->peer = onvif_client_addr;
            if (soap_valid_socket(soap->socket))
            {
                soap->ip = ntohl(soap->peer.sin_addr.s_addr);
                soap->port = (int)ntohs(soap->peer.sin_port);
                soap->keep_alive = (((soap->imode | soap->omode) & SOAP_IO_KEEPALIVE) != 0);
            }


            g_onvif_buffer = (char *)soap_malloc(soap, sizeof(current->client_stream));
            strcpy(g_onvif_buffer, current->client_stream);//mark

            soap_begin_recv(soap);
            if (soap_envelope_begin_in(soap))
            {
                soap_send_fault(soap);
            }
            if (soap_recv_header(soap))
            {
                soap_send_fault(soap);
            }
            if (soap_body_begin_in(soap))
            {
                soap_send_fault(soap);
            }

            int errorCode = 0;
            if (errorCode = soap_serve_request(soap))
            {
                fprintf(stderr, "[boa:onvif]soap_serve_request fail, errorCode %d \n", errorCode);
                soap_send_fault(soap);
            }

            memset(current->client_stream, 0, CLIENT_STREAM_SIZE );

            soap_dealloc(soap, NULL);
            soap_destroy(soap);      
            soap_end(soap);
            current->status = DONE;
            close(soap->socket);
            continue;
        }
        /* :TODO:End---  */
        time(&current_time);
        if (current->buffer_end && /* there is data in the buffer */
                current->status != DEAD && current->status != DONE) {
            retval = req_flush(current);
            /*
             * retval can be -2=error, -1=blocked, or bytes left
             */
            if (retval == -2) { /* error */
                current->status = DEAD;
                retval = 0;
            } else if (retval >= 0) {
                /* notice the >= which is different from below?
                   Here, we may just be flushing headers.
                   We don't want to return 0 because we are not DONE
                   or DEAD */

                retval = 1;
            }
        } else {
            switch (current->status) {
                case READ_HEADER:
                case ONE_CR:
                case ONE_LF:
                case TWO_CR:
                    retval = read_header(current);
                    break;
                case BODY_READ:
                    retval = read_body(current);
                    break;
                case BODY_WRITE:
                    retval = write_body(current);
                    break;
                case WRITE:
                    retval = process_get(current);
                    break;
                case PIPE_READ:
                    retval = read_from_pipe(current);
                    break;
                case PIPE_WRITE:
                    retval = write_from_pipe(current);
                    break;
                case DONE:
                    /* a non-status that will terminate the request */
                    retval = req_flush(current);
                    /*
                     * retval can be -2=error, -1=blocked, or bytes left
                     */
                    if (retval == -2) { /* error */
                        current->status = DEAD;
                        retval = 0;
                    } else if (retval > 0) {
                        retval = 1;
                    }
                    break;
                case DEAD:
                    retval = 0;
                    current->buffer_end = 0;
                    SQUASH_KA(current);
                    break;
                default:
                    retval = 0;
                    fprintf(stderr, "Unknown status (%d), "
                            "closing!\n", current->status);
                    current->status = DEAD;
                    break;
            }

        }

        if (sigterm_flag)
            SQUASH_KA(current);

        /* we put this here instead of after the switch so that
         * if we are on the last request, and get_request is successful,
         * current->next is valid!
         */
        if (pending_requests)
            get_request(server_s);

        switch (retval) {
            case -1:               /* request blocked */
                trailer = current;
                current = current->next;
                block_request(trailer);
                break;
            case 0:                /* request complete */
                current->time_last = current_time;
                trailer = current;
                current = current->next;
                free_request(&request_ready, trailer);
                break;
            case 1:                /* more to do */
                current->time_last = current_time;
                current = current->next;
                break;
            default:
                log_error_time();
                fprintf(stderr, "Unknown retval in process.c - "
                        "Status: %d, retval: %d\n", current->status, retval);
                current = current->next;
                break;
        }
    }
}
Exemple #22
0
// Returns the OS name and version for WSL when enabled
//
int get_wsl_information(bool& wsl_available, WSLS& wsls) {
    wsl_lib = NULL;
    in_read = NULL;
    in_write = NULL;
    out_read = NULL;
    out_write = NULL;
    pWslLaunch = NULL;

    std::vector<std::string> distros;
    std::string default_distro;

    if (!get_available_wsls(distros, default_distro)) {
        return 1;
    }

    wsl_lib = LoadLibrary("wslapi.dll");
    if (!wsl_lib) {
        return 1;
    }

    pWslLaunch = (PWslLaunch) GetProcAddress(wsl_lib, "WslLaunch");

    if (!pWslLaunch) {
        free_resources_and_exit(1);
    }

    wsl_available = false;

    SECURITY_ATTRIBUTES sa;
    HANDLE handle;

    sa.nLength = sizeof(SECURITY_ATTRIBUTES);
    sa.bInheritHandle = TRUE;
    sa.lpSecurityDescriptor = NULL;

    if (!CreatePipe(&out_read, &out_write, &sa, 0)) {
        return 1;
    }
    if (!SetHandleInformation(out_read, HANDLE_FLAG_INHERIT, 0)) {
        return free_resources_and_exit(1);
    }
    if (!CreatePipe(&in_read, &in_write, &sa, 0)) {
        return free_resources_and_exit(1);
    }
    if (!SetHandleInformation(in_write, HANDLE_FLAG_INHERIT, 0)) {
        return free_resources_and_exit(1);
    }

    for (size_t i = 0; i < distros.size(); ++i) {
        char wsl_dist_name[256];
        char wsl_dist_version[256];

        const std::string& distro = distros[i];
        WSL wsl;
        wsl.distro_name = distro;
        if (distro == default_distro) {
            wsl.is_default = true;
        } else {
            wsl.is_default = false;
        }

        // lsbrelease
        if (!create_wsl_process(distro, command_lsbrelease, &handle)) {
            continue;
        }
        wsl_available = HOST_INFO::parse_linux_os_info(
            read_from_pipe(handle), lsbrelease, wsl_dist_name, sizeof(wsl_dist_name), wsl_dist_version, sizeof(wsl_dist_version));
        CloseHandle(handle);

        if (!wsl_available) {
            //osrelease
            const std::string command_osrelease = "cat " + std::string(file_osrelease);
            if (!create_wsl_process(distro, command_osrelease, &handle)) {
                continue;
            }
            wsl_available = HOST_INFO::parse_linux_os_info(
                read_from_pipe(handle), osrelease, wsl_dist_name, sizeof(wsl_dist_name), wsl_dist_version, sizeof(wsl_dist_version));
            CloseHandle(handle);
        }

        //redhatrelease
        if (!wsl_available) {
            const std::string command_redhatrelease = "cat " + std::string(file_redhatrelease);
            if (!create_wsl_process(distro, command_redhatrelease, &handle)) {
                continue;
            }
            wsl_available = HOST_INFO::parse_linux_os_info(
                read_from_pipe(handle), redhatrelease, wsl_dist_name, sizeof(wsl_dist_name), wsl_dist_version, sizeof(wsl_dist_version));
            CloseHandle(handle);
        }

        if (!wsl_available) {
            continue;
        }

        std::string os_name = "";
        std::string os_version_extra = "";

        // sysctl -a
        const std::string command_sysctl = "sysctl -a";
        if (create_wsl_process(distro, command_sysctl, &handle)) {
            parse_sysctl_output(split(read_from_pipe(handle), '\n'), os_name, os_version_extra);
            CloseHandle(handle);
        }

        // uname -s
        if (os_name.empty()) {
            const std::string command_uname_s = "uname -s";
            if (create_wsl_process(distro, command_uname_s, &handle)) {
                os_name = read_from_pipe(handle);
                strip_whitespace(os_name);
                CloseHandle(handle);
            }
        }

        // uname -r
        if (os_version_extra.empty()) {
            const std::string command_uname_r = "uname -r";
            if (create_wsl_process(distro, command_uname_r ,&handle)) {
                os_version_extra = read_from_pipe(handle);
                strip_whitespace(os_version_extra);
                CloseHandle(handle);
            }
        }

        if (!os_name.empty()) {
            wsl.name = os_name + " " + wsl_dist_name;
        }
        else {
            wsl.name = wsl_dist_name;
        }
        if (!os_version_extra.empty()) {
            wsl.version = std::string(wsl_dist_version) + " [" + os_version_extra + "]";
        }
        else {
            wsl.version = wsl_dist_version;
        }
        wsls.wsls.push_back(wsl);
    }

    return free_resources_and_exit(0);
}
Exemple #23
0
int
new_server_clnt_http_request(
        new_server_conn_t conn,
        FILE *log_f,
        int out_fd,
        unsigned char *args[],
        unsigned char *envs[],
        int param_num,
        unsigned char *param_names[],
        size_t param_sizes_in[],
        unsigned char *params[],
        unsigned char **reply_bytes,
        size_t *reply_size)
{
  int arg_num = 0, env_num = 0, i;
  ej_size_t *arg_sizes = 0, *env_sizes = 0, *param_sizes = 0;
  ej_size_t *param_name_sizes = 0;
  ej_size_t t;
  struct new_server_prot_http_request *out = 0;
  size_t out_size;
  unsigned long bptr;// hope,that that's enough for pointer
  int pipe_fd[2] = { -1, -1 }, pass_fd[2];
  int data_fd[2] = { -1, -1 };
  int errcode = -NEW_SRV_ERR_PARAM_OUT_OF_RANGE, r;
  void *void_in = 0;
  size_t in_size = 0;
  struct new_server_prot_packet *in;
  char c;
  const char *emsg = 0;

  if (args) {
    for (; args[arg_num]; arg_num++);
  }
  if (arg_num < 0 || arg_num > MAX_PARAM_NUM) {
    msg(log_f, "invalid number of arguments %d", arg_num);
    goto failed;
  }
  if (envs) {
    for (; envs[env_num]; env_num++);
  }
  if (env_num < 0 || env_num > MAX_PARAM_NUM) {
    msg(log_f, "invalid number of environment vars %d", env_num);
    goto failed;
  }
  if (param_num < 0 || param_num > MAX_PARAM_NUM) {
    msg(log_f, "invalid number of parameters %d", param_num);
    goto failed;
  }

  out_size = sizeof(*out);
  out_size += arg_num * sizeof(ej_size_t);
  out_size += env_num * sizeof(ej_size_t);
  out_size += 2 * param_num * sizeof(ej_size_t);

  if (arg_num > 0) {
    XALLOCAZ(arg_sizes, arg_num);
    for (i = 0; i < arg_num; i++) {
      arg_sizes[i] = t = strlen(args[i]);
      if (/* t < 0 || */ t > MAX_PARAM_SIZE) {
        msg(log_f, "invalid argument length %d", t);
        goto failed;
      }
      out_size += t + 1;
    }
  }

  if (env_num > 0) {
    XALLOCAZ(env_sizes, env_num);
    for (i = 0; i < env_num; i++) {
      env_sizes[i] = t = strlen(envs[i]);
      if (/* t < 0 || */ t > MAX_PARAM_SIZE) {
        msg(log_f, "invalid environment var length %d", t);
        goto failed;
      }
      out_size += t + 1;
    }
  }

  if (param_num > 0) {
    XALLOCAZ(param_name_sizes, param_num);
    XALLOCAZ(param_sizes, param_num);
    for (i = 0; i < param_num; i++) {
      param_name_sizes[i] = t = strlen(param_names[i]);
      if (/* t < 0 || */ t > MAX_PARAM_SIZE) {
        msg(log_f, "invalid parameter name length %d", t);
        goto failed;
      }
      out_size += t + 1;
      param_sizes[i] = t = param_sizes_in[i];
      if (/* t < 0 || */ t > MAX_PARAM_SIZE) {
        msg(log_f, "invalid parameter value length %d", t);
        goto failed;
      }
      out_size += t + 1;
    }
  }

  if (/* out_size < 0 || */ out_size > MAX_PARAM_SIZE) {
    msg(log_f, "invalid total packet size %zu", out_size);
    goto failed;
  }

  out = (struct new_server_prot_http_request*) xcalloc(out_size, 1);
  out->b.magic = NEW_SERVER_PROT_PACKET_MAGIC;
  out->b.id = NEW_SRV_CMD_HTTP_REQUEST;
  out->arg_num = arg_num;
  out->env_num = env_num;
  out->param_num = param_num;

  bptr = (unsigned long) out;
  bptr += sizeof(*out);
  if (arg_num > 0) {
    memcpy((void*) bptr, arg_sizes, arg_num * sizeof(arg_sizes[0]));
    bptr += arg_num * sizeof(arg_sizes[0]);
  }
  if (env_num > 0) {
    memcpy((void*) bptr, env_sizes, env_num * sizeof(env_sizes[0]));
    bptr += env_num * sizeof(env_sizes[0]);
  }
  if (param_num > 0) {
    memcpy((void*) bptr, param_name_sizes, param_num * sizeof(ej_size_t));
    bptr += param_num * sizeof(param_sizes[0]);
    memcpy((void*) bptr, param_sizes, param_num * sizeof(param_sizes[0]));
    bptr += param_num * sizeof(param_sizes[0]);
  }
  for (i = 0; i < arg_num; i++) {
    memcpy((void*) bptr, args[i], arg_sizes[i]);
    bptr += arg_sizes[i] + 1;
  }
  for (i = 0; i < env_num; i++) {
    memcpy((void*) bptr, envs[i], env_sizes[i]);
    bptr += env_sizes[i] + 1;
  }
  for (i = 0; i < param_num; i++) {
    memcpy((void*) bptr, param_names[i], param_name_sizes[i]);
    bptr += param_name_sizes[i] + 1;
    memcpy((void*) bptr, params[i], param_sizes[i]);
    bptr += param_sizes[i] + 1;
  }

  if (pipe(pipe_fd) < 0) {
    emsg = os_ErrorMsg();
    msg(log_f, "waiting pipe() failed: %s", emsg);
    err("new_server_clnt_http_request: pipe() failed: %s", emsg);
    errcode = -NEW_SRV_ERR_SYSTEM_ERROR;
    goto failed;
  }
  if (out_fd < 0) {
    if (pipe(data_fd) < 0) {
      emsg = os_ErrorMsg();
      msg(log_f, "data pipe() failed: %s", emsg);
      err("new_server_clnt_http_request: pipe() failed: %s", emsg);
      errcode = -NEW_SRV_ERR_SYSTEM_ERROR;
      goto failed;
    }
    out_fd = data_fd[1];
  }
  pass_fd[0] = out_fd;
  pass_fd[1] = pipe_fd[1];
  if ((errcode = new_server_clnt_pass_fd(conn, 2, pass_fd)) < 0) {
    msg(log_f, "pass_fd failed: error code: %d", -errcode);
    goto failed;
  }
  close(pipe_fd[1]); pipe_fd[1] = -1;
  if (data_fd[1] >= 0) close(data_fd[1]);
  data_fd[1] = -1;
  if ((errcode = new_server_clnt_send_packet(conn, out_size, out)) < 0) {
    msg(log_f, "send_packet failed: error code: %d", -errcode);
    goto failed;
  }
  if ((errcode = new_server_clnt_recv_packet(conn, &in_size, &void_in)) < 0) {
    msg(log_f, "recv_packet failed: error code: %d", -errcode);
    goto failed;
  }
  errcode = -NEW_SRV_ERR_PROTOCOL_ERROR;
  if (in_size != sizeof(*in)) {
    msg(log_f, "received packet size mismatch");
    err("new_server_clnt_http_request: packet size mismatch");
    goto failed;
  }
  in = (struct new_server_prot_packet*) void_in;
  if (in->magic != NEW_SERVER_PROT_PACKET_MAGIC) {
    msg(log_f, "received packet magic mismatch");
    err("new_server_clnt_http_request: packet magic mismatch");
    goto failed;
  }
  errcode = in->id;
  if (errcode < 0) {
    msg(log_f, "server reply code is %d", -errcode);
    goto failed;
  }

  if (data_fd[0] >= 0) {
    read_from_pipe(data_fd[0], reply_bytes, reply_size);
    close(data_fd[0]); data_fd[0] = -1;
  }

  // wait for the server to complete page generation
  r = read(pipe_fd[0], &c, 1);
  if (r < 0) {
    emsg = os_ErrorMsg();
    msg(log_f, "wait pipe read() failed: %s", emsg);
    err("new_server_clnt_http_request: read() failed: %s", emsg);
    errcode = -NEW_SRV_ERR_READ_ERROR;
    goto failed;
  }
  if (r > 0) {
    msg(log_f, "wait pipe is not empty");
    err("new_server_clnt_http_request: data in wait pipe");
    goto failed;
  }
  errcode = NEW_SRV_RPL_OK;

 failed:
  xfree(out);
  xfree(void_in);
  if (pipe_fd[0] >= 0) close(pipe_fd[0]);
  if (pipe_fd[1] >= 0) close(pipe_fd[1]);
  if (data_fd[0] >= 0) close(data_fd[0]);
  if (data_fd[1] >= 0) close(data_fd[1]);
  return errcode;
}
Exemple #24
0
void llvm__get_kbuild_opts(char **kbuild_dir, char **kbuild_include_opts)
{
	static char *saved_kbuild_dir;
	static char *saved_kbuild_include_opts;
	int err;

	if (!kbuild_dir || !kbuild_include_opts)
		return;

	*kbuild_dir = NULL;
	*kbuild_include_opts = NULL;

	if (saved_kbuild_dir && saved_kbuild_include_opts &&
	    !IS_ERR(saved_kbuild_dir) && !IS_ERR(saved_kbuild_include_opts)) {
		*kbuild_dir = strdup(saved_kbuild_dir);
		*kbuild_include_opts = strdup(saved_kbuild_include_opts);

		if (*kbuild_dir && *kbuild_include_opts)
			return;

		zfree(kbuild_dir);
		zfree(kbuild_include_opts);
		/*
		 * Don't fall through: it may breaks saved_kbuild_dir and
		 * saved_kbuild_include_opts if detect them again when
		 * memory is low.
		 */
		return;
	}

	if (llvm_param.kbuild_dir && !llvm_param.kbuild_dir[0]) {
		pr_debug("[llvm.kbuild-dir] is set to \"\" deliberately.\n");
		pr_debug("Skip kbuild options detection.\n");
		goto errout;
	}

	err = detect_kbuild_dir(kbuild_dir);
	if (err) {
		pr_warning(
"WARNING:\tunable to get correct kernel building directory.\n"
"Hint:\tSet correct kbuild directory using 'kbuild-dir' option in [llvm]\n"
"     \tsection of ~/.perfconfig or set it to \"\" to suppress kbuild\n"
"     \tdetection.\n\n");
		goto errout;
	}

	pr_debug("Kernel build dir is set to %s\n", *kbuild_dir);
	force_set_env("KBUILD_DIR", *kbuild_dir);
	force_set_env("KBUILD_OPTS", llvm_param.kbuild_opts);
	err = read_from_pipe(kinc_fetch_script,
			     (void **)kbuild_include_opts,
			     NULL);
	if (err) {
		pr_warning(
"WARNING:\tunable to get kernel include directories from '%s'\n"
"Hint:\tTry set clang include options using 'clang-bpf-cmd-template'\n"
"     \toption in [llvm] section of ~/.perfconfig and set 'kbuild-dir'\n"
"     \toption in [llvm] to \"\" to suppress this detection.\n\n",
			*kbuild_dir);

		free(*kbuild_dir);
		*kbuild_dir = NULL;
		goto errout;
	}

	pr_debug("include option is set to %s\n", *kbuild_include_opts);

	saved_kbuild_dir = strdup(*kbuild_dir);
	saved_kbuild_include_opts = strdup(*kbuild_include_opts);

	if (!saved_kbuild_dir || !saved_kbuild_include_opts) {
		zfree(&saved_kbuild_dir);
		zfree(&saved_kbuild_include_opts);
	}
	return;
errout:
	saved_kbuild_dir = ERR_PTR(-EINVAL);
	saved_kbuild_include_opts = ERR_PTR(-EINVAL);
}