1 /* dtls -- a very basic DTLS implementation
2  *
3  * Copyright (C) 2011--2013 Olaf Bergmann <bergmann@tzi.org>
4  *
5  * Permission is hereby granted, free of charge, to any person
6  * obtaining a copy of this software and associated documentation
7  * files (the "Software"), to deal in the Software without
8  * restriction, including without limitation the rights to use, copy,
9  * modify, merge, publish, distribute, sublicense, and/or sell copies
10  * of the Software, and to permit persons to whom the Software is
11  * furnished to do so, subject to the following conditions:
12  *
13  * The above copyright notice and this permission notice shall be
14  * included in all copies or substantial portions of the Software.
15  *
16  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
17  * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
18  * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
19  * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
20  * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
21  * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
22  * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
23  * SOFTWARE.
24  */
25 
26 #include "global.h"
27 #include "peer.h"
28 #include "debug.h"
29 
30 #ifndef WITH_CONTIKI
peer_init()31 void peer_init()
32 {
33 }
34 
35 static inline dtls_peer_t *
dtls_malloc_peer()36 dtls_malloc_peer() {
37   return (dtls_peer_t *)malloc(sizeof(dtls_peer_t));
38 }
39 
40 void
dtls_free_peer(dtls_peer_t * peer)41 dtls_free_peer(dtls_peer_t *peer) {
42   dtls_handshake_free(peer->handshake_params);
43   dtls_security_free(peer->security_params[0]);
44   dtls_security_free(peer->security_params[1]);
45   free(peer);
46 }
47 #else /* WITH_CONTIKI */
48 
49 #include "memb.h"
50 MEMB(peer_storage, dtls_peer_t, DTLS_PEER_MAX);
51 
52 void
peer_init()53 peer_init() {
54   memb_init(&peer_storage);
55 }
56 
57 static inline dtls_peer_t *
dtls_malloc_peer()58 dtls_malloc_peer() {
59   return memb_alloc(&peer_storage);
60 }
61 
62 void
dtls_free_peer(dtls_peer_t * peer)63 dtls_free_peer(dtls_peer_t *peer) {
64   dtls_handshake_free(peer->handshake_params);
65   dtls_security_free(peer->security_params[0]);
66   dtls_security_free(peer->security_params[1]);
67   memb_free(&peer_storage, peer);
68 }
69 #endif /* WITH_CONTIKI */
70 
71 dtls_peer_t *
dtls_new_peer(const session_t * session)72 dtls_new_peer(const session_t *session) {
73   dtls_peer_t *peer;
74 
75   peer = dtls_malloc_peer();
76   if (peer) {
77     memset(peer, 0, sizeof(dtls_peer_t));
78     memcpy(&peer->session, session, sizeof(session_t));
79     peer->security_params[0] = dtls_security_new();
80 
81     if (!peer->security_params[0]) {
82       dtls_free_peer(peer);
83       return NULL;
84     }
85 
86     dtls_dsrv_log_addr(DTLS_LOG_DEBUG, "dtls_new_peer", session);
87   }
88 
89   return peer;
90 }
91