Added connectivity files for full code review
[platform/upstream/iotivity.git] / resource / csdk / stack / src / ocserverrequest.c
1 //******************************************************************
2 //
3 // Copyright 2014 Intel Mobile Communications GmbH 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 #include <string.h>
21
22 #include "ocstack.h"
23 #include "ocserverrequest.h"
24 #include "ocresourcehandler.h"
25 #include "ocmalloc.h"
26
27 #include "cacommon.h"
28 #include "cainterface.h"
29
30 #include "utlist.h"
31 #include "pdu.h"
32
33 // Module Name
34 #define VERIFY_NON_NULL(arg) { if (!arg) {OC_LOG(FATAL, TAG, #arg " is NULL"); goto exit;} }
35
36 #define TAG  PCF("ocserverrequest")
37
38 static struct OCServerRequest * serverRequestList = NULL;
39 static struct OCServerResponse * serverResponseList = NULL;
40
41 OCServerRequest * GetServerRequestUsingToken (const CAToken_t token)
42 {
43     OCServerRequest * out = NULL;
44     LL_FOREACH (serverRequestList, out)
45     {
46         OC_LOG(INFO, TAG,PCF("comparing tokens"));
47         OC_LOG_BUFFER(INFO, TAG, (const uint8_t *)token, CA_MAX_TOKEN_LEN);
48         OC_LOG_BUFFER(INFO, TAG, (const uint8_t *)out->requestToken, CA_MAX_TOKEN_LEN);
49         if(memcmp(out->requestToken, token, CA_MAX_TOKEN_LEN) == 0)
50         {
51             return out;
52         }
53     }
54     OC_LOG(INFO, TAG, PCF("Server Request not found!!"));
55     return NULL;
56 }
57
58 OCServerRequest * GetServerRequestUsingHandle (const OCServerRequest * handle)
59 {
60     OCServerRequest * out = NULL;
61     LL_FOREACH (serverRequestList, out)
62     {
63         if(out == handle)
64         {
65             return out;
66         }
67     }
68     OC_LOG(INFO, TAG, PCF("Server Request not found!!"));
69     return NULL;
70 }
71
72 OCServerResponse * GetServerResponseUsingHandle (const OCServerRequest * handle)
73 {
74     OCServerResponse * out = NULL;
75     LL_FOREACH (serverResponseList, out)
76     {
77         if(out->requestHandle == handle)
78         {
79             return out;
80         }
81     }
82     OC_LOG(INFO, TAG, PCF("Server Response not found!!"));
83     return NULL;
84 }
85
86 OCStackResult AddServerRequest (OCServerRequest ** request, uint16_t coapID,
87         uint8_t delayedResNeeded, uint8_t secured, uint8_t notificationFlag, OCMethod method,
88         uint8_t numRcvdVendorSpecificHeaderOptions, uint32_t observationOption,
89         OCQualityOfService qos, unsigned char * query,
90         OCHeaderOption * rcvdVendorSpecificHeaderOptions,
91         unsigned char * reqJSONPayload, CAToken_t * requestToken,
92         unsigned char * resourceUrl, size_t reqTotalSize,
93         CAAddress_t *addressInfo, CAConnectivityType_t connectivityType)
94 {
95     OCServerRequest * serverRequest = NULL;
96
97     //Note: OCServerRequest includes 1 byte for the JSON Payload.  payloadSize is calculated
98     //as the required length of the string, so this will result in enough room for the
99     //null terminator as well.
100     serverRequest = (OCServerRequest *) OCCalloc(1, sizeof(OCServerRequest) + reqTotalSize - 1);
101     VERIFY_NON_NULL(serverRequest);
102
103     serverRequest->coapID = coapID;
104     serverRequest->delayedResNeeded = delayedResNeeded;
105     serverRequest->secured = secured;
106     serverRequest->notificationFlag = notificationFlag;
107
108     serverRequest->method = method;
109     serverRequest->numRcvdVendorSpecificHeaderOptions = numRcvdVendorSpecificHeaderOptions;
110     serverRequest->observationOption = observationOption;
111     serverRequest->observeResult = OC_STACK_ERROR;
112     serverRequest->qos = qos;
113     serverRequest->ehResponseHandler = HandleSingleResponse;
114     serverRequest->numResponses = 1;
115
116     if(query)
117     {
118         strncpy((char*)serverRequest->query,
119                 (const char*)query, sizeof(serverRequest->query) - 1);
120     }
121
122     if(rcvdVendorSpecificHeaderOptions)
123     {
124         memcpy(serverRequest->rcvdVendorSpecificHeaderOptions, rcvdVendorSpecificHeaderOptions,
125             MAX_HEADER_OPTIONS * sizeof(OCHeaderOption));
126     }
127     if(reqJSONPayload)
128     {
129         // destination is at least 1 greater than the source, so a NULL always exists in the
130         // last character
131         strncpy((char*)serverRequest->reqJSONPayload,
132                 (const char*)reqJSONPayload, reqTotalSize - 1);
133     }
134     serverRequest->requestComplete = 0;
135     if(requestToken)
136     {
137         serverRequest->requestToken = (CAToken_t)OCMalloc(CA_MAX_TOKEN_LEN+1);
138         VERIFY_NON_NULL (serverRequest->requestToken);
139         memset(serverRequest->requestToken, 0, CA_MAX_TOKEN_LEN + 1);
140         memcpy(serverRequest->requestToken, *requestToken, CA_MAX_TOKEN_LEN);
141     }
142
143     if(resourceUrl)
144     {
145         strncpy((char*)serverRequest->resourceUrl,
146                 (const char*)resourceUrl, sizeof(serverRequest->resourceUrl) - 1);
147     }
148
149     if (addressInfo)
150     {
151         serverRequest->addressInfo = *addressInfo;
152     }
153     serverRequest->connectivityType = connectivityType;
154
155     *request = serverRequest;
156     OC_LOG(INFO, TAG, PCF("Server Request Added!!"));
157     LL_APPEND (serverRequestList, serverRequest);
158     return OC_STACK_OK;
159
160 exit:
161     if (serverRequest)
162     {
163         OCFree(serverRequest);
164         serverRequest = NULL;
165     }
166     *request = NULL;
167     return OC_STACK_NO_MEMORY;
168 }
169
170 OCStackResult AddServerResponse (OCServerResponse ** response, OCRequestHandle requestHandle)
171 {
172     OCServerResponse * serverResponse = NULL;
173
174     serverResponse = (OCServerResponse *) OCCalloc(1, sizeof(OCServerResponse));
175     VERIFY_NON_NULL(serverResponse);
176
177     serverResponse->payload = (unsigned char *) OCMalloc(MAX_RESPONSE_LENGTH);
178     VERIFY_NON_NULL(serverResponse->payload);
179     memset(serverResponse->payload, 0, MAX_RESPONSE_LENGTH);
180
181     serverResponse->remainingPayloadSize = MAX_RESPONSE_LENGTH;
182     serverResponse->requestHandle = requestHandle;
183
184     *response = serverResponse;
185     OC_LOG(INFO, TAG, PCF("Server Response Added!!"));
186     LL_APPEND (serverResponseList, serverResponse);
187     return OC_STACK_OK;
188
189 exit:
190     if (serverResponse)
191     {
192         OCFree(serverResponse);
193         serverResponse = NULL;
194     }
195     *response = NULL;
196     return OC_STACK_NO_MEMORY;
197 }
198
199 // Form the OCEntityHandlerRequest struct
200 OCStackResult FormOCEntityHandlerRequest(
201         OCEntityHandlerRequest * entityHandlerRequest,
202         OCRequestHandle request,
203         OCMethod method,
204         OCResourceHandle resource,
205         unsigned char * queryBuf,
206         unsigned char * bufReqPayload,
207         uint8_t numVendorOptions,
208         OCHeaderOption * vendorOptions,
209         OCObserveAction observeAction,
210         OCObservationId observeID)
211 {
212     if (entityHandlerRequest)
213     {
214         memset(entityHandlerRequest, 0, sizeof(OCEntityHandlerRequest));
215         entityHandlerRequest->requestHandle = request;
216         entityHandlerRequest->method = method;
217         entityHandlerRequest->resource = (OCResourceHandle) resource;
218         entityHandlerRequest->query = queryBuf;
219         entityHandlerRequest->reqJSONPayload = bufReqPayload;
220         entityHandlerRequest->numRcvdVendorSpecificHeaderOptions = numVendorOptions;
221         entityHandlerRequest->rcvdVendorSpecificHeaderOptions = vendorOptions;
222
223         entityHandlerRequest->obsInfo.action = observeAction;
224         entityHandlerRequest->obsInfo.obsId = observeID;
225         return OC_STACK_OK;
226     }
227
228     return OC_STACK_INVALID_PARAM;
229 }
230
231 void FindAndDeleteServerResponse(OCServerResponse * serverResponse)
232 {
233     OCServerResponse* tmp;
234     if(serverResponse)
235     {
236         LL_FOREACH(serverResponseList, tmp)
237         {
238             if (serverResponse == tmp)
239             {
240                 DeleteServerResponse(tmp);
241                 return;
242             }
243         }
244     }
245 }
246
247 void DeleteServerResponse(OCServerResponse * serverResponse)
248 {
249     if(serverResponse) {
250         LL_DELETE(serverResponseList, serverResponse);
251         OCFree(serverResponse->payload);
252         OCFree(serverResponse);
253         OC_LOG(INFO, TAG, PCF("Server Response Removed!!"));
254     }
255 }
256
257 void FindAndDeleteServerRequest(OCServerRequest * serverRequest)
258 {
259     OCServerRequest* tmp;
260     if(serverRequest)
261     {
262         LL_FOREACH(serverRequestList, tmp)
263         {
264             if (serverRequest == tmp)
265             {
266                 DeleteServerRequest(tmp);
267                 return;
268             }
269         }
270     }
271 }
272
273 void DeleteServerRequest(OCServerRequest * serverRequest)
274 {
275     if(serverRequest) {
276         LL_DELETE(serverRequestList, serverRequest);
277         OCFree(serverRequest);
278         serverRequest = NULL;
279         OC_LOG(INFO, TAG, PCF("Server Request Removed!!"));
280     }
281 }
282
283 OCStackResult HandleSingleResponse(OCEntityHandlerResponse * ehResponse)
284 {
285     OCStackResult result = OC_STACK_ERROR;
286     CARemoteEndpoint_t responseEndpoint = {};
287     CAResponseInfo_t responseInfo = {};
288     CAHeaderOption_t* optionsPointer;
289
290     OC_LOG_V(INFO, TAG, "Inside HandleSingleResponse: %s", ehResponse->payload);
291
292     OCServerRequest *serverRequest = (OCServerRequest *)ehResponse->requestHandle;
293
294     // Copy the address
295     responseEndpoint.resourceUri      = (CAURI_t) serverRequest->resourceUrl;
296     responseEndpoint.addressInfo      = serverRequest->addressInfo;
297     responseEndpoint.connectivityType = serverRequest->connectivityType;
298     responseEndpoint.isSecured        =  serverRequest->secured;
299
300     // Copy the info
301     switch (ehResponse->ehResult)
302     {
303         case OC_EH_OK:
304             responseInfo.result = CA_SUCCESS;
305             break;
306         case OC_EH_ERROR:
307             responseInfo.result = CA_BAD_REQ;
308             break;
309         case OC_EH_RESOURCE_CREATED:
310             responseInfo.result = CA_CREATED;
311             break;
312         case OC_EH_RESOURCE_DELETED:
313             responseInfo.result = CA_DELETED;
314             break;
315         case OC_EH_SLOW:
316             responseInfo.result = CA_SUCCESS;
317             break;
318         case OC_EH_FORBIDDEN:
319             responseInfo.result = CA_BAD_REQ;
320             break;
321         default:
322             responseInfo.result = CA_BAD_REQ;
323             break;
324     }
325
326     switch (serverRequest->qos)
327     {
328         case OC_LOW_QOS:
329             responseInfo.info.type = CA_MSG_NONCONFIRM;
330             break;
331         case OC_MEDIUM_QOS:
332             responseInfo.info.type = CA_MSG_NONCONFIRM;
333             break;
334         case OC_HIGH_QOS:
335             responseInfo.info.type = CA_MSG_CONFIRM;
336             break;
337         case OC_NA_QOS:
338             responseInfo.info.type = CA_MSG_NONCONFIRM;
339             break;
340         default:
341             responseInfo.info.type = CA_MSG_NONCONFIRM;
342             break;
343     }
344
345     responseInfo.info.token = (CAToken_t)OCMalloc(CA_MAX_TOKEN_LEN+1);
346     if (!responseInfo.info.token)
347     {
348         OC_LOG(FATAL, TAG, "Response Info Token is NULL");
349         return result;
350     }
351     memset(responseInfo.info.token, 0, CA_MAX_TOKEN_LEN + 1);
352     memcpy(responseInfo.info.token, serverRequest->requestToken, CA_MAX_TOKEN_LEN);
353
354     if(serverRequest->observeResult == OC_STACK_OK)
355     {
356         responseInfo.info.numOptions = ehResponse->numSendVendorSpecificHeaderOptions + 1;
357     }
358     else
359     {
360         responseInfo.info.numOptions = ehResponse->numSendVendorSpecificHeaderOptions;
361     }
362
363     responseInfo.info.options = (CAHeaderOption_t *)
364                                     malloc(sizeof(CAHeaderOption_t) * responseInfo.info.numOptions);
365
366     optionsPointer = responseInfo.info.options;
367
368     if(serverRequest->observeResult == OC_STACK_OK)
369     {
370         responseInfo.info.numOptions = ehResponse->numSendVendorSpecificHeaderOptions + 1;
371     }
372
373     // TODO: This exposes CoAP specific details.  At some point, this should be
374     // re-factored and handled in the CA layer.
375     if(serverRequest->observeResult == OC_STACK_OK)
376     {
377         responseInfo.info.options[0].protocolID = CA_COAP_ID;
378         responseInfo.info.options[0].optionID = COAP_OPTION_OBSERVE;
379         responseInfo.info.options[0].optionLength = sizeof(uint32_t);
380         memcpy(responseInfo.info.options[0].optionData,
381                 &(serverRequest->observationOption), sizeof(uint32_t));
382
383         // Point to the next header option before copying vender specific header options
384         optionsPointer += 1;
385     }
386
387     if (ehResponse->numSendVendorSpecificHeaderOptions)
388     {
389         memcpy(optionsPointer, ehResponse->sendVendorSpecificHeaderOptions,
390                         sizeof(OCHeaderOption) * ehResponse->numSendVendorSpecificHeaderOptions);
391     }
392
393     // Allocate memory for the payload.
394     char *payload = (char *)OCCalloc(1, MAX_RESPONSE_LENGTH);
395     if(!payload)
396     {
397         return OC_STACK_NO_MEMORY;
398     }
399
400     // Put the JSON prefix and suffix around the payload
401     strcpy(payload, (const char *)OC_JSON_PREFIX);
402     strcat(payload, (const char *)ehResponse->payload);
403     strcat(payload, (const char *)OC_JSON_SUFFIX);
404     responseInfo.info.payload = (CAPayload_t)payload;
405
406     #ifdef WITH_PRESENCE
407     //TODO: Add other connectivity types to CAConnTypes[] when enabled
408     CAConnectivityType_t CAConnTypes[] = {CA_ETHERNET, CA_WIFI};
409     const char * connTypes[] = {"ethernet", "wifi"};
410     int size = sizeof(CAConnTypes)/ sizeof(CAConnectivityType_t);
411     CAConnectivityType_t connType = responseEndpoint.connectivityType;
412     CAResult_t caResult = CA_STATUS_FAILED;
413     result = OC_STACK_OK;
414
415     //Sending response on all n/w interfaces
416     for(int i = 0; i < size; i++ )
417     {
418         responseEndpoint.connectivityType = (CAConnectivityType_t)(connType & CAConnTypes[i]);
419         if(responseEndpoint.connectivityType)
420         {
421             //The result is set to OC_STACK_OK only if CASendResponse succeeds in sending the
422             //response on all the n/w interfaces else it is set to OC_STACK_ERROR
423             caResult = CASendResponse(&responseEndpoint, &responseInfo);
424             if(caResult != CA_STATUS_OK)
425             {
426                 OC_LOG_V(ERROR, TAG, "CASendResponse failed on %s", connTypes[i]);
427                 result = OC_STACK_ERROR;
428             }
429             else
430             {
431                 OC_LOG_V(INFO, TAG, "CASendResponse succeeded on %s", connTypes[i]);
432             }
433         }
434     }
435     #else
436     CAResult_t caResult = CASendResponse(&responseEndpoint, &responseInfo);
437     if(caResult != CA_STATUS_OK)
438     {
439         OC_LOG(ERROR, TAG, PCF("CASendResponse failed"));
440     }
441     else
442     {
443         result = OC_STACK_OK;
444     }
445     #endif
446
447     OCFree(payload);
448     //Delete the request
449     FindAndDeleteServerRequest(serverRequest);
450     return result;
451 }
452
453 OCStackResult HandleAggregateResponse(OCEntityHandlerResponse * ehResponse)
454 {
455     OCStackResult stackRet = OC_STACK_ERROR;
456     OCServerRequest * serverRequest = NULL;
457     OCServerResponse * serverResponse = NULL;
458     uint16_t bufferNeeded = 0;
459
460     OC_LOG_V(INFO, TAG, "Inside HandleAggregateResponse: %s", ehResponse->payload);
461
462     serverRequest = GetServerRequestUsingHandle((OCServerRequest *)ehResponse->requestHandle);
463     serverResponse = GetServerResponseUsingHandle((OCServerRequest *)ehResponse->requestHandle);
464
465     if(serverRequest)
466     {
467         if(!serverResponse)
468         {
469             OC_LOG(INFO, TAG, PCF("This is the first response fragment"));
470             stackRet = AddServerResponse(&serverResponse, ehResponse->requestHandle);
471             if (OC_STACK_OK != stackRet)
472             {
473                 OC_LOG(ERROR, TAG, PCF("Error adding server response"));
474                 return stackRet;
475             }
476             VERIFY_NON_NULL(serverResponse);
477             VERIFY_NON_NULL(serverResponse->payload);
478         }
479
480         // If there is more than 1 response, then we need to allow for a null-termination
481         // in the server response payload buffer AND the JSON response separator
482         bufferNeeded = ehResponse->payloadSize + 1;
483         if (serverRequest->numResponses > 1)
484         {
485             bufferNeeded += strlen(OC_JSON_SEPARATOR_STR);
486         }
487         if(serverResponse->remainingPayloadSize >= bufferNeeded)
488         {
489             OC_LOG(INFO, TAG, PCF("There is room in response buffer"));
490             // append
491             strncat((char *)serverResponse->payload,
492                     (char *)ehResponse->payload,
493                     serverResponse->remainingPayloadSize);
494             OC_LOG_V(INFO, TAG, "Current aggregated response  ...%s", serverResponse->payload);
495             serverResponse->remainingPayloadSize -= strlen((char *)ehResponse->payload);
496             (serverRequest->numResponses)--;
497             if(serverRequest->numResponses == 0)
498             {
499                 OC_LOG(INFO, TAG, PCF("This is the last response fragment"));
500                 ehResponse->payload = serverResponse->payload;
501                 ehResponse->payloadSize = strlen((char *) serverResponse->payload) + 1;
502                 stackRet = HandleSingleResponse(ehResponse);
503                 //Delete the request and response
504                 FindAndDeleteServerRequest(serverRequest);
505                 FindAndDeleteServerResponse(serverResponse);
506             }
507             else
508             {
509                 OC_LOG(INFO, TAG, PCF("More response fragments to come"));
510                 strncat((char *)serverResponse->payload,
511                         OC_JSON_SEPARATOR_STR,
512                         serverResponse->remainingPayloadSize);
513                 OC_LOG_V(INFO, TAG, "Current aggregated response  ...%s", serverResponse->payload);
514                 serverResponse->remainingPayloadSize -= strlen(OC_JSON_SEPARATOR_STR);
515                 stackRet = OC_STACK_OK;
516             }
517         }
518         else
519         {
520             OC_LOG(INFO, TAG, PCF("No room in response buffer"));
521             //Delete the request and response
522             FindAndDeleteServerRequest(serverRequest);
523             FindAndDeleteServerResponse(serverResponse);
524             stackRet = OC_STACK_NO_MEMORY;
525         }
526     }
527 exit:
528     return stackRet;
529 }