1#include <dtls.h>
2#include <dtls_debug.h>
3#include <string.h>
4#include <unistd.h>
5#include <string.h>
6#include <errno.h>
7
8#include <sys/types.h>
9#include <sys/socket.h>
10
11#include "dat.h"
12#include "fns.h"
13
14static int
15dwrite(struct dtls_context_t *ctx, session_t *sess, uint8 *data, size_t len)
16{
17 struct dctx *dctx;
18
19 dctx = dtls_get_app_data(ctx);
20 return sendto(dctx->dfd, data, len, MSG_DONTWAIT,
21 &sess->addr.sa, sess->size);
22}
23
24static int
25dread(struct dtls_context_t *ctx, session_t *sess, uint8 *data, size_t len)
26{
27 (void)sess;
28 struct dctx *dctx;
29
30 dctx = dtls_get_app_data(ctx);
31 if (smode) {
32 /* in server mode connect(3) is called on the UDP socket up
33 * on creation thus we don't need to specify an address. */
34 if (send(dctx->ufd, data, len, MSG_DONTWAIT) == -1)
35 dtls_alert("send failed in dread: %s\n", strerror(errno));
36 } else {
37 /* in client mode csess should contain the address of
38 * the client from which we last received a datagram. */
39 if (csess.size <= 0) {
40 dtls_alert("Didn't receive a datagram from a client yet, "
41 "discarding received DTLS message\n");
42 return 0;
43 }
44
45 if (sendto(dctx->ufd, data, len, MSG_DONTWAIT,
46 &csess.addr.sa, csess.size) == -1)
47 dtls_alert("sendto failed in dread: %s\n", strerror(errno));
48 }
49
50 /* I have no idea why this function prototype has a return value
51 * `tests/dtls-client.c` returns 0 here so lets do that as well. */
52 return 0;
53}
54
55static int
56dpsk(struct dtls_context_t *ctx, const session_t *sess, dtls_credentials_type_t type,
57 const unsigned char *id, size_t ilen, unsigned char *res, size_t rlen)
58{
59 (void)sess;
60 void *ptr;
61 size_t len;
62 struct dctx *dctx;
63
64 dctx = dtls_get_app_data(ctx);
65 switch (type) {
66 case DTLS_PSK_HINT:
67 case DTLS_PSK_IDENTITY:
68 ptr = dctx->id;
69 len = strlen((char*)dctx->id);
70 break;
71 case DTLS_PSK_KEY:
72 ptr = dctx->key;
73 len = strlen((char*)dctx->key);
74
75 if (xmemcmp((void*)id, ilen, dctx->id, len)) {
76 dtls_warn("Received request for unknown ID\n");
77 return dtls_alert_fatal_create(DTLS_ALERT_ILLEGAL_PARAMETER);
78 }
79 break;
80 default:
81 dtls_warn("Unsupported request type: %d\n", type);
82 break;
83 }
84
85 if (len > rlen) {
86 dtls_warn("Buffer to small for request type: %d\n", type);
87 return dtls_alert_fatal_create(DTLS_ALERT_INTERNAL_ERROR);
88 }
89
90 memcpy(res, ptr, len);
91 return len;
92}
93
94dtls_handler_t dtlscb = {
95 .write = dwrite,
96 .read = dread,
97 .event = NULL,
98 .get_psk_info = dpsk
99};