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