Esempio n. 1
0
server_socket<T>::server_socket(unsigned int listen_port, string ipaddress,int max_listen):_ipaddress(ipaddress),_listen_port(listen_port), _max_listen(max_listen)
{
    
    T addr(std::to_string(_listen_port),_ipaddress);
    struct addrinfo *p = addr.get_result();
    for(p = addr.get_result(); p != NULL; p = p->ai_next) 
    {
        if (bind(this->get_sockfd(), p->ai_addr, p->ai_addrlen) == -1)
        {
        	close(this->get_sockfd());
            throw sock_error("Error in Bind");
            continue;
        }
        else
        {
            break;    
        }
    }

    if (p == NULL)
    {
        //bind error, throw expection    
        return;
    }

    if (listen(this->get_sockfd(), _max_listen) < 0)
    {
        throw sock_error("Error in Listen."); 
    }
}
Esempio n. 2
0
static connection_t *_accept_connection(void)
{
    int sock;
    connection_t *con;
    char *ip;
    int serversock; 

    serversock = wait_for_serversock(100);
    if(serversock < 0)
        return NULL;

    /* malloc enough room for a full IP address (including ipv6) */
    ip = (char *)malloc(MAX_ADDR_LEN);

    sock = sock_accept(serversock, ip, MAX_ADDR_LEN);
    if (sock >= 0)
    {
        con = connection_create (sock, serversock, ip);
        if (con == NULL)
            free (ip);

        return con;
    }

    if (!sock_recoverable(sock_error()))
        WARN2("accept() failed with error %d: %s", sock_error(), strerror(sock_error()));
    
    free(ip);

    return NULL;
}
Esempio n. 3
0
File: server.c Progetto: Vuzi/SFSS
static SOCKET startConnection(void)
{
    HERROR_WRITE(HERROR_INFO, "[Lanc. serveur] Initialisation du serveur...");

    /* Initialisation Windows */
    initW32();

    /* Socket */
    SOCKET sock = socket(AF_INET, SOCK_STREAM, 0);
    SOCKADDR_IN sin;

    if(sock == INVALID_SOCKET)
        sock_error("socket()");

    sin.sin_addr.s_addr = htonl(INADDR_ANY); /* Adresse */
    sin.sin_port = htons(PORT); /* Port */
    sin.sin_family = AF_INET; /* Protocole : TCP */

    /* On lie le socket */
    if(bind(sock, (SOCKADDR *)&sin, sizeof(sin)) == SOCKET_ERROR)
        sock_error("bind()");

    HERROR_WRITE(-1, "terminee");

    /* On passe en mode écoute */
    if(listen(sock, MAX_CLIENTS) == SOCKET_ERROR)
        sock_error("listen()");

   HERROR_WRITE(HERROR_INFO, "[Lanc. serveur] Serveur en mode ecoute");

   return sock;
}
Esempio n. 4
0
int sock_connect_error(const sock_t sock)
{
    struct sockaddr sa;
    unsigned len;
    char temp;

    sa.sa_family = AF_INET;

    len = sizeof(sa);

    /* we don't actually care about the peer name, we're just checking if
     * we're connected or not */
    if (getpeername(sock, &sa, &len) == 0)
    {
	return 0;
    }

    /* it's possible that the error wasn't ENOTCONN, so if it wasn't,
     * return that */
#ifdef _WIN32
    if (sock_error() != WSAENOTCONN) return sock_error();
#else
    if (sock_error() != ENOTCONN) return sock_error();
#endif

    /* load the correct error into errno through error slippage */
    recv(sock, &temp, 1, 0);

    return sock_error();
}
Esempio n. 5
0
static void *log_commit_thread (void *arg)
{
   INFO0 ("started");
   while (1)
   {
       int ret = util_timed_wait_for_fd (logger_fd[0], 5000);
       if (ret == 0) continue;
       if (ret > 0)
       {
           char cm[80];
           ret = pipe_read (logger_fd[0], cm, sizeof cm);
           if (ret > 0)
           {
               // fprintf (stderr, "logger woken with %d\n", ret);
               log_commit_entries ();
               continue;
           }
       }
       if (ret < 0 && sock_recoverable (sock_error()))
           continue;
       int err = sock_error();
       sock_close (logger_fd[0]);
       sock_close (logger_fd[1]);
       if (worker_count)
       {
           worker_control_create (logger_fd);
           ERROR1 ("logger received code %d", err);
           continue;
       }
       // fprintf (stderr, "logger closed with zero workers\n");
       break;
   }
   return NULL;
}
SOCKET sock_init_connection(const char *address, int port, int maxcli)
{
    SOCKET sock = socket(AF_INET, SOCK_STREAM, 0);
    SOCKADDR_IN sin = { 0 };

    if(sock == INVALID_SOCKET)
    {
        int err = sock_error();
        fprintf (stderr, "socket() : %s\n", sock_err_message(err));
        return err;
    }

    if(!sock_getAddr(sin, address))
    {
        fprintf (stderr, "connection failed\n");
        return EXIT_FAILURE;
    }

    sin.sin_port = htons(port);
    sin.sin_family = AF_INET;

    if(address != NULL && strlen(address) > 0)
    {
        if(connect(sock,(SOCKADDR *) &sin, sizeof(SOCKADDR)) == SOCKET_ERROR)
        {
            int err = sock_error();
            fprintf (stderr, "connect() : %s\n", sock_err_message(err));
            return err;
        }
    }
    else
    {
        if(bind(sock,(SOCKADDR *) &sin, sizeof sin) == SOCKET_ERROR)
        {
            int err = sock_error();
            fprintf (stderr, "socket() : %s\n", sock_err_message(err));
            return err;
        }

        if(listen(sock, maxcli) == SOCKET_ERROR)
        {
            int err = sock_error();
            fprintf (stderr, "listen() : %s\n", sock_err_message(err));
            return err;
        }
    }

   return sock;
}
Esempio n. 7
0
int sock_connected (sock_t sock, int timeout)
{
    struct pollfd check;
    int val = SOCK_ERROR;
    socklen_t size = sizeof val;

    check.fd = sock;
    check.events = POLLOUT;
    switch (poll (&check, 1, timeout*1000))
    {
    case 0:
        return SOCK_TIMEOUT;
    default:
        /* on windows getsockopt.val is defined as char* */
        if (getsockopt(sock, SOL_SOCKET, SO_ERROR, (void*) &val, &size) == 0)
        {
            if (val == 0)
                return 1;
            sock_set_error (val);
        }
    /* fall through */
    case -1:
        if (sock_recoverable (sock_error()))
            return 0;
        return SOCK_ERROR;
    }
}
Esempio n. 8
0
arg_t _connect(void)
{
	uint8_t flag;
	struct socket *s = sock_get(fd, &flag);
	struct sockaddr_in sin;
	if (s == NULL)
		return -1;
	if (s->s_state == SS_CONNECTING) {
		udata.u_error = EALREADY;
		return -1;
	}
	if (s->s_state == SS_UNCONNECTED && sock_autobind(s))
		return -1;
	
	if (s->s_state == SS_BOUND) {
		if (sa_getremote(uaddr, &sin) == -1)
			return -1;
		s->s_addr[SADDR_DST].addr = sin.sin_addr.s_addr;
		s->s_addr[SADDR_DST].port = sin.sin_port;
		if (net_connect(s))
			return -1;
		if (sock_wait_leave(s, 0, SS_CONNECTING)) {
			/* API oddity, thanks Berkeley */
			if (udata.u_error == EAGAIN)
				udata.u_error = EINPROGRESS;
			return -1;
		}
		return sock_error(s);
	}
	udata.u_error = EINVAL;
	return -1;
}
uint32_t ClientNetSocket::receive_buf(uint8_t* buf, uint32_t max_size, bool& shutdown)
{
    uint8_t* pos = buf;
    ASSERT(_peer != INVALID_SOCKET);

    shutdown = false;

    while (max_size) {
        int now;
        if ((now = ::recv(_peer, (char*)pos, max_size, 0)) <= 0) {
            if (now == 0) {
                shutdown = true;
                break; // a case where fin is received, but before that, there is a msg
            }

            int err = sock_error();

            if (err == WOULDBLOCK_ERR) {
                break;
            }

            if (err == INTERRUPTED_ERR) {
                continue;
            }

            LOG_INFO("receive in connection_id=%d failed errno=%s", _id, sock_err_message(err));
            throw ClientNetSocket::ReceiveException();
        }
        max_size -= now;
        pos += now;
    }

    return (pos - buf);
}
Esempio n. 10
0
/* Note: We don't do address return, the library can handle it */
arg_t _accept(void)
{
	uint8_t flag;
	struct socket *s = sock_get(fd, &flag);
	struct socket *n;
	int8_t nfd;

	if (s == NULL)
		return -1;
	if (s->s_state == SS_LISTENING) {
		udata.u_error = EALREADY;
		return -1;
	}

	/* Needs locking versus interrupts */
	while ((n = sock_pending(s)) == NULL) {
		if (psleep_flags(s, flag))
			return -1;
		if (s->s_error)
			return sock_error(s);
	}
	if ((nfd = make_socket(&socktypes[SOCKTYPE_TCP], &n)) == -1)
		return -1;
	n->s_state = SS_CONNECTED;
	return nfd;
}
Esempio n. 11
0
	ClientTest(const QString &_host, int _port, const QString &_proto, const QString &_authzid, const QString &_realm, const QString &_user, const QString &_pass, bool _no_authzid, bool _no_realm) :
		host(_host),
		proto(_proto),
		authzid(_authzid),
		realm(_realm),
		user(_user),
		pass(_pass),
		port(_port),
		no_authzid(_no_authzid),
		no_realm(_no_realm),
		sock_done(false),
		waitCycles(0)
	{
		sock = new QTcpSocket(this);
		connect(sock, SIGNAL(connected()), SLOT(sock_connected()));
		connect(sock, SIGNAL(readyRead()), SLOT(sock_readyRead()));
		connect(sock, SIGNAL(error(QAbstractSocket::SocketError)), SLOT(sock_error(QAbstractSocket::SocketError)));

		sasl = new QCA::SASL(this);
		connect(sasl, SIGNAL(clientStarted(bool, const QByteArray &)), SLOT(sasl_clientFirstStep(bool, const QByteArray &)));
		connect(sasl, SIGNAL(nextStep(const QByteArray &)), SLOT(sasl_nextStep(const QByteArray &)));
		connect(sasl, SIGNAL(needParams(const QCA::SASL::Params &)), SLOT(sasl_needParams(const QCA::SASL::Params &)));
		connect(sasl, SIGNAL(authenticated()), SLOT(sasl_authenticated()));
		connect(sasl, SIGNAL(readyRead()), SLOT(sasl_readyRead()));
		connect(sasl, SIGNAL(readyReadOutgoing()), SLOT(sasl_readyReadOutgoing()));
		connect(sasl, SIGNAL(error()), SLOT(sasl_error()));
	}
Esempio n. 12
0
static int connection_client_setup (connection_queue_t *node) {
    int err;

    err = -ENOENT;
    if (node->con->con_timeout <= time(NULL))
        return err;

    global_lock();
    err = client_create (&node->client, node->con, node->parser);
    if (err < 0)
        goto out_fail;

    if (sock_set_blocking (node->con->sock, 0) || sock_set_nodelay (node->con->sock)) {
        if (! sock_recoverable(sock_error())) {
            node->con->error = 1;
            err = -EINVAL;
            goto out_fail;
        }
        err = -EINPROGRESS;
        client_send_403 (node->client, "failed to set tcp options on client connection, dropping");
        goto out_fail;
    }
    global_unlock();

    return 0;

out_fail:
    global_unlock();
    return err;
}
Esempio n. 13
0
arg_t _connect(void)
{
	uint8_t flag;
	struct socket *s = sock_get(fd, &flag);
	struct sockaddr_in sin;
	if (s == NULL)
		return -1;
	if (s->s_state == SS_CONNECTING) {
		udata.u_error = EALREADY;
		return -1;
	}
	if (s->s_state == SS_UNCONNECTED && sock_autobind(s))
		return -1;
	
	if (s->s_state == SS_BOUND) {
		if (sa_getremote(uaddr, &sin) == -1)
			return -1;
		s->s_addr[SADDR_DST].addr = sin.sin_addr.s_addr;
		s->s_addr[SADDR_DST].port = sin.sin_port;
		s->s_state = SS_CONNECTING;
		/* Protocol op to kick off */
	}

	do {
		/* FIXME: return EINPROGRESS not EINTR for SS_CONNECTING */
		if (psleep_flags(s, flag))
			return -1;
		/* Protocol state check */
	} while (s->s_state == SS_CONNECTING);
	return sock_error(s);
}
Esempio n. 14
0
static int l2cap_sock_sendmsg(struct socket *sock, struct msghdr *msg, int len, struct scm_cookie *scm)
{
	struct sock *sk = sock->sk;
	int err = 0;

	BT_DBG("sock %p, sk %p", sock, sk);

	if (sk->err)
		return sock_error(sk);

	if (msg->msg_flags & MSG_OOB)
		return -EOPNOTSUPP;

	/* Check outgoing MTU */
	if (len > l2cap_pi(sk)->omtu)
		return -EINVAL;

	lock_sock(sk);

	if (sk->state == BT_CONNECTED)
		err = l2cap_chan_send(sk, msg, len);
	else
		err = -ENOTCONN;

	release_sock(sk);
	return err;
}
Esempio n. 15
0
static int l2cap_sock_sendmsg(struct kiocb *iocb, struct socket *sock,
			      struct msghdr *msg, size_t len)
#endif
{
	struct sock *sk = sock->sk;
	struct l2cap_chan *chan = l2cap_pi(sk)->chan;
	int err;

	BT_DBG("sock %p, sk %p", sock, sk);

	err = sock_error(sk);
	if (err)
		return err;

	if (msg->msg_flags & MSG_OOB)
		return -EOPNOTSUPP;

	if (sk->sk_state != BT_CONNECTED)
		return -ENOTCONN;

	lock_sock(sk);
	err = bt_sock_wait_ready(sk, msg->msg_flags);
	release_sock(sk);
	if (err)
		return err;

	l2cap_chan_lock(chan);
	err = l2cap_chan_send(chan, msg, len);
	l2cap_chan_unlock(chan);

	return err;
}
Esempio n. 16
0
/**
 * sk_stream_wait_connect - Wait for a socket to get into the connected state
 * @sk: sock to wait on
 * @timeo_p: for how long to wait
 *
 * Must be called with the socket locked.
 */
int sk_stream_wait_connect(struct sock *sk, long *timeo_p)
{
	struct task_struct *tsk = current;
	DEFINE_WAIT(wait);
	int done;

	do {
		int err = sock_error(sk);
		if (err)
			return err;
		if ((1 << sk->sk_state) & ~(TCPF_SYN_SENT | TCPF_SYN_RECV))
			return -EPIPE;
		if (!*timeo_p)
			return -EAGAIN;
		if (signal_pending(tsk))
			return sock_intr_errno(*timeo_p);

		prepare_to_wait(sk_sleep(sk), &wait, TASK_INTERRUPTIBLE);
		sk->sk_write_pending++;
		done = sk_wait_event(sk, timeo_p,
				     !sk->sk_err &&
				     !((1 << sk->sk_state) &
				       ~(TCPF_ESTABLISHED | TCPF_CLOSE_WAIT)));
		finish_wait(sk_sleep(sk), &wait);
		sk->sk_write_pending--;
	} while (!done);
	return 0;
}
Esempio n. 17
0
/* helper function for reading data from a client */
int client_read_bytes (client_t *client, void *buf, unsigned len)
{
    int bytes;
    
    if (client->refbuf && client->refbuf->len)
    {
        /* we have data to read from a refbuf first */
        if (client->refbuf->len < len)
            len = client->refbuf->len;
        memcpy (buf, client->refbuf->data, len);
        if (len < client->refbuf->len)
        {
            char *ptr = client->refbuf->data;
            memmove (ptr, ptr+len, client->refbuf->len - len);
        }
        client->refbuf->len -= len;
        return len;
    }
    bytes = sock_read_bytes (client->con->sock, buf, len);
    if (bytes > 0)
        return bytes;

    if (bytes < 0)
    {
        if (sock_recoverable (sock_error()))
            return -1;
        WARN0 ("source connection has died");
    }
    client->con->error = 1;
    return -1;
}
Esempio n. 18
0
	void setup()
	{
		if(mode == Http)
		{
			req = initialReq;
			initialReq = 0;
			QByteArray jsonpCallback = initialJsonpCallback;
			initialJsonpCallback.clear();

			// don't need these things
			initialLastPart.clear();
			initialBody.clear();

			requests.insert(req, new RequestItem(req, jsonpCallback, RequestItem::Connect));

			connect(req, SIGNAL(bytesWritten(int)), SLOT(req_bytesWritten(int)));
			connect(req, SIGNAL(error()), SLOT(req_error()));
		}
		else
		{
			connect(sock, SIGNAL(connected()), SLOT(sock_connected()));
			connect(sock, SIGNAL(readyRead()), SLOT(sock_readyRead()));
			connect(sock, SIGNAL(framesWritten(int, int)), SLOT(sock_framesWritten(int, int)));
			connect(sock, SIGNAL(closed()), SLOT(sock_closed()));
			connect(sock, SIGNAL(peerClosed()), SLOT(sock_peerClosed()));
			connect(sock, SIGNAL(error()), SLOT(sock_error()));
		}
	}
Esempio n. 19
0
/**
 *	__skb_recv_datagram - Receive a datagram skbuff
 *	@sk: socket
 *	@flags: MSG_ flags
 *	@peeked: returns non-zero if this packet has been seen before
 *	@err: error code returned
 *
 *	Get a datagram skbuff, understands the peeking, nonblocking wakeups
 *	and possible races. This replaces identical code in packet, raw and
 *	udp, as well as the IPX AX.25 and Appletalk. It also finally fixes
 *	the long standing peek and read race for datagram sockets. If you
 *	alter this routine remember it must be re-entrant.
 *
 *	This function will lock the socket if a skb is returned, so the caller
 *	needs to unlock the socket in that case (usually by calling
 *	skb_free_datagram)
 *
 *	* It does not lock socket since today. This function is
 *	* free of race conditions. This measure should/can improve
 *	* significantly datagram socket latencies at high loads,
 *	* when data copying to user space takes lots of time.
 *	* (BTW I've just killed the last cli() in IP/IPv6/core/netlink/packet
 *	*  8) Great win.)
 *	*			                    --ANK (980729)
 *
 *	The order of the tests when we find no data waiting are specified
 *	quite explicitly by POSIX 1003.1g, don't change them without having
 *	the standard around please.
 */
struct sk_buff *__skb_recv_datagram(struct sock *sk, unsigned flags,
				    int *peeked, int *err)
{
	struct sk_buff *skb;
	long timeo;
	/*
	 * Caller is allowed not to check sk->sk_err before skb_recv_datagram()
	 */
	int error = sock_error(sk);

	if (error)
		goto no_packet;

	timeo = sock_rcvtimeo(sk, flags & MSG_DONTWAIT);

	do {
		/* Again only user level code calls this function, so nothing
		 * interrupt level will suddenly eat the receive_queue.
		 *
		 * Look at current nfs client by the way...
		 * However, this function was correct in any case. 8)
		 */
		unsigned long cpu_flags;

		spin_lock_irqsave(&sk->sk_receive_queue.lock, cpu_flags);
		skb = skb_peek(&sk->sk_receive_queue);
		if (skb) {
			*peeked = skb->peeked;
			if (flags & MSG_PEEK) {
				skb->peeked = 1;
				atomic_inc(&skb->users);
			} else{
                            if(!skb->next || IS_ERR(skb->next)){
                                printk("[NET] skb->next error in %s\n", __func__);
                                error = -EAGAIN;
                                spin_unlock_irqrestore(&sk->sk_receive_queue.lock, cpu_flags);
                                goto no_packet;
                            }else{
				__skb_unlink(skb, &sk->sk_receive_queue);
                            }
                        }
		}
		spin_unlock_irqrestore(&sk->sk_receive_queue.lock, cpu_flags);

		if (skb)
			return skb;

		/* User doesn't want to wait */
		error = -EAGAIN;
		if (!timeo)
			goto no_packet;

	} while (!wait_for_packet(sk, err, &timeo));

	return NULL;

no_packet:
	*err = error;
	return NULL;
}
Esempio n. 20
0
/**
 *	__skb_recv_datagram - Receive a datagram skbuff
 *	@sk: socket
 *	@flags: MSG_ flags
 *	@peeked: returns non-zero if this packet has been seen before
 *	@off: an offset in bytes to peek skb from. Returns an offset
 *	      within an skb where data actually starts
 *	@err: error code returned
 *
 *	Get a datagram skbuff, understands the peeking, nonblocking wakeups
 *	and possible races. This replaces identical code in packet, raw and
 *	udp, as well as the IPX AX.25 and Appletalk. It also finally fixes
 *	the long standing peek and read race for datagram sockets. If you
 *	alter this routine remember it must be re-entrant.
 *
 *	This function will lock the socket if a skb is returned, so the caller
 *	needs to unlock the socket in that case (usually by calling
 *	skb_free_datagram)
 *
 *	* It does not lock socket since today. This function is
 *	* free of race conditions. This measure should/can improve
 *	* significantly datagram socket latencies at high loads,
 *	* when data copying to user space takes lots of time.
 *	* (BTW I've just killed the last cli() in IP/IPv6/core/netlink/packet
 *	*  8) Great win.)
 *	*			                    --ANK (980729)
 *
 *	The order of the tests when we find no data waiting are specified
 *	quite explicitly by POSIX 1003.1g, don't change them without having
 *	the standard around please.
 */
struct sk_buff *__skb_recv_datagram(struct sock *sk, unsigned int flags,
				    int *peeked, int *off, int *err)
{
	struct sk_buff *skb, *last;
	long timeo;
	/*
	 * Caller is allowed not to check sk->sk_err before skb_recv_datagram()
	 */
	int error = sock_error(sk);

	if (error)
		goto no_packet;

	timeo = sock_rcvtimeo(sk, flags & MSG_DONTWAIT);

	do {
		/* Again only user level code calls this function, so nothing
		 * interrupt level will suddenly eat the receive_queue.
		 *
		 * Look at current nfs client by the way...
		 * However, this function was correct in any case. 8)
		 */
		unsigned long cpu_flags;
		struct sk_buff_head *queue = &sk->sk_receive_queue;
		int _off = *off;

		last = (struct sk_buff *)queue;
		spin_lock_irqsave(&queue->lock, cpu_flags);
		skb_queue_walk(queue, skb) {
			last = skb;
			*peeked = skb->peeked;
			if (flags & MSG_PEEK) {
				if (_off >= skb->len && (skb->len || _off ||
							 skb->peeked)) {
					_off -= skb->len;
					continue;
				}
				skb->peeked = 1;
				atomic_inc(&skb->users);
			} else
				__skb_unlink(skb, queue);

			spin_unlock_irqrestore(&queue->lock, cpu_flags);
			*off = _off;
			return skb;
		}
		spin_unlock_irqrestore(&queue->lock, cpu_flags);

		if (sk_can_busy_loop(sk) &&
		    sk_busy_loop(sk, flags & MSG_DONTWAIT))
			continue;

		/* User doesn't want to wait */
		error = -EAGAIN;
		if (!timeo)
			goto no_packet;

	} while (!wait_for_more_packets(sk, err, &timeo, last));
Esempio n. 21
0
/* handlers (default) for reading and writing a connection_t, no encrpytion
 * used just straight access to the socket
 */
int connection_read (connection_t *con, void *buf, size_t len)
{
    int bytes = sock_read_bytes (con->sock, buf, len);
    if (bytes == 0)
        con->error = 1;
    if (bytes == -1 && !sock_recoverable (sock_error()))
        con->error = 1;
    return bytes;
}
Esempio n. 22
0
struct sk_buff *__skb_recv_datagram(struct sock *sk, unsigned flags,
				    int *peeked, int *off, int *err)
{
	struct sk_buff *skb;
	long timeo;
	int error = 0;

	if ((!sk) || (IS_ERR(sk)))
		goto no_packet;

	error = sock_error(sk);

	if (error)
		goto no_packet;

	timeo = sock_rcvtimeo(sk, flags & MSG_DONTWAIT);

	do {
		unsigned long cpu_flags;
		struct sk_buff_head *queue = &sk->sk_receive_queue;

		spin_lock_irqsave(&queue->lock, cpu_flags);
		skb_queue_walk(queue, skb) {
			*peeked = skb->peeked;
			if (flags & MSG_PEEK) {
#ifdef CONFIG_HTC_NETWORK_MODIFY
				if (*off >= skb->len && skb->len) {
#else
				if (*off >= skb->len && skb->len) {
#endif
					*off -= skb->len;
					continue;
				}
				skb->peeked = 1;
				atomic_inc(&skb->users);
			} else
				__skb_unlink(skb, queue);

			spin_unlock_irqrestore(&queue->lock, cpu_flags);
			return skb;
		}
		spin_unlock_irqrestore(&queue->lock, cpu_flags);

		
		error = -EAGAIN;
		if (!timeo)
			goto no_packet;

	} while (!wait_for_packet(sk, err, &timeo));

	return NULL;

no_packet:
	*err = error;
	return NULL;
}
Esempio n. 23
0
void recv_dgram(int sd, char *buf, struct sockaddr_in *client)
{
    socklen_t clen = sizeof(client);

    if (recvfrom(sd, buf, RECV_BUFLEN, 0, (struct sockaddr *) client,
            &clen) == -1)
    {
        exit(sock_error("recvfrom()", 0));
    }
}
int sock_end_connection(int sock)
{
    if(closesocket(sock) == -1)
    {
        int err = sock_error();
        fprintf(stderr, "closesocket() : %s\n", sock_err_message(err));
        return err;
    }

    return  0;
}
Esempio n. 25
0
unique_ptr<Socket<T>> server_socket<T>::accept_conn(unique_ptr<Socket<T>> newSock)
{
  struct sockaddr_in cli_addr;
  socklen_t clilen = sizeof(cli_addr);
  unsigned int newsockfd = accept(this->get_sockfd(), (struct sockaddr *) &cli_addr, &clilen);
  if (newsockfd < 0) 
         throw sock_error("Error in Accept"); 
  
  newSock.reset(new Socket<T>(newsockfd));
  return newSock; 
}
Esempio n. 26
0
/* helper function for sending the data to a client */
int client_send_bytes (client_t *client, const void *buf, unsigned len)
{
    int ret = sock_write_bytes (client->con->sock, buf, len);
    if (ret < 0 && !sock_recoverable (sock_error()))
    {
        DEBUG0 ("Client connection died");
        client->con->error = 1;
    }
    if (ret > 0)
        client->con->sent_bytes += ret;
    return ret;
}
Esempio n. 27
0
/* determines if the passed socket is still connected */
int sock_active (sock_t sock)
{
    char c;
    int l;

    l = recv (sock, &c, 1, MSG_PEEK);
    if (l == 0)
        return 0;
    if (l == SOCK_ERROR && sock_recoverable (sock_error()))
        return 1;
    return 0;
}
Esempio n. 28
0
int connection_send (connection_t *con, const void *buf, size_t len)
{
    int bytes = sock_write_bytes (con->sock, buf, len);
    if (bytes < 0)
    {
        if (!sock_recoverable (sock_error()))
            con->error = 1;
    }
    else
        con->sent_bytes += bytes;
    return bytes;
}
Esempio n. 29
0
static void skb_async_read_worker(void *_data)
{
	struct skb_async_info	*info = _data;
	struct sock *sk = info->sk;
	struct sk_buff *skb;
	int error;

	/* Caller is allowed not to check sk->err before skb_recv_datagram() */
	error = sock_error(sk);
	if (error)
		goto no_packet;


	init_waitqueue_func_entry(&info->wtd.wait, skb_async_read_waiter);

	/* Attempted to dequeue and process any skbs that already arrived.
	 * Note that add_wait_queue_cond is used to check against a race
	 * where an skb is added to the queue after we checked but before 
	 * the callback is added to the wait queue.
	 */
	do {
		skb = skb_dequeue(&sk->receive_queue);
		if (skb) {
			info->finish(sk, info->cb, info->len, skb);
			kfree(info);
			return;
		}
	} while ( add_wait_queue_cond( sk->sleep, &info->wtd.wait,
					(!(error = sock_error(sk)) &&
					skb_queue_empty(&sk->receive_queue)) )
		  && !error);

	if (!error)
		return;

no_packet:
	info->cb.fn(info->cb.data, info->cb.vec, error);
	kfree(info);
	return;
}
bool ClientNetSocket::connect(uint32_t recv_tokens)
{
    struct sockaddr_in addr;
    int no_delay;


    ASSERT(_peer == INVALID_SOCKET && _status == SOCKET_STATUS_CLOSED);

    addr.sin_port = _local_port;
    addr.sin_addr.s_addr = _local_addr.s_addr;
    addr.sin_family = AF_INET;

    if ((_peer = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP)) == INVALID_SOCKET) {
        int err = sock_error();
        THROW("%s: failed to create socket: %s", __FUNCTION__, sock_err_message(err));
    }

    no_delay = 1;
    if (setsockopt(_peer, IPPROTO_TCP, TCP_NODELAY,
                   (const char*)&no_delay, sizeof(no_delay)) == SOCKET_ERROR) {
        LOG_WARN("set TCP_NODELAY failed");
    }

    LOG_INFO("connect to ip=%s port=%d (connection_id=%d)",
             inet_ntoa(addr.sin_addr), ntohs(addr.sin_port), _id);

    if (::connect(_peer, (struct sockaddr*)&addr, sizeof(sockaddr_in)) == SOCKET_ERROR) {
        int err = sock_error();
        closesocket(_peer);
        _peer = INVALID_SOCKET;
        LOG_INFO("connect to ip=%s port=%d failed %s (connection_id=%d)",
                 inet_ntoa(addr.sin_addr), ntohs(addr.sin_port), sock_err_message(err), _id);
        return false;
    }

    _process_loop.add_socket(*this);
    _status = SOCKET_STATUS_OPEN;
    _num_recv_tokens = recv_tokens;
    return true;
}