]> git.lizzy.rs Git - dragonnet.git/blob - recv_thread.c
gen_messages: Use dragontype numbers instead of stdint
[dragonnet.git] / recv_thread.c
1 #include <assert.h>
2 #include <errno.h>
3 #include <pthread.h>
4 #include <stdbool.h>
5 #include <stdio.h>
6 #include <unistd.h>
7
8 #include "peer.h"
9 #include "recv_thread.h"
10
11 void *dragonnet_peer_recv_thread(void *g_peer)
12 {
13         DragonnetPeer *p = (DragonnetPeer *) g_peer;
14
15         pthread_rwlock_wrlock(p->mu);
16         assert(p->state == DRAGONNET_PEER_CREATED);
17         p->state++;
18         pthread_rwlock_unlock(p->mu);
19
20         while (true) {
21                 uint16_t msg;
22
23                 pthread_rwlock_rdlock(p->mu);
24                 ssize_t len = recv(p->sock, &msg, sizeof msg, MSG_WAITALL);
25                 pthread_rwlock_unlock(p->mu);
26
27                 if (len < 0 && errno != EWOULDBLOCK) {
28                         perror("recv");
29                         dragonnet_peer_delete(p);
30                         return NULL;
31                 }
32
33                 // connection closed
34                 if ((len >= 0 && len != sizeof msg) || errno == EWOULDBLOCK) {
35                         pthread_rwlock_wrlock(p->mu);
36
37                         close(p->sock);
38                         p->sock = 0;
39                         p->state++;
40
41                         pthread_rwlock_unlock(p->mu);
42                         return NULL;
43                 }
44
45                 // deserialization
46         }
47 }