]> git.lizzy.rs Git - dragonnet.git/blob - recv.c
eb47af7440bd12db8243cfc4828e98196ad2fdeb
[dragonnet.git] / recv.c
1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <string.h>
4 #include <unistd.h>
5
6 #include <dragonnet/recv.h>
7
8 void dragonnet_recv_raw(DragonnetPeer *p, void *buf, size_t n)
9 {
10         pthread_rwlock_rdlock(&p->mu);
11         int sock = p->sock;
12         pthread_rwlock_unlock(&p->mu);
13
14         ssize_t len = recv(sock, buf, n, MSG_WAITALL);
15         if (len < 0) {
16                 perror("recv");
17                 dragonnet_peer_delete(p);
18                 return;
19         }
20
21         // Connection closed
22         if (len == 0) {
23                 pthread_rwlock_wrlock(&p->mu);
24
25                 close(p->sock);
26                 p->sock = -1;
27                 p->state++;
28
29                 pthread_rwlock_unlock(&p->mu);
30         }
31 }
32
33 void dragonnet_read_raw(u8 **buf, size_t *n, void *data, size_t len)
34 {
35         memcpy(data, *buf, len);
36         memcpy(*buf, &((*buf)[len]), -len + *n);
37
38         *buf = realloc(*buf, -len + *n);
39         *n -= len;
40 }