-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathfilehandling.c
1843 lines (1804 loc) · 83.1 KB
/
filehandling.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 (eay@cryptsoft.com).
This product includes software written by
Tim Hudson (tjh@cryptsoft.com).
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 cmeDirectoryExists (const char *dirPath)
{
DIR *dp;
/**TODO (ANY#6#): Add wrappers for corresponding Cloud Storage.
0=local filesystem, 1=GoGrid, 2=RackSpace, 3=AmazonS3,...
**/
if (cmeStorageProvider==0) //Handle common
{
if ((dp = opendir(dirPath)) == NULL)
{
#ifdef ERROR_LOG
fprintf(stderr,"CaumeDSE Error: cmeDirectoryExists(), Error, directory %s doesn't exist,"
"used %d cloud storage definition!\n",dirPath,cmeStorageProvider);
#endif
return(1);
}
}
return(0);
}
int cmeCSVFileRowsToMemTable (const char *fName, char ***elements, int *numCols,
int *processedRows, int hasColNames, int rowStart, int rowEnd)
{
int cont,cont2,cont3;
int elemCont=0;
int rowCont=0;
int flag=0;
int fpEOF=0;
FILE *fp=NULL;
char **colNames=NULL;
char *resStr=NULL;
char defaultColName []="Column_";
char curElement[cmeMaxCSVElemSize];
char curRow[cmeMaxCSVRowSize]; // TODO (OHR#2#): Change to a dynamic memory method to be more efficient and avoid overflows with big tables
if(rowEnd<rowStart) //Error, incorrect start/end row; Rows are inclusive, starting from row 0
//i.e., if rowEnd==rowStart, then that row (one only) is read.
{
#ifdef ERROR_LOG
fprintf(stderr,"CaumeDSE Error: cmeCSVFileRowsToMem(), Error end row to be read"
" %d, is smaller than starting row %d !\n",rowEnd,rowStart);
#endif
return(1);
}
memset(curRow,0,cmeMaxCSVRowSize);
fp=fopen(fName,"r");
if(!fp)
{
#ifdef ERROR_LOG
fprintf(stderr,"CaumeDSE Error: cmeCSVFileRowsToMem(), fopen() Error, can't "
"open CSV file: %s !\n",fName);
#endif
return(2);
}
#ifdef DEBUG
fprintf(stdout,"CaumeDSE Debug: cmeCSVFileRowsToMem(), fopen(), CSV file "
"%s opened for reading.\n",fName);
#endif
resStr=fgets(curRow,cmeMaxCSVRowSize,fp);
cont=0;
cont2=1;
do //Get # of columns
{
if (curRow[cont]==',')
{
cont2++;
}
else if (curRow[cont]=='\"')
{
do
{
cont++;
}while ((cont<(int)strlen(curRow))&&(curRow[cont]!='\"'));
if (cont>=(int)strlen(curRow)) //Error, quoted element not closed
{
#ifdef ERROR_LOG
fprintf(stderr,"CaumeDSE Error: cmeCSVFileRowsToMem(), Error, quoted "
"element not closed at first row, in CSV file: %s !\n",fName);
#endif
fclose(fp);
return (3);
}
}
cont++;
}while (cont<(int)strlen(curRow));
*numCols=cont2;
colNames=(char **)malloc(sizeof(char **) * (*numCols)); //reserve memory for column name pointers
*elements=(char **)malloc(sizeof(char **) * (*numCols) *
(rowEnd-rowStart+2)); //reserve memory for element pointers
rowEnd++; //increment to include header row.
rowStart++;
if (hasColNames) //get Column names from first row first if CSV contains headers in 1st row.
{
if (resStr==NULL) //Error or EOF
{
if (feof(fp)==0) // Error
{
#ifdef ERROR_LOG
fprintf(stderr,"CaumeDSE Error: cmeCSVFileRowsToMem(), fgets() Error, can't "
"read CSV file: %s!\n",fName);
#endif
fclose(fp);
return (4);
}
else //EOF
{
#ifdef ERROR_LOG
fprintf(stderr,"CaumeDSE Error: cmeCSVFileRowsToMem(), fgets() Error, reached "
"EOF prematurely (before getting # of columns), in CSV file: %s!\n",fName);
#endif
fclose(fp);
return(5);
}
}
else //No error, then process column names
{
flag=1;
cont=0;
cont2=0;
cont3=0;
while(flag)
{
cont2=0;
if (curRow[cont]=='\"') //parse quoted element
{
cont++;
while ((curRow[cont]!='\"')&&(cont<(int)strlen(curRow)))
{
curElement[cont2]=curRow[cont];
cont2++;
cont++;
}
if (curRow[cont]!='\"') //error, quoted element not closed
{
#ifdef ERROR_LOG
fprintf(stderr,"CaumeDSE Error: cmeCSVFileToMem(), Error, quoted "
"element not closed at first row (column names), in CSV file: "
" %s !\n",fName);
#endif
fclose(fp);
return(6);
}
else
{
curElement[cont2]='\0';
colNames[cont3]=(char *)malloc(sizeof(char) * (cont2+1)); //reserve memory for column name
memcpy(colNames[cont3],curElement,cont2+1);
cont3++;
while ((curRow[cont]!=',')&&(cont<(int)strlen(curRow))) //Skip to next element
{
cont++;
}
cont++; //go one character after the comma.
}
}
else //parse normal element
{
while ((curRow[cont]!=',')&&(cont<(int)strlen(curRow))&&
(curRow[cont]!='\n')&&(curRow[cont]!='\r'))
{
curElement[cont2]=curRow[cont];
cont2++;
cont++;
}
curElement[cont2]='\0';
colNames[cont3]=(char *)malloc(sizeof(char) * (cont2+1)); //reserve memory for column name
memcpy(colNames[cont3],curElement,cont2+1);
cont3++;
while ((curRow[cont]!=',')&&(cont<(int)strlen(curRow))) //Skip to next element
{
cont++;
}
cont++; //go one character after the comma.
}
if (cont>=(int)strlen(curRow)) //End cycle if end of string has been reached
{
flag=0;
}
}
}
}
else //If CSV file has NO column headers at first row...
{
fseek(fp,0,SEEK_SET); //Rewind to start of file first.
for (cont3=0;cont3<*numCols;cont3++) //Fill in generic names.
{
colNames[cont3]=(char *)malloc(sizeof(char) * cmeMaxCSVDefaultColNameSize); //reserve memory for column name
strcpy(colNames[cont3],defaultColName);
sprintf((colNames[cont3])+7,"%d",cont3);
}
}
for (rowCont=1;rowCont<rowStart;rowCont++) //Skip to starting row.
{
resStr=fgets(curRow,cmeMaxCSVRowSize,fp);
if (feof(fp)) //End of File
{
#ifdef ERROR_LOG
fprintf(stderr,"CaumeDSE Error: cmeCSVFileToMem(), fgets() Error, reached "
"EOF prematurely (before getting to starting row), in CSV file: %s!\n",fName);
#endif
fclose(fp);
return(7);
}
}
*processedRows=0; //Reset counter for number of processed rows.
elemCont=0; //Reset element counter
for (cont=0;cont<*numCols; cont++) //Add column names to table of elements (1st row).
{
(*elements)[cont]=NULL;
cmeStrConstrAppend(&((*elements)[cont]),"%s",colNames[cont]);
//memcpy((*elements)[elemCont],colNames[cont],strlen(colNames[cont]));
elemCont++;
}
for (cont=0; cont<*numCols; cont++) //Free column names.
{
cmeFree(colNames[cont]);
}
cmeFree(colNames);
fpEOF=0;
while ((rowCont<=rowEnd)&&(!fpEOF)) //Process each row.
{
cont=0;
cont2=0;
resStr=fgets(curRow,cmeMaxCSVRowSize,fp); //Read one row.
rowCont++;
if (resStr==NULL) //Error or EOF
{
if (feof(fp)==0) // Error
{
#ifdef ERROR_LOG
fprintf(stderr,"CaumeDSE Error: cmeCSVFileToMem(), fgets() Error, can't "
"read CSV file: %s!\n",fName);
#endif
fclose(fp);
return (8);
}
else //EOF
{
#ifdef DEBUG
fprintf(stdout,"CaumeDSE Debug: cmeCSVFileToMem(), fgets() EOF reached "
"prematurely (before getting to end Row), in CSV file: %s!\n",fName);
#endif
fpEOF=1;
}
}
else
{
flag=1;
while(flag) //Process current row
{
cont2=0;
if (curRow[cont]=='\"') //parse quoted element
{
cont++;
while ((curRow[cont]!='\"')&&(cont<(int)strlen(curRow)))
{
curElement[cont2]=curRow[cont];
cont2++;
cont++;
}
if (curRow[cont]!='\"') //error, quoted element not closed
{
#ifdef ERROR_LOG
fprintf(stderr,"CaumeDSE Error: cmeCSVFileToMem(), Error, quoted "
"element not closed at processed row %d, in CSV file: "
"%s !\n",*processedRows,fName);
#endif
fclose(fp);
return(9);
}
else
{
curElement[cont2]='\0';
(*elements)[elemCont]=(char *)malloc(sizeof(char) *
(cont2+1)); //reserve memory for element
memcpy((*elements)[elemCont],curElement,cont2+1);
elemCont++;
while ((curRow[cont]!=',')&&(cont<(int)strlen(curRow))) //Skip to next element
{
cont++;
}
cont++; //go one character after the comma.
}
}
else //parse normal element
{
while ((curRow[cont]!=',')&&(cont<(int)strlen(curRow))&&
(curRow[cont]!='\n')&&(curRow[cont]!='\r'))
{
curElement[cont2]=curRow[cont];
cont2++;
cont++;
}
curElement[cont2]='\0';
(*elements)[elemCont]=(char *)malloc(sizeof(char) * (cont2+1)); //reserve memory for element
memcpy((*elements)[elemCont],curElement,cont2+1);
elemCont++;
while ((curRow[cont]!=',')&&(cont<(int)strlen(curRow))) //Skip to next element
{
cont++;
}
cont++; //go one character after the comma.
}
if (cont>=(int)strlen(curRow)) //End cycle, if end of string has been reached
{
flag=0;
}
}
(*processedRows)++;
}
}
#ifdef DEBUG
fprintf(stdout,"CaumeDSE Debug: cmeCSVFileToMem(), processed %d rows "
"(not counting header row, if required), from CSV file: %s!\n",*processedRows,fName);
#endif
fclose(fp);
return (0);
}
int cmeCSVFileRowsToMemTableFinal (char ***elements, int numCols,int processedRows)
{
int cont,cont2;
for (cont2=0; cont2<processedRows; cont2++) //Free elements.
{
for (cont=0; cont<numCols; cont++)
{
cmeFree ((*elements)[cont+(cont2*numCols)]);
}
}
cmeFree(*elements);
return(0);
}
int cmeLoadStrFromFile (char **pDstStr, const char *filePath, int *dstStrLen)
{
int fileLen,readBytes;
FILE *fp=NULL;
fp=fopen(filePath,"r");
if(!fp) //Error
{
#ifdef ERROR_LOG
fprintf(stdout,"CaumeDSE Error: cmeLoadStrFromFile(), can't open file %s for reading!\n",filePath);
#endif
return(1);
}
fseek(fp,0L,SEEK_END);
fileLen=ftell(fp);
rewind(fp);
*pDstStr=(char *)malloc(sizeof(char)*(fileLen+1)); //Note that caller must free *pDstStr!
if (!pDstStr) //Error
{
#ifdef ERROR_LOG
fprintf(stdout,"CaumeDSE Error: cmeLoadStrFromFile(), can't malloc() memory to read file %s, of length %d !\n",
filePath,fileLen);
#endif
fclose(fp);
return(2);
}
readBytes=fread(*pDstStr,1,fileLen,fp);
fclose(fp);
*dstStrLen=readBytes;
if (fileLen!=readBytes) //Error
{
#ifdef ERROR_LOG
fprintf(stdout,"CaumeDSE Error: cmeLoadStrFromFile(), read only %d bytes of %d from file %s!\n",
readBytes,fileLen,filePath);
#endif
return(3);
}
#ifdef DEBUG
fprintf(stdout,"CaumeDSE Debug: cmeLoadStrFromFile(), read %d bytes from file %s, of length %d.\n",
readBytes,filePath,fileLen);
#endif
return(0);
}
int cmeWriteStrToFile (char *pSrcStr, const char *filePath, int srcStrLen)
{
int written;
FILE *fp=NULL;
fp=fopen(filePath,"w");
if(!fp) //Error
{
#ifdef ERROR_LOG
fprintf(stdout,"CaumeDSE Error: cmeWriteStrToFile(), can't open file %s for writing!\n",filePath);
#endif
return(1);
}
if (!pSrcStr) //Error
{
#ifdef ERROR_LOG
fprintf(stdout,"CaumeDSE Error: cmeWriteStrToFile(), pointer to src string is NULL!\n");
#endif
fclose(fp);
return(2);
}
written=fwrite (pSrcStr,1,srcStrLen,fp);
fclose(fp);
if (srcStrLen!=written) //Error
{
#ifdef ERROR_LOG
fprintf(stdout,"CaumeDSE Error: cmeWriteStrToFile(), wrote only %d bytes of %d to file %s!\n",
written,srcStrLen,filePath);
#endif
return(3);
}
#ifdef DEBUG
fprintf(stdout,"CaumeDSE Debug: cmeWriteStrToFile(), wrote %d bytes to file %s, from srcStr of length %d.\n",
written,filePath,srcStrLen);
#endif
return(0);
}
int cmeCSVFileToSecureDB (const char *CSVfName,const int hasColNames,int *numCols,int *processedRows,
const char *userId,const char *orgId,const char *orgKey, const char **attribute,
const char **attributeData, const int numAttribute,const int replaceDB,
const char *resourceInfo, const char *documentType, const char *documentId,
const char *storageId, const char *storagePath)
{
int cont,cont2,cont3,rContLimit,result,readBytes,written;
int numEntries=0;
int totalParts=0;
int rowStart=0;
int numSQLDBfNames=0; //with column slicing this will be (*numcols)*((((*processedRows)/cmeMaxCSVRowsInPart))+(((*processedRows)%cmeMaxCSVRowsInPart > 0)? 1 : 0 ))
int cycleProcessedRows=0;
int rowEnd=cmeCSVRowBuffer-1;
sqlite3 **ppDB=NULL;
sqlite3 *resourcesDB=NULL;
char **elements=NULL; //Note: elements will be freed via the special function cmeCSVFileRowsToMemTableFinal() within the corresponding loop; it is not included in cmeCSVFileToSecureDBFree()
char **SQLDBfNames=NULL; //Will hold the name of each file part.
char **SQLDBfMACs=NULL; //Will hold the MAC of each file part.
char **SQLDBfSalts=NULL; //Will hold the salt of each file part.
char **colNames=NULL;
char *currentRawFileContent=NULL; //Will hold the binary contents of each created file part during the hashing process.
char *resourcesDBName=NULL;
char *sqlQuery=NULL;
char *value=NULL; //Just a pointer to elements within elements[]. No need to free.
char *bkpFName=NULL;
char *securedRowOrder=NULL;
char *securedValue=NULL;
char *MAC=NULL; //'data' table values depending on attributes selected.
char *salt=NULL;
char *MACProtected=NULL;
char *sign=NULL;
char *signProtected=NULL;
char *otphDkey=NULL;
char *sanitizedStr=NULL;
const char *nullParam="";
const char resourcesDBFName[]="ResourcesDB";
#define cmeCSVFileToSecureDBFree() \
do { \
cmeFree(resourcesDBName); \
cmeFree(sqlQuery); \
cmeFree(bkpFName); \
cmeFree(securedRowOrder); \
cmeFree(securedValue); \
cmeFree(MAC); \
cmeFree(salt); \
cmeFree(MACProtected); \
cmeFree(sign); \
cmeFree(signProtected); \
cmeFree(otphDkey); \
cmeFree(currentRawFileContent); \
cmeFree(sanitizedStr); \
if (resourcesDB) \
{ \
cmeDBClose(resourcesDB); \
resourcesDB=NULL; \
} \
if (ppDB) \
{ \
for (cont=0;cont<(*numCols);cont++) \
{ \
cmeDBClose(ppDB[cont]); \
ppDB[cont]=NULL; \
} \
cmeFree(ppDB); \
} \
if (SQLDBfNames) \
{ \
for (cont=0;cont<numSQLDBfNames;cont++) \
{ \
cmeFree(SQLDBfNames[cont]); \
} \
cmeFree(SQLDBfNames); \
} \
if (SQLDBfMACs) \
{ \
for (cont=0;cont<numSQLDBfNames;cont++) \
{ \
cmeFree(SQLDBfMACs[cont]); \
} \
cmeFree(SQLDBfMACs); \
} \
if (SQLDBfSalts) \
{ \
for (cont=0;cont<numSQLDBfNames;cont++) \
{ \
cmeFree(SQLDBfSalts[cont]); \
} \
cmeFree(SQLDBfSalts); \
} \
if (colNames) \
{ \
for (cont=0;cont<(*numCols);cont++) \
{ \
cmeFree(colNames[cont]); \
} \
cmeFree(colNames); \
} \
} while (0); //Local free() macro.
cmeStrConstrAppend(&resourcesDBName,"%s%s",cmeDefaultFilePath,resourcesDBFName);
result=cmeDBOpen(resourcesDBName,&resourcesDB);
if (result) //Error
{
cmeCSVFileToSecureDBFree();
return(1);
}
result=cmeExistsDocumentId(resourcesDB,documentId,orgKey,&numEntries);
if (numEntries>0) //We have the same documentId already in the database...
{
#ifdef DEBUG
fprintf(stdout,"CaumeDSE Debug: cmeCVSFileToSecureDB(), documentId %s already exists; "
"replace instruction: %d\n",documentId,replaceDB);
#endif
if (!replaceDB)
{
cmeCSVFileToSecureDBFree();
return(3);
}
else //delete old secureDB first, and then replace
{
result=cmeDeleteSecureDB(resourcesDB,documentId,orgKey,storagePath);
}
}
cmeDBClose(resourcesDB);
resourcesDB=NULL;
*numCols=0; //Set default results
*processedRows=0;
do
{
result=cmeCSVFileRowsToMemTable(CSVfName, &elements, numCols, &cycleProcessedRows, hasColNames, rowStart, rowEnd);
if(result) //Error
{
#ifdef ERROR_LOG
fprintf(stderr,"CaumeDSE Error: cmeCVSFileToSecureDB(), cmeCSVFileRowsToMem() Error, can't "
"open CSV file: %s !\n",CSVfName);
#endif
cmeCSVFileToSecureDBFree();
return(4);
}
if (colNames) //If not the first cycle, free colNames (which will also set to NULL all ptrs.)
{
for (cont=0;cont<(*numCols);cont++)
{
cmeFree(colNames[cont]);
}
cmeFree(colNames);
}
colNames=(char **)malloc((sizeof(char *)) * (*numCols)); //Reserve space and copy column names.
for (cont=0;cont<(*numCols);cont++)
{
colNames[cont]=NULL; //Set all ptrs. to NULL as required by cmeStrConstrAppend().
if(!strcmp(elements[cont],"id")) //Found column named "id"!
{
cmeStrConstrAppend(&(colNames[cont]),"_id"); //"id" name is reserved for internal databases; so we change it!
}
else //Otherwise, just copy the column name provided.
{
cmeStrConstrAppend(&(colNames[cont]),"%s",elements[cont]);
}
}
// TODO (OHR#6#): Create & call function to create DB files in memory for CSV column imports.
if (!(SQLDBfNames)) //Create (and open) DB files in memory if they have not been created.
{
totalParts=((cycleProcessedRows/cmeMaxCSVRowsInPart)+((cycleProcessedRows%cmeMaxCSVRowsInPart > 0)? 1 : 0 ));
numSQLDBfNames=(*numCols)*totalParts;
ppDB=(sqlite3 **)malloc(sizeof(sqlite3 *)*numSQLDBfNames);
if (!ppDB)
{
cmeCSVFileToSecureDBFree();
return(5);
}
SQLDBfNames=(char **)malloc(sizeof(char *)*numSQLDBfNames);
SQLDBfMACs=(char **)malloc(sizeof(char *)*numSQLDBfNames);
SQLDBfSalts=(char **)malloc(sizeof(char *)*numSQLDBfNames);
if ((!SQLDBfNames)||(!SQLDBfMACs)||(!SQLDBfSalts))
{
cmeCSVFileToSecureDBFree();
return(6);
}
for(cont=0;cont<numSQLDBfNames;cont++) //Reset memory pointers
{
SQLDBfNames[cont]=NULL;
SQLDBfMACs[cont]=NULL;
SQLDBfSalts[cont]=NULL;
cmeGetRndSaltAnySize(&(SQLDBfSalts[cont]),cmeDefaultValueSaltLen); //Get current salt for encryption (random hexstr).
}
for (cont=0;cont<numSQLDBfNames;cont++) //Create random filenames for column parts.
{
cmeGetRndSalt(&(SQLDBfNames[cont]));
//TODO (OHR#8#): Create SQLDBfNames collision handling routine. Just in case.
if (cmeDBCreateOpen(":memory:",&(ppDB[cont])))
{
#ifdef ERROR_LOG
fprintf(stderr,"CaumeDSE Error: cmeCVSFileToSecureSQL(), cmeDBCreateOpen() Error, can't "
"Create and Open memory DB corresponding to DB file: %s !\n",SQLDBfNames[cont]);
#endif
cmeCSVFileToSecureDBFree();
return(7);
}
cmeStrConstrAppend(&sqlQuery,"BEGIN TRANSACTION; CREATE TABLE data "
"(id INTEGER PRIMARY KEY, userId TEXT, orgId TEXT, salt TEXT,"
" value TEXT, rowOrder TEXT, MAC TEXT, sign TEXT, MACProtected TEXT,"
" signProtected TEXT, otphDkey TEXT);"
"COMMIT;");
if (cmeSQLRows((ppDB[cont]),sqlQuery,NULL,NULL)) //Create a table 'data'.
{
#ifdef ERROR_LOG
fprintf(stderr,"CaumeDSE Error: cmeCVSFileToSecureSQL(), cmeSQLRows() Error, can't "
"create table 'data' in DB file %d: %s!\n",cont,SQLDBfNames[cont]);
#endif
cmeCSVFileToSecureDBFree();
return(9);
}
cmeFree(sqlQuery); //Free memory that was used for queries.
cmeStrConstrAppend(&sqlQuery,"BEGIN TRANSACTION; CREATE TABLE meta "
"(id INTEGER PRIMARY KEY, userId TEXT, orgID TEXT, salt TEXT,"
" attribute TEXT, attributeData TEXT); COMMIT;");
if (cmeSQLRows((ppDB[cont]),sqlQuery,NULL,NULL)) //Create a table 'meta'.
{
#ifdef ERROR_LOG
fprintf(stderr,"CaumeDSE Error: cmeCVSFileToSecureSQL(), cmeSQLRows() Error, can't "
"create table 'meta' in DB file %d: %s!\n",cont,SQLDBfNames[cont]);
#endif
cmeCSVFileToSecureDBFree();
return(11);
}
cmeFree(sqlQuery); //Free memory that was used for queries.
}
for (cont=0;cont<numSQLDBfNames;cont++) //Insert data into meta table.
{ //Insert 'name' attribute.
cmeStrConstrAppend(&sqlQuery,"BEGIN TRANSACTION; "
"INSERT INTO meta (id, userId, orgId, attribute, attributeData) "
"VALUES (NULL");
cmeFree(sanitizedStr);
cmeSanitizeStrForSQL(userId,&sanitizedStr); //Sanitize parameter userId for use in SQL statement.
cmeStrConstrAppend(&sqlQuery,",'%s'",sanitizedStr);
cmeFree(sanitizedStr);
cmeSanitizeStrForSQL(orgId,&sanitizedStr); //Sanitize parameter orgId for use in SQL statement.
cmeStrConstrAppend(&sqlQuery,",'%s'",sanitizedStr);
cmeStrConstrAppend(&sqlQuery,",'name'"); //Add literal 'name' for attribute.
cmeFree(sanitizedStr);
cmeSanitizeStrForSQL(colNames[cont%(*numCols)],&sanitizedStr); //Sanitize parameter attributeData for use in SQL statement.
cmeStrConstrAppend(&sqlQuery,",'%s'",sanitizedStr);
cmeStrConstrAppend(&sqlQuery,");"); //End sql statement string.
cmeStrConstrAppend(&salt,"%s",nullParam); //Salt will be calculated and included in cmeMemSecureDBProtect()
for (cont2=0; cont2<numAttribute; cont2++) //Append other security attributes.
{
cmeStrConstrAppend(&sqlQuery,"INSERT INTO meta (id, userId, orgId, salt, attribute, attributeData) "
"VALUES (NULL");
cmeFree(sanitizedStr);
cmeSanitizeStrForSQL(userId,&sanitizedStr); //Sanitize parameter userId for use in SQL statement.
cmeStrConstrAppend(&sqlQuery,",'%s'",sanitizedStr);
cmeFree(sanitizedStr);
cmeSanitizeStrForSQL(orgId,&sanitizedStr); //Sanitize parameter orgId for use in SQL statement.
cmeStrConstrAppend(&sqlQuery,",'%s'",sanitizedStr);
cmeStrConstrAppend(&sqlQuery,",'%s'",salt); //Add literal salt.
cmeFree(sanitizedStr);
cmeSanitizeStrForSQL(attribute[cont2],&sanitizedStr); //Sanitize parameter attribute for use in SQL statement.
cmeStrConstrAppend(&sqlQuery,",'%s'",sanitizedStr);
cmeFree(sanitizedStr);
cmeSanitizeStrForSQL(attributeData[cont2],&sanitizedStr); //Sanitize parameter attributeData for use in SQL statement.
cmeStrConstrAppend(&sqlQuery,",'%s'",sanitizedStr);
cmeStrConstrAppend(&sqlQuery,");"); //End sql statement string.
}
cmeFree(salt);
cmeStrConstrAppend(&sqlQuery,"COMMIT;");
if (cmeSQLRows((ppDB[cont]),sqlQuery,NULL,NULL)) //Insert row.
{
#ifdef ERROR_LOG
fprintf(stderr,"CaumeDSE Error: cmeCVSFileToSecureSQL(), cmeSQLRows() Error, can't "
"insert row in DB file %d: %s!\n",cont,SQLDBfNames[cont]);
#endif
cmeCSVFileToSecureDBFree();
return(17);
}
cmeFree(sqlQuery); //Free memory that was used for queries.
}
}
//TODO (OHR#6#): Create and call function to insert data into tables (move code there).
for (cont=0;cont<totalParts;cont++) //Process each column part.
{
for (cont2=0;cont2<(*numCols);cont2++) //Process each column.
{
if ((cont+1)*cmeMaxCSVRowsInPart>cycleProcessedRows) // Last part? yes-> then set rContLimit to the remaining rows.
{
rContLimit=cycleProcessedRows-(cont*cmeMaxCSVRowsInPart);
}
else
{
rContLimit=(cycleProcessedRows>cmeMaxCSVRowsInPart)?cmeMaxCSVRowsInPart:cycleProcessedRows;
}
for(cont3=1;cont3<=rContLimit;cont3++) //Skip header row in elements[]; process each row.
{
value=elements[cont2+((*numCols)*(cont3+cont*cmeMaxCSVRowsInPart))];
//Setup attribute defaults.
cmeStrConstrAppend(&securedRowOrder,"%d",cont3+rowStart+cont*cmeMaxCSVRowsInPart);
cmeStrConstrAppend(&MAC,"%s",nullParam); // TODO (OHR#2#): Calculate MAC, MAC protected and stuff. Probably outside this function.
cmeStrConstrAppend(&MACProtected,"%s",nullParam);
cmeStrConstrAppend(&sign,"%s",nullParam);
cmeStrConstrAppend(&signProtected,"%s",nullParam);
cmeStrConstrAppend(&otphDkey,"%s",nullParam);
cmeStrConstrAppend(&salt,"%s",nullParam); //Salt wil be included in cmeMemSecureDBProtect().
cmeStrConstrAppend(&sqlQuery,"BEGIN TRANSACTION; INSERT INTO data "
"(id,userId,orgId,salt,value,rowOrder,MAC,sign,MACProtected,signProtected,otphDkey)"
" VALUES (NULL");
cmeFree(sanitizedStr);
cmeSanitizeStrForSQL(userId,&sanitizedStr); //Sanitize parameter userId for use in SQL statement.
cmeStrConstrAppend(&sqlQuery,",'%s'",sanitizedStr);
cmeFree(sanitizedStr);
cmeSanitizeStrForSQL(orgId,&sanitizedStr); //Sanitize parameter orgId for use in SQL statement.
cmeStrConstrAppend(&sqlQuery,",'%s'",sanitizedStr);
cmeStrConstrAppend(&sqlQuery,",'%s'",salt); //Add literal salt.
cmeFree(sanitizedStr);
cmeSanitizeStrForSQL(value,&sanitizedStr); //Sanitize parameter value for use in SQL statement.
cmeStrConstrAppend(&sqlQuery,",'%s'",sanitizedStr);
cmeStrConstrAppend(&sqlQuery,",'%s','%s','%s','%s','%s','%s');" //Add remaining parameters.
"COMMIT;",securedRowOrder,MAC,sign,
MACProtected,signProtected,otphDkey);
//Free stuff;
cmeFree(salt);
cmeFree(otphDkey);
cmeFree(signProtected);
cmeFree(sign);
cmeFree(MACProtected);
cmeFree(MAC);
cmeFree(securedRowOrder);
if (cmeSQLRows((ppDB[(*numCols)*cont+cont2]),sqlQuery,NULL,NULL)) //Insert row.
{
#ifdef ERROR_LOG
fprintf(stderr,"CaumeDSE Error: cmeCVSFileToSecureSQL(), cmeSQLRows() Error, can't "
"insert row in DB file %d: %s!\n",cont,SQLDBfNames[cont]);
#endif
cmeCSVFileToSecureDBFree();
return(13);
}
cmeFree(sqlQuery); //Free memory that was used for queries.
}
}
}
rowStart+=cmeCSVRowBuffer; //Process next block of rows.
rowEnd+=cmeCSVRowBuffer;
cmeCSVFileRowsToMemTableFinal(&elements,*numCols,cycleProcessedRows); //Free element table
*processedRows+=cycleProcessedRows;
} while (cycleProcessedRows==cmeCSVRowBuffer);
for (cont=0; cont<numSQLDBfNames; cont++) //Create backup DB files; copy Memory DBs there.
{
if (numAttribute) //If security attributes are defined, override corresponding defaults.
{
result=cmeMemSecureDBProtect(ppDB[cont],orgKey);
cmeStrConstrAppend(&sqlQuery,"VACUUM;"); //Reconstruct DB without slack space w/ unprotected data!
if (cmeSQLRows((ppDB[cont]),sqlQuery,NULL,NULL)) //Vacuum DB col.
{
#ifdef ERROR_LOG
fprintf(stderr,"CaumeDSE Error: cmeCVSFileToSecureSQL(), cmeSQLRows() Error, can't "
"VACUUM DB file %d: %s!\n",cont,SQLDBfNames[cont]);
#endif
cmeCSVFileToSecureDBFree();
return(14);
}
cmeFree(sqlQuery); //Free memory that was used for queries.
}
cmeFree(bkpFName);
cmeStrConstrAppend(&bkpFName,"%s%s",storagePath,SQLDBfNames[cont]);
result=cmeMemDBLoadOrSave(ppDB[cont],bkpFName,1);
if (result)
{
#ifdef ERROR_LOG
fprintf(stderr,"CaumeDSE Error: cmeCVSFileToSecureSQL(), cmeMemDBLoadOrSave() error cannot "
"load/save file: %s; Save: %d!\n",bkpFName,1);
#endif
cmeCSVFileToSecureDBFree();
return(15);
}
//Get MAC of recently created file:
result=cmeLoadStrFromFile(¤tRawFileContent,bkpFName,&readBytes);
if (result)
{
#ifdef ERROR_LOG
fprintf(stderr,"CaumeDSE Error: cmeCVSFileToSecureSQL(), cmeLoadStrFromFile() error cannot "
"load recently created file part: %s !\n",bkpFName);
#endif
cmeCSVFileToSecureDBFree();
return(16);
}
result=cmeHMACByteString((const unsigned char *)currentRawFileContent,(unsigned char **)&(SQLDBfMACs[cont]),readBytes,&written,cmeDefaultMACAlg,&(SQLDBfSalts[cont]),orgKey);
cmeFree(currentRawFileContent);
cmeFree(bkpFName);
}
result=cmeRegisterSecureDBorFile ((const char **)SQLDBfNames, numSQLDBfNames,(const char **)SQLDBfSalts, (const char **)SQLDBfMACs,totalParts,orgKey, userId, orgId, resourceInfo,
documentType,documentId,storageId,orgId);
if (result) //error
{
#ifdef ERROR_LOG
fprintf(stderr,"CaumeDSE Error: cmeCVSFileToSecureSQL(), cmeRegisterSecureDB() error cannot "
"register documentId %s with documentType %s; Error#: %d!\n",documentId,documentType,result);
#endif
cmeCSVFileToSecureDBFree();
return(17);
}
cmeCSVFileToSecureDBFree();
return (0);
}
int cmeRAWFileToSecureFile (const char *rawFileName, const char *userId,const char *orgId,const char *orgKey,
const char *resourceInfo, const char *documentType, const char *documentId,
const char *storageId, const char *storagePath)
{ //IDD v.1.0.21
int cont,result,written,written2,lastPartSize;
int bufferLen=0;
int numParts=0;
int tmpMemDataLen=0; //This will contain the size in bytes of the data read in memory from file.
char *tmpMemDataBuffer=NULL; //This will point to reserved memory that will hold the file data.
char *tmpMemCiphertext=NULL; //This will hold the encrypted data.
char *tmpMemB64Ciphertext=NULL; //This will hold the B64 encoded version of the encrypted data.
char *currentFilePartPath=NULL; //This will hold the whole file path for the current file part.
const char *pFilePartStart=NULL; //This will point to the start of each file slice (no need to free this ptr).
char **filePartNames=NULL; //This will hold the random file part names.
char **filePartMACs=NULL; //This will hold the MACs for all file parts.
char **filePartSalts=NULL; //This will hold the salts for all file parts.
#define cmeRAWFileToSecureFileFree() \
do { \
cmeFree(tmpMemDataBuffer); \
cmeFree(tmpMemCiphertext); \
cmeFree(tmpMemB64Ciphertext); \
cmeFree(currentFilePartPath); \
if (filePartNames) \
{ \
for (cont=0;cont<numParts;cont++) \
{ \
cmeFree(filePartNames[cont]); \
} \
cmeFree(filePartNames); \
} \
if (filePartMACs) \
{ \
for (cont=0;cont<numParts;cont++) \
{ \
cmeFree(filePartMACs[cont]); \
} \
cmeFree(filePartMACs); \
} \
if (filePartSalts) \
{ \
for (cont=0;cont<numParts;cont++) \
{ \
cmeFree(filePartSalts[cont]); \
} \
cmeFree(filePartSalts); \
} \
} while (0); //Local free() macro.
result=cmeLoadStrFromFile(&tmpMemDataBuffer,rawFileName,&tmpMemDataLen); //Read file into memory
if (result) //Error reading file into memory.
{
#ifdef ERROR_LOG
fprintf(stderr,"CaumeDSE Error: cmeRAWFileToSecureFile(), cmeLoadStrFromFile() error cannot "
"read raw file: %s !\n",rawFileName);
#endif
cmeRAWFileToSecureFileFree();
return(1);
}
numParts=tmpMemDataLen/cmeMaxRAWDataInPart;
lastPartSize=tmpMemDataLen%cmeMaxRAWDataInPart;
if (lastPartSize) // We have a remainder
{
numParts++;
}
filePartNames=(char **)malloc(sizeof(char *)*numParts); //Reserve memory for file part name pointers.
filePartMACs=(char **)malloc(sizeof(char *)*numParts); //Reserve memory for file part MAC pointers.
filePartSalts=(char **)malloc(sizeof(char *)*numParts); //Reserve memory for file part salt pointers.
for(cont=0;cont<numParts; cont++) // Initialize pointers.
{
filePartMACs[cont]=NULL;
filePartNames[cont]=NULL;
filePartSalts[cont]=NULL;
cmeGetRndSalt(&(filePartNames[cont])); //Get current file name (random hexstr).
cmeGetRndSaltAnySize(&(filePartSalts[cont]),cmeDefaultValueSaltLen); //Get current salt for encryption (random hexstr).
}
for (cont=0;cont<numParts;cont++)// Slice file in parts - analogous to column parts in secureDB for CSVs.
{
cmeStrConstrAppend(¤tFilePartPath,"%s%s",storagePath,filePartNames[cont]);
pFilePartStart=&(tmpMemDataBuffer[cont*cmeMaxRAWDataInPart]); //Point to beginning of file part.
if ((cont+1)==numParts) //If this is the last part.
{
bufferLen=lastPartSize;
}
else //Not the last part.
{
bufferLen=cmeMaxRAWDataInPart;
}
//Protect memory data with orgKey and default encryption algorithm:
result=cmeProtectByteString(pFilePartStart,&tmpMemB64Ciphertext,cmeDefaultEncAlg,&(filePartSalts[cont]),orgKey,
&written,bufferLen);
if (result) //Error protecting data in memory
{
#ifdef ERROR_LOG
fprintf(stderr,"CaumeDSE Error: cmeRAWFileToSecureFile(), cmeProtectByteString() error cannot "
"protect file part number %d, with algorithm %s !\n",cont,cmeDefaultEncAlg);
#endif
cmeRAWFileToSecureFileFree();
return(2);
}
cmeWriteStrToFile(tmpMemB64Ciphertext,currentFilePartPath,written); //Write encrypted data to currentFilePartPath file.
cmeHMACByteString((const unsigned char *)tmpMemB64Ciphertext,(unsigned char **)&(filePartMACs[cont]),written,&written2,
cmeDefaultHshAlg,&(filePartSalts[cont]),orgKey); //Calculate MAC on file part in memory.
cmeFree(tmpMemB64Ciphertext); //Free B64 encoded, encryptede data; we don't need it any more.
cmeFree(currentFilePartPath);
}
//Register parts as a secure file in engine DBs
result=cmeRegisterSecureDBorFile ((const char **)filePartNames,numParts,(const char **)filePartSalts,(const char **)filePartMACs,
numParts,orgKey,userId,orgId,resourceInfo,documentType,documentId,storageId,orgId);
if (result)//Error
{
cmeRAWFileToSecureFileFree();
return(4);
}
cmeRAWFileToSecureFileFree();
return (0);
}
int cmeSecureFileToTmpRAWFile (char **tmpRAWFile, sqlite3 *pResourcesDB,const char *documentId,
const char *documentType, const char *documentPath, const char *orgId,
const char *storageId, const char *orgKey)
{ //IDD v.1.0.21
int cont,cont2,result,written,written2,MACLen;
int numRows=0;
int numCols=0;
int dbNumCols=0;
int partMACmismatch=0;
FILE *fpTmpRAWFile=NULL;
int *memFilePartsOrder=NULL; //Dynamic array to store the corresponding order of the file part.
int *memFilePartsDataSize=NULL; //Dynamic array to store the corresponding size in bytes, of the file part.
char **memFilePartsData=NULL; //Dynamic array to store unencrypted data of each part of the protected file.
char **queryResult=NULL;
char **colSQLDBfNames=NULL; //Dynamic array to store part filenames of the protected RAWFile.