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