-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathproclib.c
1548 lines (1292 loc) · 40.7 KB
/
proclib.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 PolySat, California Polytechnic State University, San Luis Obispo. [email protected]
* This file is part of libproc, a PolySat library.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program 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 Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* Process Library
*
* @author Greg Eddington
* @author Dr. John Bellardo
* @author Greg Manyak
*/
#include "proclib.h"
#include "events.h"
#include "cmd.h"
#include "debug.h"
#include <sys/time.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/resource.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <signal.h>
#include <errno.h>
#include <fcntl.h>
#include <ctype.h>
#include <assert.h>
#include "watchdog_cmd.h"
#include <time.h>
#include "critical.h"
#include <pthread.h>
#include "ipc.h"
#include "pseudo_threads.h"
#include "cmd-pkt.h"
#define READ_BUFF_MIN 4096
#define READ_BUFF_MAX (READ_BUFF_MIN * 4)
#define WATCHDOG_VALIDATE_SECS 30
static int signalWriteFD = -1;
static int sigchld_handler(int, void*);
static int setup_signal_fd(ProcessData *proc);
//When a socket is written to, this is the call back that is called
static int socket_write_cb(int fd, char type, void * arg);
/* Structure which defines a signal callback */
struct ProcSignalCB
{
PROC_signal_cb cb; /* A pointer to the signal callback function */
void *arg; /* The arguments to pass */
int sigNum; /* The signal number to respond to */
int recvdCnt;
struct ProcSignalCB *next; /* The next signal callback */
};
#define FREE_DATA_AFTER_WRITE 1
#define COPY_DATA_TO_WRITE 2
#define IGNORE_DATA_AFTER_WRITE 3
/* Linked list to hold writes pending notification that the write will not
* block
*/
struct ProcWriteNode {
uint8_t *data;
uint32_t len;
int fd;
int freeMem;
proc_nb_write_cb cb;
void *arg;
struct ProcWriteNode *next;
};
/** Returns the EVTHandler context for the process. Needed to directly call
* EVT_* functions.
**/
EVTHandler *PROC_evt(ProcessData *proc)
{
if (!proc)
return NULL;
return proc->evtHandler;
}
struct CSState *proc_get_cs_state(ProcessData *proc)
{
if (!proc || proc->wdMode == WD_NOTSAT)
return NULL;
return &proc->criticalState;
}
static ProcessData *watchProc = NULL;
static int proc_cmd_sockaddr_internal(ProcessData *proc, int fd, unsigned char cmd, void *data, size_t dataLen, struct sockaddr_in *dest);
int proc_cmd_sockaddr_raw_internal(ProcessData *proc, int fd, void *data,
size_t dataLen, struct sockaddr_in *dest);
static void watchdog_reg_info(int fd, unsigned char cmd, void *data,
size_t dataLen, struct sockaddr_in *src)
{
WatchdogInfoResp *resp = (WatchdogInfoResp*)data;
if (!watchProc || !watchProc->name)
return;
// If our entry looks good, no further action is needed
if (dataLen >= strlen(watchProc->name) + sizeof(*resp) &&
0 == strcmp(watchProc->name, resp->name) &&
getpid() == ntohs(resp->pid) &&
resp->flags & WDG_PROC_FLAG_WATCHED)
return;
// Re-register!
PROC_cmd(watchProc, CMD_WDT_REGISTER, (unsigned char*)watchProc->name,
strlen(watchProc->name)+1, "watchdog");
}
static void watchdog_xdr_reg_info(struct ProcessData *proc, int timeout,
void *arg, char *resp_buff, size_t resp_len, enum IPC_CB_TYPE cb_type)
{
if (timeout)
return;
// If our entry looks good, no further action is needed
struct IPC_Response *resp = (struct IPC_Response*)resp_buff;
struct IPC_WDRegInfo *data = (struct IPC_WDRegInfo*)resp->data.data;
if (resp->result == IPC_RESULTCODE_SUCCESS &&
0 == strcmp(proc->name, data->name) &&
getpid() == data->pid && data->watched)
return;
// Re-register!
struct IPC_WDProcName name;
name.name = proc->name;
IPC_command_local(proc, IPC_CMDS_WD_REGISTER_STATIC, &name,
IPC_TYPES_WD_PROC_NAME,
"watchdog", NULL, NULL, IPC_CB_TYPE_COOKED, 5000);
}
static int validate_watch_registration(void *arg)
{
ProcessData *proc = (ProcessData*)arg;
if (!proc || !proc->name)
return EVENT_KEEP;
if (proc->wdMode == WD_ENABLED) {
watchProc = proc;
PROC_cmd(proc, WATCHDOG_CMD_REG_INFO, (unsigned char*)proc->name,
strlen(proc->name)+1, "watchdog");
return EVENT_KEEP;
}
else if (proc->wdMode == WD_XDR) {
struct IPC_WDProcName name;
name.name = proc->name;
IPC_command_local(proc, IPC_CMDS_WD_REG_INFO, &name,
IPC_TYPES_WD_PROC_NAME,
"watchdog", &watchdog_xdr_reg_info, proc, IPC_CB_TYPE_COOKED, 5000);
return EVENT_KEEP;
}
return EVENT_REMOVE;
}
void PROC_set_context(ProcessData *proc, void *ctx)
{
proc->callbackContext = ctx;
}
int PROC_udp_id(ProcessData *proc)
{
if (!proc)
return 0;
return proc->cmdPort;
}
static void PROC_debugger_state(struct IPCBuffer *buff, void *arg)
{
ProcessData *proc = (ProcessData*)arg;
ipc_printf_buffer(buff, " \"process_name\": \"%s\",\n", proc->name);
}
ProcessData *PROC_init(const char *procName, enum WatchdogMode wdMode)
{
return PROC_init_xdr_hashsize(procName, wdMode, NULL, 19);
}
ProcessData *PROC_init_hashsize(const char *procName, enum WatchdogMode wdMode, int sz)
{
return PROC_init_xdr_hashsize(procName, wdMode, NULL, sz);
}
ProcessData *PROC_init_xdr(const char *procName, enum WatchdogMode wdMode,
struct XDR_CommandHandlers *handlers)
{
return PROC_init_xdr_hashsize(procName, wdMode, handlers, 19);
}
//Initializes a ProcessData object
ProcessData *PROC_init_xdr_hashsize(const char *procName, enum WatchdogMode wdMode,
struct XDR_CommandHandlers *handlers, int hashsize)
{
ProcessData *proc;
char filepath[80];
char oldname[80];
int fd;
FILE *inp;
int oldPid = -1;
#ifdef TIME_TEST
struct timeval startTime;
struct timeval endTime;
struct timeval totalTime;
gettimeofday(&startTime, NULL);
#endif //TIME_TEST
// Allocate our internal state structure
proc = (ProcessData*)malloc(sizeof(ProcessData));
if (!proc)
return NULL;
memset(proc, 0, sizeof(*proc));
proc->wdMode = wdMode;
// Allocate enough space for process name and terminating null byte
if (procName) {
proc->name = (char*)malloc(strlen(procName)+1);
strcpy(proc->name, procName);
}
else
proc->name = NULL;
// Configure the debug interface
DBG_init(proc->name);
DBG_setLevel(DBG_LEVEL_WARN);
// write .proc file (file pid.proc contains process name)
if (proc->name) {
proc->cmdPort = socket_get_addr_by_name(proc->name);
// Read in old .pid file, if it exists
sprintf(filepath, "%s/%s.pid", PID_FILE_PATH, procName);
inp = fopen(filepath, "r");
if (inp) {
if (1 != fscanf(inp, "%d", &oldPid))
oldPid = -1;
fclose(inp);
}
// Delete old .proc file if it claims to be our process
if (oldPid > 1) {
sprintf(filepath, "%s/%d.proc", PROC_FILE_PATH, oldPid);
inp = fopen(filepath, "r");
if (inp) {
oldname[0] = 0;
if(fscanf(inp, "%s", oldname) == 1) {
fclose(inp);
if (0 == strcmp(oldname, procName))
unlink(filepath);
}
}
}
sprintf(filepath, "%s/%d.proc", PROC_FILE_PATH, getpid());
fd = open(filepath, O_WRONLY | O_CREAT | O_TRUNC, 644);
chmod(filepath, 0644);
if (fd != -1) {
int len = strlen(procName);
if(write(fd, procName, len) < len) {
ERRNO_WARN("Failed to write proc file\n");
}
ERR_WARN(close(fd), "Failed to close proc file\n");
} else {
DBG_print(DBG_LEVEL_WARN,"Failed to open proc file, %s\n", filepath);
}
// Clear variables before using them again
memset(filepath, 0, sizeof(filepath));
// write .pid file (file processName.pid that contains the process id)
sprintf(filepath, "%s/%s.pid", PID_FILE_PATH, procName);
fd = open(filepath, O_WRONLY | O_CREAT | O_TRUNC, 644);
chmod(filepath, 0644);
if (fd != -1) {
// Re-purpose filepath variable here for pid
memset(filepath, 0, sizeof(filepath));
sprintf(filepath, "%d", getpid());
int len = strlen(filepath);
if(write(fd, filepath, strlen(filepath)) < len) {
ERRNO_WARN("Failed to write pid file\n");
}
ERR_WARN(close(fd), "Failed to close pid file\n");
} else {
DBG_print(DBG_LEVEL_WARN,"Failed to open pid file, %s\n", filepath);
}
}
ERR_EXIT(proc->cmdFd = socket_named_init(procName), //Exit?
"Failed to open socket for %s\n", procName);
ERR_EXIT(proc->txFd = socket_init(0), //Exit?
"Failed to open TX socket for %s\n", procName);
// Initialize event handler and return it
proc->evtHandler = EVT_initWithSize(hashsize, PROC_debugger_state, proc);
EVT_set_debugger_port(proc->evtHandler, proc->name ?
socket_get_addr_by_name(proc->name) : 12345);
//set up sigPipe to take signals. Signals will be treated as an event with cb 'signal_fd_cb'
setup_signal_fd(proc);
PT_init(proc->evtHandler);
// initialize command handler: commands are loaded from .cmd.cfg file
if (cmd_handler_init(procName, proc, &proc->cmds) == -1) {
return NULL;
}
// Add in XDR handlers
for(; handlers && handlers->number; handlers++)
CMD_set_xdr_cmd_handler(handlers->number, handlers->cb, handlers->arg);
//Event for when something (probably a command) appears on the fd
EVT_fd_add(proc->evtHandler, proc->cmdFd, EVENT_FD_READ, cmd_handler_cb, proc);
EVT_fd_set_name(proc->evtHandler, proc->cmdFd, "UDP Command Socket");
EVT_fd_set_critical(proc->evtHandler, proc->cmdFd, 0);
//Event for when something (probably a command response) appears on the fd
EVT_fd_add(proc->evtHandler, proc->txFd, EVENT_FD_READ, tx_cmd_handler_cb, proc);
EVT_fd_set_name(proc->evtHandler, proc->txFd, "UDP Request Socket");
EVT_fd_set_critical(proc->evtHandler, proc->txFd, 0);
EVT_set_cmds_pending(proc->evtHandler,
(int (*)(void*))&CMD_pending_responses, proc->cmds);
//Set up SIGCHLD signal handler
PROC_signal(proc, SIGCHLD, &sigchld_handler, proc);
// Register process with the s/w watchdog (make sure to send null byte!)
PROC_wd_enable(proc);
if (proc->wdMode != WD_NOTSAT)
critical_state_init(&proc->criticalState, proc->name);
#if TIME_TEST
gettimeofday(&endTime, NULL);
timersub(&endTime, &startTime, &totalTime);
DBG_print(DBG_LEVEL_WARN, "Process initialization time: %d.%06d\n", totalTime.tv_sec, totalTime.tv_usec);
#endif //TIME_TEST
return proc;
}
void PROC_wd_enable(ProcessData *proc) {
if (!proc->name || proc->wdMode == WD_DISABLED || proc->wdMode == WD_NOTSAT)
return;
if (proc->wdMode == WD_ENABLED)
PROC_set_cmd_handler(proc, WATCHDOG_CMD_REG_INFO_RESP, &watchdog_reg_info,
0, 0, 0);
EVT_sched_add_with_timestep(PROC_evt(proc), EVT_ms2tv(0),
EVT_ms2tv(WATCHDOG_VALIDATE_SECS * 1000),
&validate_watch_registration, proc);
}
//Cleans the process up.
void PROC_cleanup(ProcessData *proc)
{
char filepath[80];
if (!proc) //Already clean
return;
cmd_cleanup_cb_state(proc->cmds, proc->evtHandler);
if (proc->wdMode != WD_NOTSAT)
critical_state_cleanup(&proc->criticalState);
// Clear errno to prevent false errors
errno = 0;
EVT_free_handler(proc->evtHandler);
close(proc->sigPipe[0]);
ERRNO_WARN("close sigPipe[0] error: ");
close(proc->sigPipe[1]);
ERRNO_WARN("close sigPipe[1] error: ");
close(proc->cmdFd);
ERRNO_WARN("close cmdFd error: ");
close(proc->txFd);
ERRNO_WARN("close txFd error: ");
signalWriteFD = -1;
if (proc->name) {
//** Remove the .pid and .proc files **
// write .proc file (file pid.proc contains process name)
sprintf(filepath, "%s/%d.proc", PROC_FILE_PATH, getpid());
unlink(filepath);
ERRNO_WARN("unlink error: ");
// Clear path before using it again
memset(filepath, 0, sizeof(filepath));
// write .pid file (file processName.pid that contains the process id)
sprintf(filepath, "%s/%s.pid", PID_FILE_PATH, proc->name);
unlink(filepath);
ERRNO_WARN("unlink error: ");
free(proc->name);
}
struct ProcSignalCB *curr;
while((curr = proc->signalCBHead)) {
proc->signalCBHead = curr->next;
free(curr);
}
cmd_handler_cleanup(&proc->cmds);
free(proc);
}
static void validate_pipe_flush(ProcChild *child)
{
struct ProcChild **curr;
//Child is never null when passed in
if (child->state != CHILD_STATE_FLUSH_PIPES)
return;
if (child->stdin_fd != -1 || child->stdout_fd != -1 ||
child->stderr_fd != -1)
return;
child->state = CHILD_STATE_DONE;
if (child->deathCb)
(*child->deathCb)(child, child->deathArg);
// Remove node from linked list
for (curr = &child->parentData->childHead ; *curr; curr = &(*curr)->next) {
if ( (*curr) == child) {
// Found the parent; unlink and free the child
*curr = child->next;
child->next = NULL;
if (child->streamState[0].buff)
free(child->streamState[0].buff);
if (child->streamState[1].buff)
free(child->streamState[1].buff);
free(child);
break;
}
}
}
static int sigchld_handler(int signum, void *param)
{
ProcessData *proc = (ProcessData*)param;
int more;
pid_t cpid;
struct rusage rusage;
int exitStatus;
struct ProcChild *curr, *tmp;
do {
cpid = wait4(-1, &exitStatus, WNOHANG, &rusage);
more = 0 < cpid;
if (cpid < 0) {
if (ECHILD != errno)
ERRNO_WARN("Error with wait4");
}
else if (cpid > 0) {
for(curr = proc->childHead; curr; curr = tmp) {
// Use tmp for iteration in case child is deallocated
tmp = curr->next;
if (curr->procId != cpid || curr->state == CHILD_STATE_DONE)
continue;
curr->rusage = rusage;
curr->exitStatus = exitStatus;
curr->state = CHILD_STATE_FLUSH_PIPES;
validate_pipe_flush(curr);
}
}
} while(more);
return EVENT_KEEP;
}
int signal_fd_cb(int fd, char type, void *arg)
{
ProcessData *proc = (ProcessData*)arg;
int rd, signum;
static char rdBuff[sizeof(signum)];
static int rdLen = 0;
struct ProcSignalCB **curr, *sigTmp;
int keep;
do {
rd = read(proc->sigPipe[0], &rdBuff[rdLen], sizeof(rdBuff) - rdLen);
// more = rd > 0 || (-1 == rd && EAGAIN == errno);
if (-1 >= rd && EAGAIN != errno) {
ERRNO_WARN("signal fd error, closing:");
return EVENT_REMOVE;
}
if (0 == rd) {
DBG_print(DBG_LEVEL_WARN, "signal fd closed, removing event");
return EVENT_REMOVE;
}
rdLen += rd;
if (rdLen == sizeof(rdBuff)) {
rdLen = 0;
memcpy(&signum, rdBuff, sizeof(rdBuff));
for (curr = &proc->signalCBHead; *curr; ) {
sigTmp = *curr;
if (sigTmp->sigNum == signum) {
sigTmp->recvdCnt++;
//cb is assigned in PROC_signal
keep = (*sigTmp->cb)(signum, sigTmp->arg);
if (EVENT_REMOVE == keep) {
*curr = sigTmp->next;
free(sigTmp);
}
else
curr = &sigTmp->next;
}
else
curr = &sigTmp->next;
}
}
} while(0);
return EVENT_KEEP;
}
static void PROC_signal_handler(int sigNum, siginfo_t *si, void *p)
{
if (signalWriteFD != -1)
if(write(signalWriteFD, &sigNum, sizeof(sigNum)) < sizeof(sigNum) )
ERRNO_WARN("Write error");
}
static int setup_signal_fd(ProcessData *proc)
{
int currFlags;
int res;
if (-1 != signalWriteFD)
return 0;
if (0 != pipe(proc->sigPipe))
return errno;
// Set the read end of the pipe to non-blocking
currFlags = fcntl(proc->sigPipe[0], F_GETFD);
if (-1 == currFlags)
return -1;
if (-1 == fcntl(proc->sigPipe[0], F_SETFD, O_NONBLOCK))
return -1;
signalWriteFD = proc->sigPipe[1];
res = EVT_fd_add(proc->evtHandler, proc->sigPipe[0],
EVENT_FD_READ, signal_fd_cb, proc);
EVT_fd_set_name(proc->evtHandler, proc->sigPipe[0], "Signal Pipe");
EVT_fd_set_critical(proc->evtHandler, proc->sigPipe[0], 0);
return res;
}
int PROC_signal(struct ProcessData *proc, int sigNum, PROC_signal_cb cb,
void *p)
{
struct ProcSignalCB *curr;
struct sigaction sa;
if (-1 == signalWriteFD) {
DBG_print(DBG_LEVEL_WARN, "Failed to add signal because ProcessData"
" not initialized correctly");
return -1;
}
if (proc->sigPipe[1] != signalWriteFD) {
DBG_print(DBG_LEVEL_WARN, "Failed to add signal because a different ProcessData"
" is already catching signals.");
return -1;
}
curr = malloc(sizeof(struct ProcSignalCB));
if (!curr)
return -1;
curr->cb = cb;
curr->arg = p;
curr->sigNum = sigNum;
curr->recvdCnt = 0;
curr->next = proc->signalCBHead;
proc->signalCBHead = curr;
sa.sa_sigaction = PROC_signal_handler;
sigfillset(&sa.sa_mask); //Catch all signals
sa.sa_flags = SA_SIGINFO;
if (-1 == sigaction(sigNum, &sa, NULL)) {
free(curr);
return -1;
}
return 0;
}
static int next_param(char *str, char **start, char **end)
{
int inQuote = 0;
// End of string edge cases
if (!str) {
*start = NULL;
*end = NULL;
return 0;
}
if (!*str) {
*start = str;
*end = str;
return 0;
}
// Skip leading whitespace
*start = str;
while( isspace(**start) )
(*start)++;
if (!**start) {
*end = *start;
return 0;
}
if (**start == '\'')
inQuote = 1;
if (**start == '"')
inQuote = 2;
for( *end = *start + 1; *end; (*end)++) {
if (!**end || (isspace(**end) && !inQuote)) {
(*end)--;
return 1;
}
if (**end == '\'') {
if (!inQuote)
inQuote = 1;
else if (inQuote == 1)
inQuote = 0;
}
else if (**end == '"') {
if (!inQuote)
inQuote = 2;
else if (inQuote == 2)
inQuote = 0;
}
}
DBG_print(DBG_LEVEL_WARN, "Should never get here!");
return 1;
}
static char **parse_cmd(char *cmd)
{
char *start = cmd, *end;
int cnt = 0, i;
char **argv = NULL;
int len;
while(next_param(start, &start, &end)) {
cnt++;
start = end + 1;
if (*start)
start++;
}
argv = malloc(sizeof(char*) * (cnt + 1) );
if (!argv) {
DBG_print(DBG_LEVEL_WARN, "Failed to allocate memory\n");
return NULL;
}
for (i = 0; i < cnt + 1; i++)
argv[i] = NULL;
cnt = 0;
start = cmd;
while(next_param(start, &start, &end)) {
argv[cnt] = start;
start = end + 1;
if (*start) {
*start = 0;
start++;
}
if (argv[cnt][0] == '"' || argv[cnt][0] == '\'') {
len = strlen(argv[cnt]) - 1;
if (argv[cnt][0] == argv[cnt][len]) {
argv[cnt][len] = 0;
argv[cnt]++;
}
}
cnt++;
}
return argv;
}
ProcChild *PROC_fork_child(struct ProcessData *proc, const char *cmdFmt, ...)
{
va_list ap;
va_start(ap, cmdFmt);
ProcChild *child = NULL;
int in_pipe[2], out_pipe[2], err_pipe[2];
// Create the I/O pipes
if (0 != pipe(in_pipe)) {
DBG_print(DBG_LEVEL_WARN, "stdin pipe failed");
goto err_cleanup;
}
if (0 != pipe(out_pipe)) {
DBG_print(DBG_LEVEL_WARN, "stdout pipe failed");
goto err_cleanup;
}
if (0 != pipe(err_pipe)) {
DBG_print(DBG_LEVEL_WARN, "stderr pipe failed");
goto err_cleanup;
}
child = PROC_fork_child_fd(proc, in_pipe[0], in_pipe[1], out_pipe[0], out_pipe[1], err_pipe[0], err_pipe[1], NULL, NULL, cmdFmt, ap);
close(in_pipe[0]);
close(out_pipe[1]);
close(err_pipe[1]);
err_cleanup:
return child;
}
ProcChild *PROC_fork_child_va(struct ProcessData *proc, int inFd_read, int inFd_write,
int outFd_read, int outFd_write, int errFd_read, int errFd_write, struct rlimit *cpu_limit,
struct rlimit *mem_limit, const char *cmdFmt, ...)
{
va_list ap;
va_start(ap, cmdFmt);
return PROC_fork_child_fd(proc, inFd_read, inFd_write, outFd_read, outFd_write, errFd_read,
errFd_write, cpu_limit, mem_limit, cmdFmt, ap);
}
ProcChild *PROC_fork_child_fd(struct ProcessData *proc, int inFd_read, int inFd_write,
int outFd_read, int outFd_write, int errFd_read, int errFd_write, struct rlimit *cpu_limit,
struct rlimit *mem_limit, const char *cmdFmt, va_list ap)
{
char *cmd = NULL;
ProcChild *child = NULL;
char **argv = NULL;
pid_t childPid;
if(vasprintf(&cmd, cmdFmt, ap) < 0) {
ERR_REPORT(DBG_LEVEL_WARN, "vasprintf failure\n");
goto err_cleanup;
}
va_end(ap);
if (!cmd || !cmd[0]) {
DBG_print(DBG_LEVEL_WARN, "Bad cmd in fork_child\n");
goto err_cleanup;
}
argv = parse_cmd(cmd);
if (!argv || !argv[0])
goto err_cleanup;
// Fork off the child process
if ( 0 == (childPid = fork())) {
// Executing in the child. Move the pipe FDs into place
if (0 != close(0))
exit(1);
if (0 != close(1))
exit(2);
if (0 != close(2))
exit(3);
if (inFd_read > -1 && (-1 == dup2(inFd_read, 0)))
exit(4);
if (outFd_write > -1 && (-1 == dup2(outFd_write, 1)))
exit(5);
if (errFd_write > -1 && (-1 == dup2(errFd_write, 2)))
exit(6);
if(inFd_read > -1)
close(inFd_read);
if(inFd_write > -1)
close(inFd_write);
if(outFd_read > -1)
close(outFd_read);
if(outFd_write > -1)
close(outFd_write);
if(errFd_read > -1)
close(errFd_read);
if(errFd_write > -1)
close(errFd_write);
// Move child into own group for signal isolation
setpgrp();
// Set memory limits it necessary
if(mem_limit) {
if(setrlimit(RLIMIT_AS, mem_limit) == -1) {
ERRNO_WARN("Failure to set memory limit");
exit(7);
}
}
// Set cpu limits it necessary
if(cpu_limit) {
if(setrlimit(RLIMIT_CPU, cpu_limit) == -1) {
ERRNO_WARN("Failure to set CPU limit");
exit(8);
}
}
// Retrieve the current pid for the child
pid_t childPid = getpid();
// Set the nice of the child to the default of 0
if(setpriority(PRIO_PROCESS, childPid, 0) == -1) {
ERRNO_WARN("Failure to set nice value of child");
exit(9);
}
execvp(argv[0], argv);
ERRNO_WARN("Exec failed!");
printf("Exec failure: %s\n", strerror(errno));
exit(1);
}
// The forking failed
if(childPid == -1)
goto err_cleanup;
// Inititate the child
child = malloc(sizeof(ProcChild));
if (!child) {
DBG_print(DBG_LEVEL_WARN, "Failed to allocate memory for ProcChild\n");
goto err_cleanup;
}
memset(child, 0, sizeof(ProcChild));
child->state = CHILD_STATE_INIT;
child->parentData = proc;
child->procId = childPid;
// Save the file descriptors for stdout, stderr, and stdin
// incase parent process wants to write to them.
child->stdin_fd = inFd_write;
child->stdout_fd = outFd_read;
child->stderr_fd = errFd_read;
child->next = proc->childHead;
proc->childHead = child;
// Clean up and return the child
err_cleanup:
if (argv)
free(argv);
if (cmd)
free(cmd);
return child;
}
// A callback that ignores all data on a FD
static int dump_child_data(int fd, char type, void *arg)
{
ProcChild *child = (ProcChild*)arg;
char buff[4096];
int len;
len = read(fd, buff, sizeof(buff));
if (len > 0)
return EVENT_KEEP;
if (len < 0)
ERRNO_WARN("Child read error");
else
CHLD_close_fd(child, fd);
return EVENT_REMOVE;
}
// A callback that echos all data on a FD
static int echo_child_data(int fd, char type, void *arg)
{
ProcChild *child = (ProcChild*)arg;
char buff[4096];
int len;
len = read(fd, buff, sizeof(buff));
if (len > 0) {
if (write(1, buff, len)<0);
return EVENT_KEEP;
}
if (len < 0)
ERRNO_WARN("Child read error");
else
CHLD_close_fd(child, fd);
return EVENT_REMOVE;
}
void CHLD_close_stdin(ProcChild *child)
{
CHLD_close_fd(child, child->stdin_fd);
}
void CHLD_close_fd(ProcChild *child, int fd)
{
int change = 0;
if (fd < 0)
return;
if (fd == child->stdin_fd) {
child->stdin_fd = -1;
change = 1;
}
if (fd == child->stdout_fd) {
child->stdout_fd = -1;
change = 1;
}
if (fd == child->stderr_fd) {
child->stderr_fd = -1;
change = 1;
}
if (!change)
return;
close(fd);
validate_pipe_flush(child);
}
char CHLD_ignore_stderr(ProcChild *child)
{
int res;
if (!child)
return 0;
if (child->stderr_fd < 0)
return 0;
if (!child->parentData)
return 1;
res = EVT_fd_add(child->parentData->evtHandler, child->stderr_fd,
EVENT_FD_READ, dump_child_data, child);
EVT_fd_set_name(child->parentData->evtHandler, child->stderr_fd,
"child %u stderr dump", child->procId);
EVT_fd_set_critical(child->parentData->evtHandler, child->stderr_fd,0);
return res;
}
char CHLD_echo_stderr(ProcChild *child)
{
int res;
if (!child)
return 0;
if (child->stderr_fd < 0)
return 0;
if (!child->parentData)
return 1;
res = EVT_fd_add(child->parentData->evtHandler, child->stderr_fd,
EVENT_FD_READ, echo_child_data, child);
EVT_fd_set_name(child->parentData->evtHandler, child->stderr_fd,
"child %u stderr dump", child->procId);
EVT_fd_set_critical(child->parentData->evtHandler, child->stderr_fd,0);
return res;
}
char CHLD_ignore_stdout(ProcChild *child)
{
int res;