void run(unsigned thread_id, std::string filename, Address ip,
         std::vector<Address> routing_addresses) {
  std::string log_file = "log_user.txt";
  std::string logger_name = "user_log";
  auto logger = spdlog::basic_logger_mt(logger_name, log_file, true);
  logger->flush_on(spdlog::level::info);

  std::hash<std::string> hasher;
  unsigned seed = time(NULL);
  seed += hasher(ip);
  seed += thread_id;
  logger->info("Random seed is {}.", seed);

  // mapping from key to a set of worker addresses
  std::unordered_map<Key, std::unordered_set<Address>> key_address_cache;

  UserThread ut = UserThread(ip, thread_id);

  int timeout = 10000;
  zmq::context_t context(1);
  SocketCache pushers(&context, ZMQ_PUSH);

  // responsible for pulling response
  zmq::socket_t response_puller(context, ZMQ_PULL);
  response_puller.setsockopt(ZMQ_RCVTIMEO, &timeout, sizeof(timeout));
  response_puller.bind(ut.get_request_pulling_bind_addr());

  // responsible for receiving key address responses
  zmq::socket_t key_address_puller(context, ZMQ_PULL);
  key_address_puller.setsockopt(ZMQ_RCVTIMEO, &timeout, sizeof(timeout));
  key_address_puller.bind(ut.get_key_address_bind_addr());

  unsigned rid = 0;

  std::string input;
  unsigned trial = 1;
  if (filename == "") {
    while (true) {
      std::cout << "kvs> ";

      getline(std::cin, input);
      handle_request(input, pushers, routing_addresses, key_address_cache, seed,
                     logger, ut, response_puller, key_address_puller, ip,
                     thread_id, rid, trial);
    }
  } else {
    std::ifstream infile(filename);

    while (getline(infile, input)) {
      handle_request(input, pushers, routing_addresses, key_address_cache, seed,
                     logger, ut, response_puller, key_address_puller, ip,
                     thread_id, rid, trial);
    }
  }
}
Exemple #2
0
int main(void) {
  struct sockaddr_in clnt_addr;
  socklen_t addrlen = sizeof(clnt_addr);
  int ret;
  char buf[MSGLEN];
  unsigned int time_left;

  int sock_fd = setup();
  signal(SIGALRM, ticket_reclaim);
  alarm(RECLAIM_INTERVAL);
  while (true) {
    ret = recvfrom(sock_fd, buf, MSGLEN, 0, (struct sockaddr *)&clnt_addr, &addrlen);
    if (ret != -1) {
      buf[ret] = '\0';
      narrate("GOT:", buf, &clnt_addr);
      time_left = alarm(0);
      handle_request(buf, &clnt_addr, addrlen);
      alarm(time_left);
    }
    else {
      if (errno != EINTR)
        perror("recvfrom");
    }
  }

  return EXIT_SUCCESS;
}
static void
command_dispatcher(const linkaddr_t *sender)
{
  char *msg;
  int len;
  struct deluge_msg_profile *profile;

  msg = packetbuf_dataptr();  
  len = packetbuf_datalen();
  if(len < 1)
    return;

  switch(msg[0]) {
  case DELUGE_CMD_SUMMARY:
    if(len >= sizeof(struct deluge_msg_summary))
      handle_summary((struct deluge_msg_summary *)msg, sender);
    break;
  case DELUGE_CMD_REQUEST:
    if(len >= sizeof(struct deluge_msg_request))
      handle_request((struct deluge_msg_request *)msg);
    break;
  case DELUGE_CMD_PACKET:
    if(len >= sizeof(struct deluge_msg_packet))
      handle_packet((struct deluge_msg_packet *)msg);
    break;
  case DELUGE_CMD_PROFILE:
    profile = (struct deluge_msg_profile *)msg;
    if(len >= sizeof(*profile) &&
       len >= sizeof(*profile) + profile->npages * profile->version_vector[0])
      handle_profile((struct deluge_msg_profile *)msg);
    break;
  default:
    PRINTF("Incoming packet with unknown command: %d\n", msg[0]);
  }
}
Exemple #4
0
int main(int argc, char** argv)
{
	int sockfd, clientfd;
	struct client cli;
	FILE *logfile;
	struct sockaddr_in client_addr;
	socklen_t client_len;

	init_logger(LOG_FILE, logfile);
	Logger(LOG_INFO, 0, "httpd start...\n");

	httpd_get_option(argc, argv);
	httpd_process_option();

	init_httpd_socket(&sockfd);

	while (1)
	{
		client_len = sizeof (client_addr);
		clientfd = Accept(sockfd, (struct sockaddr*)&client_addr, &client_len);
		Logger(LOG_INFO, 0, "Accept a client connection\n");
		
		memset(&cli, 0, sizeof(struct client));
		cli.clientfd = clientfd;

		handle_request(&cli);

		close(clientfd);
		
	}

	close(sockfd);
	end_logger(logfile);
	return 0;
}
static int cryptopacket_handle(void *object, IP_Port source, uint8_t *packet, uint32_t length)
{
    DHT *dht = object;

    if (packet[0] == NET_PACKET_CRYPTO) {
        if (length <= crypto_box_PUBLICKEYBYTES * 2 + crypto_box_NONCEBYTES + 1 + ENCRYPTION_PADDING ||
                length > MAX_DATA_SIZE + ENCRYPTION_PADDING)
            return 1;

        if (memcmp(packet + 1, dht->c->self_public_key, crypto_box_PUBLICKEYBYTES) == 0) { // Check if request is for us.
            uint8_t public_key[crypto_box_PUBLICKEYBYTES];
            uint8_t data[MAX_DATA_SIZE];
            uint8_t number;
            int len = handle_request(dht->c->self_public_key, dht->c->self_secret_key, public_key, data, &number, packet, length);

            if (len == -1 || len == 0)
                return 1;

            if (!dht->c->cryptopackethandlers[number].function) return 1;

            dht->c->cryptopackethandlers[number].function(dht->c->cryptopackethandlers[number].object, source, public_key, data,
                    len);

        } else { /* If request is not for us, try routing it. */
            int retval = route_packet(dht, packet + 1, packet, length);

            if ((unsigned int)retval == length)
                return 0;
        }
    }

    return 1;
}
/**
 * Handle a request and send a response
 *
 * @param cls unused
 * @param other the sender
 * @param message the message
 * @return GNUNET_OK to keep connection, GNUNET_SYSERR on error
 */
static int
core_receive_handler (void *cls,
		      const struct GNUNET_PeerIdentity *other,
		      const struct GNUNET_MessageHeader *message)
{
	if (ntohs (message->size) < sizeof (struct GNUNET_MessageHeader))
	{
			GNUNET_break (0);
			return GNUNET_SYSERR;
	}

	switch (ntohs (message->type)) {
		case GNUNET_MESSAGE_TYPE_EXPERIMENTATION_REQUEST:
			handle_request (other, message);
			break;
		case GNUNET_MESSAGE_TYPE_EXPERIMENTATION_RESPONSE:
			handle_response (other, message);
			break;
		case GNUNET_MESSAGE_TYPE_EXPERIMENTATION_START:
			handle_start (other, message);
			break;
		case GNUNET_MESSAGE_TYPE_EXPERIMENTATION_START_ACK:
			handle_start_ack (other, message);
			break;
		case GNUNET_MESSAGE_TYPE_EXPERIMENTATION_STOP:
			handle_stop (other, message);
			break;
		default:
			break;
	}

	return GNUNET_OK;
}
Exemple #7
0
	void* handle_requests_loop(void* data)
	{
	int rc;                         /* return code of pthreads functions.  */
	struct request* a_request;      /* pointer to a request.               */
	int thread_id = *((int*)data);  /* thread identifying number           */

	/* lock the mutex, to access the requests list exclusively. */
	rc = pthread_mutex_lock(&request_mutex);

	while (1) {
	   if (num_requests > 0) { /* a request is pending */
	      a_request = get_request(&list_mutex);
	      /* got a request */
	      if (a_request) {
	         /*handle request */
	         handle_request(a_request, thread_id);
	         /* free it */
	         free(a_request);
	         }
	      }
	   else {
	      if (quit) {
	         pthread_mutex_unlock(&request_mutex); // unlock mutex before exit
	         pthread_exit(NULL);
	         }
	      rc = pthread_cond_wait(&got_request, &request_mutex);
	      }
	   }
	}
Exemple #8
0
int main(int argc, char** argv)
{
	int s, bytes, val;
	struct sockaddr_in addr,from;
	socklen_t from_len;
	struct tftp_packet packet;

	if((s = socket(AF_INET, SOCK_DGRAM, 0)) < 0)
		die("socket error");
	val = 1;
	setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &val, sizeof(val));
	memset(&addr, 0 ,sizeof(addr));
	addr.sin_family = AF_INET;
	addr.sin_port = htons(1237);
	if(inet_aton(argv[1],&addr.sin_addr) < 0)
	{

		fprintf(stderr,"Ip error :");
		exit(1);

	}	
	while(1)
	{
		from_len = sizeof(from);
		bytes = recvfrom(s, &packet, sizeof(packet), 0, (struct sockaddr *)&from, &from_len);
		if(bytes < 0)
			die("recvfrom error");
		printf("Request from %s : %d\n", inet_ntoa(from.sin_addr), htons(from.sin_port));
	handle_request(s, &from, from_len, &packet);
	}
}
Exemple #9
0
static void *thread_function(void *ptr){
	arg_t *arg = (arg_t*)ptr;
	while(1) {
		if (arg->status.idle) continue;
		else {
			// add busy threads count
			busy_threads_count++;
			// send unblock message
			csiebox_protocol_header unblock;
			memset(&unblock, 0, sizeof(unblock));
			unblock.res.status = CSIEBOX_PROTOCOL_STATUS_OK;
			send_message(arg->client.fd, &unblock, sizeof(unblock));
			// start threading
			arg->client.logout = handle_request(arg->server, arg->client.fd);
			if (arg->client.logout) {
				FD_CLR(arg->client.fd, arg->status.fdset);
				arg->client.logout = 0;
			}
			arg->status.in_thread[arg->client.fd] = 0;
			arg->client.fd = -1;
			arg->status.idle = 1;
			// delete busy threads count
			busy_threads_count--;
		}
	}
	return (void*)0;
}
Exemple #10
0
int main(int, char**)
{
  cgi::request req;
/*<
At this point, the environment variables are accessible. This includes cookie
and form variables too, which are all parsed by default-constructing a
`cgi::request` (this is optional).
>*/
  cgi::response resp;
/*<
The `response` class provides a streaming interface for writing replies. You
can write to the request object directly, but for now we're going to just
use the `response`, which works well for most situations.

Writing to a `response` is buffered. If an error occurs, you can simply
`clear()` the response and send an error message instead. Buffered writing
may not always suit your use-case (eg. returning large files), but when memory
is not at a real premium, buffering the response is highly preferable.

Not only does buffering avoid network latency issues, but being able to cancel
the response and send another is much cleaner than sending half a response,
followed by "...Ooops". A `cgi::response` is not tied to a request, so the
same response can be reused across multiple requests.

When sending a response that is large relative to the amount of memory
available to the program, you may want to write unbuffered.
>*/
  return handle_request(req, resp);
}
Exemple #11
0
int main(int argc, char *argv[])
{
    int listenfd, sockfd;
    struct sockaddr_in listen_addr = {0};
    listenfd = socket(AF_INET, SOCK_STREAM, 0);
    if (listenfd < 0) 
        die("Unable to open socket");
    listen_addr.sin_family = AF_INET;
    listen_addr.sin_addr.s_addr = INADDR_ANY;
    listen_addr.sin_port = htons(HTTP_PORT);
    if (bind(listenfd, (struct sockaddr *)&listen_addr, sizeof(listen_addr)) < 0) 
        die("Unable to bind()");
    listen(listenfd, 32);
    while(1)
    {
        struct sockaddr_in client_addr = {0};
        socklen_t addr_len;
        char *request = malloc(REQUEST_BUFFER_SIZE);
        addr_len = sizeof(client_addr);
        sockfd = accept(listenfd, (struct sockaddr *) &client_addr, &addr_len);
        if (sockfd < 0) 
            die("Unable to accept new connection");
        read(sockfd, request, REQUEST_BUFFER_SIZE);
        handle_request(sockfd, request);
        close(sockfd);
        free(request);
    }
    close(listenfd);
    return 0;
}
int main (int argc, char** argv) {
		int listen_socket_descriptor, client_connection_socket_descriptor = 0;
		struct sockaddr_in listen_address;

		signal(SIGCHLD, sig_child_handler);

		memset(&listen_address, '0', sizeof(listen_address));
		listen_address.sin_family = AF_INET;
		listen_address.sin_port = htons(8080);
		listen_address.sin_addr.s_addr = htonl(INADDR_ANY);

		listen_socket_descriptor = socket(AF_INET, SOCK_STREAM, 0);

		lanyitin_bind(listen_socket_descriptor, (struct sockaddr*)&listen_address, sizeof(listen_address));

		lanyitin_listen(listen_socket_descriptor, 5);

		while ( 1 ) {
				if ( (client_connection_socket_descriptor = lanyitin_accept(listen_socket_descriptor, (struct sockaddr*)NULL, NULL)) ) {
						// if (fork() == 0) { // child process
						//		lanyitin_close(listen_socket_descriptor);
						handle_request(client_connection_socket_descriptor);
						lanyitin_close(client_connection_socket_descriptor);
						//		exit(EXIT_SUCCESS);
						// }

						// close(client_connection_socket_descriptor);
				}
		}
}
Exemple #13
0
static void*
handle_request_thread_start(void* arg)
{
    int dummy;
    handle_request(arg, &dummy);
    return NULL;
}
Exemple #14
0
/**
 * The connection thread serves a client for the duration of the
 * socket lifetime.
 */
static void *connection_main(void *arg_p)
{
    struct http_server_connection_t *connection_p = arg_p;
    struct http_server_t *self_p = connection_p->self_p;
    uint32_t mask;

    /* thrd_init_env(buf, sizeof(buf)); */
    /* thrd_set_env("CWD", self_p->root_path_p); */
    thrd_set_name(connection_p->thrd.name_p);

    /* Wait for a connection from the listener. */
    while (1) {
        log_object_print(NULL,
                         LOG_DEBUG,
                         FSTR("Connection thread '%s' waiting for a new connection.\r\n"),
                         thrd_get_name());

        mask = 0x1;
        event_read(&connection_p->events, &mask, sizeof(mask));

        if (mask & 0x1) {
            handle_request(self_p, connection_p);
            socket_close(&connection_p->socket);

            /* Add thread to the free list. */
            sys_lock();
            connection_p->state = http_server_connection_state_free_t;
            sys_unlock();
            mask = 0x1;
            event_write(&self_p->events, &mask, sizeof(mask));
        }
    }

    return (NULL);
}
Exemple #15
0
static int friendreq_handlepacket(IP_Port source, uint8_t * packet, uint32_t length)
{
    if (packet[0] == 32) {
        if (length <= crypto_box_PUBLICKEYBYTES * 2 + crypto_box_NONCEBYTES + 1 + ENCRYPTION_PADDING ||
            length > MAX_DATA_SIZE + ENCRYPTION_PADDING)
            return 1;
        if (memcmp(packet + 1, self_public_key, crypto_box_PUBLICKEYBYTES) == 0) {// check if request is for us.
            if (handle_friendrequest_isset == 0)
                return 1;

            uint8_t public_key[crypto_box_PUBLICKEYBYTES];
            uint8_t data[MAX_DATA_SIZE];
            int len = handle_request(public_key, data, packet, length);

            if (len == -1)
                return 1;
            if (request_received(public_key))
                return 1;

            addto_receivedlist(public_key);
            (*handle_friendrequest)(public_key, data, len);
        } else { /* if request is not for us, try routing it. */
            if(route_packet(packet + 1, packet, length) == length)
                return 0;
        }
    }
    return 1;
}
Exemple #16
0
/*
 * handle_requests_loop(): 处理请求的无限循环
 * 算法:如果有请求要处理,取第一个处理。然后守候指定条件变量,收到信号后
 *       重新开始循环,并把待处理的请求数加 1。
 */
void*
handle_requests_loop(void* data)
{
    int rc;	                    /* pthread 函数的返回值  */
    struct request* a_request;      /* 请求指针              */
    int thread_id = *((int*)data);  /* 线程序号              */

    /* 锁定 mutex,以保证排它性访问链表 */
    rc = pthread_mutex_lock(&request_mutex);

    /* 无限循环 ... */
    while (1) {
	if (num_requests > 0) {
	    a_request = get_request(&request_mutex);
	    if (a_request) {
		handle_request(a_request, thread_id);
		free(a_request);
	    }
	}
	else {
            /* 等待请求抵达:解锁——守候——锁定——返回 */
	    rc = pthread_cond_wait(&got_request, &request_mutex);
	}
    }
}
Exemple #17
0
//wait client to connect and handle requests from connected socket fd
int csiebox_server_run(csiebox_server* server) {
  int conn_fd, conn_len;
  struct sockaddr_in addr;
  while (1) {
    memset(&addr, 0, sizeof(addr));
    conn_len = 0;
    // waiting client connect
    conn_fd = accept(
      server->listen_fd, (struct sockaddr*)&addr, (socklen_t*)&conn_len);
    if (conn_fd < 0) {
      if (errno == ENFILE) {
          fprintf(stderr, "out of file descriptor table\n");
          continue;
        } else if (errno == EAGAIN || errno == EINTR) {
          continue;
        } else {
          fprintf(stderr, "accept err\n");
          fprintf(stderr, "code: %s\n", strerror(errno));
          break;
        }
    }
    // handle request from connected socket fd
    handle_request(server, conn_fd);
  }
  return 1;
}/*}}}*/
Exemple #18
0
/* If we are not done setting up the connection yet, return
 * -1 and ENOTCONN, otherwise call getpeername
 *
 * This is necessary since some applications, when using non-blocking connect,
 * (like ircII) use getpeername() to find out if they are connected already.
 *
 * This results in races sometimes, where the client sends data to the socket
 * before we are done with the socks connection setup.  Another solution would
 * be to intercept send().
 * 
 * This could be extended to actually set the peername to the peer the
 * client application has requested, but not for now.
 *
 * PP, Sat, 27 Mar 2004 11:30:23 +0100
 */
int getpeername(GETPEERNAME_SIGNATURE) {
   struct connreq *conn;
   int rc;

    if (realgetpeername == NULL) {
        show_msg(MSGERR, "Unresolved symbol: getpeername\n");
        return(-1);
    }

   show_msg(MSGDEBUG, "Call to getpeername for fd %d\n", __fd);


   rc = realgetpeername(__fd, __name, __namelen);
   if (rc == -1)
       return rc;

   /* Are we handling this connect? */
   if ((conn = find_socks_request(__fd, 1))) {
       /* While we are at it, we might was well try to do something useful */
       handle_request(conn);

       if (conn->state != DONE) {
           errno = ENOTCONN;
           return(-1);
       }
   }
   return rc;
}
Exemple #19
0
void server(void)
{
//	request re;
	int size = sizeof(re);

	int no = 0;
//	recv(new_sockfd, &re, size, 0);

	while(1) 
	{
		recv(new_sockfd, &req_body, 1000, 0);
		printf("%s\n", req_body);
//		parse_request(req_body);
		strcpy(res_body, "<h1> Hello </h1>");
		send_response(
			handle_request(
				parse_request(req_body)
			)
		);
		printf("%s", res_body);
		send(new_sockfd, &res_body, sizeof(res_body), 0);
//		shutdown(new_sockfd, SHUT_WR);
	//	return 0;
	}
	printf("NEW SOCKFD %d\n", new_sockfd);
	new_sockfd = 0;
}
Exemple #20
0
void* dowork(void *arg){
    sqlite3 *db;
    int err = sqlite3_open_v2(GlobalArgs.dbname, &db,\
              SQLITE_OPEN_READWRITE|SQLITE_OPEN_SHAREDCACHE, NULL);
    if (db == NULL || err != SQLITE_OK){
	syslog(LOG_CRIT,"ERROR: unable to open db, error = %d",err);
	exit(1);
    }

    void *ctx = arg;
    if (!ctx){
	syslog(LOG_CRIT,"ERROR: no zmq context available to thread");
	exit(1);
    }

    void *skt = socket_connect(ctx, ZMQ_REP, "inproc://pipe");
    if (!skt){
	syslog(LOG_CRIT,"ERROR: no socket available for thread");
	exit(1);
    }

    while (1){
	err = handle_request(skt, db);
	if (err < 0){
	    syslog(LOG_DEBUG,"dowork: msg non-conformant to msg sizes, err=%d",err);
	}
    }
    
    return NULL;
}
Exemple #21
0
/**
 * The main function that handles an HTTP request.
 */
int main(int argc, const char *argv[])
{
    req_t *req;
    if (argc < 2) {
        return -1;
    }

    document_root = argv[1];

    req = read_request(0);

    if (!req && errno != 0) {
        // internal error
        perror("httpd");
        send_error(stdout, 500, "Internal Server Error",
                   "Internal server error: %s", strerror(errno));
        return 1;
    } else if (!req || !req_is_valid(req)) {
        send_error(stdout, 400, "Bad Request", "Incomplete or invalid request.");
        return 0;
    } else {
        if (handle_request(req, stdout) < 0) {
            return 1;
        } else {
            return 0;
        }
    }
}
Exemple #22
0
static void serve_requests(int master_sd, char *addr)
{
    char               *buffer;
    ssize_t            l;
    struct sockaddr_in client;
    socklen_t          len;
    uint16_t           opcode;

    buffer = xmalloc(TFTP_MAX_PACKET_SZ);
    len = sizeof (client);
    while (true)
    {
        l = recvfrom(master_sd, buffer, TFTP_MAX_PACKET_SZ, 0,
                (struct sockaddr *)&client, &len);
        if (l == 0 || (l == -1 && errno == EAGAIN))
            continue;
        else if (l == -1)
            die("recv");
        opcode = ((uint16_t)(buffer[0] << 8));
        opcode += buffer[1];
        if (opcode == TFTP_RRQ || opcode == TFTP_WRQ)
            handle_request(opcode, master_sd, addr, buffer + 2, &client);
        else if (opcode == TFTP_ACK || opcode == TFTP_DATA)
            send_error(&client, TFTP_ERR_UNKNOWN_ID,
                    (char *)"Unknown transfer ID.", master_sd);
        else if (opcode != TFTP_ERR)
            send_error(&client, TFTP_ERR_ILLEGAL_OP,
                    (char *)"Illegal TFTP operation.", master_sd);
    }
}
Exemple #23
0
static int ds_event(event_t event, int priority,
                    event_callback_args_t *args)
{
    struct pcmcia_bus_socket *s;

    ds_dbg(1, "ds_event(0x%06x, %d, 0x%p)\n",
           event, priority, args->client_handle);
    s = args->client_data;

    switch (event) {

    case CS_EVENT_CARD_REMOVAL:
        s->state &= ~DS_SOCKET_PRESENT;
        if (!(s->state & DS_SOCKET_REMOVAL_PENDING)) {
            s->state |= DS_SOCKET_REMOVAL_PENDING;
            schedule_delayed_work(&s->removal,  HZ/10);
        }
        break;

    case CS_EVENT_CARD_INSERTION:
        s->state |= DS_SOCKET_PRESENT;
        handle_event(s, event);
        break;

    case CS_EVENT_EJECTION_REQUEST:
        return handle_request(s, event);
        break;

    default:
        handle_event(s, event);
        break;
    }

    return 0;
} /* ds_event */
Exemple #24
0
static void read_request(struct server *s, struct client *c, struct frame_buffers *fbs) {
    size_t len;
    char buf[SERVER_BUFFER_SIZE];
    memset(buf, 0, sizeof(buf));

    if (!c->request_received) {

        if ((len = client_read(c, buf, sizeof(buf))) < 1) {
            if (errno == EINTR) {
                return;
            }

            // len == 0 means that the client has disconnected
            // len == -1 means an error occured
            return remove_client(s, c);
        }
        c->last_communication = gettime();

        // Check if we have the whole thing
        strncpy(&c->request_headers[c->request_header_size], buf, MAX_REQUEST_HEADER_SIZE - c->request_header_size);
        c->request_header_size += len;

        if (strstr(c->request_headers, "\r\n\r\n") != NULL) {
            c->request_received = 1;
        }
    }

    // Parse request headers
    if (c->request_received && c->request == REQUEST_INCOMPLETE) {
        handle_request(s, c, fbs);
    }
}
int accept_connection(void)
{
      struct sockaddr remoteaddr;
      socklen_t remoteaddrlen = sizeof(remoteaddr);
      int connected_socket;
      if( (connected_socket = accept(socket_fd,&remoteaddr,&remoteaddrlen))==-1)
	{
	  print_error("%s",strerror(errno));	  
	  return -1;
	}

      switch(fork())
	{
	case -1:
	  print_error("%s",strerror(errno));
	  close(socket_fd);
	  break;

	case 0:
	  handle_request(&connected_socket);
	  break;
	default:
	  break;
	}

      if(close(connected_socket) == -1)
	{
	  print_error("%s",strerror(errno));
	  return -1;
	}

      return 0;

}
int main(void) {
  int ssock = negchke(socket(AF_INET6, SOCK_STREAM, 0), "unable to create socket");
  struct sockaddr_in6 addr = {
    .sin6_family = AF_INET6,
    .sin6_port = htons(PORT),
    .sin6_addr = IN6ADDR_ANY_INIT
  };
  int one = 1;
  negchke(setsockopt(ssock, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one)), "unable to set SO_REUSEADDR");
  negchke(bind(ssock, (struct sockaddr *)&addr, sizeof(addr)), "unable to bind");
  negchke(listen(ssock, 16), "unable to listen");

  //signal(SIGCHLD, SIG_IGN);

  while (1) {
    client_fd = negchke(accept(ssock, NULL, NULL), "unable to accept");
    pid_t pid = negchke(fork(), "unable to fork");
    if (pid == 0) {
      close(ssock);
      drop_privileges();
      handle_request();
      return 0;
    }
    close(client_fd);
  }
}
Exemple #27
0
static int
server(int sockfd)
{
	int fd;
	pid_t child;
	socklen_t len;
	struct sockaddr_un addr;

	for (;;) {
		len = sizeof(addr);
		fd = accept(sockfd, (struct sockaddr *)&addr, &len);
		if (fd < 0) {
			if (errno == EINTR) {
				continue;
			}
			else {
				perror("accept");
				return -1;
			}
		}

		printf("Accepted.\n");
		if ((child = fork()) == 0) {
			close(sockfd);
			handle_request(fd);
			exit(0);
		}
		close(fd);
	}
	return 0;
}
Exemple #28
0
// mg.redirect: Redirect the request (internally).
static int lsp_redirect(lua_State *L) {
  struct mg_connection *conn = lua_touserdata(L, lua_upvalueindex(1));
  conn->request_info.uri = lua_tostring(L, -1);
  handle_request(conn);
  lsp_abort(L);
  return 0;
}
Exemple #29
0
/**
 * toggle a breakpoint
 * 
 * \param sview
 * The source view
 *
 * \param t
 * The action to take
 *
 * \return
 * 0 on success, -1 on error.
 */
static int
toggle_breakpoint(struct sviewer *sview, enum tgdb_breakpoint_action t)
{
    char *path;
    int line;
    tgdb_request_ptr request_ptr;

    if (!sview || !sview->cur || !sview->cur->path)
        return 0;

    line = sview->cur->sel_line;

    /* Get filename (strip path off -- GDB is dumb) */
    path = strrchr(sview->cur->path, '/') + 1;
    if (path == NULL + 1)
        path = sview->cur->path;

    /* delete an existing breakpoint */
    if (sview->cur->buf.breakpts[line])
        t = TGDB_BREAKPOINT_DELETE;

    request_ptr = tgdb_request_modify_breakpoint(tgdb, path, line + 1, t);
    if (!request_ptr)
        return -1;

    handle_request(tgdb, request_ptr);

    return 0;
}
Exemple #30
0
void broker_t::run() {
    m_ctx->log(LL_INFO) << "Broker has started at " << m_ctx->config()->address();

    const size_t BROKER_SOCKET_INDEX = 0;
    const size_t HEARTBEAT_INTERVAL = m_ctx->config()->heartbeat_interval();
    m_heartbeat_time = time_point_t() + HEARTBEAT_INTERVAL;

    poller_t poller;
    poller.add(*m_socket);

    while(true) {
        if(!poller.poll_in(HEARTBEAT_INTERVAL)) {
            break; // interrupted or error occured
        }
        if(poller.check(BROKER_SOCKET_INDEX, ZMQ_POLLIN)) {
            if(!handle_request()) {
                break; // interrupted
            }
        }
        if(time_point_t() > m_heartbeat_time) {
            renew_recipients();
            m_heartbeat_time = time_point_t() + HEARTBEAT_INTERVAL;
        }
    }
    if(m_interrupted) {
        m_ctx->log(LL_INFO) << "Broker has been interrupted by a signal. Stop serving.";
    }
}