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