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