Esempio n. 1
0
int main(void) {
	// initializing first three investors for program to start with
	// initializing_END

	int PORT = 5000;
	lib_init();
	winSock = socket_new();
    db_t * db = db_new("teacher.db");
	// Checking if socket is not busy, closing app if it is
	if (socket_bind(winSock, PORT) == SOCKET_ERROR) {
		printf("Cannot bind %i port\n", PORT);
		socket_close(winSock);
		socket_free(winSock);
		return 0;
	}

	socket_listen(winSock);
	char buf[10000];
	socket_t * client = NULL;
	// main cycle of the program
	while (1) {
		printf("Awaiting for connections...\n");
		client = socket_accept(winSock);

		// Checking if client is not null, closing app if he is
		if (client == NULL) {
			printf("NULL client, closing app...\n");
			break;
		}

		int readStatus = socket_read(client, buf, sizeof(buf));

		// Skipping empty request (may appear from time to time)
		if (readStatus <= 0) {
			printf("Empty request, skipping...\n");
			socket_close(client);
			socket_free(client);
			continue;
		}

		// Printing info about the received request to console
		printf(">> Got request (readStatus: %i):\n'%s'\n", readStatus, buf);
		http_request_t request = http_request_parse(buf);

		// check the type/path of request (API/HTML) & analyze the method (GET/POST/DELETE)
		// and provide the client with proper answer
		server_analyzeRequest(&request, client, db);

		socket_free(client);
	}

	// end of program
	socket_close(winSock);
	socket_free(winSock);
	db_free(db);
	lib_free();
	return 0;
}
Esempio n. 2
0
int
main(int argc, const char *argv[])
{
  Socket* serverSock, *controlSock;
  int c;

  poptContext optCon = poptGetContext(NULL, argc, argv, options, 0);
  poptSetOtherOptionHelp(optCon, "configFile");

  while ((c = poptGetNextOpt(optCon)) >= 0) {
    switch (c) {
    case 'v':
      printf(V_STRING, VERSION);
      printf(COPYRIGHT);
      return 0;
    }
  }

  setup_logging (logfile_name, log_level);

  if (c < -1) {
    /* an error occurred during option processing */
    fprintf(stderr, "%s: %s\n",
      poptBadOption(optCon, POPT_BADOPTION_NOALIAS),
      poptStrerror(c));
    return -1;
  }

  loginfo (V_STRING, VERSION);
  loginfo (COPYRIGHT);

  struct sigaction new_action, old_action;
  new_action.sa_handler = sigpipe_handler;
  sigemptyset (&new_action.sa_mask);
  new_action.sa_flags = 0;
  sigaction (SIGPIPE, NULL, &old_action);
  if (old_action.sa_handler != SIG_IGN)
    sigaction (SIGPIPE, &new_action, NULL);

  prepare_stdin(NULL);

  eventloop_init();
  session = (Session*) malloc(sizeof(Session));
  memset(session, 0, sizeof(Session));

  session->state = ProxyState_PAUSED;

  serverSock = socket_server_new("proxy_server", listen_port, on_connect, NULL);
  controlSock = socket_server_new("proxy_server_control", listen_port + 1, on_control_connect, NULL);

  eventloop_on_stdin(stdin_handler, session);
  eventloop_run();

  socket_free(serverSock);
  socket_free(controlSock);

  return(0);
}
status_t
socket_socketpair(int family, int type, int protocol, net_socket* sockets[2])
{
	sockets[0] = NULL;
	sockets[1] = NULL;

	// create sockets
	status_t error = socket_open(family, type, protocol, &sockets[0]);
	if (error != B_OK)
		return error;

	if (error == B_OK)
		error = socket_open(family, type, protocol, &sockets[1]);

	// bind one
	if (error == B_OK)
		error = socket_bind(sockets[0], NULL, 0);

	// start listening
	if (error == B_OK)
		error = socket_listen(sockets[0], 1);

	// connect them
	if (error == B_OK) {
		error = socket_connect(sockets[1], (sockaddr*)&sockets[0]->address,
			sockets[0]->address.ss_len);
	}

	// accept a socket
	net_socket* acceptedSocket = NULL;
	if (error == B_OK)
		error = socket_accept(sockets[0], NULL, NULL, &acceptedSocket);

	if (error == B_OK) {
		// everything worked: close the listener socket
		socket_close(sockets[0]);
		socket_free(sockets[0]);
		sockets[0] = acceptedSocket;
	} else {
		// close sockets on error
		for (int i = 0; i < 2; i++) {
			if (sockets[i] != NULL) {
				socket_close(sockets[i]);
				socket_free(sockets[i]);
				sockets[i] = NULL;
			}
		}
	}

	return error;
}
Esempio n. 4
0
Socket*
socket_mc_out_new(
  char* name,   //! Name used for debugging
  char* mcast_addr,   //! IP address of the multicast socket/channel.
  int mcast_port, //! Port used
  char* iface //! Name of the interface (eth0/eth1) to bind to
) {
  SocketInt* self;
//  if ((self = (SocketInt*)socket_new(name, mcast_addr, 0)) == NULL)
//    return NULL;
  if ((self = (SocketInt*)socket_new(name, FALSE)) == NULL)
    return NULL;

  // Multicast parameters
  unsigned char ttl = 3;
  unsigned char one = 3;  // loopback

  struct in_addr addr;
  addr.s_addr = iface2addr(name, iface);
  o_log(O_LOG_DEBUG, "socket:%s: Binding to %x\n", name, addr.s_addr);
  if (setsockopt(self->sockfd, IPPROTO_IP, IP_MULTICAST_IF, &addr, sizeof(addr)) < 0) {
    o_log (O_LOG_ERROR, "socket:%s: Setting outgoing interface for socket\n\t%s",
       name, strerror(errno));
    socket_free((Socket*)socket);
    return NULL;
  }

  if (setsockopt(self->sockfd, IPPROTO_IP, IP_MULTICAST_TTL, &ttl,
        sizeof(unsigned char)) < 0) {
    o_log(O_LOG_ERROR, "socket:%s: While setting TTL parameter for multicast socket\n\t%s",
      name, strerror(errno));
    socket_free((Socket*)socket);
    return NULL;
  }
  if (setsockopt(self->sockfd, IPPROTO_IP, IP_MULTICAST_LOOP,
         &one, sizeof(unsigned char)) < 0) {
    o_log(O_LOG_ERROR, "socket%s: While setting the loopback on multicast socket\n\t%s",
      name, strerror(errno));
    socket_free((Socket*)socket);
    return NULL;
  }

  //  self->addr = mcast_addr;
  self->servAddr.sin_port = htons(mcast_port);
  self->servAddr.sin_addr.s_addr = inet_addr(mcast_addr);
  o_log(O_LOG_DEBUG, "socket:%s: Ready to send data on: %s:%d\n",
    name, mcast_addr, mcast_port);
  return (Socket*)self;
}
Esempio n. 5
0
int main(){

    lib_init();

    socket_t * serverSocket = socket_new();
    socket_bind(serverSocket, 5000);
    socket_listen(serverSocket);

    film_maker_t*  film_makers[FILM_MAKERS_AMOUNT];

     for (int i = 0; i < FILM_MAKERS_AMOUNT; i++) {
        film_makers[i] = film_maker_new();

    }

       parse(film_makers,"XML_format.xml");


    while(1) {
        socket_t * clientSocket = socket_accept(serverSocket);
        char buf[102400];

        if(socket_read(clientSocket, buf, 102400) == 0) {
            socket_close(clientSocket);
            socket_free(clientSocket);
            puts("Skipping empty request");
            continue;
        }



        http_request_t req = http_request_parse(buf);

        server_reply(clientSocket, req, film_makers);
//puts("fghj");

        socket_close(clientSocket);
        socket_free(clientSocket);
    }

    for (int i = 0; i < 3; i++)
        film_maker_free(film_makers[i]);

    socket_close(serverSocket);
    socket_free(serverSocket);
          lib_free();
        return 0;
}
Esempio n. 6
0
/** Create an IP Socket object bound to ADDR and PORT.
 *
 * This function binds the newly-created socket, but doesn't listen on it just yet.
 *
 * \param name name of the object, used for debugging
 * \param port port used
 * \param is_tcp true if TCP, false for UDP XXX: This should be more generic
 * \return a pointer to the SocketInt object, cast as a Socket
 */
Socket* socket_in_new(
  char* name,
  int port,
  int is_tcp
) {
  SocketInt* self;
  if ((self = (SocketInt*)socket_new(name, is_tcp)) == NULL)
    return NULL;


//  o_log(O_LOG_DEBUG, "socket:%s: Attempt to join %s:%d\n", name, addr, port);

  self->servAddr.sin_family = PF_INET;
  self->servAddr.sin_port = htons(port);
  self->servAddr.sin_addr.s_addr = htonl(INADDR_ANY);

  if(bind(self->sockfd, (struct sockaddr *)&self->servAddr,
      sizeof(struct sockaddr_in)) < 0) {
    o_log(O_LOG_ERROR, "socket:%s: Error binding socket to interface: %s\n",
          name, strerror(errno));
    socket_free((Socket*)self);
    return NULL;
  }

  self->localport = ntohs(self->servAddr.sin_port);
  o_log(O_LOG_DEBUG, "socket:%s: Socket bound to port: %d\n", name, self->localport);

  self->next = instances;
  instances = self;
  return (Socket*)self;
}
Esempio n. 7
0
/* Close all sockets, free all the socket structs, and send a RST
 * packet to clean up kernel state for each connection.
 * TODO(ncardwell): centralize error handling and ensure test errors
 * always result in a call to these clean-up functions, so we can make
 * sure to reset connections in all cases.
 */
static void close_all_sockets(struct state *state)
{
	struct socket *socket = state->sockets;
	while (socket != NULL) {
		if (socket->live.fd >= 0 && !socket->is_closed) {
			assert(socket->script.fd >= 0);
			DEBUGP("closing struct state socket "
			       "live.fd:%d script.fd:%d\n",
			       socket->live.fd, socket->script.fd);
			if (close(socket->live.fd))
				die_perror("close");
		}
		if ((socket->state != SOCKET_INIT) &&
		    (socket->state != SOCKET_NEW) &&
		    (socket->state != SOCKET_PASSIVE_LISTENING) &&
		    (state->config->is_wire_client == false)) {
			switch (socket->protocol) {
			case IPPROTO_TCP:
				if (reset_connection(state, socket) != STATUS_OK)
					die("error reseting connection\n");
				break;
			case IPPROTO_SCTP:
				if (abort_association(state, socket) != STATUS_OK)
					die("error aborting association\n");
				break;
			default:
				break;
			}
		}
		struct socket *dead_socket = socket;
		socket = socket->next;
		socket_free(dead_socket);
	}
}
Esempio n. 8
0
tcp_result cph_tcp_suspend(socket_connection_t *cnx)
{
	// TODO: SEMAPHORE TAKE GIVE TASK NOTIFY
	tcp_result result;

	comm_request_t request;

	request.type = REQUEST_SUSPEND;

	if(xQueueSendToBack( xCommQueueRequest, &request, (TickType_t)0) == pdTRUE) {
		while(true) {

			if(cnx->socket->socket_error > 0) {
				result = SYS_ERR_TCP_FAIL;
				break;
			}

			if(cnx->socket->socket_status == SCK_SUSPENDED) {
				result = SYS_TCP_OK;
				break;
			}
		}
	}

	if(xSemaphoreTake(tcp_suspend_signal, portMAX_DELAY)) {
		//printf("tcp_connect: connected.\r\n");
	}

	socket_free();
	return result;
}
Esempio n. 9
0
void
client_free (Client *client)
{
  if (client == NULL) return;

  if (client->file) {
    fflush (client->file);
    fclose (client->file);
    client->file = NULL;
  }

  oml_free (client->file_name);
  oml_free (client->downstream_addr);

  struct header *header = client->headers;

  while (header) {
    struct header *next = header->next;
    header_free (header);
    header = next;
  }

  msg_queue_destroy (client->messages);
  cbuf_destroy (client->cbuf);

  pthread_cond_destroy (&client->condvar);
  pthread_mutex_destroy (&client->mutex);

  socket_free (client->recv_socket);

  oml_free (client);
}
Esempio n. 10
0
/**
 * Test the connection and protocol
 */
static void check_connection(Service_T s, Port_T p) {
  Socket_T socket;
  volatile int rv = TRUE;
  char buf[STRLEN];
  char report[STRLEN] = {0};
  struct timeval t1;
  struct timeval t2;

  ASSERT(s && p);

  /* Get time of connection attempt beginning */
  gettimeofday(&t1, NULL);

  /* Open a socket to the destination INET[hostname:port] or UNIX[pathname] */
  socket = socket_create(p);
  if (!socket) {
    snprintf(report, STRLEN, "failed, cannot open a connection to %s", Util_portDescription(p, buf, sizeof(buf)));
    rv = FALSE;
    goto error;
  } else
    DEBUG("'%s' succeeded connecting to %s\n", s->name, Util_portDescription(p, buf, sizeof(buf)));

  /* Verify that the socket is ready for i|o. TCP sockets are checked anytime, UDP
   * sockets just when there is no specific protocol test used since the socket_is_ready()
   * adds 2s delay when used with UDP socket. When there is specific protocol used, we
   * don't need it for UDP, since the protocol test is sufficient */
  if ((socket_get_type(socket) != SOCK_DGRAM || p->protocol->check == check_default) && !socket_is_ready(socket)) {
    snprintf(report, STRLEN, "connection failed, %s is not ready for i|o -- %s", Util_portDescription(p, buf, sizeof(buf)), STRERROR);
    rv = FALSE;
    goto error;
  }

  /* Run the protocol verification routine through the socket */
  if (! p->protocol->check(socket)) {
    snprintf(report, STRLEN, "failed protocol test [%s] at %s", p->protocol->name, Util_portDescription(p, buf, sizeof(buf)));
    rv = FALSE;
    goto error;
  } else
    DEBUG("'%s' succeeded testing protocol [%s] at %s\n", s->name, p->protocol->name, Util_portDescription(p, buf, sizeof(buf)));

  /* Get time of connection attempt finish */
  gettimeofday(&t2, NULL);

  /* Get the response time */
  p->response = (double)(t2.tv_sec - t1.tv_sec) + (double)(t2.tv_usec - t1.tv_usec)/1000000;

  error:
  if (socket)
    socket_free(&socket);

  if (!rv) {
    p->response = -1;
    p->is_available = FALSE;
    Event_post(s, Event_Connection, STATE_FAILED, p->action, report);
  } else {
    p->is_available = TRUE;
    Event_post(s, Event_Connection, STATE_SUCCEEDED, p->action, "connection succeeded to %s", Util_portDescription(p, buf, sizeof(buf)));
  }
      
}
Esempio n. 11
0
/**
 * Pass on to methods in http/cervlet.c to start/stop services
 * @param P A service name as stated in the config file
 * @param action A string describing the action to execute
 */
void d_check_service(const char *P, const char *action) {

  Socket_T s;
  char *auth= get_basic_authentication_header();

  ASSERT(P);
  ASSERT(action);


  s= socket_new(Run.bind_addr?Run.bind_addr:"localhost",
		Run.httpdport, SOCKET_TCP, Run.httpdssl);
  
  if(!s) {
    
    log("%s: Cannot connect to the monit daemon. "
          "Did you start it with http support?\n", prog);
    goto error;
    
  } else {

    socket_print(s, "GET /%s?action=%s HTTP/1.0\r\n%s\r\n", P, action, auth);
    socket_free(&s);
      
  }
  
  error:
  FREE(auth);
  
}
Esempio n. 12
0
Socket_T socket_create_a(int socket, const char *remote_host,
                         int port, void *sslserver) {
  
  Socket_T S;
  
  ASSERT(socket>=0);
  ASSERT(remote_host);
  
  NEW(S);
  S->length= 0;
  S->offset= 0;
  S->port= port;
  S->socket= socket;
  S->type= SOCK_STREAM;
  S->timeout= NET_TIMEOUT;
  S->host= xstrdup(remote_host);
  S->connection_type= TYPE_ACCEPT;
  
  if(sslserver) {
    S->sslserver= sslserver;
    if(! (S->ssl= insert_accepted_ssl_socket(S->sslserver))) {
      goto ssl_error;
    }
    if(! embed_accepted_ssl_socket(S->ssl, S->socket)) {
      goto ssl_error;
    }
  }
  
  return S;
  
ssl_error:
    socket_free(&S);
  return NULL;
  
}
Esempio n. 13
0
/**
 * Post event or status data message to mmonit
 * @param E An event object or NULL for status data
 * @return If failed, return HANDLER_MMONIT flag or HANDLER_SUCCEEDED flag if succeeded
 */
int handle_mmonit(Event_T E) {
        int       rv = HANDLER_MMONIT;
        Socket_T  socket = NULL;
        Mmonit_T  C = Run.mmonits;

        /* The event is sent to mmonit just once - only in the case that the state changed */
        if (! C || (E && ! E->state_changed))
                return HANDLER_SUCCEEDED;

        StringBuffer_T sb = StringBuffer_create(256);
        for (; C; C = C->next) {
                if (! (socket = socket_create_t(C->url->hostname, C->url->port, SOCKET_TCP, C->ssl, C->timeout))) {
                        LogError("M/Monit: cannot open a connection to %s -- %s\n", C->url->url, STRERROR);
                        goto error;
                }
                status_xml(sb, E, E ? LEVEL_SUMMARY : LEVEL_FULL, 2, socket_get_local_host(socket));
                if (! data_send(socket, C, StringBuffer_toString(sb))) {
                        LogError("M/Monit: cannot send %s message to %s\n", E ? "event" : "status", C->url->url);
                        goto error;
                }
                StringBuffer_clear(sb);
                socket_shutdown_write(socket);
                if (! data_check(socket, C)) {
                        LogError("M/Monit: %s message to %s failed\n", E ? "event" : "status", C->url->url);
                        goto error;
                }
                rv = HANDLER_SUCCEEDED; // Return success if at least one M/Monit succeeded
                DEBUG("M/Monit: %s message sent to %s\n", E ? "event" : "status", C->url->url);
error:
                if (socket)
                        socket_free(&socket);
        }
        StringBuffer_free(&sb);
        return rv;
}
Esempio n. 14
0
static void accept_ready(socket_t *socket, UNUSED_ATTR void *context) {
  assert(socket != NULL);
  assert(socket == listen_socket);

  socket = socket_accept(socket);
  if (!socket)
    return;

  client_t *client = (client_t *)osi_calloc(sizeof(client_t));
  if (!client) {
    LOG_ERROR(LOG_TAG, "%s unable to allocate memory for client.", __func__);
    socket_free(socket);
    return;
  }

  client->socket = socket;

  if (!list_append(clients, client)) {
    LOG_ERROR(LOG_TAG, "%s unable to add client to list.", __func__);
    client_free(client);
    return;
  }

  socket_register(socket, thread_get_reactor(thread), client, read_ready, NULL);
}
Esempio n. 15
0
/* Close all sockets, free all the socket structs, and send a RST
 * packet to clean up kernel state for each connection.
 * TODO(ncardwell): centralize error handling and ensure test errors
 * always result in a call to these clean-up functions, so we can make
 * sure to reset connections in all cases.
 */
static void close_all_sockets(struct state *state)
{
	struct socket *socket = state->sockets;
	while (socket != NULL)
	{
		if (socket->live.fd >= 0 && !socket->is_closed)
		{
			assert(socket->script.fd >= 0);
			DEBUGP("closing struct state socket "
			       "live.fd:%d script.fd:%d\n",
			       socket->live.fd, socket->script.fd);
			if (close(socket->live.fd))
				die_perror("close");
		}
		if (socket->protocol == IPPROTO_TCP &&
		        !state->config->is_wire_client &&
		        reset_connection(state, socket))
		{
			die("error reseting connection\n");
		}
		struct socket *dead_socket = socket;
		socket = socket->next;
		socket_free(dead_socket);
	}
}
Esempio n. 16
0
File: hlib.c Progetto: cafiend/W12
Display *OpenDisplay(char *hostname, int port)
{
    Display *display = NULL;
    Socket *socket = NULL;
    char *port_buf = NULL;

    port_buf = int_to_string(port);
    if (port_buf == NULL)
        return NULL;

    socket = socket_new(Socket_Blocking);
    if (socket_connect(socket, hostname, port_buf) != 0) {
        socket_free(socket);
        free(port_buf);
        return NULL;
    }

    free(port_buf);

    display = (Display *) malloc(sizeof(Display));
    
    display->socket = socket;
    display->hostname = strdup(hostname);
    display->port = port;
    display->callbacks = callbacks_new();
    
    return display;
}
Esempio n. 17
0
static void client_free(void *ptr) {
  if (!ptr)
    return;

  client_t *client = (client_t *)ptr;
  socket_free(client->socket);
  osi_free(client);
}
Esempio n. 18
0
PRIVATE socket_t *socket_udp6(uint32_t scope_id)
{
    socket_t *s = socket_new6(scope_id);
    if (s == NULL) {
        return NULL;
    }
#if defined(HAVE_LIBC_IPV6)
    __winsock_init();
    if (ip6disabled) {
        goto compat;
    }
    s->fd = __winsock_errno(socket(PF_INET6, SOCK_DGRAM, IPPROTO_UDP));
    if (s->fd == -1) {
        if (errno == EINVAL ||
            errno == EAFNOSUPPORT ||
            errno == EPFNOSUPPORT ||
            errno == EPROTONOSUPPORT) {
compat:
            s->fd = __winsock_errno(socket(AF_INET, SOCK_DGRAM, 0));
            ip6disabled = true;
            if (s->fd == -1) {
                socket_free(s);
                return NULL;
            }
        }
        if (s->fd == -1) {
            socket_free(s);
            return NULL;
        }
        return s;
    }
#if defined(IPV6_V6ONLY)
    int zero = 0;
    __winsock_errno(setsockopt(s->fd, IPPROTO_IPV6, IPV6_V6ONLY, (void *)&zero, sizeof(zero)));
#endif
    if (socket_nodelay(s->fd) == -1) {
        close(s->fd);
        socket_free(s);
        return NULL;
    }
    return s;
#else // HAVE_LIBC_IPV6
    return s;
#endif
}
Esempio n. 19
0
// Must be called with |lock| held except during teardown when we know the socket thread
// is no longer alive.
static void sco_socket_free_locked(sco_socket_t *sco_socket) {
  if (!sco_socket)
    return;

  if (sco_socket->sco_handle != BTM_INVALID_SCO_INDEX)
    BTM_RemoveSco(sco_socket->sco_handle);
  socket_free(sco_socket->socket);
  osi_free(sco_socket);
}
Esempio n. 20
0
void hci_inject_close(void) {
  socket_free(listen_socket);
  list_free(clients);
  thread_free(thread);

  listen_socket = NULL;
  thread = NULL;
  clients = NULL;
}
Esempio n. 21
0
/** Create an unbound Socket object.
 *
 * \param name name of the object, used for debugging
 * \param is_tcp  true if TCP, false for UDP XXX: This should be more generic
 * \return a pointer to the SocketInt object, cast as a Socket, with a newly opened system socket
 * \see socket_free, socket_close
 */
Socket* socket_new(char* name, int is_tcp) {
  SocketInt* self = initialize(name);
  self->is_tcp = is_tcp;
  if (!s_socket(self)) {
    socket_free((Socket*)self);
    return NULL;
  }
  return (Socket*)self;
}
Esempio n. 22
0
int main() {
    lib_init();

    list_t* list=list_new();

    lanser * freeLanser[10];

    for (int i = 0; i < 10; i++)
        freeLanser[i] = Freelanser_new();

  //  parse(freeLanser);

    socket_t * serverSocket = socket_new();
    socket_bind(serverSocket, 5000);
    socket_listen(serverSocket);


   while (1) {
        socket_t * clientSocket = socket_accept(serverSocket);

        char buf[10000]="";

        if (!socket_read(clientSocket, buf, sizeof(buf))) {
            puts("Skipping empty request");
            socket_close(clientSocket);
            socket_free(clientSocket);
            continue;
        }

        http_request_t req = http_request_parse(buf);

        server_answer(list,req,clientSocket,freeLanser);

        socket_close(clientSocket);
        socket_free(clientSocket);
    }

    socket_close(serverSocket);
    socket_free(serverSocket);

    lib_free();
    list_free(list);
    return 0;
}
Esempio n. 23
0
int proxy_free(struct proxy *self)
{
	assert(self);
	assert(self->s);

	socket_free(self->s);
	
	free(self);

	return 0;
}
Esempio n. 24
0
PRIVATE socket_t *socket_udp4(void)
{
    socket_t *s = socket_new4();
    if (s == NULL) {
        errno = EINVAL;
        return NULL;
    }
    __winsock_init();
    s->fd = __winsock_errno(socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP));
    if (s->fd == -1) {
        socket_free(s);
        return NULL;
    }
    if (socket_nodelay(s->fd) == -1) {
        close(s->fd);
        socket_free(s);
        return NULL;
    }
    return s;
}
Esempio n. 25
0
int main() {
    lib_init();
    socket_t * server = socket_new();
    socket_bind(server, 5000);
    socket_listen(server);
	
   char buf[10000];
    char pathBuf[256];
    socket_t * client = NULL;

    while(1) {
		client = socket_accept(server);
        socket_read(client, buf, sizeof(buf));
		if (strlen(buf) == 0)
			continue;
        printf(">> Got request:\n%s\n", buf);

        http_getPath(buf, pathBuf, sizeof(pathBuf));

        http_request_t request = http_request_parse(buf);

        if (strcmp(request.uri, "/") == 0) {
            server_homepage(client);
        } else if (strcmp(request.uri, "/database") == 0) {
            server_students(client, &request);
        }  
        else if (strcmp(request.uri, "/info") == 0) {
            server_info(client);
        }
        else if (strcmp(request.uri, "/filename") == 0) {
            server_file_parse(client);
        }
        else {
            server_notFound(client);
        }
		socket_free(client);
    }
    socket_free(server);
    lib_free();
    return 0;
}
Esempio n. 26
0
void client_destroy(int s)
{
	client *c;

	c = clients[s];	
	clients[s] = NULL;
	
	socket_free(c->si);
	buffer_free(c->buffer);
	character_free(c->ch);
	free(c);
}
Esempio n. 27
0
/**
 * Process a HTTP request. This is done by dispatching to the service
 * function. 
 * @param s A Socket_T representing the client connection
 */
void *http_processor(Socket_T s) {

  if(! can_read(socket_get_socket(s), REQUEST_TIMEOUT)) {
    internal_error(s, SC_REQUEST_TIMEOUT, "Time out when handling the Request");
  } else {
    do_service(s);
  }
  socket_free(&s);

  return NULL;

}
Esempio n. 28
0
void client_destroy(client *c)
{
	int fd;

	fd = socket_get(c->si);
	clients[fd] = NULL;

	socket_free(c->si);
	buffer_free(c->buffer);
	character_free(c->ch);
	free(c);
}
Esempio n. 29
0
/** Do the actual writing into the OComm Socket, with error handling
 * \param self OmlNetOutStream through which the data should be written
 * \param buffer data to write
 * \param length length of the data to write
 *
 * \return the size of data written, or -1 on error
 *
 * \see write(3)
 */
static ssize_t
socket_write(OmlOutStream* outs, uint8_t* buffer, size_t  length)
{
    OmlNetOutStream *self = (OmlNetOutStream*) outs;
    int result = socket_sendto(self->socket, (char*)buffer, length);

    if (result == -1 && socket_is_disconnected (self->socket)) {
        logwarn ("%s: Connection lost\n", self->dest);
        socket_free(self->socket);
        self->socket = NULL;      // Server closed the connection
    }
    return result;
}
Esempio n. 30
0
int
socket(socket_family_t family, socket_type_t type, socket_protocol_t protocol)
{
    if (m_initialization_state == false)
    {
        (void) socket_init();
    }
    VERIFY_MODULE_IS_INITIALIZED();

    int ret_sock = -1;
    int sock = socket_allocate();
    SOCKET_TRACE("Got value %d from allocate\r\n", (int)sock);
    if (sock >= 0)
    {
        socket_entry_t *p_socket_entry = &m_socket_table[sock];
        p_socket_entry->handle.params.family = family;
        p_socket_entry->handle.params.protocol = protocol;
        p_socket_entry->handle.params.type = type;
        p_socket_entry->handler = NULL;

        if (family == AF_INET6)
        {
#if SOCKET_IPV6_ENABLE == 1 || SOCKET_LWIP_ENABLE == 1
            p_socket_entry->handler = &transport_handler;
#else
            set_errno(EAFNOSUPPORT);
#endif
        // } else if (family == AF_BLE) {
            // TODO: Handle BLE
        }
        else
        {
            set_errno(EAFNOSUPPORT);
        }

        if (p_socket_entry->handler != NULL)
        {
            uint32_t err_code = p_socket_entry->handler->create_handler(&p_socket_entry->handle);
            socket_set_errno(err_code);
            ret_sock = (err_code == NRF_SUCCESS) ? sock : ret_sock;
        }

        if (ret_sock < 0)
        {
            socket_free(sock);
        }
    }
    SOCKET_TRACE("Returning socket value %d\r\n", (int)ret_sock);
    return ret_sock;
}