forked from ChatScript/ChatScript
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathos.cpp
More file actions
2205 lines (2033 loc) · 71.5 KB
/
os.cpp
File metadata and controls
2205 lines (2033 loc) · 71.5 KB
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
#include "common.h"
#ifdef SAFETIME // some time routines are not thread safe (not relevant with EVSERVER)
#include <mutex>
static std::mutex mtx;
#endif
int loglimit = 0;
int ide = 0;
bool idestop = false;
bool idekey = false;
bool inputAvailable = false;
static char encryptUser[200];
static char encryptLTM[200];
static char logLastCharacter = 0;
#define MAX_STRING_SPACE 100000000 // transient+heap space 100MB
size_t maxHeapBytes = MAX_STRING_SPACE;
char* heapBase; // start of heap space (runs backward)
char* heapFree; // current free string ptr
char* stackFree;
char* infiniteCaller = "";
char* stackStart;
char* heapEnd;
static bool infiniteStack = false;
bool userEncrypt = false;
bool ltmEncrypt = false;
unsigned long minHeapAvailable;
bool showDepth = false;
char serverLogfileName[200]; // file to log server to
char dbTimeLogfileName[200]; // file to log db time to
char logFilename[MAX_WORD_SIZE]; // file to user log to
bool logUpdated = false; // has logging happened
int logsize = MAX_BUFFER_SIZE;
int outputsize = MAX_BUFFER_SIZE;
char* logmainbuffer = NULL; // where we build a log line
static bool pendingWarning = false; // log entry we are building is a warning message
static bool pendingError = false; // log entry we are building is an error message
int userLog = LOGGING_NOT_SET; // do we log user
int serverLog = LOGGING_NOT_SET; // do we log server
char hide[4000]; // dont log this json field
bool serverPreLog = true; // show what server got BEFORE it works on it
bool serverctrlz = false; // close communication with \0 and ctrlz
bool echo = false; // show log output onto console as well
bool oob = false; // show oob data
bool silent = false; // dont display outputs of chat
bool logged = false;
bool showmem = false;
int filesystemOverride = NORMALFILES;
bool inLog = false;
char* testOutput = NULL; // testing commands output reroute
static char encryptServer[1000];
static char decryptServer[1000];
// buffer information
#define MAX_BUFFER_COUNT 80
unsigned int maxReleaseStack = 0;
unsigned int maxReleaseStackGap = 0xffffffff;
unsigned int maxBufferLimit = MAX_BUFFER_COUNT; // default number of system buffers for AllocateBuffer
unsigned int maxBufferSize = MAX_BUFFER_SIZE; // how big std system buffers from AllocateBuffer should be
unsigned int maxBufferUsed = 0; // worst case buffer use - displayed with :variables
unsigned int bufferIndex = 0; // current allocated index into buffers[]
unsigned baseBufferIndex = 0; // preallocated buffers at start
char* buffers = 0; // collection of output buffers
#define MAX_OVERFLOW_BUFFERS 20
static char* overflowBuffers[MAX_OVERFLOW_BUFFERS]; // malloced extra buffers if base allotment is gone
CALLFRAME* releaseStackDepth[MAX_GLOBAL]; // ReleaseStack at start of depth
static unsigned int overflowLimit = 0;
unsigned int overflowIndex = 0;
USERFILESYSTEM userFileSystem;
static char staticPath[MAX_WORD_SIZE]; // files that never change
static char readPath[MAX_WORD_SIZE]; // readonly files that might be overwritten from outside
static char writePath[MAX_WORD_SIZE]; // files written by app
unsigned int currentFileLine = 0; // line number in file being read
unsigned int maxFileLine = 0; // line number in file being read
unsigned int peekLine = 0;
char currentFilename[MAX_WORD_SIZE]; // name of file being read
// error recover
jmp_buf scriptJump[5];
int jumpIndex = -1;
unsigned int randIndex = 0;
unsigned int oldRandIndex = 0;
#ifdef WIN32
#include <conio.h>
#include <direct.h>
#include <io.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <Winbase.h>
#endif
void Bug()
{
int xx = 0; // a hook to debug bug reports
}
/////////////////////////////////////////////////////////
/// KEYBOARD
/////////////////////////////////////////////////////////
bool KeyReady()
{
if (sourceFile && sourceFile != stdin) return true;
#ifdef WIN32
if (ide) return idekey;
return _kbhit() ? true : false;
#else
bool ready = false;
struct termios oldSettings, newSettings;
if (tcgetattr( fileno( stdin ), &oldSettings ) == -1) return false; // could not get terminal attributes
newSettings = oldSettings;
newSettings.c_lflag &= (~ICANON & ~ECHO);
tcsetattr( fileno( stdin ), TCSANOW, &newSettings );
fd_set set;
struct timeval tv;
tv.tv_sec = 0;
tv.tv_usec = 0;
FD_ZERO( &set );
FD_SET( fileno( stdin ), &set );
int res = select( fileno( stdin )+1, &set, NULL, NULL, &tv );
ready = ( res > 0 );
tcsetattr( fileno( stdin ), TCSANOW, &oldSettings );
return ready;
#endif
}
/////////////////////////////////////////////////////////
/// EXCEPTION/ERROR
/////////////////////////////////////////////////////////
void SafeLock()
{
#ifdef SAFETIME
mtx.lock();
#endif
}
void SafeUnlock()
{
#ifdef SAFETIME
mtx.unlock();
#endif
}
void JumpBack()
{
if (jumpIndex < 0) return; // not under handler control
globalDepth = 0;
longjmp(scriptJump[jumpIndex], 1);
}
void myexit(char* msg, int code)
{
#ifndef DISCARDTESTING
// CheckAbort(msg);
#endif
#ifndef DISCARDPOSTGRES
if (*postgresparams)
{
PostgresShutDown(); // any script connection
PGUserFilesCloseCode(); // filesystem
}
#endif
char name[MAX_WORD_SIZE];
sprintf(name,(char*)"%s/exitlog.txt",logs);
FILE* in = FopenUTF8WriteAppend(name);
if (in)
{
struct tm ptm;
fprintf(in,(char*)"%s %d - called myexit at %s\r\n",msg,code,GetTimeInfo(&ptm,true));
FClose(in);
}
if (code == 0) exit(0);
else exit(EXIT_FAILURE);
}
void mystart(char* msg)
{
char name[MAX_WORD_SIZE];
MakeDirectory(logs);
sprintf(name, (char*)"%s/startlog.txt", logs);
FILE* in = FopenUTF8WriteAppend(name);
char word[MAX_WORD_SIZE];
struct tm ptm;
sprintf(word, (char*)"System startup %s %s\r\n", msg, GetTimeInfo(&ptm, true));
if (in)
{
fprintf(in, (char*)"%s", word);
FClose(in);
}
if (server) Log(SERVERLOG, "%s",word);
}
/////////////////////////////////////////////////////////
/// Fatal Error/signal logging
/////////////////////////////////////////////////////////
#ifdef LINUX
void signalHandler( int signalcode ) {
char word[MAX_WORD_SIZE];
void *array[30];
size_t size;
// get void*'s for all entries on the stack
size = backtrace(array, 30);
// print out all the frames to stderr
sprintf(word, (char*)"Fatal Error: signal code %d\n", signalcode);
Log(SERVERLOG, word);
FILE*fp = FopenUTF8WriteAppend(serverLogfileName);
fseek(fp, 0, SEEK_END);
int fd = fileno(fp);
backtrace_symbols_fd(array, size, fd); //STDERR_FILENO);
fclose(fp);
// terminate program
exit(signalcode);
}
void setSignalHandlers () {
char word[MAX_WORD_SIZE];
struct sigaction sa;
sa.sa_handler = &signalHandler;
sigfillset(&sa.sa_mask); // Block every signal during the handler
// Handle relevant signals
if (sigaction(SIGSEGV, &sa, NULL) == -1) {
sprintf(word, (char*)"Error: cannot handle SIGSEGV");
Log(SERVERLOG, word);
}
if (sigaction(SIGHUP, &sa, NULL) == -1) {
sprintf(word, (char*)"Error: cannot handle SIGHUP");
Log(SERVERLOG, word);
}
if (sigaction(SIGINT, &sa, NULL) == -1) {
sprintf(word, (char*)"Error: cannot handle SIGINT");
Log(SERVERLOG, word);
}
if (sigaction(SIGBUS, &sa, NULL) == -1) {
sprintf(word, (char*)"Error: cannot handle SIGBUS");
Log(SERVERLOG, word);
}
}
#endif
/////////////////////////////////////////////////////////
/// MEMORY SYSTEM
/////////////////////////////////////////////////////////
void ResetBuffers()
{
globalDepth = 0;
bufferIndex = baseBufferIndex;
memset(releaseStackDepth,0,sizeof(releaseStackDepth));
outputNest = oldOutputIndex = 0;
currentRuleOutputBase = currentOutputBase = ourMainOutputBuffer;
currentOutputLimit = outputsize;
}
void CloseBuffers()
{
while (overflowLimit > 0)
{
free(overflowBuffers[--overflowLimit]);
overflowBuffers[overflowLimit] = 0;
}
free(buffers);
buffers = 0;
}
char* AllocateBuffer(char* name)
{// CANNOT USE LOG INSIDE HERE, AS LOG ALLOCATES A BUFFER
char* buffer = buffers + (maxBufferSize * bufferIndex);
if (++bufferIndex >= maxBufferLimit ) // want more than nominally allowed
{
if (bufferIndex > (maxBufferLimit+2) || overflowIndex > 20)
{
char word[MAX_WORD_SIZE];
sprintf(word,(char*)"Corrupt bufferIndex %d or overflowIndex %d\r\n",bufferIndex,overflowIndex);
Log(STDTRACELOG,(char*)"%s\r\n",word);
ReportBug(word);
myexit(word);
}
--bufferIndex;
// try to acquire more space, permanently
if (overflowIndex >= overflowLimit)
{
overflowBuffers[overflowLimit] = (char*) malloc(maxBufferSize);
if (!overflowBuffers[overflowLimit])
{
ReportBug((char*)"FATAL: out of buffers\r\n");
}
overflowLimit++;
if (overflowLimit >= MAX_OVERFLOW_BUFFERS) ReportBug((char*)"FATAL: Out of overflow buffers\r\n");
Log(STDTRACELOG,(char*)"Allocated extra buffer %d\r\n",overflowLimit);
}
buffer = overflowBuffers[overflowIndex++];
}
else if (bufferIndex > maxBufferUsed) maxBufferUsed = bufferIndex;
if (showmem) Log(STDTRACELOG,(char*)"Buffer alloc %d %s\r\n",bufferIndex,name);
*buffer++ = 0; // prior value
*buffer = 0; // empty string
return buffer;
}
void FreeBuffer(char* name)
{
if (showmem) Log(STDTRACELOG,(char*)"Buffer free %d %s\r\n",bufferIndex,name);
if (overflowIndex) --overflowIndex; // keep the dynamically allocated memory for now.
else if (bufferIndex) --bufferIndex;
else ReportBug((char*)"Buffer allocation underflow")
}
void InitStackHeap()
{
size_t size = maxHeapBytes / 64;
size = (size * 64) + 64; // 64 bit align both ends
heapEnd = ((char*) malloc(size)); // point to end
if (!heapEnd)
{
(*printer)((char*)"Out of memory space for text space %d\r\n",(int)size);
ReportBug((char*)"FATAL: Cannot allocate memory space for text %d\r\n",(int)size)
}
heapFree = heapBase = heapEnd + size; // allocate backwards
stackFree = heapEnd;
minHeapAvailable = maxHeapBytes;
stackStart = stackFree;
ClearNumbers();
}
void FreeStackHeap()
{
if (heapEnd)
{
free(heapEnd);
heapEnd = NULL;
}
}
char* AllocateStack(char* word, size_t len,bool localvar,int align) // call with (0,len) to get a buffer
{
if (infiniteStack)
ReportBug("Allocating stack while InfiniteStack in progress from %s\r\n",infiniteCaller);
if (len == 0)
{
if (!word ) return NULL;
len = strlen(word);
}
if (align == 1 || align == 4) // 1 is old true value
{
stackFree += 3;
uint64 x = (uint64)stackFree;
x &= 0xfffffffffffffffc;
stackFree = (char*)x;
}
else if (align == 8)
{
stackFree += 7;
uint64 x = (uint64)stackFree;
x &= 0xfffffffffffffff8;
stackFree = (char*)x;
}
if ((stackFree + len + 1) >= heapFree - 30000000) // dont get close
{
int xx = 0;
}
if ((stackFree + len + 1) >= heapFree - 5000) // dont get close
{
ReportBug((char*)"Out of stack space stringSpace:%d ReleaseStackspace:%d \r\n",heapBase-heapFree,stackFree - stackStart);
return NULL;
}
char* answer = stackFree;
if (localvar) // give hidden data
{
*answer = '`';
answer[1] = '`';
answer += 2;
}
if (word) strncpy(answer,word,len);
else *answer = 0;
answer[len++] = 0;
answer[len++] = 0;
if (localvar) len += 2;
stackFree += len;
len = stackFree - stackStart; // how much stack used are we?
len = heapBase - heapFree; // how much heap used are we?
len = heapFree - stackFree; // size of gap between
if (len < maxReleaseStackGap) maxReleaseStackGap = len;
return answer;
}
void ReleaseStack(char* word)
{
stackFree = word;
}
bool AllocateStackSlot(char* variable)
{
WORDP D = StoreWord(variable,AS_IS);
unsigned int len = sizeof(char*);
if ((stackFree + len + 1) >= (heapFree - 5000)) // dont get close
{
ReportBug((char*)"Out of stack space\r\n")
return false;
}
char* answer = stackFree;
memcpy(answer,&D->w.userValue,sizeof(char*));
if (D->word[1] == LOCALVAR_PREFIX) D->w.userValue = NULL; // autoclear local var
stackFree += sizeof(char*);
len = heapFree - stackFree;
if (len < maxReleaseStackGap) maxReleaseStackGap = len;
return true;
}
char** RestoreStackSlot(char* variable,char** slot)
{
WORDP D = FindWord(variable);
if (!D) return slot; // should never happen, we allocate dict entry on save
memcpy(&D->w.userValue,slot,sizeof(char*));
if (!stricmp(variable, "$_specialty"))
{
int xx = 0;
}
#ifndef DISCARDTESTING
if (debugVar) (*debugVar)(variable, D->w.userValue);
#endif
return ++slot;
}
char* InfiniteStack(char*& limit,char* caller)
{
if (infiniteStack) ReportBug("Allocating InfiniteStack from %s while one already in progress from %s\r\n",caller, infiniteCaller);
infiniteCaller = caller;
infiniteStack = true;
limit = heapFree - 5000; // leave safe margin of error
*stackFree = 0;
return stackFree;
}
char* InfiniteStack64(char*& limit,char* caller)
{
if (infiniteStack) ReportBug("Allocating InfiniteStack from %s while one already in progress from %s\r\n",caller, infiniteCaller);
infiniteCaller = caller;
infiniteStack = true;
limit = heapFree - 5000; // leave safe margin of error
uint64 base = (uint64) (stackFree+7);
base &= 0xFFFFFFFFFFFFFFF8ULL;
return (char*) base; // slop may be lost when allocated finally, but it can be reclaimed later
}
void ReleaseInfiniteStack()
{
infiniteStack = false;
infiniteCaller = "";
}
void CompleteBindStack64(int n,char* base)
{
stackFree = base + ((n+1) * sizeof(FACT*)); // convert infinite allocation to fixed one given element count
size_t len = heapFree - stackFree;
if (len < maxReleaseStackGap) maxReleaseStackGap = len;
infiniteStack = false;
}
void CompleteBindStack()
{
stackFree += strlen(stackFree) + 1; // convert infinite allocation to fixed one
size_t len = heapFree - stackFree;
if (len < maxReleaseStackGap) maxReleaseStackGap = len;
infiniteStack = false;
}
char* Index2Heap(HEAPREF offset)
{
if (!offset) return NULL;
char* ptr = heapBase - offset;
if (ptr < heapFree)
{
ReportBug((char*)"String offset into free space\r\n")
return NULL;
}
if (ptr > heapBase)
{
ReportBug((char*)"String offset before heap space\r\n")
return NULL;
}
return ptr;
}
bool PreallocateHeap(size_t len) // do we have the space
{
char* used = heapFree - len;
if (used <= ((char*)stackFree + 2000))
{
ReportBug("Heap preallocation fails");
return false;
}
return true;
}
bool InHeap(char* ptr)
{
return (ptr >= heapFree && ptr <= heapBase);
}
bool InStack(char* ptr)
{
return (ptr < heapFree && ptr >= stackStart);
}
void ShowMemory(char* label)
{
(*printer)("%s: HeapUsed: %d Gap: %d\r\n", label, heapBase - heapFree,heapFree - stackFree);
}
char* AllocateHeap(char* word,size_t len,int bytes,bool clear, bool purelocal) // BYTES means size of unit
{ // string allocation moves BACKWARDS from end of dictionary space (as do meanings)
/* Allocations during setup as :
2 when setting up cs using current dictionary and livedata for extensions (plurals, comparatives, tenses, canonicals)
3 preserving flags or properties when removing them or adding them while the dictionary is unlocked - only during builds
4 reading strings during dictionary setup
5 assigning meanings or glosses or posconditionsfor the dictionary
6 reading in postag information
---
Allocations happen during volley processing as
1 adding a new dictionary word - all the time on user input
2. saving plan backtrack data
3 altering concepts[] and topics[] lists as a result of a mark operation or normal behavior
4. temps information
5 spellcheck adjusted word in sentence list
6 tokenizing words and quoted stuff adjustments
7. assignment onto user variables
8. JSON reading
*/
len *= bytes; // this many units of this size
if (len == 0)
{
if (!word ) return NULL;
len = strlen(word);
}
if (word) ++len; // null terminate string
if (purelocal) len += 2; // for `` prefix
size_t allocationSize = len;
if (bytes == 1 && dictionaryLocked && !compiling && !loading)
{
allocationSize += ALLOCATESTRING_SIZE_PREFIX + ALLOCATESTRING_SIZE_SAFEMARKER;
// reserve space at front for allocation sizing not in dict items though (variables not in plannning mode can reuse space if prior is big enough)
// initial 2 test area
}
// always allocate in word units
unsigned int allocate = ((allocationSize + 3) / 4) * 4;
heapFree -= allocate; // heap grows lower, stack grows higher til they collide
if (bytes > 4) // force 64bit alignment alignment
{
uint64 base = (uint64) heapFree;
base &= 0xFFFFFFFFFFFFFFF8ULL; // 8 byte align
heapFree = (char*) base;
}
else if (bytes == 4) // force 32bit alignment alignment
{
uint64 base = (uint64) heapFree;
base &= 0xFFFFFFFFFFFFFFFCULL; // 4 byte align
heapFree = (char*) base;
}
else if (bytes == 2) // force 16bit alignment alignment
{
uint64 base = (uint64) heapFree;
base &= 0xFFFFFFFFFFFFFFFEULL; // 2 byte align
heapFree = (char*) base;
}
else if (bytes != 1)
ReportBug((char*)"Allocation of bytes is not std unit %d", bytes);
// create marker
if (bytes == 1 && dictionaryLocked && !compiling && !loading)
{
heapFree[0] = ALLOCATESTRING_MARKER; // we put ff ff just before the sizing data
heapFree[1] = ALLOCATESTRING_MARKER;
}
char* newword = heapFree;
if (bytes == 1 && dictionaryLocked && !compiling && !loading) // store size of allocation to enable potential reuse by $var assign and by wordStarts tokenize
{
newword += ALLOCATESTRING_SIZE_SAFEMARKER;
allocationSize -= ALLOCATESTRING_SIZE_PREFIX + ALLOCATESTRING_SIZE_SAFEMARKER; // includes the end of string marker
if (ALLOCATESTRING_SIZE_PREFIX == 3) *newword++ = (unsigned char)(allocationSize >> 16);
*newword++ = (unsigned char)(allocationSize >> 8) & 0x000000ff;
*newword++ = (unsigned char) (allocationSize & 0x000000ff);
}
int nominalLeft = maxHeapBytes - (heapBase - heapFree);
if ((unsigned long) nominalLeft < minHeapAvailable) minHeapAvailable = nominalLeft;
if ((heapBase-heapFree) > 50000000) // when heap has used up 50Mb
{
int xx = 0;
}
char* used = heapFree - len;
if (used <= ((char*)stackFree + 2000) || nominalLeft < 0)
ReportBug((char*)"FATAL: Out of permanent heap space\r\n")
if (word)
{
if (purelocal) // never use clear true with this
{
*newword++ = LCLVARDATA_PREFIX;
*newword++ = LCLVARDATA_PREFIX;
len -= 2;
}
memcpy(newword,word,--len);
newword[len] = 0;
}
else if (clear) memset(newword,0,len);
return newword;
}
/////////////////////////////////////////////////////////
/// FILE SYSTEM
/////////////////////////////////////////////////////////
int FClose(FILE* file)
{
if (file) fclose(file);
*currentFilename = 0;
return 0;
}
void InitUserFiles()
{
// these are dynamically stored, so CS can be a DLL.
userFileSystem.userCreate = FopenBinaryWrite;
userFileSystem.userOpen = FopenReadWritten;
userFileSystem.userClose = FClose;
userFileSystem.userRead = fread;
userFileSystem.userWrite = fwrite;
userFileSystem.userDelete = FileDelete;
userFileSystem.userDecrypt = NULL;
userFileSystem.userEncrypt = NULL;
filesystemOverride = NORMALFILES;
}
static size_t CleanupCryption(char* buffer,bool decrypt,char* filekind)
{
// clean up answer data: {"datavalues": {"USER": xxxx }}
char* answer = strstr(buffer,filekind);
if (!answer)
{
*buffer = 0;
return 0;
}
answer += strlen(filekind) + 2; // skip USER":
int realsize = jsonOpenSize - (answer-buffer) - 2; // the closing two }
memmove(buffer,answer,realsize); // drop head data
buffer[realsize] = 0; // remove trailing data
// legal json doesnt allow control characters, but we cannot change our file system ones to \r\n because
// we cant tell which are ours and which are users. So we changed to 7f7f coding.
if (decrypt)
{
char* at = buffer-1;
while (*++at)
{
if (*at == 0x7f && at[1] == 0x7f)
{
*at = '\r';
at[1] = '\n';
}
}
}
return realsize;
}
void ProtectNL(char* buffer) // save ascii \r\n in json - only comes from userdata write using them
{
char* at = buffer;
while ((at = strchr(at,'\r'))) // legal convert
{
if (at[1] == '\n' ) // legal convert
{
*at++ = 0x7f;
*at++ = 0x7f;
}
}
}
bool notcrypting = false;
static int JsonOpenCryption(char* buffer, size_t size, char* xserver, bool decrypt,char* filekind)
{
if (size == 0) return 0;
if (notcrypting) return size;
if (decrypt && size > 50) return size; // it was never encrypted, this is original material
char server[1000];
char* id = loginID;
if (*id == 'b' && !id[1]) id = "u-8b02518d-c148-5d45-936b-491d39ced70c"; // cheat override to test outside of kore logins
if (decrypt) sprintf(server, "%s%s/datavalues/decryptedtokens", xserver, id);
else sprintf(server, "%s%s/datavalues/encryptedtokens", xserver, id);
//loginID
// for decryption, the value we are passed is a quoted string. We need to avoid doubling those
#ifdef INFORMATION
// legal json requires these characters be escaped, but we cannot change our file system ones to \r\n because
// we cant tell which are ours and which are users. So we change to 7f7f coding for /r/n.
// and we change to 0x31 for double quote.
\b Backspace (ascii code 08) -- never seeable
\f Form feed (ascii code 0C) -- never seable
\n New line -- only from our user topic write
\r Carriage return -- only from our user topic write
\t Tab -- never seeable
\" Double quote -- seeable in user data
\\ Backslash character -- ??? not expected but possible
UserFile encoding responsible for normal JSON safe data.
Note MongoDB code also encrypts \r\n the same way. but we dont know HERE that mongo is used
and we don't know THERE that encryption was used. That is redundant but minor.
#endif
if (!decrypt) ProtectNL(buffer); // should not alter size
else // remember what we decrypt so we can overwrite it later when we save
{
if (!stricmp(filekind, "USER")) strcpy(encryptUser,buffer);
else strcpy(encryptLTM, buffer);
}
// prepare body for transfer to server to look like this for encryption:
// {"datavalues":{"user": {"data": {"userdata1":"abc"}}}
// or {"datavalues":{"ltm": {"data": {"userdata1":"abc"}}}
// or "{datavalues":{ "user": {"data": {"userdata1":"abc", "token" : "Sy4KoML_e"}}}
// FOR decryption: {"datavalues":{"USER": "HkD_r-KFl"}}
if (decrypt) sprintf(buffer + size, "}}"); // add suffix to data - no quote
else // encrypt gives a token if reusing
{
char* at = buffer + size;
char* which = NULL;
if (!stricmp(filekind, "USER")) which = encryptUser;
else which = encryptLTM;
if (which && *which)
{
sprintf(at,"\",\"token\": %s",which);
at += strlen(at);
}
else
{
*at++ = '"';
}
sprintf(at, "}}}"); // add suffix to data
}
size += strlen(buffer+size);
char url[500];
if (decrypt) sprintf(url, "{\"datavalues\":{\"%s\": ", filekind);
else sprintf(url, "{\"datavalues\":{\"%s\": {\"data\": \"", filekind);
int headerlen = strlen(url);
memmove(buffer+headerlen,buffer,size+1); // move the data over to put in the header
strncpy(buffer,url,headerlen);
// set up call to json open
char header[500];
strcpy(header,"Content-Type: application/json");
int oldArgumentIndex = callArgumentIndex;
int oldArgumentBase = callArgumentBase;
callArgumentBase = callArgumentIndex - 1;
callArgumentList[callArgumentIndex++] = "direct"; // get the text of it gives us, dont make facts out of it
callArgumentList[callArgumentIndex++] = "POST";
strcpy(url,server);
callArgumentList[callArgumentIndex++] = url;
callArgumentList[callArgumentIndex++] = (char*) buffer;
callArgumentList[callArgumentIndex++] = header;
callArgumentList[callArgumentIndex++] = ""; // timer override
FunctionResult result = FAILRULE_BIT;
#ifndef DISCARDJSONOPEN
result = JSONOpenCode((char*) buffer);
#endif
callArgumentIndex = oldArgumentIndex;
callArgumentBase = oldArgumentBase;
if (http_response != 200 || result != NOPROBLEM_BIT)
{
ReportBug("Encrpytion/decryption server failed %s doing %s\r\n",buffer,decrypt ? (char*) "decrypt" : (char*) "encrypt");
return 0;
}
return CleanupCryption((char*) buffer,decrypt,filekind);
}
static size_t Decrypt(void* buffer,size_t size, size_t count, FILE* file,char* filekind)
{
return JsonOpenCryption((char*) buffer, size * count,decryptServer,true,filekind);
}
static size_t Encrypt(const void* buffer, size_t size, size_t count, FILE* file,char* filekind)
{
return JsonOpenCryption((char*) buffer, size * count,encryptServer,false,filekind);
}
void EncryptInit(char* params) // required
{
*encryptServer = 0;
if (*params) strcpy(encryptServer,params);
if (*encryptServer) userFileSystem.userEncrypt = Encrypt;
}
void ResetEncryptTags()
{
encryptUser[0] = 0;
encryptLTM[0] = 0;
}
void DecryptInit(char* params) // required
{
*decryptServer = 0;
if (*params) strcpy(decryptServer,params);
if (*decryptServer) userFileSystem.userDecrypt = Decrypt;
}
void EncryptRestart() // required
{
if (*encryptServer) userFileSystem.userEncrypt = Encrypt; // reestablish encrypt/decrypt bindings
if (*decryptServer) userFileSystem.userDecrypt = Decrypt; // reestablish encrypt/decrypt bindings
}
size_t DecryptableFileRead(void* buffer,size_t size, size_t count, FILE* file,bool decrypt,char* filekind)
{
size_t len = userFileSystem.userRead(buffer,size,count,file);
if (userFileSystem.userDecrypt && decrypt) return userFileSystem.userDecrypt(buffer,1,len,file,filekind); // can revise buffer
return len;
}
size_t EncryptableFileWrite(void* buffer,size_t size, size_t count, FILE* file,bool encrypt,char* filekind)
{
if (userFileSystem.userEncrypt && encrypt)
{
size_t msgsize = userFileSystem.userEncrypt(buffer,size,count,file,filekind); // can revise buffer
return userFileSystem.userWrite(buffer,1,msgsize,file);
}
else return userFileSystem.userWrite(buffer,size,count,file);
}
void CopyFile2File(const char* newname,const char* oldname, bool automaticNumber)
{
char name[MAX_WORD_SIZE];
FILE* out;
if (automaticNumber) // get next number
{
const char* at = strchr(newname,'.'); // get suffix
int len = at - newname;
strncpy(name,newname,len);
strcpy(name,newname); // base part
char* endbase = name + len;
int j = 0;
while (++j)
{
sprintf(endbase,(char*)"%d.%s",j,at+1);
out = FopenReadWritten(name);
if (out) fclose(out);
else break;
}
}
else strcpy(name,newname);
FILE* in = FopenReadWritten(oldname);
if (!in)
{
unlink(name); // kill any old one
return;
}
out = FopenUTF8Write(name);
if (!out) // cannot create
{
return;
}
fseek (in, 0, SEEK_END);
unsigned long size = ftell(in);
fseek (in, 0, SEEK_SET);
char buffer[RECORD_SIZE];
while (size >= RECORD_SIZE)
{
fread(buffer,1,RECORD_SIZE,in);
fwrite(buffer,1,RECORD_SIZE,out);
size -= RECORD_SIZE;
}
if (size > 0)
{
fread(buffer,1,size,in);
fwrite(buffer,1,size,out);
}
fclose(out);
fclose(in);
}
int MakeDirectory(char* directory)
{
int result;
#ifdef WIN32
char word[MAX_WORD_SIZE];
char* path = _getcwd(word,MAX_WORD_SIZE);
strcat(word,(char*)"/");
strcat(word,directory);
if( _access( path, 0 ) == 0 ){ // does directory exist, yes
struct stat status;
stat( path, &status );
if ((status.st_mode & S_IFDIR) != 0) return -1;
}
result = _mkdir(directory);
#else
result = mkdir(directory, 0777);
#endif
return result;
}
void C_Directories(char* x)
{
char word[MAX_WORD_SIZE];
size_t len = MAX_WORD_SIZE;
int bytes;
#ifdef WIN32
bytes = GetModuleFileName(NULL, word, len);
#else
char szTmp[32];
sprintf(szTmp, "/proc/%d/exe", getpid());
bytes = readlink(szTmp, word, len);
#endif
if (bytes >= 0)
{
word[bytes] = 0;
Log(STDTRACELOG,(char*)"execution path: %s\r\n",word);
}
if (GetCurrentDir(word, MAX_WORD_SIZE)) Log(STDTRACELOG,(char*)"current directory path: %s\r\n",word);
Log(STDTRACELOG,(char*)"readPath: %s\r\n",readPath);
Log(STDTRACELOG,(char*)"writeablePath: %s\r\n",writePath);
Log(STDTRACELOG,(char*)"untouchedPath: %s\r\n",staticPath);
}
void InitFileSystem(char* untouchedPath,char* readablePath,char* writeablePath)
{
if (readablePath) strcpy(readPath,readablePath);
else *readPath = 0;
if (writeablePath) strcpy(writePath,writeablePath);
else *writePath = 0;
if (untouchedPath) strcpy(staticPath,untouchedPath);
else *staticPath = 0;
InitUserFiles(); // default init all the io operations to file routines
}
void StartFile(const char* name)
{
if (strnicmp(name,"TMP",3)) maxFileLine = currentFileLine = 0;
strcpy(currentFilename,name); // in case name is simple
char* at = strrchr((char*) name,'/'); // last end of path
if (at) strcpy(currentFilename,at+1);
at = strrchr(currentFilename,'\\'); // windows last end of path
if (at) strcpy(currentFilename,at+1);
}
FILE* FopenStaticReadOnly(const char* name) // static data file read path, never changed (DICT/LIVEDATA/src)
{
StartFile(name);
char path[MAX_WORD_SIZE];
if (*readPath) sprintf(path,(char*)"%s/%s",staticPath,name);
else strcpy(path,name);
return fopen(path,(char*)"rb");
}
FILE* FopenReadOnly(const char* name) // read-only potentially changed data file read path (TOPIC)
{
StartFile(name);
char path[MAX_WORD_SIZE];
if (*readPath) sprintf(path,(char*)"%s/%s",readPath,name);
else strcpy(path,name);
return fopen(path,(char*)"rb");
}
FILE* FopenReadNormal(char* name) // normal C read unrelated to special paths
{
StartFile(name);
return fopen(name,(char*)"rb");
}
void FileDelete(const char* name)
{
}
int FileSize(FILE* in, char* buffer, size_t allowedSize)
{
fseek(in, 0, SEEK_END);
int actualSize = (int) ftell(in);
fseek(in, 0, SEEK_SET);
return actualSize;
}
FILE* FopenBinaryWrite(const char* name) // writeable file path