-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathwebservice_interface.c
12301 lines (12196 loc) · 673 KB
/
webservice_interface.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/***
Copyright 2010-2021 by Omar Alejandro Herrera Reyna
Caume Data Security Engine, also known as CaumeDSE is released under the
GNU General Public License by the Copyright holder, with the additional
exemption that compiling, linking, and/or using OpenSSL is allowed.
LICENSE
This file is part of Caume Data Security Engine, also called CaumeDSE.
CaumeDSE is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
CaumeDSE is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with CaumeDSE. If not, see <http://www.gnu.org/licenses/>.
INCLUDED SOFTWARE
This product includes software developed by the OpenSSL Project
for use in the OpenSSL Toolkit (http://www.openssl.org/).
This product includes cryptographic software written by
Eric Young ([email protected]).
This product includes software written by
Tim Hudson ([email protected]).
This product includes software from the SQLite library that is in
the public domain (http://www.sqlite.org/copyright.html).
This product includes software from the GNU Libmicrohttpd project, Copyright
© 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007,
2008, 2009, 2010 , 2011, 2012 Free Software Foundation, Inc.
This product includes software from Perl5, which is Copyright (C) 1993-2005,
by Larry Wall and others.
***/
#include "common.h"
int cmeWebServiceAnswerConnection (void *cls, struct MHD_Connection *connection, const char *url,
const char *method, const char *version, const char *upload_data,
size_t *upload_data_size, void **con_cls)
{
#define GET 0
#define POST 1
int cont,responseEncoding __attribute__((unused)),result;
int exitcode=1;
int numUrlElements=0;
int responseCode=0;
static time_t connectionStartTime=0;
static long int requestDataSize=0;
long int responseDataSize=0;
char *page=NULL;
const char *pOutputType=NULL; //Ptr to constant str. for output type. No need to free.
char **urlElements=NULL;
struct MHD_Response *response=NULL;
struct MHD_Response *responseFile=NULL;
char **headerElements=NULL;
char **argumentElements=NULL;
char **responseHeaders=NULL;
char *responseText=NULL;
char *responseFilePath=NULL;
struct cmeWebServiceConnectionInfoStruct *con_info=NULL; //We will free this struct in cmeWebServiceRequestCompleted().
struct cmeWebServiceContentReaderStruct *cr_info=NULL; //We will free this struct in cmeContentReaderFreeCallback();
struct stat statResponseFile;
#define cmeWebServiceAnswerConnectionFree() \
do { \
cmeFree(page); \
cmeFree(responseText); \
if (response) \
{ \
MHD_destroy_response (response); \
} \
if (responseFile) \
{ \
MHD_destroy_response (responseFile); \
} \
if (numUrlElements) \
{ \
cont=0; \
while (cont<numUrlElements) \
{ \
cmeFree(urlElements[cont]); \
cont++; \
} \
cmeFree(urlElements); \
} \
if (headerElements) \
{ \
cont=0; \
while (cont<(cmeWSHTTPMaxHeaders*2)) \
{ \
cmeFree(headerElements[cont]); \
cont++; \
} \
cmeFree(headerElements); \
} \
if (argumentElements) \
{ \
cont=0; \
while (cont<(cmeWSURIMaxArguments*2)) \
{ \
cmeFree(argumentElements[cont]); \
cont++; \
} \
cmeFree(argumentElements); \
} \
if (responseHeaders) \
{ \
cont=0; \
while (cont<(cmeWSHTTPMaxHeaders*2)) \
{ \
cmeFree(responseHeaders[cont]); \
cont++; \
} \
cmeFree(responseHeaders); \
} \
if (responseFilePath) \
{ \
cmeFree(responseFilePath); \
} \
} while (0); //Local free() macro.
responseEncoding=cmeWSEncoding_HTML; //by default we use HTML responses on new requests
if (NULL == *con_cls) //New connection; set POST processor if needed.
{
con_info = (struct cmeWebServiceConnectionInfoStruct *) malloc (sizeof (struct cmeWebServiceConnectionInfoStruct));
if (NULL == con_info) //Error.
{
#ifdef ERROR_LOG
fprintf(stderr,"CaumeDSE Error: cmeWebServiceAnswerConnection(), malloc() can't allocate memory for cmeWebServiceConnectionInfoStruct."
" Method: '%s', url: '%s'!\n",method,url);
#endif
return MHD_NO;
}
connectionStartTime=time(NULL);
requestDataSize=(long int)*upload_data_size;
con_info->threadStatus=0;
con_info->answerString=NULL;
con_info->answerCode=0;
con_info->filePointer=NULL;
con_info->fileName=NULL;
con_info->connectionType=0;
con_info->connection=connection;
con_info->postProcessor=NULL;
con_info->postArglist=(char **)malloc((sizeof (char *))*cmeWSHTTPMaxHeaders*2); //*2 since Argument lists consist of argumentElements PAIRS.
for (cont=0;cont<(cmeWSHTTPMaxHeaders*2);cont++) //Clear pointers.
{
con_info->postArglist[cont]=NULL;
}
con_info->postArgCont=0;
if (0 == strcmp (method, "POST"))
{ // NOTE (OHR#9#): For MHD_create_post_processor to work properly, encoding (form "enctype" / header "Content-Type") must be defined;
// otherwise NULL will be returned. It should be either "application/x-www-form-urlencoded", "text/plain" or "multipart/form-data".
con_info->postProcessor=MHD_create_post_processor(connection,cmeWSPostBufferSize,(MHD_PostDataIterator)&cmeWebServicePOSTIteration,(void *) con_info);
if (!con_info->postProcessor) //Warning, can't create post processor; we probably need an emulated POST with a GET style method (i.e. URL parameters).
{
#ifdef DEBUG
fprintf(stderr,"CaumeDSE Debug: cmeWebServiceAnswerConnection(), MHD_create_post_processor() Failed."
" Method: '%s', url: '%s'!\n",method,url);
fprintf(stdout,"CaumeDSE Debug: cmeWebServiceAnswerConnection(), new connectionType = GET (emulated GET for POST). "
"Method: %s, url: %s.\n", method, url);
#endif
//cmeFree(con_info);
con_info->connectionType=GET; //Don't reject a POST with parameters in the URI, process as a GET request
con_info->threadStatus=2;
//return MHD_NO;
}
else
{
#ifdef DEBUG
fprintf(stdout,"CaumeDSE Debug: cmeWebServiceAnswerConnection(), new connectionType = POST. "
"Method: %s, url: %s.\n", method, url);
#endif
con_info->connectionType=POST;
}
}
else
{
#ifdef DEBUG
fprintf(stdout,"CaumeDSE Debug: cmeWebServiceAnswerConnection(), new connectionType = GET. "
"Method: %s, url: %s.\n", method, url);
#endif
con_info->connectionType=GET;
con_info->threadStatus=2;
}
*con_cls=(void *)con_info;
return MHD_YES;
}
else
{
con_info=*con_cls;
requestDataSize+=(long int)*upload_data_size;
}
if ((con_info->connectionType)==POST) //Iterate POST request.
{
if (*upload_data_size != 0) //If data is available, retrieve it and exit function for another iteration.
{
MHD_post_process (con_info->postProcessor, upload_data,*upload_data_size);
*upload_data_size = 0;
return MHD_YES;
}
else if (NULL != con_info->answerString) //If no data is available but we have an answer, signal job is done.
{
con_info->threadStatus=1; //Signal: POST iterator job is done, waiting...
}
if (con_info->filePointer) //We need to close the file before cmeWebServiceRequestCompleted() is called, since cmeWebServiceProcessRequest() will use it.
{
fclose (con_info->filePointer);
con_info->filePointer=NULL;
}
}
do //Wait until the POST processor has collected all data.
{
sleep(cmeDefaultThreadWaitSeconds);
} while (con_info->threadStatus==0);
//Allocate space for headers and response headers:
headerElements=(char **)malloc((sizeof (char *))*cmeWSHTTPMaxHeaders*2); //*2 since headers consist of headerElements PAIRS.
responseHeaders=(char **)malloc((sizeof (char *))*cmeWSHTTPMaxResponseHeaders*2); //*2 since headers consist of headerElements PAIRS.
for (cont=0;cont<(cmeWSHTTPMaxHeaders*2);cont++) //Clear pointers.
{
headerElements[cont]=NULL;
responseHeaders[cont]=NULL;
}
//Allocate space for arguments:
argumentElements=(char **)malloc((sizeof (char *))*cmeWSURIMaxArguments*2); //*2 since elements consist of argumentElements PAIRS.
for (cont=0;cont<(cmeWSURIMaxArguments*2);cont++) //Clear pointers.
{
argumentElements[cont]=NULL;
}
#ifdef DEBUG
fprintf(stdout,"CaumeDSE Debug: cmeWebServiceAnswerConnection(), new %s request for %s using version %s\n", method, url, version);
#endif
cmeWebServiceParseURL(url, &urlElements, &numUrlElements); //Parse URL.
MHD_get_connection_values (connection, MHD_GET_ARGUMENT_KIND, (MHD_KeyValueIterator)&cmeWebServiceParseKeys, argumentElements); //Parse Headers.
MHD_get_connection_values (connection, MHD_HEADER_KIND, (MHD_KeyValueIterator)&cmeWebServiceParseKeys, headerElements); //Parse Arguments.
result=cmeWebServiceProcessRequest (&responseText,&responseFilePath,&responseHeaders,&responseCode,
url,(const char **)urlElements,numUrlElements,
(const char **)headerElements,(const char **)argumentElements,method,connection);
con_info->answerCode=responseCode;
if (responseFilePath) //We have a response File.
{
cr_info=(struct cmeWebServiceContentReaderStruct *) malloc (sizeof (struct cmeWebServiceContentReaderStruct)); //Create structure to pass among ContentReader iterations.
cr_info->fpResponseFile=NULL;
cr_info->fileName=NULL;
cmeStrConstrAppend(&(cr_info->fileName),"%s",responseFilePath); //Copy file path.
result=stat(responseFilePath,&statResponseFile);
if (!result) //OK, file exists and we got statistics
{
cr_info->fpResponseFile=fopen(responseFilePath,"rb");
if (cr_info->fpResponseFile) //File opened correctly
{
#ifdef DEBUG
fprintf(stdout,"CaumeDSE Debug: cmeWebServiceAnswerConnection(), user request successful "
"Method: '%s'. Url: '%s'. responseFilePath: '%s'.\n",method,url,responseFilePath);
#endif
//Create response from file:
responseDataSize=(long int)statResponseFile.st_size;
responseFile=MHD_create_response_from_callback(statResponseFile.st_size, //Size of file to read.
cmeDefaultContentReaderCallbackPageSize, //Page size for reading content.
&cmeContentReaderCallback, //MHD_ContentReaderCallback function.
cr_info, //void *crc_cls (i.e. ContentReaderCallback parameter).
&cmeContentReaderFreeCallback); //MHD_ContentReaderFreeCallback function.
if (!responseFile)//Error, could not create MHD_Response!
{
fclose(cr_info->fpResponseFile);
exitcode=MHD_NO;
}
else //OK, proceed creating response and adding headers.
{
if (responseHeaders[0] && responseHeaders[1]) //We got at least 1 response header. Process them
{
cont=0;
while ((responseHeaders[cont])&&(responseHeaders[cont+1])&&(cont<(cmeWSHTTPMaxHeaders*2)))
{
result=MHD_add_response_header(responseFile,responseHeaders[cont],responseHeaders[cont+1]);
cont+=2;
}
}
//Add default Headers:
result=MHD_add_response_header(responseFile,"Server","CaumeDSE " cmeEngineVersion);
exitcode=MHD_queue_response (connection, responseCode, responseFile); //Note that WebService processing function needs to define appropriate Content-Type headers
}
}
}
}
else // responseText with content or empty
{
if (responseText)
{
//Add default Headers:
if (cmeFindInArgPairList((const char **)responseHeaders,"Content-Type",&pOutputType)) //No Content-Type defined, so set one with the default: text/html.
{
cmeStrConstrAppend(&page,"%s%s%s",cmeWSHTMLPageStart,responseText,
cmeWSHTMLPageEnd); //Add page opening/closing tags and (c) to response page.
responseDataSize=(long int)strlen(page);
//Create response body:
response=MHD_create_response_from_buffer((size_t)responseDataSize,(void*) page, MHD_RESPMEM_MUST_COPY); //We have to create response body before adding headers.
result=MHD_add_response_header(response,"Content-Type","text/html; charset=utf-8");
}
else
{
cmeStrConstrAppend(&page,"%s",responseText); //Add plain response to response page.
responseDataSize=(long int)strlen(page);
//Create response body:
response=MHD_create_response_from_buffer((size_t)responseDataSize,(void*) page, MHD_RESPMEM_MUST_COPY);
}
#ifdef DEBUG
fprintf(stdout,"CaumeDSE Debug: cmeWebServiceAnswerConnection(), user request successful "
"Method: '%s'. Url: '%s'.\n responseText: '%s'.\n",method,url,page);
#endif
result=MHD_add_response_header(response,"Server","CaumeDSE " cmeEngineVersion);
}
else
{
//Create empty response body (e.g. for HEAD method):
responseDataSize=0;
response=MHD_create_response_from_buffer(0,NULL, MHD_RESPMEM_MUST_COPY);
//Add default Headers:
result=MHD_add_response_header(response,"Server","CaumeDSE " cmeEngineVersion);
}
if (responseHeaders[0] && responseHeaders[1]) //We got at least 1 response header. Process them
{
cont=0;
while ((responseHeaders[cont])&&(responseHeaders[cont+1])&&(cont<(cmeWSHTTPMaxHeaders*2)))
{
result=MHD_add_response_header(response,responseHeaders[cont],responseHeaders[cont+1]);
cont+=2;
}
}
exitcode=MHD_queue_response (connection, responseCode, response);
}
con_info->threadStatus=2; //Now the POST handling routing thread can free memory and finish.
result=cmeWebServiceLogConnection (connection,con_info,connectionStartTime,method,url,requestDataSize,responseDataSize,
(const char **)headerElements,(const char **)responseHeaders,(const char **)argumentElements,
(const char **)urlElements,numUrlElements);
cmeWebServiceAnswerConnectionFree(); //Free stuff
return (exitcode);
}
int cmeWebServiceParseURL(const char *url, char ***urlElements, int *numUrlElements)
{
int cont=0;
char *urlCopy=NULL;
char *token=NULL;
*numUrlElements=0;
*urlElements=(char **)malloc(sizeof(char *)*cmeIDDURIMaxDepth);
cmeStrConstrAppend(&urlCopy,"%s",url); //Because strtok() modifies parsed string.
token=strtok(urlCopy,"/?");
while ((cont<cmeIDDURIMaxDepth)&&(token))
{
(*numUrlElements)++;
(*urlElements)[cont]=NULL;
cmeStrConstrAppend(&((*urlElements)[cont]),"%s",token);
token=strtok(NULL,"/?");
#ifdef DEBUG
fprintf(stdout,"CaumeDSE Debug: cmeWebServiceParseURL(), element at level %d: '%s'.\n",
*numUrlElements,(*urlElements)[cont]);
#endif
cont++;
}
cmeFree(urlCopy);
return (0);
}
int cmeWebServiceParseKeys(void *cls, enum MHD_ValueKind kind, const char *key, const char *value)
{
int cont=0;
if (kind==MHD_GET_ARGUMENT_KIND)
{
//Jump to last free argumentElements space
while ((((char **)cls)[cont])&&(cont<cmeWSURIMaxArguments)) //We iterate each time for thread safety. No static vars. then.
{
cont+=2;
}
if (cont<cmeWSURIMaxArguments)
{
cmeStrConstrAppend(&(((char **)cls)[cont]),"%s",key);
cmeStrConstrAppend(&(((char **)cls)[cont+1]),"%s",value);
//Note that caller must free each cls[cont]!
}
#ifdef DEBUG
fprintf(stdout,"CaumeDSE Debug: cmeWebServiceParseKeys(), ARGUMENT:, key:%s, value:%s\n", key, value);
#endif
}
//MHD_RESPONSE_HEADER_KIND DEPRECATED in recent versions of libmicrohttpd:
/* else if (kind==MHD_RESPONSE_HEADER_KIND)
{
//Jump to last free responseElements space
while ((((char **)cls)[cont])&&(cont<cmeWSHTTPMaxResponseHeaders)) //We iterate each time for thread safety. No static vars. then.
{
cont+=2;
}
if (cont<cmeWSHTTPMaxResponseHeaders)
{
cmeStrConstrAppend(&(((char **)cls)[cont]),"%s",key);
cmeStrConstrAppend(&(((char **)cls)[cont+1]),"%s",value);
//Note that caller must free each cls[cont]!
}
#ifdef DEBUG
fprintf(stdout,"CaumeDSE Debug: cmeWebServiceParseKeys(), RESPONSE HEADER:, key:%s, value:%s\n", key, value);
#endif
}
*/
else if (kind==MHD_HEADER_KIND)
{
//Jump to last free headerElements space
while ((((char **)cls)[cont])&&(cont<cmeWSHTTPMaxHeaders)) //We iterate each time for thread safety. No static vars. then.
{
cont+=2;
}
if (cont<cmeWSHTTPMaxHeaders)
{
cmeStrConstrAppend(&(((char **)cls)[cont]),"%s",key);
cmeStrConstrAppend(&(((char **)cls)[cont+1]),"%s",value);
//Note that caller must free each cls[cont]!
}
#ifdef DEBUG
fprintf(stdout,"CaumeDSE Debug: cmeWebServiceParseKeys(), HEADER:, key:%s, value:%s\n", key, value);
#endif
}
return MHD_YES;
}
int cmeWebServiceProcessRequest (char **responseText, char **responseFilePath, char ***responseHeaders, int *responseCode,
const char *url, const char **urlElements, int numUrlElements,
const char **headerElements,const char **argumentElements, const char *method,
struct MHD_Connection *connection)
{ //IDD 1.0.21
int cont,result;
int authentication=0;
static int powerStatus=1; //TODO (OHR#5#) Set engine default to 'off'?
char *userId=NULL;
char *orgId=NULL;
char *orgKey=NULL;
char *newOrgKey=NULL;
char *storagePath=NULL;
const union MHD_ConnectionInfo *connectionInfo=NULL;
#define cmeWebServiceProcessRequestFree() \
do { \
cmeFree(userId); \
cmeFree(orgId); \
cmeFree(storagePath); \
if(orgKey) \
{ \
memset(orgKey,0,strlen(orgKey)); \
cmeFree(orgKey); \
} \
if(newOrgKey) \
{ \
memset(newOrgKey,0,strlen(newOrgKey)); \
cmeFree(newOrgKey); \
} \
cmeResultMemTableClean(); \
} while (0); //Local free() macro.
//TODO (OHR#2#): Sanitizing function for all inputs (filter: ",',;,=,`)
if ((numUrlElements==1)&&(strcmp("favicon.ico",urlElements[0])==0)&&(strcmp("GET",method)==0)) //Process favicon.ico; powerStatus='on' not required.
{
#ifdef DEBUG
fprintf(stdout,"CaumeDSE Debug: cmeWebServiceProcessRequest(), client requests "
"favicon.ico.\n");
#endif
cmeWebServiceProcessRequestFree();
cmeStrConstrAppend (responseFilePath,"%sfavicon.ico",cmeDefaultFilePath);
cmeStrConstrAppend(&((*responseHeaders)[0]),"Content-Type");
cmeStrConstrAppend(&((*responseHeaders)[1]),"image/x-icon");
*responseCode=200; //Response: OK
cmeWebServiceProcessRequestFree();
return (0);
}
if (numUrlElements==0) //Error; depth does not match a valid value
{
cmeStrConstrAppend(responseText,"<b>404 ERROR Resource not found.</b><br><br>"
"Resource depth %d. method: '%s', url: '%s'",numUrlElements,method,url);
#ifdef ERROR_LOG
fprintf(stderr,"CaumeDSE Error: cmeWebServiceProcessRequest(). Error, Resource not found."
"Resource depth %d. method: '%s', url: '%s'\n",numUrlElements,method,url);
#endif
cmeWebServiceProcessRequestFree();
*responseCode=404; //Response: Error 404 (resource not found).
return(1);
}
//Get user credentials (parameters userId, orgId, orgKey and newOrgKey).
cont=0;
while ((cont<cmeWSURIMaxArguments)&&(argumentElements[cont]))
{
if (!strcmp(argumentElements[cont],"userId")) //Copy userId.
{
cmeStrConstrAppend(&userId,"%s",argumentElements[cont+1]);
}
else if (!strcmp(argumentElements[cont],"orgId")) //Copy orgId.
{
cmeStrConstrAppend(&orgId,"%s",argumentElements[cont+1]);
}
else if (!strcmp(argumentElements[cont],"orgKey")) //Copy orgKey.
{
cmeStrConstrAppend(&orgKey,"%s",argumentElements[cont+1]);
}
else if (!strcmp(argumentElements[cont],"newOrgKey")) //Copy newOrgKey (this is an optional parameter for POST requests).
{
cmeStrConstrAppend(&newOrgKey,"%s",argumentElements[cont+1]);
}
cont+=2;
}
if ((!userId)||(!orgId)||(!orgKey)) //Error, some essential parameters for the next functions are not included!
{
result=1;
cmeStrConstrAppend(responseText,"<b>401 ERROR Unauthorized. Parameter userId|orgId|orgKey is missing.</b><br>"
"Internal server error number '%d'."
"METHOD: '%s' URL: '%s'."
"Latest IDD version: <code>%s</code>",result,method,url,
cmeInternalDBDefinitionsVersion);
#ifdef DEBUG
fprintf(stdout,"CaumeDSE Debug: cmeWebServiceProcessRequest(), Warning, unauthorized '%d'."
" Method: '%s', URL: '%s' userId, orgId and/or orgKey parameter(s) missing!\n",result,method,url);
#endif
cmeWebServiceProcessRequestFree();
*responseCode=401;
return(2);
}
else //Authenticate and authorize (roles) for requesting user.
{
//AUTHENTICATION PHASE:
if (cmeUseOAUTHAuthentication) //Try OAUTH client authentication.
{
result=1; // TODO (OHR#2#): Add OAUTH authentication mechanism. The engine will still handle the same org. key (e.g. for authenticating owners with OAUTH), but for authorized users different from the owner another layer (e.g. an engine manager) should create another organization with different key and a standard name (e.g. <orgId>_OAUTH), put the authorized user and their permissions within this "temporal organization", and add any resources authorized by the user to this organization. When the OAUTH permissions timeout, the added layer should delete this organization and all associated resources (the engine doesn't store keys, so the added layer must maintain its own indexes).
if (!result) //OAUTH Authentication Successful.
{
authentication+=1;
}
}
connectionInfo=MHD_get_connection_info(connection, MHD_CONNECTION_INFO_PROTOCOL); //Get gnutls connection protocol information.
if ((cmeUseTLSAuthentication)&&(connectionInfo)) //Try TLS client certificate authentication.
{ //NOTE: CA (ca.pem) signs org certificate; org certificate signs user certificate. Client certificate chain must include both org and user certificates!
#ifdef DEBUG
fprintf(stdout,"CaumeDSE Debug: cmeWebServiceProcessRequest(), will try TLS authentication; GnuTLS reports protocol version: %d.\n",
connectionInfo->protocol);
#endif
result=cmeWebServiceClientCertAuth(userId, orgId, connection);
if (!result) //TLS Authentication Successful.
{
authentication+=2;
}
}
else
{
if ((cmeBypassTLSAuthenticationInHTTP)&&(cmeUseTLSAuthentication))
{
#ifdef DEBUG
fprintf(stdout,"CaumeDSE Debug: cmeWebServiceProcessRequest(), WARNING: bypassing TLS authentication in an HTTP session.\n");
#endif
authentication+=4; //If TLS authentication is required but session is not HTTPS/TLS, assume authentication is correct. (For testing purposes only, e.g. HTTP in DEBUG mode)
}
}
if (!authentication) //Error, all authentication methods failed!
{
cmeStrConstrAppend(responseText,"<b>401 User authentication failed!</b><br>"
"METHOD: '%s' URL: '%s'."
" Latest IDD version: <code>%s</code>",method,url,
cmeInternalDBDefinitionsVersion);
#ifdef DEBUG
fprintf(stdout,"CaumeDSE Debug: cmeWebServiceProcessRequest(), User authentication failed."
" Method: '%s', URL: '%s'.\n",method,url);
#endif
cmeWebServiceProcessRequestFree();
*responseCode=401;
return(3);
}
//AUTHORIZATION PHASE:
result=cmeWebServiceConfirmUserId(userId,orgKey);
if (result==1) //System Error, can't open ResourceDB to check userId.
{
cmeStrConstrAppend(responseText,"<b>500 ERROR Internal server error.</b><br>"
"Internal server error number '%d'."
"METHOD: '%s' URL: '%s'."
"Latest IDD version: <code>%s</code>",result,method,url,
cmeInternalDBDefinitionsVersion);
#ifdef ERROR_LOG
fprintf(stderr,"CaumeDSE Error: cmeWebServiceProcessRequest(), Error, internal server error '%d'."
" Method: '%s', URL: '%s', can't open ResourceDB to check userId: %s !\n",result,method,url,userId);
#endif
cmeWebServiceProcessRequestFree();
*responseCode=500;
return(4);
}
else if (result==2) //Error, invalid userId.
{
cmeStrConstrAppend(responseText,"<b>403 ERROR request forbidden for the specified userResourceId</b><br>"
"Internal server error number '%d'."
"METHOD: '%s' URL: '%s'."
"Latest IDD version: <code>%s</code>",result,method,url,
cmeInternalDBDefinitionsVersion);
#ifdef DEBUG
fprintf(stdout,"CaumeDSE Debug: cmeWebServiceProcessRequest(), Warning, '%d'."
" Method: '%s', URL: '%s', can't find userResourceId for userId %s!\n",result,method,url,userId);
#endif
cmeWebServiceProcessRequestFree();
*responseCode=403;
return(5);
}
result=cmeWebServiceConfirmOrgId(orgId,orgKey);
if (result==1) //System Error, can't open ResourceDB to check orgId.
{
cmeStrConstrAppend(responseText,"<b>500 ERROR Internal server error.</b><br>"
"Internal server error number '%d'."
"METHOD: '%s' URL: '%s'."
"Latest IDD version: <code>%s</code>",result,method,url,
cmeInternalDBDefinitionsVersion);
#ifdef ERROR_LOG
fprintf(stderr,"CaumeDSE Error: cmeWebServiceProcessRequest(), Error, internal server error '%d'."
" Method: '%s', URL: '%s', can't open ResourceDB to check orgId: %s !\n",result,method,url,orgId);
#endif
cmeWebServiceProcessRequestFree();
*responseCode=500;
return(6);
}
else if (result==2) //Error, invalid orgId.
{
cmeStrConstrAppend(responseText,"<b>403 ERROR request forbidden for the specified orgResourceId.</b><br>"
"Internal server error number '%d'."
"METHOD: '%s' URL: '%s'."
"Latest IDD version: <code>%s</code>",result,method,url,
cmeInternalDBDefinitionsVersion);
#ifdef DEBUG
fprintf(stdout,"CaumeDSE Debug: cmeWebServiceProcessRequest(), Warning, '%d'."
" Method: '%s', URL: '%s', can't find userResourceId for orgId %s!\n",result,method,url,orgId);
#endif
cmeWebServiceProcessRequestFree();
*responseCode=403;
return(7);
}
result=cmeWebServiceCheckPermissions (method, url, urlElements, numUrlElements,
responseText, responseCode, userId, orgId, orgKey);
if (result) //System Error or authorization error. cmeWebServiceCheckPermissions() already filled in the response text and code.
{
#ifdef DEBUG
fprintf(stdout,"CaumeDSE Debug: cmeWebServiceProcessRequest(), Warning, '%s'."
" Method: '%s', URL: '%s' invalid credentials!\n",*responseText,method,url);
#endif
cmeWebServiceProcessRequestFree();
return(8);
}
}
//Check URL resource parameters:
if ((numUrlElements>2)&&(strcmp(urlElements[0],"organizations")==0)) //We have an organization resource in the URL. Check that it is valid.
{
if (newOrgKey) //check using newOrgKey
{
result=cmeWebServiceConfirmOrgId(urlElements[1],newOrgKey);
}
else //check using orgKey
{
result=cmeWebServiceConfirmOrgId(urlElements[1],orgKey);
}
if (result==1) //System Error, can't open ResourceDB to check orgId.
{
cmeStrConstrAppend(responseText,"<b>500 ERROR Internal server error.</b><br>"
"Internal server error number '%d'."
"METHOD: '%s' URL: '%s'."
"Latest IDD version: <code>%s</code>",result,method,url,
cmeInternalDBDefinitionsVersion);
#ifdef ERROR_LOG
fprintf(stderr,"CaumeDSE Error: cmeWebServiceProcessRequest(), Error, internal server error '%d'."
" Method: '%s', URL: '%s', can't open ResourceDB to check orgResourceId: %s !\n",result,method,url,urlElements[1]);
#endif
cmeWebServiceProcessRequestFree();
*responseCode=500;
return(9);
}
else if (result==2) //Error, invalid organization in URL.
{
cmeStrConstrAppend(responseText,"<b>404 ERROR The organization resource specified in the URL was not found. Check parameters.</b><br>"
"Internal server error number '%d'."
"METHOD: '%s' URL: '%s'."
"Latest IDD version: <code>%s</code>",result,method,url,
cmeInternalDBDefinitionsVersion);
#ifdef DEBUG
fprintf(stdout,"CaumeDSE Error: cmeWebServiceProcessRequest(), Warning, '%d'."
" Method: '%s', URL: '%s', can't find orgResourceId: %s!\n",result,method,url,urlElements[1]);
#endif
cmeWebServiceProcessRequestFree();
*responseCode=404;
return(10);
}
}
if ((numUrlElements>4)&&(strcmp(urlElements[2],"storage")==0))// We have a storage resource in the URL. Check it is valid and get the corresponding storage path.
{
//Get storage path:
if (newOrgKey) //check using newOrgKey
{
result=cmeWebServiceGetStoragePath(&storagePath,urlElements[3],urlElements[1],newOrgKey);
}
else //check using orgKey
{
result=cmeWebServiceGetStoragePath(&storagePath,urlElements[3],urlElements[1],orgKey);
}
if (result==1) //System Error, can't open ResourceDB to check storageId and storagePath.
{
cmeStrConstrAppend(responseText,"<b>500 ERROR Internal server error.</b><br>"
"Internal server error number '%d'."
"METHOD: '%s' URL: '%s'."
"Latest IDD version: <code>%s</code>",result,method,url,
cmeInternalDBDefinitionsVersion);
#ifdef ERROR_LOG
fprintf(stderr,"CaumeDSE Error: cmeWebServiceProcessRequest(), Error, internal server error '%d'."
" Method: '%s', URL: '%s', can't find storageId: %s !\n",result,method,url,urlElements[3]);
#endif
cmeWebServiceProcessRequestFree();
*responseCode=500;
return(11);
}
else if (result==2) //Error, invalid storageId, can't get path.
{
cmeStrConstrAppend(responseText,"<b>404 ERROR The storage resource specified in the URL was not found. Check parameters.</b><br>"
"Internal server error number '%d'."
"METHOD: '%s' URL: '%s'."
"Latest IDD version: <code>%s</code>",result,method,url,
cmeInternalDBDefinitionsVersion);
#ifdef DEBUG
fprintf(stdout,"CaumeDSE Error: cmeWebServiceProcessRequest(), Warning, '%d'."
" Method: '%s', URL: '%s', can't find storageId; can't get storage path of storageId: %s !\n",result,method,url,urlElements[3]);
#endif
cmeWebServiceProcessRequestFree();
*responseCode=404;
return(12);
}
}
if ((numUrlElements>4)&&(strcmp(urlElements[2],"users")==0))// We have a users resource in the URL. Check it is valid.
{
if (newOrgKey) //check using newOrgKey
{
result=cmeWebServiceConfirmUserId(urlElements[3],newOrgKey);
}
else //check using orgKey
{
result=cmeWebServiceConfirmUserId(urlElements[3],orgKey);
}
if (result==1) //System Error, can't open ResourceDB to check userId.
{
cmeStrConstrAppend(responseText,"<b>500 ERROR Internal server error.</b><br>"
"Internal server error number '%d'."
"METHOD: '%s' URL: '%s'."
"Latest IDD version: <code>%s</code>",result,method,url,
cmeInternalDBDefinitionsVersion);
#ifdef ERROR_LOG
fprintf(stderr,"CaumeDSE Error: cmeWebServiceProcessRequest(), Error, internal server error '%d'."
" Method: '%s', URL: '%s', can't open ResourceDB to check userId: %s !\n",result,method,url,urlElements[3]);
#endif
cmeWebServiceProcessRequestFree();
*responseCode=500;
return(13);
}
else if (result==2) //Error, invalid userId.
{
cmeStrConstrAppend(responseText,"<b>404 ERROR The userId specified in the URL was not found. Check parameters.</b><br>"
"Internal server error number '%d'."
"METHOD: '%s' URL: '%s'."
"Latest IDD version: <code>%s</code>",result,method,url,
cmeInternalDBDefinitionsVersion);
#ifdef DEBUG
fprintf(stdout,"CaumeDSE Debug: cmeWebServiceProcessRequest(), Warning, '%d'."
" Method: '%s', URL: '%s', can't the userId specified in the URL: %s!\n",result,method,url,urlElements[3]);
#endif
cmeWebServiceProcessRequestFree();
*responseCode=404;
return(14);
}
}
//Process web service requests:
if ((numUrlElements==1)&&(strcmp(urlElements[0],"engineCommands")==0)) // engine command resource (ignore powerStatus)
{
#ifdef DEBUG
fprintf(stdout,"CaumeDSE Debug: cmeWebServiceProcessRequest(), client requests "
"engine command resource: '%s'. Method: '%s'. Url: '%s'.\n",urlElements[numUrlElements-1],method,url);
#endif
result=cmeWebServiceProcessEngineResource(responseText, responseCode, url, argumentElements, method, &powerStatus);
if (result) //Error, return error code + 100.
{
return(result+100);
}
else
{
return(0);
}
}
//Check engine power status:
else if (!powerStatus) //powerStatus is off
{
cmeStrConstrAppend(responseText,"<b>503 ERROR Engine is off.</b><br><br>Turn engine on "
"using administrator credentials with PUT request: <code>https://{engine}"
"?userId=<admin_userid>&orgId=<admin_orgid>&"
"orgKey=<admin_orgpwd>&setEnginePower=on </code>");
#ifdef ERROR_LOG
fprintf(stderr,"CaumeDSE Error: cmeWebServiceProcessRequest(), Error, Web Services are off; "
"no access to admin. databases for method: %s, url: %s!\n",method,url);
#endif
cmeWebServiceProcessRequestFree();
*responseCode=503; //Response: Error 503 service unavailable.
return(15);
}
//Process trasactions (logs) requests:
else if ((numUrlElements==1)&&(strcmp(urlElements[0],"transactions")==0)) //transaction class resource.
{
#ifdef DEBUG
fprintf(stdout,"CaumeDSE Debug: cmeWebServiceProcessRequest(), client requests "
"engine command resource: '%s'. Method: '%s'. Url: '%s'.\n",urlElements[numUrlElements-1],method,url);
#endif
result=cmeWebServiceProcessTransactionClass(responseText,responseHeaders,responseCode,
url,argumentElements,method);
if (result) //Error, return error code + 100.
{
return(result+100);
}
else
{
return(0);
}
}
//Good so far, now process the URL according to the resource depth level:
else if ((numUrlElements>=1)&&(numUrlElements<=cmeIDDURIMaxDepth)&&(powerStatus)) //organization resource tree.
{ //Check URL depth level an process response accordingly (CME Web Services Definition)
if ((numUrlElements==1)&&(strcmp(urlElements[0],"organizations")==0)) // organization class resource
{
#ifdef DEBUG
fprintf(stdout,"CaumeDSE Debug: cmeWebServiceProcessRequest(), client requests "
"organization class resource: '%s'. Method: '%s'. Url: '%s'.\n",urlElements[numUrlElements-1],method,url);
#endif
result=cmeWebServiceProcessOrgClass (responseText, responseFilePath, responseHeaders, responseCode,
url, argumentElements, method);
if (result) //Error, return error code + 100.
{
return(result+100);
}
else
{
return(0);
}
}
else if ((numUrlElements==2)&&(strcmp(urlElements[0],"organizations")==0))// organization resource
{
#ifdef DEBUG
fprintf(stdout,"CaumeDSE Debug: cmeWebServiceProcessRequest(), client requests "
"organization resource: '%s'. Method: '%s'. Url: '%s'.\n",urlElements[numUrlElements-1],method,url);
#endif
result=cmeWebServiceProcessOrgResource(responseText, responseHeaders, responseCode,
url, urlElements, argumentElements, method);
if (result) //Error, return error code + 100.
{
return(result+100);
}
else
{
return(0);
}
}
else if ((numUrlElements==3)&&(strcmp(urlElements[2],"users")==0))// user class resource
{
#ifdef DEBUG
fprintf(stdout,"CaumeDSE Debug: cmeWebServiceProcessRequest(), client requests "
"user class resource: '%s'. Method: '%s'. Url: '%s'.\n",urlElements[numUrlElements-1],method,url);
#endif
result=cmeWebServiceProcessUserClass(responseText, responseHeaders, responseCode,
url, urlElements, argumentElements, method);
if (result) //Error, return error code + 100.
{
return(result+100);
}
else
{
return(0);
}
}
else if ((numUrlElements==4)&&(strcmp(urlElements[2],"users")==0))// user resource
{
#ifdef DEBUG
fprintf(stdout,"CaumeDSE Debug: cmeWebServiceProcessRequest(), client requests "
"user resource: '%s'. Method: '%s'. Url: '%s'.\n",urlElements[numUrlElements-1],method,url);
#endif
result=cmeWebServiceProcessUserResource(responseText, responseFilePath, responseHeaders, responseCode,
url, urlElements, argumentElements, method);
if (result) //Error, return error code + 100.
{
return(result+100);
}
else
{
return(0);
}
}
else if ((numUrlElements==5)&&(strcmp(urlElements[4],"roleTables")==0))// roleTable class resource
{
#ifdef DEBUG
fprintf(stdout,"CaumeDSE Debug: cmeWebServiceProcessRequest(), client requests "
"roleTable class resource: '%s'. Method: '%s'. Url: '%s'.\n",urlElements[numUrlElements-1],method,url);
#endif
cmeStrConstrAppend(responseText,"<b>403 ERROR No methods are currently available for this resource type.</b><br><br>"
"Resource: '%s'. method: '%s', url: '%s'",urlElements[numUrlElements-1],method,url);
#ifdef ERROR_LOG
fprintf(stderr,"CaumeDSE Error: cmeWebServiceProcessRequest(). Error, no methods are currently available for this resource type."
"Unknown resource: '%s'. Method: '%s', url: '%s'\n",urlElements[numUrlElements-1],method,url);
#endif
cmeWebServiceProcessRequestFree();
*responseCode=403; //Response: Error 404 (resource not found).
return (15);
}
else if ((numUrlElements==6)&&(strcmp(urlElements[4],"roleTables")==0))// roleTable resource
{
#ifdef DEBUG
fprintf(stdout,"CaumeDSE Debug: cmeWebServiceProcessRequest(), client requests "
"roleTable resource: '%s'. Method: '%s'. Url: '%s'.\n",urlElements[numUrlElements-1],method,url);
#endif
result=cmeWebServiceProcessRoleTableResource(responseText, responseFilePath, responseHeaders, responseCode,
url, urlElements, argumentElements, method);
if (result) //Error, return error code + 100.
{
return(result+100);
}
else
{
return(0);
}
}
//TODO (OHR#2#) process storage documentTypes and documents resource tree requests.
else if ((numUrlElements==3)&&(strcmp(urlElements[2],"storage")==0)) //storage class resource
{
#ifdef DEBUG
fprintf(stdout,"CaumeDSE Debug: cmeWebServiceProcessRequest(), client requests "
"storage class resource: '%s'. Method: '%s'. Url: '%s'.\n",urlElements[numUrlElements-1],method,url);
#endif
result=cmeWebServiceProcessStorageClass (responseText, responseHeaders, responseCode,
url, urlElements, argumentElements, method);
if (result) //Error, return error code + 100.
{
return(result+100);
}
else
{
return(0);
}
}
else if ((numUrlElements==4)&&(strcmp(urlElements[2],"storage")==0))// storage resource
{
#ifdef DEBUG
fprintf(stdout,"CaumeDSE Debug: cmeWebServiceProcessRequest(), client requests "
"storage resource: '%s'. Method: '%s'. Url: '%s'.\n",urlElements[numUrlElements-1],method,url);
#endif
result=cmeWebServiceProcessStorageResource(responseText, responseFilePath, responseHeaders, responseCode,
url, urlElements, argumentElements, method);
if (result) //Error, return error code + 100.
{
return(result+100);
}
else
{
return(0);
}
}
else if ((numUrlElements==5)&&(strcmp(urlElements[4],"documentTypes")==0))// documentTypes class resource
{
#ifdef DEBUG
fprintf(stdout,"CaumeDSE Debug: cmeWebServiceProcessRequest(), client requests "
"documentType class resource: '%s'. Method: '%s'. Url: '%s'.\n",urlElements[numUrlElements-1],method,url);
#endif
cmeStrConstrAppend(responseText,"<b>403 ERROR No methods are currently available for this resource type.</b><br><br>"
"Resource: '%s'. method: '%s', url: '%s'",urlElements[numUrlElements-1],method,url);
#ifdef ERROR_LOG
fprintf(stderr,"CaumeDSE Error: cmeWebServiceProcessRequest(). Error, no methods are currently available for this resource type."
"Unknown resource: '%s'. Method: '%s', url: '%s'\n",urlElements[numUrlElements-1],method,url);
#endif
cmeWebServiceProcessRequestFree();
*responseCode=403; //Response: Error 404 (resource not found).
return (16);
}
else if ((numUrlElements==6)&&(strcmp(urlElements[4],"documentTypes")==0)) //documentType resource
{
#ifdef DEBUG
fprintf(stdout,"CaumeDSE Debug: cmeWebServiceProcessRequest(), client requests "
"documentType resource: '%s'. Method: '%s'. Url: '%s'.\n",urlElements[numUrlElements-1],method,url);
#endif
result=cmeWebServiceProcessDocumentTypeResource(responseText, responseFilePath, responseCode,
url, urlElements, argumentElements, method);
if (result) //Error, return error code + 100.
{
return(result+100);
}
else
{