Imported Upstream version 0.9.2
[platform/upstream/iotivity.git] / extlibs / tinydtls / dtls.h
1 /* dtls -- a very basic DTLS implementation
2  *
3  * Copyright (C) 2011--2013 Olaf Bergmann <bergmann@tzi.org>
4  * Copyright (C) 2013 Hauke Mehrtens <hauke@hauke-m.de>
5  *
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:
13  *
14  * The above copyright notice and this permission notice shall be
15  * included in all copies or substantial portions of the Software.
16  *
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
24  * SOFTWARE.
25  */
26
27 /**
28  * @file dtls.h
29  * @brief High level DTLS API and visible structures. 
30  */
31
32 #ifndef _DTLS_DTLS_H_
33 #define _DTLS_DTLS_H_
34
35 #include <stdint.h>
36
37 #include "t_list.h"
38 #include "state.h"
39 #include "peer.h"
40
41 #ifndef WITH_CONTIKI
42 #include "uthash.h"
43 #include "t_list.h"
44 #endif /* WITH_CONTIKI */
45
46 #include "alert.h"
47 #include "crypto.h"
48 #include "hmac.h"
49
50 #include "global.h"
51 #include "dtls_time.h"
52
53 #ifndef DTLSv12
54 #define DTLS_VERSION 0xfeff     /* DTLS v1.1 */
55 #else
56 #define DTLS_VERSION 0xfefd     /* DTLS v1.2 */
57 #endif
58
59 typedef enum dtls_credentials_type_t {
60   DTLS_PSK_HINT, DTLS_PSK_IDENTITY, DTLS_PSK_KEY
61 } dtls_credentials_type_t;
62
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 > */
68 } dtls_ecc_key_t;
69
70 /** Length of the secret that is used for generating Hello Verify cookies. */
71 #define DTLS_COOKIE_SECRET_LENGTH 12
72
73 struct dtls_context_t;
74
75 /**
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.
83  */ 
84 typedef struct {
85   /** 
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.
89    *
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 
97    *         error.
98    */
99   int (*write)(struct dtls_context_t *ctx, 
100                session_t *session, uint8 *buf, size_t len);
101
102   /** 
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. 
106    *
107    * @param ctx  The current DTLS context.
108    * @param session The session object, including the address of the
109    *              data's origin. 
110    * @param buf  The received data packet.
111    * @param len  The actual length of @p buf.
112    * @return ignored
113    */
114   int (*read)(struct dtls_context_t *ctx, 
115                session_t *session, uint8 *buf, size_t len);
116
117   /**
118    * The event handler is called when a message from the alert
119    * protocol is received or the state of the DTLS session changes.
120    *
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 
124    *                is not an alert. 
125    * @param code    Values less than @c 256 indicate alerts, while
126    *                @c 256 or greater indicate internal DTLS session changes.
127    * @return ignored
128    */
129   int (*event)(struct dtls_context_t *ctx, session_t *session, 
130                 dtls_alert_level_t level, unsigned short code);
131
132 #ifdef DTLS_PSK
133   /**
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.
144    *
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.
154    */
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);
160
161 #endif /* DTLS_PSK */
162
163 #ifdef DTLS_ECC
164   /**
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.
170    *
171    * If ECDSA should not be supported, set this pointer to NULL.
172    *
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.
177    *
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
181    *                session.
182    * @return @c 0 if result is set, or less than zero on error.
183    */
184   int (*get_ecdsa_key)(struct dtls_context_t *ctx, 
185                        const session_t *session,
186                        const dtls_ecc_key_t **result);
187
188   /**
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.
193    *
194    * If ECDSA should not be supported, set this pointer to NULL.
195    *
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.
200    *
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.
206    * error codes:
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);
213    */
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,
218                           size_t key_size);
219 #endif /* DTLS_ECC */
220 } dtls_handler_t;
221
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 */
226
227 #ifndef WITH_CONTIKI
228   dtls_peer_t *peers;           /**< peer hash map */
229 #else /* WITH_CONTIKI */
230   LIST_STRUCT(peers);
231
232   struct etimer retransmit_timer; /**< fires when the next packet must be sent */
233 #endif /* WITH_CONTIKI */
234
235   LIST_STRUCT(sendqueue);       /**< the packets to send */
236
237   void *app;                    /**< application-specific data */
238
239   dtls_handler_t *h;            /**< callback handlers */
240
241   dtls_cipher_enable_t is_anon_ecdh_eabled;    /**< enable/disable the TLS_ECDH_anon_WITH_AES_128_CBC_SHA */
242
243   dtls_cipher_t selected_cipher; /**< selected ciper suite for handshake */
244
245   unsigned char readbuf[DTLS_MAX_BUF];
246 } dtls_context_t;
247
248 /** 
249  * This function initializes the tinyDTLS memory management and must
250  * be called first.
251  */
252 void dtls_init();
253
254 /** 
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);
258
259 /** Releases any storage that has been allocated for \p ctx. */
260 void dtls_free_context(dtls_context_t *ctx);
261
262 #define dtls_set_app_data(CTX,DATA) ((CTX)->app = (DATA))
263 #define dtls_get_app_data(CTX) ((CTX)->app)
264
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) {
267   ctx->h = h;
268 }
269
270  /**
271   * @brief Enabling the TLS_ECDH_anon_WITH_AES_128_CBC_SHA
272   *
273   * @param ctx              The DTLS context to use.
274   * @param is_enable    DTLS_CIPHER_ENABLE(1) or DTLS_CIPHER_DISABLE(0)
275   */
276 void dtls_enables_anon_ecdh(dtls_context_t* ctx, dtls_cipher_enable_t is_enable);
277
278 /**
279  * @brief Select the cipher suite for handshake
280  *
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)
285  */
286 void dtls_select_cipher(dtls_context_t* ctx, const dtls_cipher_t cipher);
287
288 /**
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.
293  *
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.
297  */
298 int dtls_connect(dtls_context_t *ctx, const session_t *dst);
299
300 /**
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.
305  *
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.
309  */
310 int dtls_connect_peer(dtls_context_t *ctx, dtls_peer_t *peer);
311
312 /**
313  * Closes the DTLS connection associated with @p remote. This function
314  * returns zero on success, and a value less than zero on error.
315  */
316 int dtls_close(dtls_context_t *ctx, const session_t *remote);
317
318 int dtls_renegotiate(dtls_context_t *ctx, const session_t *dst);
319
320 /** 
321  * Writes the application data given in @p buf to the peer specified
322  * by @p session. 
323  * 
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.
328  * 
329  * @return The number of bytes written or @c -1 on error.
330  */
331 int dtls_write(struct dtls_context_t *ctx, session_t *session, 
332                uint8 *buf, size_t len);
333
334 /**
335  * Checks sendqueue of given DTLS context object for any outstanding
336  * packets to be transmitted. 
337  *
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
341  *  waiting.
342  */
343 void dtls_check_retransmit(dtls_context_t *context, clock_time_t *next);
344
345 #define DTLS_COOKIE_LENGTH 16
346
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
351
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 */
359   /* fragment */
360 } dtls_record_header_t;
361
362 /* Handshake types */
363
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
375
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. */
383   /* body */
384 } dtls_handshake_header_t;
385
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;
396
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;  
403
404 #if 0
405 /** 
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. 
409  * 
410  * \param state The DTLS record state for the current session. 
411  * \param 
412  */
413 int dtls_record_read(dtls_state_t *state, uint8 *msg, int msglen);
414 #endif
415
416 /** 
417  * Handles incoming data as DTLS message from given peer.
418  *
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.
424  */
425 int dtls_handle_message(dtls_context_t *ctx, session_t *session,
426                         uint8 *msg, int msglen);
427
428 /**
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.
431  *
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
435  *  none exists.
436  */
437 dtls_peer_t *dtls_get_peer(const dtls_context_t *context,
438                            const session_t *session);
439
440 /**
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.
444 *
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.
455 *
456 * @return The actual number of bytes written to @p buf or @c 0 on error.
457 */
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);
463
464
465 #endif /* _DTLS_DTLS_H_ */
466
467 /**
468  * @mainpage 
469  *
470  * @author Olaf Bergmann, TZI Uni Bremen
471  *
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
475  * embedded systems.
476  *
477  * @section license License
478  *
479  * This software is under the <a 
480  * href="http://www.opensource.org/licenses/mit-license.php">MIT License</a>.
481  * 
482  * @subsection uthash UTHash
483  *
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>.
487  *
488  * @subsection sha256 Aaron D. Gifford's SHA256 Implementation
489  *
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>.
492  *
493  * @subsection aes Rijndael Implementation From OpenBSD
494  *
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> 
499  * for License info.
500  *
501  * @section download Getting the Files
502  *
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>.
507  *
508  * @section config Configuration
509  *
510  * Use @c configure to set up everything for a successful build. For Contiki, use the
511  * option @c --with-contiki.
512  *
513  * @section build Building
514  *
515  * After configuration, just type 
516  * @code
517 make
518  * @endcode
519  * optionally followed by
520  * @code
521 make install
522  * @endcode
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.
526  *
527  * @addtogroup dtls_usage DTLS Usage
528  *
529  * @section dtls_server_example DTLS Server Example
530  *
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. 
541  * 
542  * @code 
543  dtls_context_t *the_context = NULL;
544  int fd, result;
545
546  static dtls_handler_t cb = {
547    .write = send_to_peer,
548    .read  = read_from_peer,
549    .event = NULL,
550    .get_psk_key = get_psk_key
551  };
552
553  fd = socket(...);
554  if (fd < 0 || bind(fd, ...) < 0)
555    exit(-1);
556
557  the_context = dtls_new_context(&fd);
558  dtls_set_handler(the_context, &cb);
559
560  while (1) {
561    ...initialize fd_set rfds and timeout ...
562    result = select(fd+1, &rfds, NULL, 0, NULL);
563     
564    if (FD_ISSET(fd, &rfds))
565      dtls_handle_read(the_context);
566  }
567
568  dtls_free_context(the_context);
569  * @endcode
570  * 
571  * @subsection dtls_read_cb The Read Callback
572  *
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:
577  * 
578  * @code
579 int dtls_handle_read(struct dtls_context_t *ctx) {
580   int *fd;
581   session_t session;
582   static uint8 buf[DTLS_MAX_BUF];
583   int len;
584
585   fd = dtls_get_app_data(ctx);
586
587   assert(fd);
588
589   session.size = sizeof(session.addr);
590   len = recvfrom(*fd, buf, sizeof(buf), 0, &session.addr.sa, &session.size);
591   
592   return len < 0 ? len : dtls_handle_message(ctx, &session, buf, len);
593 }    
594  * @endcode 
595  * 
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:
600  * @code
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);
603 }
604  * @endcode 
605  * 
606  * @subsection dtls_send_cb The Send Callback
607  * 
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.
616  * @code
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);
620 }
621  * @endcode
622  * 
623  * @subsection dtls_get_psk_info The Key Storage
624  *
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
634  * @p result_length.
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.
637  * 
638  * @code
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) {
644
645   switch (type) {
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);
650     }
651
652     memcpy(result, psk_id, psk_id_length);
653     return psk_id_length;
654   case DTLS_PSK_KEY:
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);
661     }
662
663     memcpy(result, psk_key, psk_key_length);
664     return psk_key_length;
665   default:
666     dtls_warn("unsupported request type: %d\n", type);
667   }
668
669   return dtls_alert_fatal_create(DTLS_ALERT_INTERNAL_ERROR);
670 }
671  * @endcode
672  * 
673  * @subsection dtls_events The Event Notifier
674  *
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. 
682  *
683  * Internal events are DTLS_EVENT_CONNECTED, @c DTLS_EVENT_CONNECT, and
684  * @c DTLS_EVENT_RENEGOTIATE.
685  *
686  * @code
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 ...
690   return 0;
691 }
692  * @endcode
693  *
694  * @section dtls_client_example DTLS Client Example
695  *
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.
701  *
702  */
703
704 /**
705  * @addtogroup contiki Contiki
706  *
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
713  * @code
714 ./configure --with-contiki --build=x86_64-linux-gnu --host=arm-none-eabi 
715  * @endcode
716  * on an x86_64 linux host.
717  *
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).
720  *
721  * @code
722 #include "contiki.h"
723
724 #include "tinydtls.h"
725 #include "dtls.h"
726
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])
729
730 int send_to_peer(struct dtls_context_t *, session_t *, uint8 *, size_t);
731
732 static struct uip_udp_conn *server_conn;
733 static dtls_context_t *dtls_context;
734
735 static dtls_handler_t cb = {
736   .write = send_to_peer,
737   .read  = read_from_peer,
738   .event = NULL,
739   .get_psk_key = get_psk_key
740 };
741
742 PROCESS(server_process, "DTLS server process");
743 AUTOSTART_PROCESSES(&server_process);
744
745 PROCESS_THREAD(server_process, ev, data)
746 {
747   PROCESS_BEGIN();
748
749   dtls_init();
750
751   server_conn = udp_new(NULL, 0, NULL);
752   udp_bind(server_conn, UIP_HTONS(5684));
753
754   dtls_context = dtls_new_context(server_conn);
755   if (!dtls_context) {
756     dtls_emerg("cannot create context\n");
757     PROCESS_EXIT();
758   }
759
760   dtls_set_handler(dtls_context, &cb);
761
762   while(1) {
763     PROCESS_WAIT_EVENT();
764     if(ev == tcpip_event && uip_newdata()) {
765       session_t session;
766
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);
770     
771       dtls_handle_message(ctx, &session, uip_appdata, uip_datalen());
772     }
773   }
774
775   PROCESS_END();
776 }
777
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);
780
781   uip_ipaddr_copy(&conn->ripaddr, &session->addr);
782   conn->rport = session->port;
783
784   uip_udp_packet_send(conn, data, len);
785
786   memset(&conn->ripaddr, 0, sizeof(server_conn->ripaddr));
787   memset(&conn->rport, 0, sizeof(conn->rport));
788
789   return len;
790 }
791  * @endcode
792  */