-
Notifications
You must be signed in to change notification settings - Fork 153
Expand file tree
/
Copy pathutil.cpp
More file actions
1399 lines (1303 loc) · 51.4 KB
/
Copy pathutil.cpp
File metadata and controls
1399 lines (1303 loc) · 51.4 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
// This line will make ftello/fseeko work with 64 bits numbers
#define _FILE_OFFSET_BITS 64
#include "bitfields.h"
#include "defines.h"
#include "dtsc.h"
#include "procs.h"
#include "timing.h"
#include "util.h"
#include "url.h"
#include "urireader.h"
#include <errno.h> // errno, ENOENT, EEXIST
#include <iomanip>
#include <iostream>
#include <sstream>
#include <stdio.h>
#include <sys/stat.h> // stat
#if defined(_WIN32)
#include <direct.h> // _mkdir
#endif
#include <stdlib.h>
#include <sys/resource.h>
#include <fstream>
#define RAXHDR_FIELDOFFSET p[1]
#define RAX_REQDFIELDS_LEN 36
// Converts the given record number into an offset of records after getOffset()'s offset.
// Does no bounds checking whatsoever, allowing access to not-yet-created or already-deleted
// records.
// This access method is stable with changing start/end positions and present record counts,
// because it only
// depends on the record count, which may not change for ring buffers.
#define RECORD_POINTER p + *hdrOffset + (((*hdrRecordCnt)?(recordNo % *hdrRecordCnt) : recordNo) * *hdrRecordSize) + fd.offset
namespace Util{
Util::DataCallback defaultDataCallback;
/// Helper function that cross-platform checks if a given directory exists.
bool isDirectory(const std::string &path){
#if defined(_WIN32)
struct _stat info;
if (_stat(path.c_str(), &info) != 0){return false;}
return (info.st_mode & _S_IFDIR) != 0;
#else
struct stat info;
if (stat(path.c_str(), &info) != 0){return false;}
return (info.st_mode & S_IFDIR) != 0;
#endif
}
bool createPathFor(const std::string &file){
int pos = file.find_last_of('/');
#if defined(_WIN32)
// Windows also supports backslashes as directory separator
if (pos == std::string::npos){pos = file.find_last_of('\\');}
#endif
if (pos == std::string::npos){
return true; // There is no parent
}
// Fail if we cannot create a parent
return createPath(file.substr(0, pos));
}
/// Helper function that will attempt to create the given path if it not yet exists.
/// Returns true if path exists or was successfully created, false otherwise.
bool createPath(const std::string &path){
#if defined(_WIN32)
int ret = _mkdir(path.c_str());
#else
mode_t mode = 0755;
int ret = mkdir(path.c_str(), mode);
#endif
if (ret == 0){// Success!
INFO_MSG("Created directory: %s", path.c_str());
return true;
}
switch (errno){
case ENOENT:{// Parent does not exist
int pos = path.find_last_of('/');
#if defined(_WIN32)
// Windows also supports backslashes as directory separator
if (pos == std::string::npos){pos = path.find_last_of('\\');}
#endif
if (pos == std::string::npos){
// fail if there is no parent
// Theoretically cannot happen, but who knows
FAIL_MSG("Could not create %s: %s", path.c_str(), strerror(errno));
return false;
}
// Fail if we cannot create a parent
if (!createPath(path.substr(0, pos))) return false;
#if defined(_WIN32)
ret = _mkdir(path.c_str());
#else
ret = mkdir(path.c_str(), mode);
#endif
if (ret){FAIL_MSG("Could not create %s: %s", path.c_str(), strerror(errno));}
return (ret == 0);
}
case EEXIST: // Is a file or directory
if (isDirectory(path)){
return true; // All good, already exists
}else{
FAIL_MSG("Not a directory: %s", path.c_str());
return false;
}
default: // Generic failure
FAIL_MSG("Could not create %s: %s", path.c_str(), strerror(errno));
return false;
}
}
bool stringScan(const std::string &src, const std::string &pattern, std::deque<std::string> &result){
result.clear();
std::deque<size_t> positions;
size_t pos = pattern.find("%", 0);
while (pos != std::string::npos){
positions.push_back(pos);
pos = pattern.find("%", pos + 1);
}
if (positions.size() == 0){return false;}
size_t sourcePos = 0;
size_t patternPos = 0;
std::deque<size_t>::iterator posIter = positions.begin();
while (sourcePos != std::string::npos){
// Match first part of the string
if (pattern.substr(patternPos, *posIter - patternPos) != src.substr(sourcePos, *posIter - patternPos)){
break;
}
sourcePos += *posIter - patternPos;
std::deque<size_t>::iterator nxtIter = posIter + 1;
if (nxtIter != positions.end()){
patternPos = *posIter + 2;
size_t tmpPos = src.find(pattern.substr(*posIter + 2, *nxtIter - patternPos), sourcePos);
result.push_back(src.substr(sourcePos, tmpPos - sourcePos));
sourcePos = tmpPos;
}else{
result.push_back(src.substr(sourcePos));
sourcePos = std::string::npos;
}
posIter++;
}
return result.size() == positions.size();
}
void stringToLower(std::string &val){
int i = 0;
while (val[i]){
val.at(i) = tolower(val.at(i));
i++;
}
}
/// Replaces any occurrences of 'from' with 'to' in 'str', returns how many replacements were made
size_t replace(std::string &str, const std::string &from, const std::string &to){
if (from.empty()){return 0;}
size_t counter = 0;
size_t start_pos = 0;
while ((start_pos = str.find(from, start_pos)) != std::string::npos){
str.replace(start_pos, from.length(), to);
++counter;
start_pos += to.length();
}
return counter;
}
/// \brief Removes whitespace from the beginning and end of a given string
void stringTrim(std::string &val){
if (!val.size()){ return; }
uint64_t startPos = 0;
uint64_t length = 0;
// Set startPos to the first character which does not have value 09-13
for (uint64_t i = 0; i < val.size(); i++){
if (val[i] == 32){continue;}
if (val[i] < 9 || val[i] > 13){
startPos = i;
break;
}
}
// Same thing in reverse for endPos
for (uint64_t i = val.size() - 1; i > 0 ; i--){
if (val[i] == 32){continue;}
if (val[i] < 9 || val[i] > 13){
length = i + 1 - startPos;
break;
}
}
val = val.substr(startPos, length);
}
/// \brief splits a string on commas and returns a list of substrings
void splitString(std::string &src, char delim, std::deque<std::string> &result){
result.clear();
std::deque<uint64_t> positions;
uint64_t pos = src.find(delim, 0);
while (pos != std::string::npos){
positions.push_back(pos);
pos = src.find(delim, pos + 1);
}
if (positions.size() == 0){
result.push_back(src);
return;
}
uint64_t prevPos = 0;
for (int i = 0; i < positions.size(); i++) {
if (!prevPos){result.push_back(src.substr(prevPos, positions[i]));}
else{result.push_back(src.substr(prevPos + 1, positions[i] - prevPos - 1));}
prevPos = positions[i];
}
if (prevPos < src.size()){result.push_back(src.substr(prevPos + 1));}
}
/// \brief Connects the given file descriptor to a file or uploader binary
/// \param uri target URL or filepath
/// \param outFile file descriptor which will be used to send data
/// \param append whether to open this connection in truncate or append mode
bool externalWriter(const std::string & uri, int &outFile, bool append){
HTTP::URL target = HTTP::localURIResolver().link(uri);
// If it is a remote target, we might need to spawn an external binary
if (!target.isLocalPath()){
bool matchedProtocol = false;
// Read configured external writers
IPC::sharedPage extwriPage(EXTWRITERS, 0, false, false);
if (extwriPage.mapped){
Util::RelAccX extWri(extwriPage.mapped, false);
if (extWri.isReady()){
for (uint64_t i = 0; i < extWri.getEndPos(); i++){
// Retrieve binary config
std::string name = extWri.getPointer("name", i);
std::string cmdline = extWri.getPointer("cmdline", i);
Util::RelAccX protocols = Util::RelAccX(extWri.getPointer("protocols", i));
uint8_t protocolCount = protocols.getPresent();
JSON::Value protocolArray;
for (uint8_t idx = 0; idx < protocolCount; idx++){
protocolArray.append(protocols.getPointer("protocol", idx));
}
jsonForEach(protocolArray, protocol){
if (target.protocol != (*protocol).asStringRef()){ continue; }
HIGH_MSG("Using %s in order connect to URL with protocol %s", name.c_str(), target.protocol.c_str());
matchedProtocol = true;
// Split configured parameters for this writer on whitespace
// TODO: we might want to trim whitespaces and remove empty parameters
std::deque<std::string> parameterList;
Util::splitString(cmdline, ' ', parameterList);
// Build the startup command, which needs space for the program name, each parameter, the target url and a null at the end
char **cmd = (char**)malloc(sizeof(char*) * (parameterList.size() + 2));
size_t curArg = 0;
// Write each parameter
for (size_t j = 0; j < parameterList.size(); j++) {
cmd[curArg++] = (char*)parameterList[j].c_str();
}
// Write the target URL as the last positional argument then close with a null at the end
cmd[curArg++] = (char*)uri.c_str();
cmd[curArg++] = 0;
pid_t child = startConverted(cmd, outFile);
if (child == -1){
ERROR_MSG("'%s' process did not start, aborting", cmd[0]);
return false;
}
Util::Procs::forget(child);
free(cmd);
break;
}
if (matchedProtocol){ break; }
}
}
}
if (!matchedProtocol){
ERROR_MSG("Could not connect to '%s', since we do not have a configured external writer to handle '%s' protocols", uri.c_str(), target.protocol.c_str());
return false;
}
}else{
int flags = S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH;
int mode = O_RDWR | O_CREAT | (append ? O_APPEND : O_TRUNC);
std::string path = target.getFilePath();
if (!Util::createPathFor(path)){
ERROR_MSG("Cannot not create file %s: could not create parent folder", path.c_str());
return false;
}
outFile = open(path.c_str(), mode, flags);
if (outFile < 0){
ERROR_MSG("Failed to open file %s, error: %s", path.c_str(), strerror(errno));
return false;
}
}
return true;
}
//Returns the time to wait in milliseconds for exponential back-off waiting.
//If currIter > maxIter, always returns 5ms to prevent tight eternal loops when mistakes are made
//Otherwise, exponentially increases wait time for a total of maxWait milliseconds after maxIter calls.
//Wildly inaccurate for very short max durations and/or very large maxIter values, but otherwise works as expected.
int64_t expBackoffMs(const size_t currIter, const size_t maxIter, const int64_t maxWait){
if (currIter > maxIter){return 5;}
int64_t w = maxWait >> 1;
for (size_t i = maxIter; i > currIter; --i){
w >>= 1;
if (w < 2){w = 2;}
}
DONTEVEN_MSG("Waiting %" PRId64 " ms out of %" PRId64 " for iteration %zu/%zu", w, maxWait, currIter, maxIter);
return w;
}
/// Secure random bytes generator
/// Uses /dev/urandom internally
void getRandomBytes(void * dest, size_t len){
std::ifstream rndSrc("/dev/urandom", std::ifstream::binary);
rndSrc.read((char*)dest, len);
size_t cnt = rndSrc.gcount();
if (!rndSrc.good()){
WARN_MSG("Reading random data failed - generating using rand() as backup");
for (size_t i = cnt; i < len; ++i){((char*)dest)[i] = rand() % 255;}
}
rndSrc.close();
}
/// Secure random alphanumeric string generator
/// Uses getRandomBytes internally
std::string getRandomAlphanumeric(size_t len){
std::string ret(len, 'X');
getRandomBytes((void*)ret.data(), len);
for (size_t i = 0; i < len; ++i){
uint8_t v = (ret[i] % 62);
if (v < 10){
ret[i] = v + '0';
}else if (v < 36){
ret[i] = v - 10 + 'A';
}else{
ret[i] = v - 10 - 26 + 'a';
}
}
return ret;
}
std::string generateUUID(){
const char * charset = "0123456789abcdef";
uint8_t randNums[36];
Util::getRandomBytes(&randNums, sizeof(randNums));
std::string uuid = "00000000-0000-4000-D000-000000000000";
for (size_t i = 0; i < uuid.size(); ++i){
if (uuid[i] == 'D'){
uuid[i] = charset[8+randNums[i]%4];
continue;
}
if (uuid[i] != '0'){continue;}
uuid[i] = charset[randNums[i]%16];
}
return uuid;
}
/// 64-bits version of ftell
uint64_t ftell(FILE *stream){
/// \TODO Windows implementation (e.g. _ftelli64 ?)
return ftello(stream);
}
/// 64-bits version of fseek
uint64_t fseek(FILE *stream, uint64_t offset, int whence){
/// \TODO Windows implementation (e.g. _fseeki64 ?)
clearerr(stream);
return fseeko(stream, offset, whence);
}
ResizeablePointer::ResizeablePointer(){
currSize = 0;
ptr = 0;
maxSize = 0;
}
ResizeablePointer::~ResizeablePointer(){
if (ptr){free(ptr);}
currSize = 0;
ptr = 0;
maxSize = 0;
}
ResizeablePointer::ResizeablePointer(const ResizeablePointer & rhs){
currSize = 0;
ptr = 0;
maxSize = 0;
append(rhs, rhs.size());
}
ResizeablePointer& ResizeablePointer::operator= (const ResizeablePointer& rhs){
if (this == &rhs){return *this;}
truncate(0);
append(rhs, rhs.size());
return *this;
}
void ResizeablePointer::shift(size_t byteCount){
//Shifting the entire buffer is easy, we do nothing and set size to zero
if (byteCount >= currSize){
currSize = 0;
return;
}
//Shifting partial needs a memmove and size change
memmove(ptr, ((char*)ptr)+byteCount, currSize-byteCount);
currSize -= byteCount;
}
/// Takes another ResizeablePointer as argument and swaps their pointers around,
/// thus exchanging them without needing to copy anything.
void ResizeablePointer::swap(ResizeablePointer & rhs){
void * tmpPtr = ptr;
size_t tmpCurrSize = currSize;
size_t tmpMaxSize = maxSize;
ptr = rhs.ptr;
currSize = rhs.currSize;
maxSize = rhs.maxSize;
rhs.ptr = tmpPtr;
rhs.currSize = tmpCurrSize;
rhs.maxSize = tmpMaxSize;
}
bool ResizeablePointer::assign(const void *p, uint32_t l){
if (!allocate(l)){return false;}
memcpy(ptr, p, l);
currSize = l;
return true;
}
bool ResizeablePointer::assign(const std::string &str){
return assign(str.data(), str.length());
}
bool ResizeablePointer::append(const void *p, uint32_t l){
// We're writing from null pointer - assume outside write (e.g. fread or socket operation) and update the size
if (!p){
if (currSize + l > maxSize){
FAIL_MSG("Pointer write went beyond allocated size! Memory corruption likely.");
BACKTRACE;
return false;
}
currSize += l;
return true;
}
if (!allocate(l + currSize)){return false;}
memcpy(((char *)ptr) + currSize, p, l);
currSize += l;
return true;
}
bool ResizeablePointer::append(const std::string &str){
return append(str.data(), str.length());
}
bool ResizeablePointer::allocate(uint32_t l){
if (l > maxSize){
void *tmp = realloc(ptr, l);
if (!tmp){
FAIL_MSG("Could not allocate %" PRIu32 " bytes of memory", l);
return false;
}
ptr = tmp;
maxSize = l;
}
return true;
}
/// Returns amount of space currently reserved for this pointer
uint32_t ResizeablePointer::rsize(){return maxSize;}
void ResizeablePointer::truncate(const size_t newLen){
if (currSize > newLen){currSize = newLen;}
}
/// Redirects stderr to log parser, writes log parser to the old stderr.
/// Does nothing if the MIST_CONTROL environment variable is set.
void redirectLogsIfNeeded(){
// The controller sets this environment variable.
// We don't do anything if set, since the controller wants the messages raw.
if (getenv("MIST_CONTROL")){return;}
setenv("MIST_CONTROL", "1", 1);
// Okay, we're stand-alone, lets do some parsing!
int true_stderr = dup(STDERR_FILENO);
int pipeErr[2];
if (pipe(pipeErr) >= 0){
// Start reading log messages from the unnamed pipe
Util::Procs::fork_prepare();
pid_t pid = fork();
if (pid == 0){// child
Util::Procs::fork_complete();
close(pipeErr[1]); // close the unneeded pipe file descriptor
// Close all sockets in the socketList
for (std::set<int>::iterator it = Util::Procs::socketList.begin();
it != Util::Procs::socketList.end(); ++it){
close(*it);
}
close(2);
struct sigaction new_action;
new_action.sa_handler = SIG_IGN;
sigemptyset(&new_action.sa_mask);
new_action.sa_flags = 0;
sigaction(SIGINT, &new_action, NULL);
sigaction(SIGHUP, &new_action, NULL);
sigaction(SIGTERM, &new_action, NULL);
sigaction(SIGPIPE, &new_action, NULL);
Util::logParser(pipeErr[0], true_stderr, isatty(true_stderr));
exit(0);
}
Util::Procs::fork_complete();
if (pid == -1){
FAIL_MSG("Failed to fork child process for log handling!");
}else{
dup2(pipeErr[1], STDERR_FILENO); // cause stderr to write to the pipe
}
close(pipeErr[1]); // close the unneeded pipe file descriptor
close(pipeErr[0]);
close(true_stderr);
}
}
/// \brief Forks to a log converter, which spawns an external writer and pretty prints it stdout and stderr
pid_t startConverted(const char *const *argv, int &outFile){
int p[2];
if (pipe(p) == -1){
ERROR_MSG("Unable to create pipe in order to connect to the STDIN of the target binary");
return -1;
}
Util::Procs::fork_prepare();
pid_t converterPid = fork();
// Child process
if (converterPid == 0){
Util::Procs::fork_complete();
close(p[1]);
// Override signals
struct sigaction new_action;
new_action.sa_handler = SIG_IGN;
sigemptyset(&new_action.sa_mask);
new_action.sa_flags = 0;
sigaction(SIGINT, &new_action, NULL);
sigaction(SIGHUP, &new_action, NULL);
sigaction(SIGTERM, &new_action, NULL);
sigaction(SIGPIPE, &new_action, NULL);
// Start external writer
int fdOut = -1;
int fdErr = -1;
pid_t binPid = Util::Procs::StartPiped(argv, &p[0], &fdOut, &fdErr);
close(p[0]);
if (binPid == -1){
FAIL_MSG("Failed to start binary `%s`", argv[0]);
}
// Close all sockets in the socketList
for (std::set<int>::iterator it = Util::Procs::socketList.begin();
it != Util::Procs::socketList.end(); ++it){
close(*it);
}
// Okay, so.... hear me out here.
// This code normalizes the stdin and stdout file descriptors, so that
// they are connected to the pipes we're reading from the child process.
// This is not technically needed, but it makes it easier to debug pipe-
// related problems, and works around a nasty issue were left-over stdout
// connected to another converted process may keep that other process alive
// when it really shouldn't.
// This isn't pretty, it's not fully correct, but it's good enough for now.
// If somebody writes a prettier version of this, please do sent a pull request.
// Thanks <3
std::set<int> toClose;
while (fdErr == 0 || fdErr == 1){
int tmp = dup(fdErr);
if (tmp > -1){
toClose.insert(fdErr);
fdErr = tmp;
}
}
while (fdOut == 0 || fdOut == 1){
int tmp = dup(fdOut);
if (tmp > -1){
toClose.insert(fdOut);
fdOut = tmp;
}
}
while (toClose.size()){
close(*toClose.begin());
toClose.erase(toClose.begin());
}
dup2(fdErr, 1);
dup2(fdOut, 0);
close(fdErr);
close(fdOut);
// Read pipes and write to the stdErr of parent process
Util::logConverter(1, 0, 2, argv[0], binPid);
exit(0);
}
if (converterPid == -1){
FAIL_MSG("Failed to fork log converter for log handling!");
close(p[1]);
}else{
Util::Procs::remember(converterPid);
outFile = p[1];
}
close(p[0]);
Util::Procs::fork_complete();
return converterPid;
}
void logConverter(int inErr, int inOut, int out, const char *progName, pid_t pid){
Socket::Connection errStream(-1, inErr);
Socket::Connection outStream(-1, inOut);
errStream.setBlocking(false);
outStream.setBlocking(false);
while (errStream || outStream){
if (errStream.spool() || errStream.Received().size()){
while (errStream.Received().size()){
std::string &line = errStream.Received().get();
while (line.find('\r') != std::string::npos){line.erase(line.find('\r'));}
while (line.find('\n') != std::string::npos){line.erase(line.find('\n'));}
dprintf(out, "INFO|%s|%d||%s|%s\n", progName, pid, Util::streamName, line.c_str());
line.clear();
}
}else if (outStream.spool() || outStream.Received().size()){
while (outStream.Received().size()){
std::string &line = outStream.Received().get();
while (line.find('\r') != std::string::npos){line.erase(line.find('\r'));}
while (line.find('\n') != std::string::npos){line.erase(line.find('\n'));}
dprintf(out, "INFO|%s|%d||%s|%s\n", progName, pid, Util::streamName, line.c_str());
line.clear();
}
}else{Util::sleep(25);}
}
errStream.close();
outStream.close();
}
/// Parses log messages from the given file descriptor in, printing them to out, optionally
/// calling the given callback for each valid message. Closes the file descriptor on read error
void logParser(int in, int out, bool colored,
void callback(const std::string &, const std::string &, const std::string &, uint64_t, bool)){
if (getenv("MIST_COLOR")){colored = true;}
bool sysd_log = getenv("MIST_LOG_SYSTEMD");
char *color_time, *color_msg, *color_end, *color_strm, *CONF_msg, *FAIL_msg, *ERROR_msg,
*WARN_msg, *INFO_msg;
if (colored){
color_end = (char *)"\033[0m";
if (getenv("MIST_COLOR_END")){color_end = getenv("MIST_COLOR_END");}
color_strm = (char *)"\033[0m";
if (getenv("MIST_COLOR_STREAM")){color_strm = getenv("MIST_COLOR_STREAM");}
color_time = (char *)"\033[2m";
if (getenv("MIST_COLOR_TIME")){color_time = getenv("MIST_COLOR_TIME");}
CONF_msg = (char *)"\033[0;1;37m";
if (getenv("MIST_COLOR_CONF")){CONF_msg = getenv("MIST_COLOR_CONF");}
FAIL_msg = (char *)"\033[0;1;31m";
if (getenv("MIST_COLOR_FAIL")){FAIL_msg = getenv("MIST_COLOR_FAIL");}
ERROR_msg = (char *)"\033[0;31m";
if (getenv("MIST_COLOR_ERROR")){ERROR_msg = getenv("MIST_COLOR_ERROR");}
WARN_msg = (char *)"\033[0;1;33m";
if (getenv("MIST_COLOR_WARN")){WARN_msg = getenv("MIST_COLOR_WARN");}
INFO_msg = (char *)"\033[0;36m";
if (getenv("MIST_COLOR_INFO")){INFO_msg = getenv("MIST_COLOR_INFO");}
}else{
color_end = (char *)"";
color_strm = (char *)"";
color_time = (char *)"";
CONF_msg = (char *)"";
FAIL_msg = (char *)"";
ERROR_msg = (char *)"";
WARN_msg = (char *)"";
INFO_msg = (char *)"";
}
Socket::Connection O(-1, in);
O.setBlocking(true);
Util::ResizeablePointer buf;
while (O){
if (O.spool()){
while (O.Received().size()){
std::string & t = O.Received().get();
buf.append(t);
if (buf.size() && (buf.size() > 1024 || *t.rbegin() == '\n')){
unsigned int i = 0;
char *kind = buf; // type of message, at begin of string
char *progname = 0;
char *progpid = 0;
char *lineno = 0;
char *strmNm = 0;
char *message = 0;
while (i < 9 && buf[i] != '|' && buf[i] != 0 && buf[i] < 128){++i;}
if (buf[i] != '|'){
// on parse error, skip to next message
t.clear();
buf.truncate(0);
continue;
}
buf[i] = 0; // insert null byte
++i;
progname = buf + i; // progname starts here
while (i < 40 && buf[i] != '|' && buf[i] != 0){++i;}
if (buf[i] != '|'){
// on parse error, skip to next message
t.clear();
buf.truncate(0);
continue;
}
buf[i] = 0; // insert null byte
++i;
progpid = buf + i; // progpid starts here
while (i < 60 && buf[i] != '|' && buf[i] != 0){++i;}
if (buf[i] != '|'){
// on parse error, skip to next message
t.clear();
buf.truncate(0);
continue;
}
buf[i] = 0; // insert null byte
++i;
lineno = buf + i; // lineno starts here
while (i < 180 && buf[i] != '|' && buf[i] != 0){++i;}
if (buf[i] != '|'){
// on parse error, skip to next message
t.clear();
buf.truncate(0);
continue;
}
buf[i] = 0; // insert null byte
++i;
strmNm = buf + i; // stream name starts here
while (i < 380 && buf[i] != '|' && buf[i] != 0){++i;}
if (buf[i] != '|'){
// on parse error, skip to next message
t.clear();
buf.truncate(0);
continue;
}
buf[i] = 0; // insert null byte
++i;
message = buf + i; // message starts here
// insert null byte for end of line
buf[buf.size()-1] = 0;
// print message
if (callback){callback(kind, message, strmNm, JSON::Value(progpid).asInt(), true);}
color_msg = color_end;
if (colored){
if (!strcmp(kind, "CONF")){color_msg = CONF_msg;}
if (!strcmp(kind, "FAIL")){color_msg = FAIL_msg;}
if (!strcmp(kind, "ERROR")){color_msg = ERROR_msg;}
if (!strcmp(kind, "WARN")){color_msg = WARN_msg;}
if (!strcmp(kind, "INFO")){color_msg = INFO_msg;}
}
if (sysd_log){
if (!strcmp(kind, "CONF")){dprintf(out, "<5>");}
if (!strcmp(kind, "FAIL")){dprintf(out, "<0>");}
if (!strcmp(kind, "ERROR")){dprintf(out, "<1>");}
if (!strcmp(kind, "WARN")){dprintf(out, "<2>");}
if (!strcmp(kind, "INFO")){dprintf(out, "<5>");}
if (!strcmp(kind, "VERYHIGH") || !strcmp(kind, "EXTREME") || !strcmp(kind, "INSANE") || !strcmp(kind, "DONTEVEN")){
dprintf(out, "<7>");
}
}else{
time_t rawtime;
struct tm *timeinfo;
struct tm timetmp;
char buffer[100];
time(&rawtime);
timeinfo = localtime_r(&rawtime, &timetmp);
strftime(buffer, 100, "%F %H:%M:%S", timeinfo);
dprintf(out, "%s[%s] ", color_time, buffer);
}
if (progname && progpid && strlen(progname) && strlen(progpid)){
if (strmNm && strlen(strmNm)){
dprintf(out, "%s:%s%s%s (%s) ", progname, color_strm, strmNm, color_time, progpid);
}else{
dprintf(out, "%s (%s) ", progname, progpid);
}
}else{
if (strmNm && strlen(strmNm)){dprintf(out, "%s%s%s ", color_strm, strmNm, color_time);}
}
dprintf(out, "%s%s: %s%s", color_msg, kind, message, color_end);
if (lineno && strlen(lineno)){dprintf(out, " (%s) ", lineno);}
dprintf(out, "\n");
buf.truncate(0);
}
t.clear();
}
}else{
Util::sleep(50);
}
}
close(out);
close(in);
}
FieldAccX::FieldAccX(RelAccX *_src, RelAccXFieldData _field) : src(_src), field(_field){}
uint64_t FieldAccX::uint(size_t recordNo) const{return src->getInt(field, recordNo);}
std::string FieldAccX::string(size_t recordNo) const{
return std::string(src->getPointer(field, recordNo));
}
const char * FieldAccX::ptr(size_t recordNo) const{
return src->getPointer(field, recordNo);
}
void FieldAccX::set(uint64_t val, size_t recordNo){src->setInt(field, val, recordNo);}
void FieldAccX::set(const std::string &val, size_t recordNo){
char *place = src->getPointer(field, recordNo);
memcpy(place, val.data(), std::min((size_t)field.size, val.size()));
if ((field.type & 0xF0) == RAX_STRING){
place[std::min((size_t)field.size - 1, val.size())] = 0;
}
}
/// If waitReady is true (default), waits for isReady() to return true in 50ms sleep increments.
RelAccX::RelAccX(char *data, bool waitReady){
if (!data){
p = 0;
return;
}
p = data;
hdrRecordCnt = (uint32_t*)(p+2);
hdrRecordSize = (uint32_t*)(p+6);
hdrStartPos = (uint32_t*)(p+10);
hdrDeleted = (uint64_t*)(p+14);
hdrPresent = (uint32_t*)(p+22);
hdrOffset = (uint16_t*)(p+26);
hdrEndPos = (uint64_t*)(p+28);
if (waitReady){
uint64_t maxWait = Util::bootMS() + 10000;
while (!isReady()){
if (Util::bootMS() > maxWait){
FAIL_MSG("Waiting for RelAccX structure to be ready timed out, aborting");
p = 0;
return;
}
Util::sleep(50);
}
}
if (isReady()){
uint16_t offset = RAXHDR_FIELDOFFSET;
if (offset < 11 || offset >= getOffset()){
FAIL_MSG("Invalid field offset: %u", offset);
p = 0;
return;
}
uint64_t dataOffset = 0;
while (offset < getOffset()){
const uint8_t sizeByte = p[offset];
const uint8_t nameLen = sizeByte >> 3;
const uint8_t typeLen = sizeByte & 0x7;
const uint8_t fieldType = p[offset + 1 + nameLen];
const std::string fieldName(p + offset + 1, nameLen);
uint32_t size = 0;
switch (typeLen){
case 1: // derived from field type
if ((fieldType & 0xF0) == RAX_UINT || (fieldType & 0xF0) == RAX_INT){
// Integer types - lower 4 bits +1 are size in bytes
size = (fieldType & 0x0F) + 1;
}else{
if ((fieldType & 0xF0) == RAX_STRING || (fieldType & 0xF0) == RAX_RAW){
// String types - 8*2^(lower 4 bits) is size in bytes
size = 16 << (fieldType & 0x0F);
}else{
WARN_MSG("Unhandled field type!");
}
}
break;
// Simple sizes in bytes
case 2: size = p[offset + 1 + nameLen + 1]; break;
case 3: size = *(uint16_t *)(p + offset + 1 + nameLen + 1); break;
case 4: size = Bit::btoh24(p + offset + 1 + nameLen + 1); break;
case 5: size = *(uint32_t *)(p + offset + 1 + nameLen + 1); break;
default: WARN_MSG("Unhandled field data size!"); break;
}
fields[fieldName] = RelAccXFieldData(fieldType, size, dataOffset);
DONTEVEN_MSG("Field %s: type %u, size %" PRIu32 ", offset %" PRIu64, fieldName.c_str(),
fieldType, size, dataOffset);
dataOffset += size;
offset += nameLen + typeLen + 1;
}
}
}
/// Gets the amount of records present in the structure.
uint32_t RelAccX::getRCount() const{return *hdrRecordCnt;}
/// Gets the size in bytes of a single record in the structure.
uint32_t RelAccX::getRSize() const{return *hdrRecordSize;}
/// Gets the position in the records where the entries start
uint32_t RelAccX::getStartPos() const{return *hdrStartPos;}
/// Gets the number of deleted records
uint64_t RelAccX::getDeleted() const{return *hdrDeleted;}
/// Gets the number of records present
size_t RelAccX::getPresent() const{return *hdrPresent;}
/// Gets the number of the last valid index
uint64_t RelAccX::getEndPos() const{return *hdrEndPos;}
/// Gets the number of fields per recrd
uint32_t RelAccX::getFieldCount() const{return fields.size();}
/// Gets the offset from the structure start where records begin.
uint16_t RelAccX::getOffset() const{return *hdrOffset;}
/// Returns true if the structure is ready for read operations.
bool RelAccX::isReady() const{return p && (p[0] & 1);}
/// Returns true if the structure will no longer be updated.
bool RelAccX::isExit() const{return !p || (p[0] & 2);}
/// Returns true if the structure should be reloaded through out of band means.
bool RelAccX::isReload() const{return !p || (p[0] & 4);}
/// Returns true if the given record number can be accessed.
bool RelAccX::isRecordAvailable(uint64_t recordNo) const{
// Check if the record has been deleted
if (getDeleted() > recordNo){return false;}
// Check if the record hasn't been created yet
if (recordNo >= getEndPos()){return false;}
return true;
}
/// Returns true if the given field exists.
bool RelAccX::hasField(const std::string & name) const{
return (fields.find(name) != fields.end());
}
/// Returns the (max) size of the given field.
/// For string types, returns the exact size excluding terminating null byte.
/// For other types, returns the maximum size possible.
/// Returns 0 if the field does not exist.
uint32_t RelAccX::getSize(const std::string &name, uint64_t recordNo) const{
if (!isRecordAvailable(recordNo)){return 0;}
std::map<std::string, RelAccXFieldData>::const_iterator it = fields.find(name);
if (it == fields.end()){return 0;}
const RelAccXFieldData &fd = it->second;
if ((fd.type & 0xF0) == RAX_STRING){return strnlen(RECORD_POINTER, fd.size);}
return fd.size;
}
/// Returns a pointer to the given field in the given record number.
/// Returns a null pointer if the field does not exist.
char *RelAccX::getPointer(const std::string &name, uint64_t recordNo) const{
std::map<std::string, RelAccXFieldData>::const_iterator it = fields.find(name);
if (it == fields.end()){return 0;}
return getPointer(it->second, recordNo);
}
char *RelAccX::getPointer(const RelAccXFieldData &fd, uint64_t recordNo) const{
return RECORD_POINTER;
}
/// Returns the value of the given integer-type field in the given record, as an uint64_t type.
/// Returns 0 if the field does not exist or is not an integer type.
uint64_t RelAccX::getInt(const std::string &name, uint64_t recordNo) const{
std::map<std::string, RelAccXFieldData>::const_iterator it = fields.find(name);
if (it == fields.end()){return 0;}
return getInt(it->second, recordNo);
}
uint64_t RelAccX::getInt(const RelAccXFieldData &fd, uint64_t recordNo) const{
char *ptr = RECORD_POINTER;
if ((fd.type & 0xF0) == RAX_UINT){// unsigned int
switch (fd.size){
case 1: return *(uint8_t *)ptr;
case 2: return *(uint16_t *)ptr;
case 3: return Bit::btoh24(ptr);
case 4: return *(uint32_t *)ptr;
case 8: return *(uint64_t *)ptr;
default: WARN_MSG("Unimplemented integer");
}
}
if ((fd.type & 0xF0) == RAX_INT){// signed int
switch (fd.size){
case 1: return *(int8_t *)ptr;
case 2: return *(int16_t *)ptr;
case 3: return Bit::btoh24(ptr);
case 4: return *(int32_t *)ptr;
case 8: return *(int64_t *)ptr;
default: WARN_MSG("Unimplemented integer");
}
}
return 0; // Not an integer type, or not implemented
}
std::string RelAccX::toPrettyString(size_t indent) const{
std::stringstream r;
uint64_t delled = getDeleted();
uint64_t max = getEndPos();
if (delled >= max || max - delled > getRCount()){
r << std::string(indent, ' ') << "(Note: deleted count (" << delled << ") >= total count (" << max << "))" << std::endl;
delled = max - getRCount();
}
if (max == 0){max = getRCount();}
r << std::string(indent, ' ') << "RelAccX: " << getRCount() << " x " << getRSize() << "b @"
<< getOffset() << " (#" << delled << " - #" << max - 1 << ")" << std::endl;
for (uint64_t i = delled; i < max; ++i){
r << std::string(indent + 2, ' ') << "#" << i << ":" << std::endl;
for (std::map<std::string, RelAccXFieldData>::const_iterator it = fields.begin();
it != fields.end(); ++it){
r << std::string(indent + 4, ' ') << it->first << ": ";
switch (it->second.type & 0xF0){