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