-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlistenfork.cc
803 lines (645 loc) · 19 KB
/
listenfork.cc
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
/*
* Copyright (c) 2011, Adrian Thurston <[email protected]>
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#define __STDC_FORMAT_MACROS 1
#define __STDC_LIMIT_MACROS 1
#include "dsnp.h"
#include "error.h"
#include "dlist.h"
#include "keyagent.h"
#include <inttypes.h>
#include <stdint.h>
#include <openssl/rand.h>
#include <openssl/bio.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>
#include <sys/time.h>
#include <sys/resource.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <iostream>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <pwd.h>
bool stop = false;
bool logFileReopen = false;
void sigLogFileReopen( int signum )
{
logFileReopen = true;
}
void quit( int signum )
{
stop = true;
}
void thatsOkay( int signum )
{
}
void dieHandler( int signum )
{
error( "caught signal %d, exiting\n", signum );
exit(1);
}
void workerSignalHandlers()
{
signal( SIGHUP, &dieHandler );
signal( SIGINT, &dieHandler );
signal( SIGQUIT, &dieHandler );
signal( SIGILL, &dieHandler );
signal( SIGABRT, &dieHandler );
signal( SIGFPE, &dieHandler );
signal( SIGSEGV, &dieHandler );
signal( SIGPIPE, &dieHandler );
signal( SIGTERM, &dieHandler );
}
void listenerSignalHandlers()
{
signal( SIGHUP, gbl.background ? sigLogFileReopen : quit );
signal( SIGINT, quit );
signal( SIGQUIT, quit );
signal( SIGTERM, quit );
signal( SIGILL, quit );
signal( SIGABRT, quit );
signal( SIGFPE, quit );
signal( SIGSEGV, quit );
signal( SIGPIPE, quit );
signal( SIGALRM, quit );
signal( SIGCHLD, thatsOkay );
}
void Server::runServerBare( int sockFd )
{
/* This can throw. */
bioWrap.makeNonBlocking();
/* Setup the parser and run it off the server's bioWrap. */
ServerParser parser( this );
bioWrap.readParse( parser );
close( sockFd );
}
void Server::runServer( int sockFd )
{
/* Set BIOs that wrap up the input BIO to wrap stdin. */
bioWrap.setSockFd( sockFd );
try {
runServerBare( sockFd );
}
catch ( UserError &e ) {
e.print( bioWrap );
}
if ( mysql != 0 )
mysql_close( mysql );
}
int serverProcess( Config *c, TlsContext &tlsContext, int sockFd, int privFd, int notifFd )
{
/* Drop privs. */
setgid( gbl.dsnpdGid );
setuid( gbl.dsnpdUid );
workerSignalHandlers();
KeyAgent keyAgent( privFd );
NotifAgent notifAgent( notifFd );
Server server( c, tlsContext, keyAgent, notifAgent );
server.runServer( sockFd );
message( "SERVER EXITING\n" );
/* Tell the priv and notification processes to quit. */
notifAgent.quit();
keyAgent.quit();
return 0;
}
int receivedQueueRun( Config *c, TlsContext &tlsContext, int privFd, int notifFd )
{
/* Drop privs. */
setgid( gbl.dsnpdGid );
setuid( gbl.dsnpdUid );
workerSignalHandlers();
KeyAgent keyAgent( privFd );
NotifAgent notifAgent( notifFd );
Server server( c, tlsContext, keyAgent, notifAgent );
server.runReceivedQueue();
debug( DBG_PROC, "RECEIVED QUEUE RUN SERVER EXITING\n" );
/* Tell the priv and notification processes to quit. */
notifAgent.quit();
keyAgent.quit();
return 0;
}
int issueCommand( Config *c, TlsContext &tlsContext, int privFd, int notifFd )
{
/* Drop privs. */
setgid( gbl.dsnpdGid );
setuid( gbl.dsnpdUid );
workerSignalHandlers();
KeyAgent keyAgent( privFd );
NotifAgent notifAgent( notifFd );
Server server( c, tlsContext, keyAgent, notifAgent );
int exitStatus = server.runCommand();
debug( DBG_PROC, "COMAND EXITING\n" );
/* Tell the priv and notification processes to quit. */
notifAgent.quit();
keyAgent.quit();
return exitStatus;
}
void ListenFork::dispatch( Config *c,
TlsContext &tlsContext, DispatchType dispatchType,
int listenFd, int sockFd, sockaddr_in *, socklen_t )
{
int result, pair[2], privFd, notifFd;
/* Make the socket pair for comm with dsnpk. Transmit it. */
result = socketpair( PF_UNIX, SOCK_STREAM, 0, pair );
if ( result < 0 )
fatal( "socketpair failed: %s\n", strerror(errno) );
debug( DBG_PROC, "sending comm socket (%d) to dsnpk\n", pair[1] );
privFd = pair[0];
transmitFd( gbl.privCmdFd, AC_SOCKET, pair[1] );
close( pair[1] );
/* Make the socket pair for comm with the notification process. Transmit
* it. */
result = socketpair( PF_UNIX, SOCK_STREAM, 0, pair );
if ( result < 0 )
fatal( "socketpair failed: %s\n", strerror(errno) );
notifFd = pair[0];
debug( DBG_PROC, "sending comm socket (%d) to "
"notif dispatcher\n", pair[1] );
transmitFd( gbl.notifCmdFd, AC_SOCKET, pair[1] );
close( pair[1] );
debug( DBG_PROC, "forking server process\n" );
pid_t pid = fork();
if ( pid < 0 )
fatal( "fork failed %s\n", strerror(errno) );
if ( pid == 0 ) {
/* child. */
gbl.pid = getpid();
debug( DBG_PROC, "forked server process\n" );
/* Not used for deplay queue runs. */
int exitVal = 250; /* just cause. */
/* The listenFd may not be supplied if this is a command context. */
if ( listenFd >= 0 )
close( listenFd );
switch ( dispatchType ) {
case ServerProcess:
exitVal = ::serverProcess( c, tlsContext, sockFd, privFd, notifFd );
break;
case ReceivedQueueRun:
exitVal = ::receivedQueueRun( c, tlsContext, privFd, notifFd );
break;
case Command:
exitVal = ::issueCommand( c, tlsContext, privFd, notifFd );
break;
}
exit( exitVal );
}
Reap *reap = new Reap( pid );
reapList.append( reap );
result = close( privFd );
if ( result < 0 )
error( "priv fd close faild: %s\n", strerror(errno) );
result = close( notifFd );
if ( result < 0 )
error( "notif fd close faild: %s\n", strerror(errno) );
if ( sockFd >= 0 ) {
result = close( sockFd );
if ( result < 0 )
error( "sock fd close faild: %s\n", strerror(errno) );
}
}
SSL_CTX *sslClientCtx( ConfigSection *c )
{
/* FIXME: these should not be throws. Done at startup before any
* connections come in. */
/* Create the SSL_CTX. */
SSL_CTX *ctx = SSL_CTX_new(TLSv1_client_method());
if ( ctx == NULL )
throw SslNewContextFailure();
/* Load the CA certificates that we will use to verify. */
int result = SSL_CTX_load_verify_locations( ctx, CA_CERT_FILE, NULL );
if ( !result )
throw SslCaCertLoadFailure( CA_CERT_FILE );
return ctx;
}
SSL_CTX *sslServerCtx( ConfigSection *c )
{
/* FIXME: these should not be throws. Done at startup before any
* connections come in. */
/* Create the SSL_CTX. */
SSL_CTX *ctx = SSL_CTX_new(SSLv23_method());
if ( ctx == NULL )
throw SslContextCreationFailed();
if ( c->CFG_TLS_CRT.length == 0 )
throw SslParamNotSet( "CFG_TLS_CRT" );
if ( c->CFG_TLS_KEY.length == 0 )
throw SslParamNotSet( "CFG_TLS_KEY" );
int result = SSL_CTX_use_certificate_chain_file( ctx, c->CFG_TLS_CRT );
if ( result != 1 )
fatal( "failed to load TLS CRT file %s\n", c->CFG_TLS_CRT() );
result = SSL_CTX_use_PrivateKey_file( ctx, c->CFG_TLS_KEY, SSL_FILETYPE_PEM );
if ( result != 1 )
fatal( "failed to load TLS KEY file %s\n", c->CFG_TLS_KEY() );
return ctx;
}
void tlsInitialization( TlsContext &tlsContext, Config *c )
{
/* Global initialization. */
SSL_load_error_strings();
ERR_load_BIO_strings();
OpenSSL_add_all_algorithms();
SSL_library_init();
for ( ConfigSection *sect = c->hostList.head;
sect != 0; sect = sect->next )
{
/* Something strange here: doing the client load first causes problems.
* */
SSL_CTX *serverCtx = sslServerCtx( sect );
tlsContext.serverCtx.push_back( serverCtx );
SSL_CTX *clientCtx = sslClientCtx( sect );
tlsContext.clientCtx.push_back( clientCtx );
}
}
void randomDataInitialization()
{
/* FIXME: this needs improvement. */
RAND_load_file("/dev/urandom", 1024);
}
void QueueRunner::runQueue()
{
/*
* This is rather noisy.
* message("running queue\n");
*/
try {
runMessageQueue();
runFofMessageQueue();
runBroadcastQueue();
}
catch ( UserError &e ) {
/* We have no more output. */
BioWrap bioWrap( BioWrap::Null );
e.print( bioWrap );
}
}
void TokenFlusher::flushLoginTokens()
{
DbQuery loginTokens( mysql,
"SELECT user_id, login_token, session_id, expires "
"FROM login_token"
);
while ( true ) {
MYSQL_ROW row = loginTokens.fetchRow();
if ( !row )
break;
long long userId = parseId( row[0] );
const char *loginToken = row[1];
const char *sessionId = row[2];
const char *expires = row[3];
User user( mysql, userId );
String site = user.site();
message( "expiring %lld %s %s %s\n", userId, loginToken, sessionId, expires );
notifAgent.notifLogout( site, sessionId );
}
/* Clear the login tokens. */
DbQuery ( mysql, "DELETE FROM login_token" );
}
void TokenFlusher::flushFloginTokens()
{
DbQuery loginTokens( mysql,
"SELECT user_id, identity_id, login_token, session_id, expires "
"FROM flogin_token"
);
while ( true ) {
MYSQL_ROW row = loginTokens.fetchRow();
if ( !row )
break;
long long userId = parseId( row[0] );
long long identityId = parseId( row[1] );
const char *loginToken = row[2];
const char *sessionId = row[3];
const char *expires = row[4];
User user( mysql, userId );
String site = user.site();
message( "expiring %lld %lld %s %s %s\n", userId, identityId, loginToken, sessionId, expires );
notifAgent.notifLogout( site, sessionId );
}
/* Clear the login tokens. */
DbQuery ( mysql, "DELETE FROM flogin_token" );
}
void TokenFlusher::flush()
{
message("flushing all tokens\n");
mysql = dbConnect();
flushLoginTokens();
flushFloginTokens();
mysql_close( mysql );
}
void initialTimerRunProcess( Config *c, int notifFd )
{
/* Drop privs. */
setgid( gbl.dsnpdGid );
setuid( gbl.dsnpdUid );
NotifAgent notifAgent( notifFd );
if ( gbl.tokenFlush ) {
TokenFlusher tokenFlusher( c, notifAgent );
tokenFlusher.flush();
}
notifAgent.quit();
}
void ListenFork::initialTimerRun( Config *c )
{
int result, pair[2], notifFd;
/* Make the socket pair for comm with the notification process. Transmit
* it. */
result = socketpair( PF_UNIX, SOCK_STREAM, 0, pair );
if ( result < 0 )
fatal( "socketpair failed: %s\n", strerror(errno) );
notifFd = pair[0];
debug( DBG_PROC, "sending comm socket (%d) to "
"notif dispatcher\n", pair[1] );
transmitFd( gbl.notifCmdFd, AC_SOCKET, pair[1] );
close( pair[1] );
debug( DBG_PROC, "forking initial timer run\n" );
pid_t pid = fork();
if ( pid < 0 )
fatal( "fork failed %s\n", strerror(errno) );
if ( pid == 0 ) {
close( gbl.privCmdFd );
close( gbl.notifCmdFd );
/* child. */
gbl.pid = getpid();
debug( DBG_PROC, "forked initial timer run\n" );
initialTimerRunProcess( c, notifFd );
exit( 0 );
}
close( notifFd );
Reap *reap = new Reap( pid );
reapList.append( reap );
}
void deliverQueueRunProcess( Config *c, TlsContext &tlsContext )
{
/* Drop privs. */
setgid( gbl.dsnpdGid );
setuid( gbl.dsnpdUid );
QueueRunner queueRunner( c, tlsContext );
queueRunner.runQueue();
}
void ListenFork::deliverQueueRun( Config *c, TlsContext &tlsContext, int listenFd )
{
debug( DBG_PROC | DBG_QUEUE, "forking a delivery queue run\n" );
pid_t pid = fork();
if ( pid < 0 )
fatal( "fork failed %s\n", strerror(errno) );
if ( pid == 0 ) {
close( listenFd );
close( gbl.privCmdFd );
close( gbl.notifCmdFd );
/* child. */
gbl.pid = getpid();
debug( DBG_PROC, "forked timer run\n" );
deliverQueueRunProcess( c, tlsContext );
exit( 0 );
}
Reap *reap = new Reap( pid );
reapList.append( reap );
}
void ListenFork::dispatchReceivedQueueRun( Config *c, TlsContext &tlsContext, int listenFd )
{
/* Use the dispatch mechanism for dealing with deplayed brodcast . */
dispatch( c, tlsContext, ReceivedQueueRun, listenFd, -1, 0, 0 );
}
void ListenFork::dispatchIssueCommand( Config *c, TlsContext &tlsContext )
{
/* Use the dispatch mechanism for dealing with deplayed brodcast . */
dispatch( c, tlsContext, Command, -1, -1, 0, 0 );
}
void finalTimerRunProcess( Config *c, int notifFd )
{
/* Drop privs. */
setgid( gbl.dsnpdGid );
setuid( gbl.dsnpdUid );
NotifAgent notifAgent( notifFd );
if ( gbl.tokenFlush ) {
TokenFlusher tokenFlusher( c, notifAgent );
tokenFlusher.flush();
}
notifAgent.quit();
}
void ListenFork::finalTimerRun( Config *c )
{
int result, pair[2], notifFd;
/* Make the socket pair for comm with the notification process. Transmit
* it. */
result = socketpair( PF_UNIX, SOCK_STREAM, 0, pair );
if ( result < 0 )
fatal( "socketpair failed: %s\n", strerror(errno) );
notifFd = pair[0];
transmitFd( gbl.notifCmdFd, AC_SOCKET, pair[1] );
close( pair[1] );
debug( DBG_PROC, "forking final timer run\n" );
pid_t pid = fork();
if ( pid < 0 )
fatal( "fork failed %s\n", strerror(errno) );
if ( pid == 0 ) {
close( gbl.privCmdFd );
close( gbl.notifCmdFd );
/* child. */
gbl.pid = getpid();
debug( DBG_PROC, "forked final timer run\n" );
finalTimerRunProcess( c, notifFd );
exit( 0 );
}
Reap *reap = new Reap( pid );
reapList.append( reap );
}
int ListenFork::reapChildren( bool wait )
{
int exitStatus = 0;
for ( Reap *reap = reapList.head; reap != 0; ) {
debug( DBG_PROC, "waiting on pid %d\n", reap->pid );
Reap *next = reap->next;
int status = 0;
int result = waitpid( reap->pid, &status, (wait ? 0 : WNOHANG) );
if ( result < 0 )
fatal( "waitpid failed: %s\n", strerror(errno) );
if ( result > 0 && ( WIFEXITED(status) || WIFSIGNALED(status) ) ) {
debug( DBG_PROC, "pid %d exited\n", reap->pid );
exitStatus = WEXITSTATUS(status);
reapList.detach ( reap );
delete reap;
}
reap = next;
}
return exitStatus;
}
/* Opens and transmits log files. We do this in the listener because we still
* have root. */
void sendAgentLogFiles()
{
int dsnpkLogFd = openLogFile( DSNPK_LOG_FILE );
int notifLogFd = openLogFile( NOTIF_LOG_FILE );
debug( DBG_PROC, "sending log file descriptors %d %d\n",
dsnpkLogFd, dsnpkLogFd );
transmitFd( gbl.privCmdFd, AC_LOG_FD, dsnpkLogFd );
transmitFd( gbl.notifCmdFd, AC_LOG_FD, notifLogFd );
/* The dsnpd log file will get wrapped by gbl.logFile and closed when
* reopened. */
close( dsnpkLogFd );
close( notifLogFd );
}
void openLogFile()
{
int dsnpdLogFd = openLogFile( DSNPD_LOG_FILE );
setLogFd( dsnpdLogFd );
}
int ListenFork::run( int port )
{
time_t lastTimerRun = time(0);
long lastReapListSize = 0;
uint64_t lastNextDelivery = UINT64_MAX;
bool lastNextDeliveryValid = false;
long connectionsSinceTimer = 0;
message("STARTING\n");
/* Read the conf file. */
Config *c = new Config;
ConfigParser configParser( DSNPD_CONF, SliceDaemon, c );
listenerSignalHandlers();
/* Open and transmit log files. */
if ( gbl.background )
sendAgentLogFiles();
TlsContext tlsContext;
randomDataInitialization();
tlsInitialization( tlsContext, c );
/* Before going into select we dispatch any commands. */
if ( gbl.issueCommand )
dispatchIssueCommand( c, tlsContext );
else {
/* Start with a listen loop initialization. This initialization gets a
* notification process. */
initialTimerRun( c );
/* Create the socket. */
int listenFd = socket( PF_INET, SOCK_STREAM, 0 );
if ( listenFd < 0 ) {
error( "unable to allocate socket\n" );
return -1;
}
/* Set its address to reusable. */
int optionVal = 1;
setsockopt( listenFd, SOL_SOCKET, SO_REUSEADDR,
(char*)&optionVal, sizeof(int) );
/* bind. */
sockaddr_in sockName;
sockName.sin_family = AF_INET;
sockName.sin_port = htons(port);
sockName.sin_addr.s_addr = htonl (INADDR_ANY);
if ( bind(listenFd, (sockaddr*)&sockName, sizeof(sockName)) < 0 ) {
error( "unable to bind to port %d", port );
close( listenFd );
return -1;
}
/* listen. */
if ( listen( listenFd, 1 ) < 0 ) {
error( "unable put socket in listen mode\n" );
close( listenFd );
return -1;
}
/* accept loop. */
while ( true ) {
fd_set readSet;
FD_ZERO( &readSet );
FD_SET( listenFd, &readSet );
/* Wait no longer than a second. */
timeval tv;
tv.tv_usec = 0;
tv.tv_sec = 1;
int result = select( listenFd+1, &readSet, 0, 0, &tv );
if ( result < 0 && ( errno != EAGAIN && errno != EINTR ) )
fatal("select returned an unexpected error %s\n", strerror(errno) );
if ( stop ) {
message( "received signal to stop\n" );
break;
}
if ( logFileReopen ) {
message("triggering logfile reopen\n");
logFileReopen = false;
openLogFile();
sendAgentLogFiles();
message("completed logfile reopen\n");
}
if ( result > 0 && FD_ISSET( listenFd, &readSet ) ) {
connectionsSinceTimer += 1;
sockaddr_in peer;
socklen_t len = sizeof(sockaddr_in);
result = accept( listenFd, (sockaddr*)&peer, &len );
if ( result < 0 ) {
error( "failed to accept connection: %s\n",
strerror(errno) );
}
else {
dispatch( c, tlsContext, ServerProcess, listenFd, result, &peer, len );
}
}
time_t now = time(0);
if ( now - lastTimerRun > 0 ) {
bool deliveryQueues = false;
bool receiveQueue = false;
bool skipCheck = false;
/* If the last time we checked there were no active children, there
* have been no connections since the last timer (there never were
* any children), the next delivery time is valid, and we haven't
* yet reached it, then we can skip the check. */
if ( lastReapListSize == 0 && connectionsSinceTimer == 0 &&
lastNextDeliveryValid && (uint64_t)now < lastNextDelivery )
{
debug( DBG_QUEUE, "skipping check, now %"PRIu64", lastNextDelivery %"PRIu64"\n",
(uint64_t)now, lastNextDelivery );
skipCheck = true;
}
if ( ! skipCheck ) {
debug( DBG_QUEUE, "checking delivery queues\n" );
ConfigCtx cc( c );
MYSQL *mysql = cc.dbConnect();
deliveryQueues = checkDeliveryQueues( mysql );
receiveQueue = checkReceiveQueue( mysql );
if ( deliveryQueues ) {
/* Goig to run a delivery. The next delivery time will not be valid. */
lastNextDelivery = UINT64_MAX;
lastNextDeliveryValid = false;
}
else {
lastNextDelivery = nextDelivery( mysql );
lastNextDeliveryValid = true;
}
mysql_close( mysql );
}
/* Note we need to do this before the queue runs because they will
* fork children and populate the reap list. */
lastReapListSize = reapList.length();
if ( deliveryQueues )
deliverQueueRun( c, tlsContext, listenFd );
if ( receiveQueue )
dispatchReceivedQueueRun( c, tlsContext, listenFd );
lastTimerRun = now;
connectionsSinceTimer = 0;
}
reapChildren( false );
}
finalTimerRun( c );
close( listenFd );
}
int exitStatus = reapChildren( true );
/* All ok. */
return exitStatus;
}