1 /* dtls -- a very basic DTLS implementation
3 * Copyright (C) 2011--2013 Olaf Bergmann <bergmann@tzi.org>
4 * Copyright (C) 2013 Hauke Mehrtens <hauke@hauke-m.de>
6 * Permission is hereby granted, free of charge, to any person
7 * obtaining a copy of this software and associated documentation
8 * files (the "Software"), to deal in the Software without
9 * restriction, including without limitation the rights to use, copy,
10 * modify, merge, publish, distribute, sublicense, and/or sell copies
11 * of the Software, and to permit persons to whom the Software is
12 * furnished to do so, subject to the following conditions:
14 * The above copyright notice and this permission notice shall be
15 * included in all copies or substantial portions of the Software.
17 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
18 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
19 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
20 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
21 * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
22 * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
23 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
29 * @brief High level DTLS API and visible structures.
44 #endif /* WITH_CONTIKI */
51 #include "dtls_time.h"
54 #define DTLS_VERSION 0xfeff /* DTLS v1.1 */
56 #define DTLS_VERSION 0xfefd /* DTLS v1.2 */
59 typedef enum dtls_credentials_type_t {
60 DTLS_PSK_HINT, DTLS_PSK_IDENTITY, DTLS_PSK_KEY
61 } dtls_credentials_type_t;
63 typedef struct dtls_ecc_key_t {
64 dtls_ecdh_curve curve;
65 const unsigned char *priv_key; /** < private key as bytes > */
66 const unsigned char *pub_key_x; /** < x part of the public key for the given private key > */
67 const unsigned char *pub_key_y; /** < y part of the public key for the given private key > */
70 /** Length of the secret that is used for generating Hello Verify cookies. */
71 #define DTLS_COOKIE_SECRET_LENGTH 12
73 struct dtls_context_t;
76 * This structure contains callback functions used by tinydtls to
77 * communicate with the application. At least the write function must
78 * be provided. It is called by the DTLS state machine to send packets
79 * over the network. The read function is invoked to deliver decrypted
80 * and verfified application data. The third callback is an event
81 * handler function that is called when alert messages are encountered
82 * or events generated by the library have occured.
86 * Called from dtls_handle_message() to send DTLS packets over the
87 * network. The callback function must use the network interface
88 * denoted by session->ifindex to send the data.
90 * @param ctx The current DTLS context.
91 * @param session The session object, including the address of the
92 * remote peer where the data shall be sent.
93 * @param buf The data to send.
94 * @param len The actual length of @p buf.
95 * @return The callback function must return the number of bytes
96 * that were sent, or a value less than zero to indicate an
99 int (*write)(struct dtls_context_t *ctx,
100 session_t *session, uint8 *buf, size_t len);
103 * Called from dtls_handle_message() deliver application data that was
104 * received on the given session. The data is delivered only after
105 * decryption and verification have succeeded.
107 * @param ctx The current DTLS context.
108 * @param session The session object, including the address of the
110 * @param buf The received data packet.
111 * @param len The actual length of @p buf.
114 int (*read)(struct dtls_context_t *ctx,
115 session_t *session, uint8 *buf, size_t len);
118 * The event handler is called when a message from the alert
119 * protocol is received or the state of the DTLS session changes.
121 * @param ctx The current dtls context.
122 * @param session The session object that was affected.
123 * @param level The alert level or @c 0 when an event ocurred that
125 * @param code Values less than @c 256 indicate alerts, while
126 * @c 256 or greater indicate internal DTLS session changes.
129 int (*event)(struct dtls_context_t *ctx, session_t *session,
130 dtls_alert_level_t level, unsigned short code);
134 * Called during handshake to get information related to the
135 * psk key exchange. The type of information requested is
136 * indicated by @p type which will be one of DTLS_PSK_HINT,
137 * DTLS_PSK_IDENTITY, or DTLS_PSK_KEY. The called function
138 * must store the requested item in the buffer @p result of
139 * size @p result_length. On success, the function must return
140 * the actual number of bytes written to @p result, of a
141 * value less than zero on error. The parameter @p desc may
142 * contain additional request information (e.g. the psk_identity
143 * for which a key is requested when @p type == @c DTLS_PSK_KEY.
145 * @param ctx The current dtls context.
146 * @param session The session where the key will be used.
147 * @param type The type of the requested information.
148 * @param desc Additional request information
149 * @param desc_len The actual length of desc.
150 * @param result Must be filled with the requested information.
151 * @param result_length Maximum size of @p result.
152 * @return The number of bytes written to @p result or a value
153 * less than zero on error.
155 int (*get_psk_info)(struct dtls_context_t *ctx,
156 const session_t *session,
157 dtls_credentials_type_t type,
158 const unsigned char *desc, size_t desc_len,
159 unsigned char *result, size_t result_length);
161 #endif /* DTLS_PSK */
165 * Called during handshake to get the server's or client's ecdsa
166 * key used to authenticate this server or client in this
167 * session. If found, the key must be stored in @p result and
168 * the return value must be @c 0. If not found, @p result is
169 * undefined and the return value must be less than zero.
171 * If ECDSA should not be supported, set this pointer to NULL.
173 * Implement this if you want to provide your own certificate to
174 * the other peer. This is mandatory for a server providing ECDSA
175 * support and optional for a client. A client doing DTLS client
176 * authentication has to implementing this callback.
178 * @param ctx The current dtls context.
179 * @param session The session where the key will be used.
180 * @param result Must be set to the key object to used for the given
182 * @return @c 0 if result is set, or less than zero on error.
184 int (*get_ecdsa_key)(struct dtls_context_t *ctx,
185 const session_t *session,
186 const dtls_ecc_key_t **result);
189 * Called during handshake to check the peer's pubic key in this
190 * session. If the public key matches the session and should be
191 * considerated valid the return value must be @c 0. If not valid,
192 * the return value must be less than zero.
194 * If ECDSA should not be supported, set this pointer to NULL.
196 * Implement this if you want to verify the other peers public key.
197 * This is mandatory for a DTLS client doing based ECDSA
198 * authentication. A server implementing this will request the
199 * client to do DTLS client authentication.
201 * @param ctx The current dtls context.
202 * @param session The session where the key will be used.
203 * @param other_pub_x x component of the public key.
204 * @param other_pub_y y component of the public key.
205 * @return @c 0 if public key matches, or less than zero on error.
207 * return dtls_alert_fatal_create(DTLS_ALERT_BAD_CERTIFICATE);
208 * return dtls_alert_fatal_create(DTLS_ALERT_UNSUPPORTED_CERTIFICATE);
209 * return dtls_alert_fatal_create(DTLS_ALERT_CERTIFICATE_REVOKED);
210 * return dtls_alert_fatal_create(DTLS_ALERT_CERTIFICATE_EXPIRED);
211 * return dtls_alert_fatal_create(DTLS_ALERT_CERTIFICATE_UNKNOWN);
212 * return dtls_alert_fatal_create(DTLS_ALERT_UNKNOWN_CA);
214 int (*verify_ecdsa_key)(struct dtls_context_t *ctx,
215 const session_t *session,
216 const unsigned char *other_pub_x,
217 const unsigned char *other_pub_y,
219 #endif /* DTLS_ECC */
222 /** Holds global information of the DTLS engine. */
223 typedef struct dtls_context_t {
224 unsigned char cookie_secret[DTLS_COOKIE_SECRET_LENGTH];
225 clock_time_t cookie_secret_age; /**< the time the secret has been generated */
228 dtls_peer_t *peers; /**< peer hash map */
229 #else /* WITH_CONTIKI */
232 struct etimer retransmit_timer; /**< fires when the next packet must be sent */
233 #endif /* WITH_CONTIKI */
235 LIST_STRUCT(sendqueue); /**< the packets to send */
237 void *app; /**< application-specific data */
239 dtls_handler_t *h; /**< callback handlers */
241 dtls_cipher_enable_t is_anon_ecdh_eabled; /**< enable/disable the TLS_ECDH_anon_WITH_AES_128_CBC_SHA */
243 dtls_cipher_t selected_cipher; /**< selected ciper suite for handshake */
245 unsigned char readbuf[DTLS_MAX_BUF];
249 * This function initializes the tinyDTLS memory management and must
255 * Creates a new context object. The storage allocated for the new
256 * object must be released with dtls_free_context(). */
257 dtls_context_t *dtls_new_context(void *app_data);
259 /** Releases any storage that has been allocated for \p ctx. */
260 void dtls_free_context(dtls_context_t *ctx);
262 #define dtls_set_app_data(CTX,DATA) ((CTX)->app = (DATA))
263 #define dtls_get_app_data(CTX) ((CTX)->app)
265 /** Sets the callback handler object for @p ctx to @p h. */
266 static inline void dtls_set_handler(dtls_context_t *ctx, dtls_handler_t *h) {
271 * @brief Enabling the TLS_ECDH_anon_WITH_AES_128_CBC_SHA
273 * @param ctx The DTLS context to use.
274 * @param is_enable DTLS_CIPHER_ENABLE(1) or DTLS_CIPHER_DISABLE(0)
276 void dtls_enables_anon_ecdh(dtls_context_t* ctx, dtls_cipher_enable_t is_enable);
279 * @brief Select the cipher suite for handshake
281 * @param ctx The DTLS context to use.
282 * @param cipher TLS_ECDH_anon_WITH_AES_128_CBC_SHA (0xC018)
283 * TLS_PSK_WITH_AES_128_CCM_8 (0xX0A8)
284 * TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8 (0xC0AE)
286 void dtls_select_cipher(dtls_context_t* ctx, const dtls_cipher_t cipher);
289 * Establishes a DTLS channel with the specified remote peer @p dst.
290 * This function returns @c 0 if that channel already exists, a value
291 * greater than zero when a new ClientHello message was sent, and
292 * a value less than zero on error.
294 * @param ctx The DTLS context to use.
295 * @param dst The remote party to connect to.
296 * @return A value less than zero on error, greater or equal otherwise.
298 int dtls_connect(dtls_context_t *ctx, const session_t *dst);
301 * Establishes a DTLS channel with the specified remote peer.
302 * This function returns @c 0 if that channel already exists, a value
303 * greater than zero when a new ClientHello message was sent, and
304 * a value less than zero on error.
306 * @param ctx The DTLS context to use.
307 * @param peer The peer object that describes the session.
308 * @return A value less than zero on error, greater or equal otherwise.
310 int dtls_connect_peer(dtls_context_t *ctx, dtls_peer_t *peer);
313 * Closes the DTLS connection associated with @p remote. This function
314 * returns zero on success, and a value less than zero on error.
316 int dtls_close(dtls_context_t *ctx, const session_t *remote);
318 int dtls_renegotiate(dtls_context_t *ctx, const session_t *dst);
321 * Writes the application data given in @p buf to the peer specified
324 * @param ctx The DTLS context to use.
325 * @param session The remote transport address and local interface.
326 * @param buf The data to write.
327 * @param len The actual length of @p data.
329 * @return The number of bytes written or @c -1 on error.
331 int dtls_write(struct dtls_context_t *ctx, session_t *session,
332 uint8 *buf, size_t len);
335 * Checks sendqueue of given DTLS context object for any outstanding
336 * packets to be transmitted.
338 * @param context The DTLS context object to use.
339 * @param next If not NULL, @p next is filled with the timestamp
340 * of the next scheduled retransmission, or @c 0 when no packets are
343 void dtls_check_retransmit(dtls_context_t *context, clock_time_t *next);
345 #define DTLS_COOKIE_LENGTH 16
347 #define DTLS_CT_CHANGE_CIPHER_SPEC 20
348 #define DTLS_CT_ALERT 21
349 #define DTLS_CT_HANDSHAKE 22
350 #define DTLS_CT_APPLICATION_DATA 23
352 /** Generic header structure of the DTLS record layer. */
353 typedef struct __attribute__((__packed__)) {
354 uint8 content_type; /**< content type of the included message */
355 uint16 version; /**< Protocol version */
356 uint16 epoch; /**< counter for cipher state changes */
357 uint48 sequence_number; /**< sequence number */
358 uint16 length; /**< length of the following fragment */
360 } dtls_record_header_t;
362 /* Handshake types */
364 #define DTLS_HT_HELLO_REQUEST 0
365 #define DTLS_HT_CLIENT_HELLO 1
366 #define DTLS_HT_SERVER_HELLO 2
367 #define DTLS_HT_HELLO_VERIFY_REQUEST 3
368 #define DTLS_HT_CERTIFICATE 11
369 #define DTLS_HT_SERVER_KEY_EXCHANGE 12
370 #define DTLS_HT_CERTIFICATE_REQUEST 13
371 #define DTLS_HT_SERVER_HELLO_DONE 14
372 #define DTLS_HT_CERTIFICATE_VERIFY 15
373 #define DTLS_HT_CLIENT_KEY_EXCHANGE 16
374 #define DTLS_HT_FINISHED 20
376 /** Header structure for the DTLS handshake protocol. */
377 typedef struct __attribute__((__packed__)) {
378 uint8 msg_type; /**< Type of handshake message (one of DTLS_HT_) */
379 uint24 length; /**< length of this message */
380 uint16 message_seq; /**< Message sequence number */
381 uint24 fragment_offset; /**< Fragment offset. */
382 uint24 fragment_length; /**< Fragment length. */
384 } dtls_handshake_header_t;
386 /** Structure of the Client Hello message. */
387 typedef struct __attribute__((__packed__)) {
388 uint16 version; /**< Client version */
389 uint32 gmt_random; /**< GMT time of the random byte creation */
390 unsigned char random[28]; /**< Client random bytes */
391 /* session id (up to 32 bytes) */
392 /* cookie (up to 32 bytes) */
393 /* cipher suite (2 to 2^16 -1 bytes) */
394 /* compression method */
395 } dtls_client_hello_t;
397 /** Structure of the Hello Verify Request. */
398 typedef struct __attribute__((__packed__)) {
399 uint16 version; /**< Server version */
400 uint8 cookie_length; /**< Length of the included cookie */
401 uint8 cookie[]; /**< up to 32 bytes making up the cookie */
402 } dtls_hello_verify_t;
406 * Checks a received DTLS record for consistency and eventually decrypt,
407 * verify, decompress and reassemble the contained fragment for
408 * delivery to high-lever clients.
410 * \param state The DTLS record state for the current session.
413 int dtls_record_read(dtls_state_t *state, uint8 *msg, int msglen);
417 * Handles incoming data as DTLS message from given peer.
419 * @param ctx The dtls context to use.
420 * @param session The current session
421 * @param msg The received data
422 * @param msglen The actual length of @p msg.
423 * @return A value less than zero on error, zero on success.
425 int dtls_handle_message(dtls_context_t *ctx, session_t *session,
426 uint8 *msg, int msglen);
429 * Check if @p session is associated with a peer object in @p context.
430 * This function returns a pointer to the peer if found, NULL otherwise.
432 * @param context The DTLS context to search.
433 * @param session The remote address and local interface
434 * @return A pointer to the peer associated with @p session or NULL if
437 dtls_peer_t *dtls_get_peer(const dtls_context_t *context,
438 const session_t *session);
441 * Invokes the DTLS PRF using the current key block for @p session as
442 * key and @p label + @p random1 + @p random2 as its input. This function
443 * writes upto @p buflen bytes into the given output buffer @p buf.
445 * @param ctx The dtls context to use.
446 * @param session The session whose key shall be used.
447 * @param label A PRF label.
448 * @param labellen Actual length of @p label.
449 * @param random1 Random seed.
450 * @param random1len Actual length of @p random1 (may be zero).
451 * @param random2 Random seed.
452 * @param random2len Actual length of @p random2 (may be zero).
453 * @param buf Output buffer for generated random data.
454 * @param buflen Maximum size of @p buf.
456 * @return The actual number of bytes written to @p buf or @c 0 on error.
458 size_t dtls_prf_with_current_keyblock(dtls_context_t *ctx, session_t *session,
459 const uint8_t* label, const uint32_t labellen,
460 const uint8_t* random1, const uint32_t random1len,
461 const uint8_t* random2, const uint32_t random2len,
462 uint8_t* buf, const uint32_t buflen);
465 #endif /* _DTLS_DTLS_H_ */
470 * @author Olaf Bergmann, TZI Uni Bremen
472 * This library provides a very simple datagram server with DTLS
473 * support. It is designed to support session multiplexing in
474 * single-threaded applications and thus targets specifically on
477 * @section license License
479 * This software is under the <a
480 * href="http://www.opensource.org/licenses/mit-license.php">MIT License</a>.
482 * @subsection uthash UTHash
484 * This library uses <a href="http://uthash.sourceforge.net/">uthash</a> to manage
485 * its peers (not used for Contiki). @b uthash uses the <b>BSD revised license</b>, see
486 * <a href="http://uthash.sourceforge.net/license.html">http://uthash.sourceforge.net/license.html</a>.
488 * @subsection sha256 Aaron D. Gifford's SHA256 Implementation
490 * tinyDTLS provides HMAC-SHA256 with BSD-licensed code from Aaron D. Gifford,
491 * see <a href="http://www.aarongifford.com/">www.aarongifford.com</a>.
493 * @subsection aes Rijndael Implementation From OpenBSD
495 * The AES implementation is taken from rijndael.{c,h} contained in the crypto
496 * sub-system of the OpenBSD operating system. It is copyright by Vincent Rijmen, *
497 * Antoon Bosselaers and Paulo Barreto. See <a
498 * href="http://www.openbsd.org/cgi-bin/cvsweb/src/sys/crypto/rijndael.c">rijndael.c</a>
501 * @section download Getting the Files
503 * You can get the sources either from the <a
504 * href="http://sourceforge.net/projects/tinydtls/files">downloads</a> section or
505 * through git from the <a
506 * href="http://sourceforge.net/projects/tinydtls/develop">project develop page</a>.
508 * @section config Configuration
510 * Use @c configure to set up everything for a successful build. For Contiki, use the
511 * option @c --with-contiki.
513 * @section build Building
515 * After configuration, just type
519 * optionally followed by
523 * The Contiki version is integrated with the Contiki build system, hence you do not
524 * need to invoke @c make explicitely. Just add @c tinydtls to the variable @c APPS
525 * in your @c Makefile.
527 * @addtogroup dtls_usage DTLS Usage
529 * @section dtls_server_example DTLS Server Example
531 * This section shows how to use the DTLS library functions to setup a
532 * simple secure UDP echo server. The application is responsible for the
533 * entire network communication and thus will look like a usual UDP
534 * server with socket creation and binding and a typical select-loop as
535 * shown below. The minimum configuration required for DTLS is the
536 * creation of the dtls_context_t using dtls_new_context(), and a callback
537 * for sending data. Received packets are read by the application and
538 * passed to dtls_handle_message() as shown in @ref dtls_read_cb.
539 * For any useful communication to happen, read and write call backs
540 * and a key management function should be registered as well.
543 dtls_context_t *the_context = NULL;
546 static dtls_handler_t cb = {
547 .write = send_to_peer,
548 .read = read_from_peer,
550 .get_psk_key = get_psk_key
554 if (fd < 0 || bind(fd, ...) < 0)
557 the_context = dtls_new_context(&fd);
558 dtls_set_handler(the_context, &cb);
561 ...initialize fd_set rfds and timeout ...
562 result = select(fd+1, &rfds, NULL, 0, NULL);
564 if (FD_ISSET(fd, &rfds))
565 dtls_handle_read(the_context);
568 dtls_free_context(the_context);
571 * @subsection dtls_read_cb The Read Callback
573 * The DTLS library expects received raw data to be passed to
574 * dtls_handle_message(). The application is responsible for
575 * filling a session_t structure with the address data of the
576 * remote peer as illustrated by the following example:
579 int dtls_handle_read(struct dtls_context_t *ctx) {
582 static uint8 buf[DTLS_MAX_BUF];
585 fd = dtls_get_app_data(ctx);
589 session.size = sizeof(session.addr);
590 len = recvfrom(*fd, buf, sizeof(buf), 0, &session.addr.sa, &session.size);
592 return len < 0 ? len : dtls_handle_message(ctx, &session, buf, len);
596 * Once a new DTLS session was established and DTLS ApplicationData has been
597 * received, the DTLS server invokes the read callback with the MAC-verified
598 * cleartext data as its argument. A read callback for a simple echo server
599 * could look like this:
601 int read_from_peer(struct dtls_context_t *ctx, session_t *session, uint8 *data, size_t len) {
602 return dtls_write(ctx, session, data, len);
606 * @subsection dtls_send_cb The Send Callback
608 * The callback function send_to_peer() is called whenever data must be
609 * sent over the network. Here, the sendto() system call is used to
610 * transmit data within the given session. The socket descriptor required
611 * by sendto() has been registered as application data when the DTLS context
612 * was created with dtls_new_context().
613 * Note that it is on the application to buffer the data when it cannot be
614 * sent at the time this callback is invoked. The following example thus
615 * is incomplete as it would have to deal with EAGAIN somehow.
617 int send_to_peer(struct dtls_context_t *ctx, session_t *session, uint8 *data, size_t len) {
618 int fd = *(int *)dtls_get_app_data(ctx);
619 return sendto(fd, data, len, MSG_DONTWAIT, &session->addr.sa, session->size);
623 * @subsection dtls_get_psk_info The Key Storage
625 * When a new DTLS session is created, the library must ask the application
626 * for keying material. To do so, it invokes the registered call-back function
627 * get_psk_info() with the current context and session information as parameter.
628 * When the call-back function is invoked with the parameter @p type set to
629 * @c DTLS_PSK_IDENTITY, the result parameter @p result must be filled with
630 * the psk_identity_hint in case of a server, or the actual psk_identity in
631 * case of a client. When @p type is @c DTLS_PSK_KEY, the result parameter
632 * must be filled with a key for the given identity @p id. The function must
633 * return the number of bytes written to @p result which must not exceed
635 * In case of an error, the function must return a negative value that
636 * corresponds to a valid error code defined in alert.h.
639 int get_psk_info(struct dtls_context_t *ctx UNUSED_PARAM,
640 const session_t *session UNUSED_PARAM,
641 dtls_credentials_type_t type,
642 const unsigned char *id, size_t id_len,
643 unsigned char *result, size_t result_length) {
646 case DTLS_PSK_IDENTITY:
647 if (result_length < psk_id_length) {
648 dtls_warn("cannot set psk_identity -- buffer too small\n");
649 return dtls_alert_fatal_create(DTLS_ALERT_INTERNAL_ERROR);
652 memcpy(result, psk_id, psk_id_length);
653 return psk_id_length;
655 if (id_len != psk_id_length || memcmp(psk_id, id, id_len) != 0) {
656 dtls_warn("PSK for unknown id requested, exiting\n");
657 return dtls_alert_fatal_create(DTLS_ALERT_ILLEGAL_PARAMETER);
658 } else if (result_length < psk_key_length) {
659 dtls_warn("cannot set psk -- buffer too small\n");
660 return dtls_alert_fatal_create(DTLS_ALERT_INTERNAL_ERROR);
663 memcpy(result, psk_key, psk_key_length);
664 return psk_key_length;
666 dtls_warn("unsupported request type: %d\n", type);
669 return dtls_alert_fatal_create(DTLS_ALERT_INTERNAL_ERROR);
673 * @subsection dtls_events The Event Notifier
675 * Applications that want to be notified whenever the status of a DTLS session
676 * has changed can register an event handling function with the field @c event
677 * in the dtls_handler_t structure (see \ref dtls_server_example). The call-back
678 * function is called for alert messages and internal state changes. For alert
679 * messages, the argument @p level will be set to a value greater than zero, and
680 * @p code will indicate the notification code. For internal events, @p level
681 * is @c 0, and @p code a value greater than @c 255.
683 * Internal events are DTLS_EVENT_CONNECTED, @c DTLS_EVENT_CONNECT, and
684 * @c DTLS_EVENT_RENEGOTIATE.
687 int handle_event(struct dtls_context_t *ctx, session_t *session,
688 dtls_alert_level_t level, unsigned short code) {
689 ... do something with event ...
694 * @section dtls_client_example DTLS Client Example
696 * A DTLS client is constructed like a server but needs to actively setup
697 * a new session by calling dtls_connect() at some point. As this function
698 * usually returns before the new DTLS channel is established, the application
699 * must register an event handler and wait for @c DTLS_EVENT_CONNECT before
700 * it can send data over the DTLS channel.
705 * @addtogroup contiki Contiki
707 * To use tinyDTLS as Contiki application, place the source code in the directory
708 * @c apps/tinydtls in the Contiki source tree and invoke configure with the option
709 * @c --with-contiki. This will define WITH_CONTIKI in tinydtls.h and include
710 * @c Makefile.contiki in the main Makefile. To cross-compile for another platform
711 * you will need to set your host and build system accordingly. For example,
712 * when configuring for ARM, you would invoke
714 ./configure --with-contiki --build=x86_64-linux-gnu --host=arm-none-eabi
716 * on an x86_64 linux host.
718 * Then, create a Contiki project with @c APPS += tinydtls in its Makefile. A sample
719 * server could look like this (with read_from_peer() and get_psk_key() as shown above).
724 #include "tinydtls.h"
727 #define UIP_IP_BUF ((struct uip_ip_hdr *)&uip_buf[UIP_LLH_LEN])
728 #define UIP_UDP_BUF ((struct uip_udp_hdr *)&uip_buf[UIP_LLIPH_LEN])
730 int send_to_peer(struct dtls_context_t *, session_t *, uint8 *, size_t);
732 static struct uip_udp_conn *server_conn;
733 static dtls_context_t *dtls_context;
735 static dtls_handler_t cb = {
736 .write = send_to_peer,
737 .read = read_from_peer,
739 .get_psk_key = get_psk_key
742 PROCESS(server_process, "DTLS server process");
743 AUTOSTART_PROCESSES(&server_process);
745 PROCESS_THREAD(server_process, ev, data)
751 server_conn = udp_new(NULL, 0, NULL);
752 udp_bind(server_conn, UIP_HTONS(5684));
754 dtls_context = dtls_new_context(server_conn);
756 dtls_emerg("cannot create context\n");
760 dtls_set_handler(dtls_context, &cb);
763 PROCESS_WAIT_EVENT();
764 if(ev == tcpip_event && uip_newdata()) {
767 uip_ipaddr_copy(&session.addr, &UIP_IP_BUF->srcipaddr);
768 session.port = UIP_UDP_BUF->srcport;
769 session.size = sizeof(session.addr) + sizeof(session.port);
771 dtls_handle_message(ctx, &session, uip_appdata, uip_datalen());
778 int send_to_peer(struct dtls_context_t *ctx, session_t *session, uint8 *data, size_t len) {
779 struct uip_udp_conn *conn = (struct uip_udp_conn *)dtls_get_app_data(ctx);
781 uip_ipaddr_copy(&conn->ripaddr, &session->addr);
782 conn->rport = session->port;
784 uip_udp_packet_send(conn, data, len);
786 memset(&conn->ripaddr, 0, sizeof(server_conn->ripaddr));
787 memset(&conn->rport, 0, sizeof(conn->rport));