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