TLS support
[platform/upstream/iotivity.git] / resource / csdk / connectivity / api / cacommon.h
1 /* ****************************************************************
2  *
3  * Copyright 2014 Samsung Electronics All Rights Reserved.
4  *
5  *
6  *
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  *
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  *
19  ******************************************************************/
20
21 /**
22  * @file cacommon.h
23  * This file contains the common data structures between Resource , CA and adapters
24  */
25
26 #ifndef CA_COMMON_H_
27 #define CA_COMMON_H_
28
29 #ifndef WITH_ARDUINO
30 #ifdef TCP_ADAPTER
31 #define HAVE_SYS_POLL_H
32 #endif
33 #endif
34
35 #include <stdint.h>
36 #include <stdlib.h>
37 #include <stdbool.h>
38
39 #ifdef HAVE_SYS_POLL_H
40 #include <sys/poll.h>
41 #endif
42
43 #ifdef HAVE_WINSOCK2_H
44 #include <winsock2.h>
45 #include <mswsock.h>
46 #endif
47
48 #ifdef __cplusplus
49 extern "C"
50 {
51 #endif
52
53 /**
54  * IP address Length.
55  */
56 #define CA_IPADDR_SIZE 16
57
58 /**
59  * Remote Access jabber ID length.
60  */
61 #define CA_RAJABBERID_SIZE 256
62
63 /**
64  * Mac address length for BT port.
65  */
66 #define CA_MACADDR_SIZE 18
67
68 /**
69  * Max header options data length.
70  */
71 #define CA_MAX_HEADER_OPTION_DATA_LENGTH 20
72
73 /**
74 * Max token length.
75 */
76 #define CA_MAX_TOKEN_LEN (8)
77
78 /**
79  * Max URI length.
80  */
81 #ifdef ARDUINO
82 #define CA_MAX_URI_LENGTH 128  /* maximum size of URI for embedded platforms*/
83 #else
84 #define CA_MAX_URI_LENGTH 512 /* maximum size of URI for other platforms*/
85 #endif
86
87 /**
88  * Max PDU length supported.
89  */
90 #ifdef ARDUINO
91 #define COAP_MAX_PDU_SIZE           320  /* maximum size of a CoAP PDU for embedded platforms*/
92 #else
93 #define COAP_MAX_PDU_SIZE           1400 /* maximum size of a CoAP PDU for big platforms*/
94 #endif
95
96 #ifdef WITH_BWT
97 #define CA_DEFAULT_BLOCK_SIZE       CA_BLOCK_SIZE_1024_BYTE
98 #endif
99
100 /**
101  *Maximum length of the remoteEndpoint identity.
102  */
103 #define CA_MAX_ENDPOINT_IDENTITY_LEN   (32)
104
105 /**
106  * option types - the highest option number 63.
107  */
108 #define CA_OPTION_IF_MATCH 1
109 #define CA_OPTION_ETAG 4
110 #define CA_OPTION_IF_NONE_MATCH 5
111 #define CA_OPTION_OBSERVE 6
112 #define CA_OPTION_LOCATION_PATH 8
113 #define CA_OPTION_URI_PATH 11
114 #define CA_OPTION_CONTENT_FORMAT 12
115 #define CA_OPTION_CONTENT_TYPE COAP_OPTION_CONTENT_FORMAT
116 #define CA_OPTION_MAXAGE 14
117 #define CA_OPTION_URI_QUERY 15
118 #define CA_OPTION_ACCEPT 17
119 #define CA_OPTION_LOCATION_QUERY 20
120
121 /**
122  * Payload information from resource model.
123  */
124 typedef uint8_t *CAPayload_t;
125
126 /**
127  * URI for the OIC base.CA considers relative URI as the URI.
128  */
129 typedef char *CAURI_t;
130
131 /**
132  * Token information for mapping the request and responses by resource model.
133  */
134 typedef char *CAToken_t;
135
136 /*
137  * Socket types and error definitions.
138  */
139 #ifdef HAVE_WINSOCK2_H
140 # define OC_SOCKET_ERROR      SOCKET_ERROR
141 # define OC_INVALID_SOCKET    INVALID_SOCKET
142 typedef SOCKET CASocketFd_t;
143 #else // HAVE_WINSOCK2_H
144 # define OC_SOCKET_ERROR      (-1)
145 # define OC_INVALID_SOCKET    (-1)
146 typedef int    CASocketFd_t;
147 #endif
148
149 /*
150  * The following flags are the same as the equivalent OIC values in
151  * octypes.h, allowing direct copying with slight fixup.
152  * The CA layer should used the OC types when build allows that.
153  */
154 #ifdef RA_ADAPTER
155 #define MAX_ADDR_STR_SIZE_CA (256)
156 #else
157 /*
158  * Max Address could be "coaps+tcp://[xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:yyy.yyy.yyy.yyy]:xxxxx"
159  * Which is 65, +1 for null terminator => 66
160  * OCDevAddr (defined in OCTypes.h) must be the same
161  * as CAEndpoint_t (defined here)
162  */
163 #define MAX_ADDR_STR_SIZE_CA (66)
164 #endif
165
166 typedef enum
167 {
168     CA_DEFAULT_ADAPTER = 0,
169
170     // value zero indicates discovery
171     CA_ADAPTER_IP            = (1 << 0),   // IPv4 and IPv6, including 6LoWPAN
172     CA_ADAPTER_GATT_BTLE     = (1 << 1),   // GATT over Bluetooth LE
173     CA_ADAPTER_RFCOMM_BTEDR  = (1 << 2),   // RFCOMM over Bluetooth EDR
174
175 #ifdef RA_ADAPTER
176     CA_ADAPTER_REMOTE_ACCESS = (1 << 3),   // Remote Access over XMPP.
177 #endif
178
179     CA_ADAPTER_TCP           = (1 << 4),   // CoAP over TCP
180     CA_ADAPTER_NFC           = (1 << 5),   // NFC Adapter
181
182     CA_ALL_ADAPTERS          = 0xffffffff
183 } CATransportAdapter_t;
184
185 typedef enum
186 {
187     CA_DEFAULT_FLAGS = 0,
188
189     // Insecure transport is the default (subject to change)
190     CA_SECURE          = (1 << 4),   // secure the transport path
191     // IPv4 & IPv6 autoselection is the default
192     CA_IPV6            = (1 << 5),   // IP adapter only
193     CA_IPV4            = (1 << 6),   // IP adapter only
194     // Indication that a message was received by multicast.
195     CA_MULTICAST       = (1 << 7),
196     // Link-Local multicast is the default multicast scope for IPv6.
197     // These correspond in both value and position to the IPv6 address bits.
198     CA_SCOPE_INTERFACE = 0x1, // IPv6 Interface-Local scope
199     CA_SCOPE_LINK      = 0x2, // IPv6 Link-Local scope (default)
200     CA_SCOPE_REALM     = 0x3, // IPv6 Realm-Local scope
201     CA_SCOPE_ADMIN     = 0x4, // IPv6 Admin-Local scope
202     CA_SCOPE_SITE      = 0x5, // IPv6 Site-Local scope
203     CA_SCOPE_ORG       = 0x8, // IPv6 Organization-Local scope
204     CA_SCOPE_GLOBAL    = 0xE, // IPv6 Global scope
205 } CATransportFlags_t;
206
207 #define CA_IPFAMILY_MASK (CA_IPV6|CA_IPV4)
208 #define CA_SCOPE_MASK 0xf     // mask scope bits above
209
210 /**
211  * Information about the network status.
212  */
213 typedef enum
214 {
215     CA_INTERFACE_DOWN,   /**< Connection is not available */
216     CA_INTERFACE_UP    /**< Connection is Available */
217 } CANetworkStatus_t;
218
219 /*
220  * remoteEndpoint identity.
221  */
222 typedef struct
223 {
224     uint16_t id_length;
225     unsigned char id[CA_MAX_ENDPOINT_IDENTITY_LEN];
226 } CARemoteId_t;
227
228 /**
229  * Message Type for Base source code.
230  */
231 typedef enum
232 {
233     CA_MSG_CONFIRM = 0,  /**< confirmable message (requires ACK/RST) */
234     CA_MSG_NONCONFIRM,   /**< non-confirmable message (one-shot message) */
235     CA_MSG_ACKNOWLEDGE,  /**< used to acknowledge confirmable messages */
236     CA_MSG_RESET         /**< used to indicates not-interested or error (lack of context)in
237                                                   received messages */
238 } CAMessageType_t;
239
240 /**
241  * Allowed method to be used by resource model.
242  */
243 typedef enum
244 {
245     CA_GET = 1, /**< GET Method  */
246     CA_POST,    /**< POST Method */
247     CA_PUT,     /**< PUT Method */
248     CA_DELETE   /**< DELETE Method */
249 } CAMethod_t;
250
251 /**
252  * block size.
253  * it depends on defined size in libCoAP.
254  */
255 typedef enum
256 {
257     CA_BLOCK_SIZE_16_BYTE = 0,    /**< 16byte */
258     CA_BLOCK_SIZE_32_BYTE = 1,    /**< 32byte */
259     CA_BLOCK_SIZE_64_BYTE = 2,    /**< 64byte */
260     CA_BLOCK_SIZE_128_BYTE = 3,   /**< 128byte */
261     CA_BLOCK_SIZE_256_BYTE = 4,   /**< 256byte */
262     CA_BLOCK_SIZE_512_BYTE = 5,   /**< 512byte */
263     CA_BLOCK_SIZE_1024_BYTE = 6     /**< 1Kbyte */
264 } CABlockSize_t;
265
266 /**
267  * Endpoint information for connectivities.
268  * Must be identical to OCDevAddr.
269  */
270 typedef struct
271 {
272     CATransportAdapter_t    adapter;    // adapter type
273     CATransportFlags_t      flags;      // transport modifiers
274     uint16_t                port;       // for IP
275     char                    addr[MAX_ADDR_STR_SIZE_CA]; // address for all
276     uint32_t                ifindex;    // usually zero for default interface
277 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
278     char                    routeData[MAX_ADDR_STR_SIZE_CA]; /**< GatewayId:ClientId of
279                                                                     destination. **/
280 #endif
281 } CAEndpoint_t;
282
283 /**
284  * Endpoint information for secure messages.
285  */
286 typedef struct
287 {
288     CAEndpoint_t endpoint;      /**< endpoint */
289     // TODO change name to deviceId
290     CARemoteId_t identity;      /**< endpoint device uuid */
291     CARemoteId_t userId;        /**< endpoint user uuid */
292 } CASecureEndpoint_t;
293
294 /**
295  * Enums for CA return values.
296  */
297 typedef enum
298 {
299     /* Result code - START HERE */
300     CA_STATUS_OK = 0,               /**< Success */
301     CA_STATUS_INVALID_PARAM,        /**< Invalid Parameter */
302     CA_ADAPTER_NOT_ENABLED,         /**< Adapter is not enabled */
303     CA_SERVER_STARTED_ALREADY,      /**< Server is started already */
304     CA_SERVER_NOT_STARTED,          /**< Server is not started */
305     CA_DESTINATION_NOT_REACHABLE,   /**< Destination is not reachable */
306     CA_SOCKET_OPERATION_FAILED,     /**< Socket operation failed */
307     CA_SEND_FAILED,                 /**< Send request failed */
308     CA_RECEIVE_FAILED,              /**< Receive failed */
309     CA_MEMORY_ALLOC_FAILED,         /**< Memory allocation failed */
310     CA_REQUEST_TIMEOUT,             /**< Request is Timeout */
311     CA_DESTINATION_DISCONNECTED,    /**< Destination is disconnected */
312     CA_NOT_SUPPORTED,               /**< Not supported */
313     CA_STATUS_NOT_INITIALIZED,      /**< Not Initialized*/
314     CA_DTLS_AUTHENTICATION_FAILURE, /**< Decryption error in DTLS */
315     CA_STATUS_FAILED =255           /**< Failure */
316     /* Result code - END HERE */
317 } CAResult_t;
318
319 /**
320  * Enums for CA Response values.
321  */
322 typedef enum
323 {
324     /* Response status code - START HERE */
325     CA_EMPTY = 0,                           /**< Empty */
326     CA_CREATED = 201,                       /**< Created */
327     CA_DELETED = 202,                       /**< Deleted */
328     CA_VALID = 203,                         /**< Valid */
329     CA_CHANGED = 204,                       /**< Changed */
330     CA_CONTENT = 205,                       /**< Content */
331     CA_CONTINUE = 231,                      /**< Continue */
332     CA_BAD_REQ = 400,                       /**< Bad Request */
333     CA_UNAUTHORIZED_REQ = 401,              /**< Unauthorized Request */
334     CA_BAD_OPT = 402,                       /**< Bad Option */
335     CA_FORBIDDEN_REQ = 403,                 /**< Forbidden Request */
336     CA_NOT_FOUND = 404,                     /**< Not found */
337     CA_METHOD_NOT_ALLOWED = 405,            /**< Method Not Allowed */
338     CA_NOT_ACCEPTABLE = 406,                /**< Not Acceptable */
339     CA_REQUEST_ENTITY_INCOMPLETE = 408,     /**< Request Entity Incomplete */
340     CA_REQUEST_ENTITY_TOO_LARGE = 413,      /**< Request Entity Too Large */
341     CA_INTERNAL_SERVER_ERROR = 500,         /**< Internal Server Error */
342     CA_RETRANSMIT_TIMEOUT = 504             /**< Retransmit timeout */
343     /* Response status code - END HERE */
344 } CAResponseResult_t;
345
346 /**
347  * Data type whether the data is Request Message or Response Message.
348  * if there is some failure before send data on network.
349  * Type will be set as error type for error callback.
350  */
351 typedef enum
352 {
353     CA_REQUEST_DATA = 1,
354     CA_RESPONSE_DATA,
355     CA_ERROR_DATA,
356     CA_RESPONSE_FOR_RES
357 } CADataType_t;
358
359 /**
360  * Transport Protocol IDs for additional options.
361  */
362 typedef enum
363 {
364     CA_INVALID_ID = (1 << 0),   /**< Invalid ID */
365     CA_COAP_ID = (1 << 1)       /**< COAP ID */
366 } CATransportProtocolID_t;
367
368 /**
369  * Adapter State to indicate the network changed notifications.
370  */
371 typedef enum
372 {
373     CA_ADAPTER_DISABLED,   /**< Adapter is Disabled */
374     CA_ADAPTER_ENABLED     /**< Adapter is Enabled */
375 } CAAdapterState_t;
376
377 /**
378  * Format indicating which encoding has been used on the payload.
379  */
380 typedef enum
381 {
382     CA_FORMAT_UNDEFINED = 0,            /**< Undefined enoding format */
383     CA_FORMAT_TEXT_PLAIN,
384     CA_FORMAT_APPLICATION_LINK_FORMAT,
385     CA_FORMAT_APPLICATION_XML,
386     CA_FORMAT_APPLICATION_OCTET_STREAM,
387     CA_FORMAT_APPLICATION_RDF_XML,
388     CA_FORMAT_APPLICATION_EXI,
389     CA_FORMAT_APPLICATION_JSON,
390     CA_FORMAT_APPLICATION_CBOR,
391     CA_FORMAT_UNSUPPORTED
392 } CAPayloadFormat_t;
393
394 /**
395  * Header options structure to be filled.
396  *
397  * This structure is used to hold header information.
398  */
399 typedef struct
400 {
401     CATransportProtocolID_t protocolID;                     /**< Protocol ID of the Option */
402     uint16_t optionID;                                      /**< The header option ID which will be
403                                                             added to communication packets */
404     uint16_t optionLength;                                  /**< Option Length **/
405     char optionData[CA_MAX_HEADER_OPTION_DATA_LENGTH];      /**< Optional data values**/
406 } CAHeaderOption_t;
407
408 /**
409  * Base Information received.
410  *
411  * This structure is used to hold request & response base information.
412  */
413 typedef struct
414 {
415     CAMessageType_t type;       /**< Qos for the request */
416 #ifdef ROUTING_GATEWAY
417     bool skipRetransmission;    /**< Will not attempt retransmission even if type is CONFIRM.
418                                      Required for packet forwarding */
419 #endif
420     uint16_t messageId;         /**< Message id.
421                                  * if message id is zero, it will generated by CA inside.
422                                  * otherwise, you can use it */
423     CAToken_t token;            /**< Token for CA */
424     uint8_t tokenLength;        /**< token length */
425     CAHeaderOption_t *options;  /** Header Options for the request */
426     uint8_t numOptions;         /**< Number of Header options */
427     CAPayload_t payload;        /**< payload of the request  */
428     size_t payloadSize;         /**< size in bytes of the payload */
429     CAPayloadFormat_t payloadFormat;    /**< encoding format of the request payload */
430     CAPayloadFormat_t acceptFormat;     /**< accept format for the response payload */
431     CAURI_t resourceUri;        /**< Resource URI information **/
432     CARemoteId_t identity;      /**< endpoint identity */
433     CADataType_t dataType;      /**< data type */
434 } CAInfo_t;
435
436 /**
437  * Request Information to be sent.
438  *
439  * This structure is used to hold request information.
440  */
441 typedef struct
442 {
443     CAMethod_t method;  /**< Name of the Method Allowed */
444     CAInfo_t info;      /**< Information of the request. */
445     bool isMulticast;   /**< is multicast request */
446 } CARequestInfo_t;
447
448 /**
449  * Response information received.
450  *
451  * This structure is used to hold response information.
452  */
453 typedef struct
454 {
455     CAResponseResult_t result;  /**< Result for response by resource model */
456     CAInfo_t info;              /**< Information of the response */
457     bool isMulticast;
458 } CAResponseInfo_t;
459
460 /**
461  * Error information from CA
462  *        contains error code and message information.
463  *
464  * This structure holds error information.
465  */
466 typedef struct
467 {
468     CAResult_t result;  /**< CA API request result  */
469     CAInfo_t info;      /**< message information such as token and payload data
470                              helpful to identify the error */
471 } CAErrorInfo_t;
472
473 /**
474  * Hold global variables for CA layer. (also used by RI layer)
475  */
476 typedef struct
477 {
478     CASocketFd_t fd;    /**< socket fd */
479     uint16_t port;      /**< socket port */
480 } CASocket_t;
481
482 #define HISTORYSIZE (4)
483
484 typedef struct
485 {
486     CATransportFlags_t flags;
487     uint16_t messageId;
488     char token[CA_MAX_TOKEN_LEN];
489     uint8_t tokenLength;
490 } CAHistoryItem_t;
491
492 typedef struct
493 {
494     int nextIndex;
495     CAHistoryItem_t items[HISTORYSIZE];
496 } CAHistory_t;
497
498 /**
499  * Hold interface index for keeping track of comings and goings.
500  */
501 typedef struct
502 {
503     int32_t ifIndex; /**< network interface index */
504 } CAIfItem_t;
505
506 /**
507  * Hold the port number assigned from application.
508  * It will be used when creating a socket.
509  */
510 typedef struct
511 {
512     struct udpports
513     {
514         uint16_t u6;    /**< unicast IPv6 socket port */
515         uint16_t u6s;   /**< unicast IPv6 socket secure port */
516         uint16_t u4;    /**< unicast IPv4 socket port */
517         uint16_t u4s;   /**< unicast IPv4 socket secure port */
518     } udp;
519 #ifdef TCP_ADAPTER
520     struct tcpports
521     {
522         uint16_t u4;    /**< unicast IPv4 socket port */
523         uint16_t u6;    /**< unicast IPv6 socket port */
524     } tcp;
525 #endif
526 } CAPorts_t;
527
528 typedef struct
529 {
530     CATransportFlags_t clientFlags; /**< flag for client */
531     CATransportFlags_t serverFlags; /**< flag for server */
532     bool client; /**< client mode */
533     bool server; /**< server mode */
534
535     CAPorts_t ports;
536
537     struct sockets
538     {
539         void *threadpool;           /**< threadpool between Initialize and Start */
540         CASocket_t u6;              /**< unicast   IPv6 */
541         CASocket_t u6s;             /**< unicast   IPv6 secure */
542         CASocket_t u4;              /**< unicast   IPv4 */
543         CASocket_t u4s;             /**< unicast   IPv4 secure */
544         CASocket_t m6;              /**< multicast IPv6 */
545         CASocket_t m6s;             /**< multicast IPv6 secure */
546         CASocket_t m4;              /**< multicast IPv4 */
547         CASocket_t m4s;             /**< multicast IPv4 secure */
548         CASocketFd_t netlinkFd;     /**< netlink */
549 #if defined(_WIN32)
550         WSAEVENT shutdownEvent;     /**< Event used to signal threads to stop */
551 #else
552         int shutdownFds[2];         /**< fds used to signal threads to stop */
553 #endif
554         int selectTimeout;          /**< in seconds */
555         int maxfd;                  /**< highest fd (for select) */
556         bool started;               /**< the IP adapter has started */
557         bool terminate;             /**< the IP adapter needs to stop */
558         bool ipv6enabled;           /**< IPv6 enabled by OCInit flags */
559         bool ipv4enabled;           /**< IPv4 enabled by OCInit flags */
560         bool dualstack;             /**< IPv6 and IPv4 enabled */
561 #if defined (_WIN32)
562         LPFN_WSARECVMSG wsaRecvMsg; /**< Win32 function pointer to WSARecvMsg() */
563 #endif
564
565         struct networkmonitors
566         {
567             CAIfItem_t *ifItems; /**< current network interface index list */
568             size_t sizeIfItems;  /**< size of network interface index array */
569             size_t numIfItems;   /**< number of valid network interfaces */
570         } nm;
571     } ip;
572
573     struct calayer
574     {
575         CAHistory_t requestHistory;  /**< filter IP family in requests */
576     } ca;
577
578 #ifdef TCP_ADAPTER
579     /**
580      * Hold global variables for TCP Adapter.
581      */
582     struct tcpsockets
583     {
584         void *threadpool;       /**< threadpool between Initialize and Start */
585         CASocket_t ipv4;        /**< IPv4 accept socket */
586         CASocket_t ipv6;        /**< IPv6 accept socket */
587         void *svrlist;          /**< unicast IPv4 TCP server information*/
588         int selectTimeout;      /**< in seconds */
589         int listenBacklog;      /**< backlog counts*/
590         int shutdownFds[2];     /**< shutdown pipe */
591         int connectionFds[2];   /**< connection pipe */
592         int maxfd;              /**< highest fd (for select) */
593         bool started;           /**< the TCP adapter has started */
594         bool terminate;         /**< the TCP adapter needs to stop */
595         bool ipv4tcpenabled;    /**< IPv4 TCP enabled by OCInit flags */
596         bool ipv6tcpenabled;    /**< IPv6 TCP enabled by OCInit flags */
597     } tcp;
598 #endif
599 } CAGlobals_t;
600
601 extern CAGlobals_t caglobals;
602
603 /**
604  * Callback function type for request delivery.
605  * @param[out]   object       Endpoint object from which the request is received.
606  *                            It contains endpoint address based on the connectivity type.
607  * @param[out]   requestInfo  Info for resource model to understand about the request.
608  */
609 typedef void (*CARequestCallback)(const CAEndpoint_t *object,
610                                   const CARequestInfo_t *requestInfo);
611
612 /**
613  * Callback function type for response delivery.
614  * @param[out]   object           Endpoint object from which the response is received.
615  * @param[out]   responseInfo     Identifier which needs to be mapped with response.
616  */
617 typedef void (*CAResponseCallback)(const CAEndpoint_t *object,
618                                    const CAResponseInfo_t *responseInfo);
619 /**
620  * Callback function type for error.
621  * @param[out]   object           remote device information.
622  * @param[out]   errorInfo        CA Error information.
623  */
624 typedef void (*CAErrorCallback)(const CAEndpoint_t *object,
625                                 const CAErrorInfo_t *errorInfo);
626
627 /**
628  * Callback function type for network status changes delivery from CA common logic.
629  * @param[out]   info       Endpoint object from which the network status is changed.
630  *                          It contains endpoint address based on the connectivity type.
631  * @param[out]   status     Current network status info.
632  */
633 typedef void (*CANetworkMonitorCallback)(const CAEndpoint_t *info, CANetworkStatus_t status);
634
635 #ifdef __cplusplus
636 } /* extern "C" */
637 #endif
638
639 #endif // CA_COMMON_H_