-
-
Notifications
You must be signed in to change notification settings - Fork 373
/
Copy pathupssched.c
1363 lines (1056 loc) · 29.4 KB
/
upssched.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
/* upssched.c - upsmon's scheduling helper for offset timers
Copyright (C) 2000 Russell Kroll <[email protected]>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 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 General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
/* design notes for the curious:
*
* 1. we get called with a upsname and notifytype from upsmon
* 2. the config file is searched for an AT condition that matches
* 3. the conditions on any matching lines are parsed
*
* starting a timer: the timer is added to the daemon's timer queue
* cancelling a timer: the timer is removed from that queue
* execute a command: the command is passed straight to the cmdscript
*
* if the daemon is not already running and is required (to start a timer)
* it will be started automatically
*
* when the time arrives, the command associated with a timer will be
* executed by the daemon (via the cmdscript)
*
* timers can be cancelled at any time before they trigger
*
* the daemon will shut down automatically when no more timers are active
*
*/
#include "common.h"
#include <sys/types.h>
#ifndef WIN32
#include <sys/wait.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <netinet/in.h>
#include <unistd.h>
#include <fcntl.h>
#else
#include "wincompat.h"
#include <winsock2.h>
#include <ws2tcpip.h>
#endif
#include "upssched.h"
#include "timehead.h"
#include "nut_stdint.h"
typedef struct ttype_s {
char *name;
time_t etime;
struct ttype_s *next;
} ttype_t;
static ttype_t *thead = NULL;
static conn_t *connhead = NULL;
static char *cmdscript = NULL, *pipefn = NULL, *lockfn = NULL;
static int verbose = 0; /* use for debugging */
/* ups name and notify type (string) as received from upsmon */
static const char *upsname, *notify_type;
#ifdef WIN32
static OVERLAPPED connect_overlapped;
#define BUF_LEN 512
#endif
#define PARENT_STARTED -2
#define PARENT_UNNECESSARY -3
#define MAX_TRIES 30
#define EMPTY_WAIT 15 /* min passes with no timers to exit */
#define US_LISTEN_BACKLOG 16
#define US_SOCK_BUF_LEN 256
#define US_MAX_READ 128
/* --- server functions --- */
static void exec_cmd(const char *cmd)
{
int err;
char buf[LARGEBUF];
snprintf(buf, sizeof(buf), "%s %s", cmdscript, cmd);
err = system(buf);
#ifndef WIN32
if (WIFEXITED(err)) {
if (WEXITSTATUS(err)) {
upslogx(LOG_INFO, "exec_cmd(%s) returned %d", buf, WEXITSTATUS(err));
}
} else {
if (WIFSIGNALED(err)) {
upslogx(LOG_WARNING, "exec_cmd(%s) terminated with signal %d", buf, WTERMSIG(err));
} else {
upslogx(LOG_ERR, "Execute command failure: %s", buf);
}
}
#else
if(err != -1) {
upslogx(LOG_INFO, "Execute command \"%s\" OK", buf);
}
else {
upslogx(LOG_ERR, "Execute command failure : %s", buf);
}
#endif
return;
}
static void removetimer(ttype_t *tfind)
{
ttype_t *tmp, *last;
last = NULL;
tmp = thead;
while (tmp) {
if (tmp == tfind) { /* found it */
if (last == NULL) /* deleting first */
thead = tmp->next;
else
last->next = tmp->next;
free(tmp->name);
free(tmp);
return;
}
last = tmp;
tmp = tmp->next;
}
/* this one should never happen */
upslogx(LOG_ERR, "removetimer: failed to locate target at %p", (void *)tfind);
}
static void checktimers(void)
{
ttype_t *tmp, *tmpnext;
time_t now;
static int emptyctr = 0;
/* if the queue is empty we might be ready to exit */
if (!thead) {
emptyctr++;
/* wait a little while in case someone wants us again */
if (emptyctr < EMPTY_WAIT)
return;
if (verbose)
upslogx(LOG_INFO, "Timer queue empty, exiting");
#ifdef UPSSCHED_RACE_TEST
upslogx(LOG_INFO, "triggering race: sleeping 15 sec before exit");
sleep(15);
#endif
unlink(pipefn);
exit(EXIT_SUCCESS);
}
emptyctr = 0;
/* flip through LL, look for activity */
tmp = thead;
time(&now);
while (tmp) {
tmpnext = tmp->next;
if (now >= tmp->etime) {
if (verbose)
upslogx(LOG_INFO, "Event: %s ", tmp->name);
exec_cmd(tmp->name);
/* delete from queue */
removetimer(tmp);
}
tmp = tmpnext;
}
}
static void start_timer(const char *name, const char *ofsstr)
{
time_t now;
long ofs;
ttype_t *tmp, *last;
/* get the time */
time(&now);
/* add an event for <now> + <time> */
ofs = strtol(ofsstr, (char **) NULL, 10);
if (ofs < 0) {
upslogx(LOG_INFO, "bogus offset for timer, ignoring");
return;
}
if (verbose)
upslogx(LOG_INFO, "New timer: %s (%ld seconds)", name, ofs);
/* now add to the queue */
tmp = last = thead;
while (tmp) {
last = tmp;
tmp = tmp->next;
}
tmp = xmalloc(sizeof(ttype_t));
tmp->name = xstrdup(name);
tmp->etime = now + ofs;
tmp->next = NULL;
if (last)
last->next = tmp;
else
thead = tmp;
}
static void cancel_timer(const char *name, const char *cname)
{
ttype_t *tmp;
for (tmp = thead; tmp != NULL; tmp = tmp->next) {
if (!strcmp(tmp->name, name)) { /* match */
if (verbose)
upslogx(LOG_INFO, "Cancelling timer: %s", name);
removetimer(tmp);
return;
}
}
/* this is not necessarily an error */
if (cname && cname[0]) {
if (verbose)
upslogx(LOG_INFO, "Cancel %s, event: %s", name, cname);
exec_cmd(cname);
}
}
#ifndef WIN32
static void us_serialize(int op)
{
static int pipefd[2];
ssize_t ret;
char ch;
switch(op) {
case SERIALIZE_INIT:
ret = pipe(pipefd);
if (ret != 0)
fatal_with_errno(EXIT_FAILURE, "serialize: pipe");
break;
case SERIALIZE_SET:
close(pipefd[0]);
close(pipefd[1]);
break;
case SERIALIZE_WAIT:
close(pipefd[1]);
ret = read(pipefd[0], &ch, 1);
close(pipefd[0]);
break;
}
}
#endif
static TYPE_FD open_sock(void)
{
TYPE_FD fd;
#ifndef WIN32
int ret;
struct sockaddr_un ssaddr;
check_unix_socket_filename(pipefn);
fd = socket(AF_UNIX, SOCK_STREAM, 0);
if (INVALID_FD(fd))
fatal_with_errno(EXIT_FAILURE, "Can't create a unix domain socket");
ssaddr.sun_family = AF_UNIX;
snprintf(ssaddr.sun_path, sizeof(ssaddr.sun_path), "%s", pipefn);
unlink(pipefn);
umask(0007);
ret = bind(fd, (struct sockaddr *) &ssaddr, sizeof ssaddr);
if (ret < 0)
fatal_with_errno(EXIT_FAILURE, "bind %s failed", pipefn);
ret = chmod(pipefn, 0660);
if (ret < 0)
fatal_with_errno(EXIT_FAILURE, "chmod(%s, 0660) failed", pipefn);
ret = listen(fd, US_LISTEN_BACKLOG);
if (ret < 0)
fatal_with_errno(EXIT_FAILURE, "listen(%d, %d) failed", fd, US_LISTEN_BACKLOG);
/* don't leak socket to CMDSCRIPT */
set_close_on_exec(fd);
#else /* WIN32 */
fd = CreateNamedPipe(
pipefn, /* pipe name */
PIPE_ACCESS_DUPLEX | /* read/write access */
FILE_FLAG_OVERLAPPED, /* async IO */
PIPE_TYPE_BYTE |
PIPE_READMODE_BYTE |
PIPE_WAIT,
PIPE_UNLIMITED_INSTANCES, /* max. instances */
BUF_LEN, /* output buffer size */
BUF_LEN, /* input buffer size */
0, /* client time-out */
NULL); /* FIXME: default security attributes */
if (INVALID_FD(fd)) {
fatal_with_errno(EXIT_FAILURE,
"Can't create a state socket (windows named pipe)");
}
/* Prepare an async wait on a connection on the pipe */
memset(&connect_overlapped,0,sizeof(connect_overlapped));
connect_overlapped.hEvent = CreateEvent(NULL, /*Security*/
FALSE, /* auto-reset*/
FALSE, /* inital state = non signaled*/
NULL /* no name*/);
if (connect_overlapped.hEvent == NULL) {
fatal_with_errno(EXIT_FAILURE, "Can't create event");
}
/* Wait for a connection */
ConnectNamedPipe(fd,&connect_overlapped);
#endif
return fd;
}
static void conn_del(conn_t *target)
{
conn_t *tmp, *last = NULL;
tmp = connhead;
while (tmp) {
if (tmp == target) {
if (last)
last->next = tmp->next;
else
connhead = tmp->next;
pconf_finish(&tmp->ctx);
free(tmp);
return;
}
last = tmp;
tmp = tmp->next;
}
upslogx(LOG_ERR, "Tried to delete a bogus state connection");
}
static int send_to_one(conn_t *conn, const char *fmt, ...)
{
ssize_t ret;
size_t buflen;
va_list ap;
char buf[US_SOCK_BUF_LEN];
va_start(ap, fmt);
#ifdef HAVE_PRAGMAS_FOR_GCC_DIAGNOSTIC_IGNORED_FORMAT_NONLITERAL
#pragma GCC diagnostic push
#endif
#ifdef HAVE_PRAGMA_GCC_DIAGNOSTIC_IGNORED_FORMAT_NONLITERAL
#pragma GCC diagnostic ignored "-Wformat-nonliteral"
#endif
#ifdef HAVE_PRAGMA_GCC_DIAGNOSTIC_IGNORED_FORMAT_SECURITY
#pragma GCC diagnostic ignored "-Wformat-security"
#endif
vsnprintf(buf, sizeof(buf), fmt, ap);
#ifdef HAVE_PRAGMAS_FOR_GCC_DIAGNOSTIC_IGNORED_FORMAT_NONLITERAL
#pragma GCC diagnostic pop
#endif
va_end(ap);
buflen = strlen(buf);
if (buflen >= SSIZE_MAX) {
/* Can't compare buflen to ret */
upsdebugx(2, "send_to_one(): buffered message too large");
if (VALID_FD(conn->fd)) {
#ifndef WIN32
close(conn->fd);
#else
FlushFileBuffers(conn->fd);
CloseHandle(conn->fd);
#endif
conn->fd = ERROR_FD;
}
conn_del(conn);
return 0; /* failed */
}
#ifndef WIN32
ret = write(conn->fd, buf, buflen);
if ((ret < 1) || (ret != (ssize_t) buflen)) {
upsdebugx(2, "write failed on socket %d, disconnecting", conn->fd);
close(conn->fd);
conn_del(conn);
return 0; /* failed */
}
#else
DWORD bytesWritten = 0;
BOOL result = FALSE;
result = WriteFile (conn->fd, buf, buflen, &bytesWritten, NULL);
if (result == 0) {
upsdebugx(2, "write failed on handle %p, disconnecting", conn->fd);
/* FIXME not sure this is the right way to close a connection */
if( conn->read_overlapped.hEvent != INVALID_HANDLE_VALUE) {
CloseHandle(conn->read_overlapped.hEvent);
conn->read_overlapped.hEvent = INVALID_HANDLE_VALUE;
}
DisconnectNamedPipe(conn->fd);
CloseHandle(conn->fd);
conn_del(conn);
return 0;
}
else {
ret = (ssize_t)bytesWritten;
}
if ((ret < 1) || (ret != (ssize_t)buflen)) {
upsdebugx(2, "write to fd %p failed", conn->fd);
/* FIXME not sure this is the right way to close a connection */
if (conn->read_overlapped.hEvent != INVALID_HANDLE_VALUE) {
CloseHandle(conn->read_overlapped.hEvent);
conn->read_overlapped.hEvent = INVALID_HANDLE_VALUE;
}
DisconnectNamedPipe(conn->fd);
CloseHandle(conn->fd);
return 0; /* failed */
}
#endif
return 1; /* OK */
}
static TYPE_FD conn_add(TYPE_FD sockfd)
{
TYPE_FD acc;
#ifndef WIN32
int ret;
conn_t *tmp, *last;
struct sockaddr_un saddr;
#if defined(__hpux) && !defined(_XOPEN_SOURCE_EXTENDED)
int salen;
#else
socklen_t salen;
#endif
salen = sizeof(saddr);
acc = accept(sockfd, (struct sockaddr *) &saddr, &salen);
if (INVALID_FD(acc)) {
upslog_with_errno(LOG_ERR, "accept on unix fd failed");
return ERROR_FD;
}
/* don't leak connection to CMDSCRIPT */
set_close_on_exec(acc);
/* enable nonblocking I/O */
ret = fcntl(acc, F_GETFL, 0);
if (ret < 0) {
upslog_with_errno(LOG_ERR, "fcntl get on unix fd failed");
close(acc);
return ERROR_FD;
}
ret = fcntl(acc, F_SETFL, ret | O_NDELAY);
if (ret < 0) {
upslog_with_errno(LOG_ERR, "fcntl set O_NDELAY on unix fd failed");
close(acc);
return ERROR_FD;
}
tmp = last = connhead;
while (tmp) {
last = tmp;
tmp = tmp->next;
}
tmp = xmalloc(sizeof(conn_t));
tmp->fd = acc;
tmp->next = NULL;
if (last)
last->next = tmp;
else
connhead = tmp;
upsdebugx(3, "new connection on fd %d", acc);
pconf_init(&tmp->ctx, NULL);
#else /* WIN32 */
conn_t *conn, *tmp, *last;
/* We have detected a connection on the opened pipe. So we start
by saving its handle and create a new pipe for future connection */
conn = xcalloc(1, sizeof(*conn));
conn->fd = sockfd;
/* sock is the handle of the connection pending pipe */
acc = CreateNamedPipe(
pipefn, /* pipe name */
PIPE_ACCESS_DUPLEX | /* read/write access */
FILE_FLAG_OVERLAPPED, /* async IO */
PIPE_TYPE_BYTE |
PIPE_READMODE_BYTE |
PIPE_WAIT,
PIPE_UNLIMITED_INSTANCES, /* max. instances */
BUF_LEN, /* output buffer size */
BUF_LEN, /* input buffer size */
0, /* client time-out */
NULL); /* FIXME: default security attribute */
if (INVALID_FD(acc)) {
fatal_with_errno(EXIT_FAILURE,
"Can't create a state socket (windows named pipe)");
}
/* Prepare a new async wait for a connection on the pipe */
CloseHandle(connect_overlapped.hEvent);
memset(&connect_overlapped,0,sizeof(connect_overlapped));
connect_overlapped.hEvent = CreateEvent(NULL, /*Security*/
FALSE, /* auto-reset*/
FALSE, /* inital state = non signaled*/
NULL /* no name*/);
if (connect_overlapped.hEvent == NULL) {
fatal_with_errno(EXIT_FAILURE, "Can't create event");
}
/* Wait for a connection */
ConnectNamedPipe(acc,&connect_overlapped);
/* A new pipe waiting for new client connection has been created.
We could manage the current connection now */
/* Start a read operation on the newly connected pipe so we could wait
on the event associated to this IO */
memset(&conn->read_overlapped,0,sizeof(conn->read_overlapped));
memset(conn->buf,0,sizeof(conn->buf));
conn->read_overlapped.hEvent = CreateEvent(NULL, /*Security*/
FALSE, /* auto-reset*/
FALSE, /* inital state = non signaled*/
NULL /* no name*/);
if (conn->read_overlapped.hEvent == NULL) {
fatal_with_errno(EXIT_FAILURE, "Can't create event");
}
ReadFile (conn->fd,conn->buf,1,NULL,&(conn->read_overlapped));
conn->next = NULL;
tmp = last = connhead;
while (tmp) {
last = tmp;
tmp = tmp->next;
}
if (last)
last->next = conn;
else
connhead = conn;
upsdebugx(3, "new connection on fd %p", acc);
pconf_init(&conn->ctx, NULL);
#endif
return acc;
}
static int sock_arg(conn_t *conn)
{
if (conn->ctx.numargs < 1)
return 0;
/* CANCEL <name> [<cmd>] */
if (!strcmp(conn->ctx.arglist[0], "CANCEL")) {
if (conn->ctx.numargs < 3)
cancel_timer(conn->ctx.arglist[1], NULL);
else
cancel_timer(conn->ctx.arglist[1], conn->ctx.arglist[2]);
send_to_one(conn, "OK\n");
return 1;
}
if (conn->ctx.numargs < 3)
return 0;
/* START <name> <length> */
if (!strcmp(conn->ctx.arglist[0], "START")) {
start_timer(conn->ctx.arglist[1], conn->ctx.arglist[2]);
send_to_one(conn, "OK\n");
return 1;
}
/* unknown */
return 0;
}
static void log_unknown(size_t numarg, char **arg)
{
size_t i;
upslogx(LOG_INFO, "Unknown command on socket: ");
for (i = 0; i < numarg; i++)
upslogx(LOG_INFO, "arg %" PRIuSIZE ": %s", i, arg[i]);
}
static int sock_read(conn_t *conn)
{
int i;
ssize_t ret;
char ch;
for (i = 0; i < US_MAX_READ; i++) {
#ifndef WIN32
ret = read(conn->fd, &ch, 1);
if (ret < 1) {
/* short read = no parsing, come back later */
if ((ret == -1) && (errno == EAGAIN))
return 0;
/* O_NDELAY with zero bytes means nothing to read but
* since read() follows a succesful select() with
* ready file descriptor, ret shouldn't be 0. */
if (ret == 0)
continue;
/* some other problem */
return -1; /* error */
}
#else
DWORD bytesRead;
GetOverlappedResult(conn->fd, &conn->read_overlapped, &bytesRead,FALSE);
if( bytesRead < 1 ) {
/* Restart async read */
memset(conn->buf,0,sizeof(conn->buf));
ReadFile(conn->fd,conn->buf,1,NULL,&(conn->read_overlapped));
return 0;
}
ch = conn->buf[0];
/* Restart async read */
memset(conn->buf,0,sizeof(conn->buf));
ReadFile(conn->fd,conn->buf,1,NULL,&(conn->read_overlapped));
#endif
ret = pconf_char(&conn->ctx, ch);
if (ret == 0) /* nothing to parse yet */
continue;
if (ret == -1) {
upslogx(LOG_NOTICE, "Parse error on sock: %s",
conn->ctx.errmsg);
return 0; /* nothing parsed */
}
/* try to use it, and complain about unknown commands */
if (!sock_arg(conn)) {
log_unknown(conn->ctx.numargs, conn->ctx.arglist);
send_to_one(conn, "ERR UNKNOWN\n");
}
return 1; /* we did some work */
}
return 0; /* fell out without parsing anything */
}
static void start_daemon(TYPE_FD lockfd)
{
int maxfd = 0; /* Unidiomatic use vs. "pipefd" below, which is "int" on non-WIN32 */
TYPE_FD pipefd;
struct timeval tv;
conn_t *tmp;
#ifndef WIN32
int pid, ret;
fd_set rfds;
conn_t *tmpnext;
us_serialize(SERIALIZE_INIT);
if ((pid = fork()) < 0)
fatal_with_errno(EXIT_FAILURE, "Unable to enter background");
if (pid != 0) { /* parent */
/* wait for child to set up the listener */
us_serialize(SERIALIZE_WAIT);
return;
}
/* child */
close(0);
close(1);
close(2);
/* make fds 0-2 point somewhere defined */
if (open("/dev/null", O_RDWR) != 0)
fatal_with_errno(EXIT_FAILURE, "open /dev/null");
if (dup(0) == -1)
fatal_with_errno(EXIT_FAILURE, "dup");
if (dup(0) == -1)
fatal_with_errno(EXIT_FAILURE, "dup");
pipefd = open_sock();
if (verbose)
upslogx(LOG_INFO, "Timer daemon started");
/* release the parent */
us_serialize(SERIALIZE_SET);
/* drop the lock now that the background is running */
unlink(lockfn);
close(lockfd);
/* now watch for activity */
for (;;) {
/* wait at most 1s so we can check our timers regularly */
tv.tv_sec = 1;
tv.tv_usec = 0;
FD_ZERO(&rfds);
FD_SET(pipefd, &rfds);
maxfd = pipefd;
for (tmp = connhead; tmp != NULL; tmp = tmp->next) {
FD_SET(tmp->fd, &rfds);
if (tmp->fd > maxfd)
maxfd = tmp->fd;
}
ret = select(maxfd + 1, &rfds, NULL, NULL, &tv);
if (ret > 0) {
if (FD_ISSET(pipefd, &rfds))
conn_add(pipefd);
tmp = connhead;
while (tmp) {
tmpnext = tmp->next;
if (FD_ISSET(tmp->fd, &rfds)) {
if (sock_read(tmp) < 0) {
close(tmp->fd);
conn_del(tmp);
}
}
tmp = tmpnext;
}
}
checktimers();
}
#else /* WIN32 */
DWORD timeout_ms;
HANDLE rfds[32];
char module[MAX_PATH];
STARTUPINFO sinfo;
PROCESS_INFORMATION pinfo;
if( !GetModuleFileName(NULL,module,MAX_PATH) ) {
fatal_with_errno(EXIT_FAILURE, "Can't retrieve module name");
}
memset(&sinfo,0,sizeof(sinfo));
if(!CreateProcess(module, NULL, NULL,NULL,FALSE,0,NULL,NULL,&sinfo,&pinfo)) {
fatal_with_errno(EXIT_FAILURE, "Can't create child process");
}
pipefd = open_sock();
if (verbose)
upslogx(LOG_INFO, "Timer daemon started");
/* drop the lock now that the background is running */
CloseHandle(lockfd);
DeleteFile(lockfn);
/* now watch for activity */
for (;;) {
/* wait at most 1s so we can check our timers regularly */
tv.tv_sec = 1;
tv.tv_usec = 0;
timeout_ms = (tv.tv_sec * 1000) + (tv.tv_usec / 1000);
maxfd = 0;
/* Wait on the read IO of each connections */
for (tmp = connhead; tmp != NULL; tmp = tmp->next) {
rfds[maxfd] = tmp->read_overlapped.hEvent;
maxfd++;
}
/* Add the connect event */
rfds[maxfd] = connect_overlapped.hEvent;
maxfd++;
DWORD ret_val;
ret_val = WaitForMultipleObjects(
maxfd, /* number of objects in array */
rfds, /* array of objects */
FALSE, /* wait for any object */
timeout_ms); /* timeout in millisecond */
if (ret_val == WAIT_FAILED) {
upslog_with_errno(LOG_ERR, "waitfor failed");
return;
}
/* timer has not expired */
if (ret_val != WAIT_TIMEOUT) {
/* Retrieve the signaled connection */
for(tmp = connhead; tmp != NULL; tmp = tmp->next) {
if( tmp->read_overlapped.hEvent == rfds[ret_val-WAIT_OBJECT_0]) {
break;
}
}
/* the connection event handle has been signaled */
if (rfds[ret_val] == connect_overlapped.hEvent) {
pipefd = conn_add(pipefd);
}
/* one of the read event handle has been signaled */
else {
if( tmp != NULL) {
if (sock_read(tmp) < 0) {
CloseHandle(tmp->fd);
conn_del(tmp);
}
}
}
}
checktimers();
}
#endif
}
/* --- 'client' functions --- */
static TYPE_FD try_connect(void)
{
TYPE_FD pipefd;
#ifndef WIN32
int ret;
struct sockaddr_un saddr;
check_unix_socket_filename(pipefn);
memset(&saddr, '\0', sizeof(saddr));
saddr.sun_family = AF_UNIX;
snprintf(saddr.sun_path, sizeof(saddr.sun_path), "%s", pipefn);
pipefd = socket(AF_UNIX, SOCK_STREAM, 0);
if (INVALID_FD(pipefd))
fatal_with_errno(EXIT_FAILURE, "socket");
ret = connect(pipefd, (const struct sockaddr *) &saddr, sizeof(saddr));
if (ret != -1)
return pipefd;
#else /* WIN32 */
BOOL result = FALSE;
result = WaitNamedPipe(pipefn,NMPWAIT_USE_DEFAULT_WAIT);
if (result == FALSE) {
return ERROR_FD;
}
pipefd = CreateFile(
pipefn, /* pipe name */
GENERIC_READ | /* read and write access */
GENERIC_WRITE,
0, /* no sharing */
NULL, /* default security attributes FIXME */
OPEN_EXISTING, /* opens existing pipe */
FILE_FLAG_OVERLAPPED, /* enable async IO */
NULL); /* no template file */
if (VALID_FD(pipefd))
return pipefd;
#endif
return ERROR_FD;
}
static TYPE_FD get_lock(const char *fn)
{
#ifndef WIN32
return open(fn, O_RDONLY | O_CREAT | O_EXCL, 0);
#else
return CreateFile(fn,GENERIC_ALL,0,NULL,CREATE_NEW,FILE_ATTRIBUTE_NORMAL,NULL);
#endif
}
/* try to connect to bg process, and start one if necessary */
static TYPE_FD check_parent(const char *cmd, const char *arg2)
{
TYPE_FD pipefd, lockfd;
int tries = 0;
for (tries = 0; tries < MAX_TRIES; tries++) {
pipefd = try_connect();
if (VALID_FD(pipefd))
return pipefd;
/* timer daemon isn't running */
/* it's not running, so there's nothing to cancel */
if (!strcmp(cmd, "CANCEL") && (arg2 == NULL))