socket.c 12.1 KB
Newer Older
1
2
3
4
5
6
#include <arpa/inet.h>
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
7
#include <sys/poll.h>
8
#include <assert.h>
9
10
11
12
#include "../defines.h"
#include "packet.h"
#include "../util/dbg.h"
#include "../util/common.h"
Andreas Schmidt's avatar
Andreas Schmidt committed
13
14
15
#include "processes/feedbackReceiver.h"
#include "processes/dataTransmitter.h"
#include "processes/dataReceiver.h"
16
#include "socket.h"
17
#include "block.h"
18
#include "receiver.h"
19

20
PrrtSocket *PrrtSocket_create(const bool is_sender)
Andreas Schmidt's avatar
Andreas Schmidt committed
21
{
22
    assert(sizeof(float) == 4);
23
    PrrtSocket *sock_ptr = (PrrtSocket*) calloc(1, sizeof(PrrtSocket));
24
    check_mem(sock_ptr);
25

26

27
    sock_ptr->isSender = is_sender;
28

29
30
    sock_ptr->clock = PrrtClock_create();

Andreas Schmidt's avatar
Andreas Schmidt committed
31
    sock_ptr->isBound = false;
32

33
34
    sock_ptr->sequenceNumberSource = 1;
    sock_ptr->sequenceNumberRedundancy = 1;
35

36
    sock_ptr->csi = PrrtChannelStateInformation_create();
37
    sock_ptr->applicationConstraints = PrrtApplicationConstraints_create();
38

39
40
    sock_ptr->dataStore = NULL;

41
42
    check(sock_ptr->dataSocketFd = socket(AF_INET, SOCK_DGRAM, 0), "Cannot create data socket.")
    check(sock_ptr->feedbackSocketFd = socket(AF_INET, SOCK_DGRAM, 0), "Cannot create feedback socket.");
43

44
    pthread_mutexattr_t attr;
45
46
47
    check(pthread_mutexattr_init(&attr) == 0, "Mutex attr init failed.");
    check(pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE) == 0, "Setting type failed.");
    check(pthread_mutex_init(&sock_ptr->closingMutex, &attr) == 0, "Mutex init failed.");
48

49
    if (is_sender) {
50
51
        check(pthread_mutex_init(&sock_ptr->outQueueFilledMutex, NULL) == 0, "Mutex init failed.");
        check(pthread_cond_init(&sock_ptr->outQueueFilledCv, NULL) == 0, "Cond init failed.");
52
        sock_ptr->outQueue = List_create();
53

54
        sock_ptr->receivers = List_create();
55
    } else {
Andreas Schmidt's avatar
Andreas Schmidt committed
56
        sock_ptr->forwardPacketTable = PrrtForwardPacketTable_create();
57

58
59
        check(pthread_mutex_init(&sock_ptr->inQueueFilledMutex, NULL) == 0, "Mutex init failed.");
        check(pthread_cond_init(&sock_ptr->inQueueFilledCv, NULL) == 0, "Cond init failed.");
60
        sock_ptr->inQueue = List_create();
61
62
    }

63
    return sock_ptr;
64
65

    error:
66
        PrrtSocket_close(sock_ptr);
67
        return NULL;
68
69
}

Andreas Schmidt's avatar
Andreas Schmidt committed
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
bool PrrtSocket_bind(PrrtSocket *sock_ptr, const char* ipAddress, const uint16_t port) {
    check(port <= 65534, "Port %d cannot be bound to.", port);

    size_t size = sizeof(struct sockaddr_in);
    struct sockaddr_in* address = calloc(1, size);
    check_mem(address);

    address->sin_family = AF_INET;
    address->sin_addr.s_addr = inet_addr(ipAddress);
    address->sin_port = htons((uint16_t) (port + 1));
    sock_ptr->address = address;

    check(bind(sock_ptr->feedbackSocketFd, (struct sockaddr *) address, size) == EXIT_SUCCESS,
          "Cannot bind feedback socket.");

    address->sin_port = htons((uint16_t) (port));

    check(bind(sock_ptr->dataSocketFd, (struct sockaddr *) address, size) == EXIT_SUCCESS,
          "Cannot bind data socket.");

90
    if(sock_ptr->isSender) {
Andreas Schmidt's avatar
Andreas Schmidt committed
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
        check(pthread_create(&sock_ptr->receiveFeedbackThread, NULL, receive_feedback_loop, (void *) sock_ptr) ==
              EXIT_SUCCESS, "Cannot create receive feedback thread.");
        check(pthread_create(&sock_ptr->sendThread, NULL, send_data_loop, (void *) sock_ptr) == EXIT_SUCCESS,
              "Cannot create send thread.");
    } else {
        check(pthread_create(&sock_ptr->receiveDataThread, NULL, receive_data_loop, (void *) sock_ptr) == EXIT_SUCCESS,
              "Cannot create data receiving thread.");
    }

    return true;
    error:
    PrrtSocket_close(sock_ptr);
    return false;
}

106
int PrrtSocket_connect(PrrtSocket *sock_ptr, const char *host, const uint16_t port) {
107
    PrrtReceiver *recv = PrrtReceiver_create(host, port);
108
    List_push(sock_ptr->receivers, recv);
109
110
111
    return 0;
}

112
int PrrtSocket_send(PrrtSocket *sock_ptr, const uint8_t *data, const size_t data_len) {
113
    check(sock_ptr->isSender, "Cannot send on receiver socket.")
114
    check(pthread_mutex_lock(&sock_ptr->outQueueFilledMutex) == 0, "Lock failed.");
115

116
    PrrtPacket *packet = PrrtPacket_create_data_packet(5, data, (prrtPacketLength_t) data_len, 0, PrrtApplicationConstraints_get_target_delay(sock_ptr->applicationConstraints));
117

118
    List_push(sock_ptr->outQueue, packet);
119
120
    check(pthread_cond_signal(&sock_ptr->outQueueFilledCv) == 0, "Signal failed.");
    check(pthread_mutex_unlock(&sock_ptr->outQueueFilledMutex) == 0, "Unlock failed");
121

122
    return 0;
123
    error:
124
        PERROR("There was a failure while sending from socket.%s", "");
125
        return -1;
126
127
}

128
int32_t PrrtSocket_recv(PrrtSocket *sock_ptr, void *buf_ptr) {
129
    check(sock_ptr->isSender == false, "Cannot receive on sender socket.")
130
    while (1) {
131
        check(pthread_mutex_lock(&sock_ptr->inQueueFilledMutex) == 0, "Lock failed.");
132
        while (List_count(sock_ptr->inQueue) == 0) {
133
            check(pthread_mutex_lock(&sock_ptr->closingMutex) == 0, "Lock failed.");
134
            if (sock_ptr->closing) {
135
136
                check(pthread_mutex_unlock(&sock_ptr->closingMutex) == 0, "Unlock failed.");
                check(pthread_mutex_unlock(&sock_ptr->inQueueFilledMutex) == 0, "Unlock failed.");
137
138
                return -1;
            }
139
140
            check(pthread_mutex_unlock(&sock_ptr->closingMutex) == 0, "Unlock failed.");
            check(pthread_cond_wait(&sock_ptr->inQueueFilledCv, &sock_ptr->inQueueFilledMutex) == 0, "Wait failed.");
141
        }
142
        PrrtPacket *packet = List_shift(sock_ptr->inQueue);
143

144
        prrtPacketLength_t len = (prrtPacketLength_t) (packet->payloadLength - PRRT_PACKET_DATA_HEADER_SIZE);
145
        PrrtPacket_copy_payload_to_buffer(buf_ptr, packet, PRRT_PACKET_DATA_HEADER_SIZE);
146
147
        PrrtPacket_destroy(packet);

148
        check(pthread_mutex_unlock(&sock_ptr->inQueueFilledMutex) == 0, "Unlock failed.");
149
        return len;
150
    }
151
    error:
152
        PERROR("There was a failure while receiving from socket.%s", "");
153
        return -1;
154
155
}

156
int PrrtSocket_interrupt(PrrtSocket *sock_ptr) {
157
    check(pthread_mutex_lock(&sock_ptr->closingMutex) == 0, "Lock failed.");
158
    sock_ptr->closing = true;
159
    check(pthread_mutex_unlock(&sock_ptr->closingMutex) == 0, "Unlock failed.");
160

161
    void **res = NULL;
162
    if (sock_ptr->sendThread != 0) {
163
164
165
        check(pthread_mutex_lock(&sock_ptr->outQueueFilledMutex) == 0, "Lock failed.");
        check(pthread_cond_broadcast(&sock_ptr->outQueueFilledCv) == 0, "Broadcast failed.");
        check(pthread_mutex_unlock(&sock_ptr->outQueueFilledMutex) == 0, "Unlock failed.");
166

167
        check(pthread_join(sock_ptr->sendThread, res) == 0, "Join failed.");
168
169
170
        sock_ptr->sendThread = 0;
    }

171
    if (sock_ptr->receiveDataThread != 0) {
172
173
174
        check(pthread_mutex_lock(&sock_ptr->inQueueFilledMutex) == 0, "Lock failed.");
        check(pthread_cond_broadcast(&sock_ptr->inQueueFilledCv) == 0, "Broadcast failed");
        check(pthread_mutex_unlock(&sock_ptr->inQueueFilledMutex) == 0, "Unlock failed");
175

176
177
        check(pthread_cancel(sock_ptr->receiveDataThread) == 0, "Cancel failed.");
        check(pthread_join(sock_ptr->receiveDataThread, res) == 0, "Join failed.");
178
179
180
181

        sock_ptr->receiveDataThread = 0;
    }

182
    if (sock_ptr->receiveFeedbackThread != 0) {
183
184
        check(pthread_cancel(sock_ptr->receiveFeedbackThread) == 0, "Cancel failed.");
        check(pthread_join(sock_ptr->receiveFeedbackThread, res) == 0, "Join failed.");
185
186
187

        sock_ptr->receiveFeedbackThread = 0;
    }
Andreas Schmidt's avatar
Andreas Schmidt committed
188
    return EXIT_SUCCESS;
189
190
191
192

    error:
        PERROR("Interruping socket failed.%s","");
        return EXIT_FAILURE;
193
194
195
}

int PrrtSocket_close(PrrtSocket *sock_ptr) {
196
    debug("Closing socket.");
197
    check(pthread_mutex_lock(&sock_ptr->closingMutex) == 0, "Lock failed.");
198
    if (!sock_ptr->closing) {
199
200
        check(pthread_mutex_unlock(&sock_ptr->closingMutex) == 0, "Unlock failed.");
        check(PrrtSocket_interrupt(sock_ptr) == EXIT_SUCCESS, "Interrupt failed.");
201
    } else {
202
        check(pthread_mutex_unlock(&sock_ptr->closingMutex) == 0, "Unlock failed.");
203
204
    }

205
206
207
208
209
    if (sock_ptr->dataStore != NULL) {
        List *dataList = List_create();
        BPTree_get_range(sock_ptr->dataStore, dataList, 0, SEQNO_SPACE - 1);
        while (List_count(dataList) > 0) {
            PrrtPacket *packet = List_shift(dataList);
210
211
212
213
214
            PrrtPacket_destroy(packet);
        }

        List_destroy(dataList);

215
216
217
        sock_ptr->dataStore = BPTree_destroy(sock_ptr->dataStore);
    }

218
219
220
221
222
    if (sock_ptr->blockStore != NULL) {
        List *blockList = List_create();
        BPTree_get_range(sock_ptr->blockStore, blockList, 0, SEQNO_SPACE - 1);
        while (List_count(blockList) > 0) {
            PrrtBlock *block = List_shift(blockList);
Andreas Schmidt's avatar
Andreas Schmidt committed
223
            PrrtBlock_destroy(block);
224
225
226
227
        }

        List_destroy(blockList);

228
        sock_ptr->blockStore = BPTree_destroy(sock_ptr->blockStore);
229
230
    }

231
    if (sock_ptr->receivers != NULL) {
232
        while (List_count(sock_ptr->receivers) > 0) {
Andreas Schmidt's avatar
Andreas Schmidt committed
233
            PrrtReceiver *recv = List_shift(sock_ptr->receivers);
234
            PrrtReceiver_destroy(recv);
235
236
        }
        List_destroy(sock_ptr->receivers);
237
        sock_ptr->receivers = NULL;
238
239
    }

240
    if (sock_ptr->outQueue != NULL) {
241
242
        check(pthread_mutex_destroy(&sock_ptr->outQueueFilledMutex) == 0, "Mutex destroy failed.");
        check(pthread_cond_destroy(&sock_ptr->outQueueFilledCv) == 0, "Cond destroy failed.");
243
        List_destroy(sock_ptr->outQueue);
244
        sock_ptr->outQueue = NULL;
245
246
    }

247
    if (sock_ptr->inQueue != NULL) {
248
249
        check(pthread_mutex_destroy(&sock_ptr->inQueueFilledMutex) == 0, "Mutex destroy failed.");
        check(pthread_cond_destroy(&sock_ptr->inQueueFilledCv) == 0, "Cond destroy failed.");
250
        List_destroy(sock_ptr->inQueue);
251
252
253
        sock_ptr->inQueue = NULL;
    }

254
    if (sock_ptr->forwardPacketTable != NULL) {
255
        check(PrrtForwardPacketTable_destroy(sock_ptr->forwardPacketTable), "Destroy failed.");
256
        sock_ptr->forwardPacketTable = NULL;
257
    }
258

259
    check(pthread_mutex_destroy(&sock_ptr->closingMutex) == 0, "Mutex destroy failed.");
260

Andreas Schmidt's avatar
Andreas Schmidt committed
261
262
263
264
    if(sock_ptr->address != NULL) {
        free(sock_ptr->address);
    }

265
266
267
268
269
270
271
272
    if(sock_ptr->csi != NULL) {
        check(PrrtChannelStateInformation_destroy(sock_ptr->csi), "Could not destroy channel state information.")
    }

    if(sock_ptr->applicationConstraints) {
        check(PrrtApplicationConstraints_destroy(sock_ptr->applicationConstraints), "Could not destroy application constraints.")
    }

273
274
275
    if(sock_ptr->clock != NULL) {
        check(PrrtClock_destroy(sock_ptr->clock), "Destroy clock failed");
    }
276

277
278
    close(sock_ptr->dataSocketFd);
    close(sock_ptr->feedbackSocketFd);
279
    debug("Socket closed.");
280
    return 0;
281
282
283
284

    error:
        PERROR("Closing socket failed.%s", "");
        return -1;
285
286
}

287
PrrtPacket *PrrtSocket_recv_feedback(PrrtSocket *prrtSocket, const size_t length)
288
289
{
    char bufin[MAX_PAYLOAD_LENGTH];
290
291
292
    ssize_t n;
    struct sockaddr_in remote;
    socklen_t addrlen = sizeof(remote);
293
294
295

    struct pollfd fds;
    int timeout_msecs = 1000;
296
    fds.fd = prrtSocket->feedbackSocketFd;
297
298
299
300
301
302
303
    fds.events = POLLIN;

    n = poll(&fds, 1, timeout_msecs);
    check(n >= 0, "Select failed.")
    if (n == 0) {
        return NULL;
    }
304
    prrtTimestamp_t receiveTime = PrrtClock_get_current_time_us();
305

306
    n = recvfrom(prrtSocket->feedbackSocketFd, bufin, length, 0, (struct sockaddr *) &remote, &addrlen);
307
    check(n >= 0, "Receiving feedback failed.");
308

309
310
311
    PrrtPacket *prrtPacket = calloc(1, sizeof(PrrtPacket));
    check_mem(prrtPacket);
    PrrtPacket_decode(bufin, (uint16_t) n, prrtPacket);
312

Andreas Schmidt's avatar
Andreas Schmidt committed
313
314
    PrrtPacketFeedbackPayload* payload = prrtPacket->payload;
    struct in_addr a;
315
    a.s_addr = payload->receiverAddress;
Andreas Schmidt's avatar
Andreas Schmidt committed
316
317
    printf("%s\n", inet_ntoa(a));

318
    prrtTimestamp_t forwardTripTimestamp = ((PrrtPacketFeedbackPayload*) prrtPacket->payload)->forwardTripTimestamp_us;
319

320
    PrrtChannelStateInformation_update_rtt(prrtSocket->csi, (prrtTimedelta_t) (receiveTime - forwardTripTimestamp));
321
    PrrtChannelStateInformation_print(prrtSocket->csi);
322

323
    return prrtPacket;
324
325

    error:
326
    return NULL;
327
}
328
329
330
331

bool PrrtSocket_set_sock_opt(PrrtSocket *sock_ptr, const char *name, const uint32_t value)
{
    if(strcmp(name, "targetdelay") == 0) {
332
        PrrtApplicationConstraints_set_target_delay(sock_ptr->applicationConstraints, value);
333
334
335
336
337
338
    } else {
        return false;
    }

    return true;
}