-
Notifications
You must be signed in to change notification settings - Fork 4
/
fcgi_pm.c
2164 lines (1820 loc) · 67.4 KB
/
fcgi_pm.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
/*
* $Id: fcgi_pm.c,v 1.96 2009/09/29 00:34:10 robs Exp $
*/
#include "fcgi.h"
#if defined(APACHE2) && !defined(WIN32)
#include <pwd.h>
#include <unistd.h>
#include "unixd.h"
#include "apr_signal.h"
#endif
#ifndef WIN32
#include <utime.h>
#endif
#ifdef _HPUX_SOURCE
#include <unistd.h>
#define seteuid(arg) setresuid(-1, (arg), -1)
#endif
int fcgi_dynamic_total_proc_count = 0; /* number of running apps */
time_t fcgi_dynamic_epoch = 0; /* last time kill_procs was
* invoked by process mgr */
time_t fcgi_dynamic_last_analyzed = 0; /* last time calculation was
* made for the dynamic procs */
static time_t now = 0;
#ifdef WIN32
#ifdef APACHE2
#include "mod_cgi.h"
#include "apr_version.h"
#endif
#pragma warning ( disable : 4100 4102 )
static BOOL bTimeToDie = FALSE; /* process termination flag */
HANDLE fcgi_event_handles[3];
#ifndef SIGKILL
#define SIGKILL 9
#endif
#endif
#ifndef WIN32
static int seteuid_root(void)
{
int rc = seteuid(getuid());
if (rc) {
ap_log_error(FCGI_LOG_ALERT, fcgi_apache_main_server,
"FastCGI: seteuid(0) failed");
}
return rc;
}
static int seteuid_user(void)
{
int rc = seteuid(ap_user_id);
if (rc) {
ap_log_error(FCGI_LOG_ALERT, fcgi_apache_main_server,
"FastCGI: seteuid(%u) failed", (unsigned)ap_user_id);
}
return rc;
}
#endif
/*
* Signal the process to exit. How (or if) the process responds
* depends on the FastCGI application library (esp. on Win32) and
* possibly application code (signal handlers and whether or not
* SA_RESTART is on). At any rate, we send the signal with the
* hopes that the process will exit on its own. Later, as we
* review the state of application processes, if we see one marked
* for death, but that hasn't died within a specified period of
* time, fcgi_kill() is called again with a KILL)
*/
static void fcgi_kill(ServerProcess *process, int sig)
{
FCGIDBG3("fcgi_kill(%ld, %d)", (long) process->pid, sig);
process->state = FCGI_VICTIM_STATE;
#ifdef WIN32
if (sig == SIGTERM)
{
SetEvent(process->terminationEvent);
}
else if (sig == SIGKILL)
{
TerminateProcess(process->handle, 1);
}
else
{
ap_assert(0);
}
#else /* !WIN32 */
if (fcgi_wrapper)
{
seteuid_root();
}
kill(process->pid, sig);
if (fcgi_wrapper)
{
seteuid_user();
}
#endif /* !WIN32 */
}
/*******************************************************************************
* Send SIGTERM to each process in the server class, remove socket
* file if appropriate. Currently this is only called when the PM is shutting
* down and thus memory isn't freed and sockets and files aren't closed.
*/
static void shutdown_all()
{
fcgi_server *s = fcgi_servers;
while (s)
{
ServerProcess *proc = s->procs;
int i;
int numChildren = (s->directive == APP_CLASS_DYNAMIC)
? dynamicMaxClassProcs
: s->numProcesses;
/* Send TERM to all processes */
for (i = 0; i < numChildren; i++, proc++)
{
if (proc->state == FCGI_RUNNING_STATE)
{
fcgi_kill(proc, SIGTERM);
}
}
s = s->next;
}
#ifndef WIN32
s = fcgi_servers;
while (s)
{
if (s->socket_path != NULL && s->directive != APP_CLASS_EXTERNAL)
{
struct timeval tv;
/* sleep two seconds to let the children terminate themselves */
tv.tv_sec = 2;
tv.tv_usec = 0;
ap_select(0, NULL, NULL, NULL, &tv);
while (s)
{
if (s->socket_path != NULL && s->directive != APP_CLASS_EXTERNAL)
{
/* Remove the socket file */
if (unlink(s->socket_path) != 0 && errno != ENOENT) {
ap_log_error(FCGI_LOG_ERR, fcgi_apache_main_server,
"FastCGI: unlink() failed to remove socket file \"%s\" for%s server \"%s\"",
s->socket_path,
(s->directive == APP_CLASS_DYNAMIC) ? " (dynamic)" : "", s->fs_path);
}
}
s = s->next;
}
break;
}
s = s->next;
}
#endif
#if defined(WIN32) && (WIN32_SHUTDOWN_GRACEFUL_WAIT > 0)
/*
* WIN32 applications may not have support for the shutdown event
* depending on their application library version
*/
Sleep(WIN32_SHUTDOWN_GRACEFUL_WAIT);
s = fcgi_servers;
while (s)
{
ServerProcess *proc = s->procs;
int i;
int numChildren = (s->directive == APP_CLASS_DYNAMIC)
? dynamicMaxClassProcs
: s->numProcesses;
/* Send KILL to all processes */
for (i = 0; i < numChildren; i++, proc++)
{
if (proc->state == FCGI_RUNNING_STATE)
{
fcgi_kill(proc, SIGKILL);
}
}
s = s->next;
}
#endif /* WIN32 */
}
static int init_listen_sock(fcgi_server * fs)
{
ap_assert(fs->directive != APP_CLASS_EXTERNAL);
/* Create the socket */
if ((fs->listenFd = socket(fs->socket_addr->sa_family, SOCK_STREAM, 0)) < 0)
{
#ifdef WIN32
errno = WSAGetLastError(); /* Not sure if this will work as expected */
#endif
ap_log_error(FCGI_LOG_CRIT_ERRNO, fcgi_apache_main_server,
"FastCGI: can't create %sserver \"%s\": socket() failed",
(fs->directive == APP_CLASS_DYNAMIC) ? "(dynamic) " : "",
fs->fs_path);
return -1;
}
#ifndef WIN32
if (fs->socket_addr->sa_family == AF_UNIX)
{
/* Remove any existing socket file.. just in case */
unlink(((struct sockaddr_un *)fs->socket_addr)->sun_path);
}
else
#endif
{
int flag = 1;
setsockopt(fs->listenFd, SOL_SOCKET, SO_REUSEADDR, (char *)&flag, sizeof(flag));
}
/* Bind it to the socket_addr */
if (bind(fs->listenFd, fs->socket_addr, fs->socket_addr_len))
{
char port[11];
#ifdef WIN32
errno = WSAGetLastError();
#endif
ap_snprintf(port, sizeof(port), "port=%d",
((struct sockaddr_in *)fs->socket_addr)->sin_port);
ap_log_error(FCGI_LOG_CRIT_ERRNO, fcgi_apache_main_server,
"FastCGI: can't create %sserver \"%s\": bind() failed [%s]",
(fs->directive == APP_CLASS_DYNAMIC) ? "(dynamic) " : "",
fs->fs_path,
#ifndef WIN32
(fs->socket_addr->sa_family == AF_UNIX) ?
((struct sockaddr_un *)fs->socket_addr)->sun_path :
#endif
port);
}
#ifndef WIN32
/* Twiddle Unix socket permissions */
else if (fs->socket_addr->sa_family == AF_UNIX
&& chmod(((struct sockaddr_un *)fs->socket_addr)->sun_path, S_IRUSR | S_IWUSR))
{
ap_log_error(FCGI_LOG_CRIT, fcgi_apache_main_server,
"FastCGI: can't create %sserver \"%s\": chmod() of socket failed",
(fs->directive == APP_CLASS_DYNAMIC) ? "(dynamic) " : "",
fs->fs_path);
}
#endif
/* Set to listen */
else if (listen(fs->listenFd, fs->listenQueueDepth))
{
#ifdef WIN32
errno = WSAGetLastError();
#endif
ap_log_error(FCGI_LOG_CRIT_ERRNO, fcgi_apache_main_server,
"FastCGI: can't create %sserver \"%s\": listen() failed",
(fs->directive == APP_CLASS_DYNAMIC) ? "(dynamic) " : "",
fs->fs_path);
}
else
{
return 0;
}
#ifdef WIN32
closesocket(fs->listenFd);
#else
close(fs->listenFd);
#endif
fs->listenFd = -1;
return -2;
}
/*
*----------------------------------------------------------------------
*
* pm_main
*
* The FastCGI process manager, which runs as a separate
* process responsible for:
* - Starting all the FastCGI proceses.
* - Restarting any of these processes that die (indicated
* by SIGCHLD).
* - Catching SIGTERM and relaying it to all the FastCGI
* processes before exiting.
*
* Inputs:
* Uses global variable fcgi_servers.
*
* Results:
* Does not return.
*
* Side effects:
* Described above.
*
*----------------------------------------------------------------------
*/
#ifndef WIN32
static int caughtSigTerm = FALSE;
static int caughtSigChld = FALSE;
static int caughtSigAlarm = FALSE;
static void signal_handler(int signo)
{
if ((signo == SIGTERM) || (signo == SIGUSR1) || (signo == SIGHUP)) {
/* SIGUSR1 & SIGHUP are sent by apache to its process group
* when apache get 'em. Apache follows up (1.2.x) with attacks
* on each of its child processes, but we've got the KillMgr
* sitting between us so we never see the KILL. The main loop
* in ProcMgr also checks to see if the KillMgr has terminated,
* and if it has, we handl it as if we should shutdown too. */
caughtSigTerm = TRUE;
} else if(signo == SIGCHLD) {
caughtSigChld = TRUE;
} else if(signo == SIGALRM) {
caughtSigAlarm = TRUE;
}
}
#endif
/*
*----------------------------------------------------------------------
*
* spawn_fs_process --
*
* Fork and exec the specified fcgi process.
*
* Results:
* 0 for successful fork, -1 for failed fork.
*
* In case the child fails before or in the exec, the child
* obtains the error log by calling getErrLog, logs
* the error, and exits with exit status = errno of
* the failed system call.
*
* Side effects:
* Child process created.
*
*----------------------------------------------------------------------
*/
static pid_t spawn_fs_process(fcgi_server *fs, ServerProcess *process)
{
#ifndef WIN32
pid_t child_pid;
int i;
char *dirName;
char *dnEnd, *failedSysCall;
child_pid = fork();
if (child_pid) {
return child_pid;
}
/* We're the child. We're gonna exec() so pools don't matter. */
dnEnd = strrchr(fs->fs_path, '/');
if (dnEnd == NULL) {
dirName = "./";
} else {
dirName = ap_pcalloc(fcgi_config_pool, dnEnd - fs->fs_path + 1);
dirName = memcpy(dirName, fs->fs_path, dnEnd - fs->fs_path);
}
if (chdir(dirName) < 0) {
failedSysCall = "chdir()";
goto FailedSystemCallExit;
}
#ifndef __EMX__
/* OS/2 dosen't support nice() */
if (fs->processPriority != 0) {
if (nice(fs->processPriority) == -1) {
failedSysCall = "nice()";
goto FailedSystemCallExit;
}
}
#endif
/* Open the listenFd on spec'd fd */
if (fs->listenFd != FCGI_LISTENSOCK_FILENO)
dup2(fs->listenFd, FCGI_LISTENSOCK_FILENO);
/* Close all other open fds, except stdout/stderr. Leave these two open so
* FastCGI applications don't have to find and fix ALL 3rd party libs that
* write to stdout/stderr inadvertantly. For now, just leave 'em open to the
* main server error_log - @@@ provide a directive control where this goes.
*/
ap_error_log2stderr(fcgi_apache_main_server);
dup2(2, 1);
for (i = 0; i < FCGI_MAX_FD; i++) {
if (i != FCGI_LISTENSOCK_FILENO && i != 2 && i != 1) {
close(i);
}
}
/* Ignore SIGPIPE by default rather than terminate. The fs SHOULD
* install its own handler. */
signal(SIGPIPE, SIG_IGN);
if (fcgi_wrapper)
{
char *shortName;
/* Relinquish our root real uid powers */
seteuid_root();
setuid(ap_user_id);
/* Apache (2 anyway) doesn't use suexec if there is no user/group in
* effect - this translates to a uid/gid of 0/0 (which should never
* be a valid uid/gid for an suexec invocation so it should be safe */
if (fs->uid == 0 && fs->gid == 0) {
goto NO_SUEXEC;
}
#ifdef NO_SUEXEC_FOR_AP_USER_N_GROUP
/* AP13 does not use suexec if the target uid/gid is the same as the
* server's - AP20 does. I (now) consider the AP2 approach better
* (fcgi_pm.c v1.42 incorporated the 1.3 behaviour, v1.84 reverted it,
* v1.85 added the compile time option to use the old behaviour). */
if (fcgi_user_id == fs->uid && fcgi_group_id == fs->gid) {
goto NO_SUEXEC;
}
#endif
shortName = strrchr(fs->fs_path, '/') + 1;
do {
execle(fcgi_wrapper, fcgi_wrapper, fs->username, fs->group,
shortName, NULL, fs->envp);
} while (errno == EINTR);
}
else
{
NO_SUEXEC:
do {
execle(fs->fs_path, fs->fs_path, NULL, fs->envp);
} while (errno == EINTR);
}
failedSysCall = "execle()";
FailedSystemCallExit:
fprintf(stderr, "FastCGI: can't start server \"%s\" (pid %ld), %s failed: %s\n",
fs->fs_path, (long) getpid(), failedSysCall, strerror(errno));
exit(-1);
/* avoid an irrelevant compiler warning */
return(0);
#else /* WIN32 */
#ifdef APACHE2
/* based on mod_cgi.c:run_cgi_child() */
apr_pool_t * tp;
char * termination_env_string;
HANDLE listen_handle = INVALID_HANDLE_VALUE;
apr_procattr_t * procattr;
apr_proc_t proc = { 0 };
apr_file_t * file;
int i = 0;
cgi_exec_info_t e_info = { 0 };
request_rec r = { 0 };
const char *command;
const char **argv;
int rv;
APR_OPTIONAL_FN_TYPE(ap_cgi_build_command) *cgi_build_command;
cgi_build_command = APR_RETRIEVE_OPTIONAL_FN(ap_cgi_build_command);
if (cgi_build_command == NULL)
{
ap_log_error(FCGI_LOG_CRIT, fcgi_apache_main_server,
"FastCGI: can't exec server \"%s\", mod_cgi isn't loaded",
fs->fs_path);
return 0;
}
if (apr_pool_create(&tp, fcgi_config_pool))
return 0;
process->terminationEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
if (process->terminationEvent == NULL)
goto CLEANUP;
SetHandleInformation(process->terminationEvent, HANDLE_FLAG_INHERIT, TRUE);
termination_env_string = ap_psprintf(tp,
"_FCGI_SHUTDOWN_EVENT_=%ld", process->terminationEvent);
while (fs->envp[i]) i++;
fs->envp[i++] = termination_env_string;
fs->envp[i] = (char *) fs->mutex_env_string;
ap_assert(fs->envp[i + 1] == NULL);
if (fs->socket_path)
{
SECURITY_ATTRIBUTES sa = { 0 };
sa.bInheritHandle = TRUE;
sa.nLength = sizeof(sa);
listen_handle = CreateNamedPipe(fs->socket_path,
PIPE_ACCESS_DUPLEX,
PIPE_TYPE_BYTE | PIPE_READMODE_BYTE | PIPE_WAIT,
PIPE_UNLIMITED_INSTANCES, 4096, 4096, 0, &sa);
if (listen_handle == INVALID_HANDLE_VALUE)
{
ap_log_error(FCGI_LOG_CRIT, fcgi_apache_main_server,
"FastCGI: can't exec server \"%s\", CreateNamedPipe() failed",
fs->fs_path);
goto CLEANUP;
}
}
else
{
listen_handle = (HANDLE) fs->listenFd;
}
r.per_dir_config = fcgi_apache_main_server->lookup_defaults;
r.server = fcgi_apache_main_server;
r.filename = (char *) fs->fs_path;
r.pool = tp;
r.subprocess_env = apr_table_make(tp, 0);
e_info.cmd_type = APR_PROGRAM;
rv = cgi_build_command(&command, &argv, &r, tp, &e_info);
if (rv != APR_SUCCESS)
{
ap_log_error(FCGI_LOG_CRIT, fcgi_apache_main_server,
"FastCGI: don't know how to spawn cmd child process: %s",
fs->fs_path);
goto CLEANUP;
}
if (apr_procattr_create(&procattr, tp))
goto CLEANUP;
if (apr_procattr_dir_set(procattr, ap_make_dirstr_parent(tp, fs->fs_path)))
goto CLEANUP;
if (apr_procattr_cmdtype_set(procattr, e_info.cmd_type))
goto CLEANUP;
if (apr_procattr_detach_set(procattr, 1))
goto CLEANUP;
if (apr_os_file_put(&file, &listen_handle, 0, tp))
goto CLEANUP;
#if (APR_MAJOR_VERSION >= 1) && (APR_MINOR_VERSION >= 3)
if (apr_procattr_io_set(procattr, APR_FULL_BLOCK, APR_NO_FILE, APR_NO_FILE))
goto CLEANUP;
#endif
/* procattr is opaque so we have to use this - unfortuantely it dups */
if (apr_procattr_child_in_set(procattr, file, NULL))
goto CLEANUP;
if (apr_proc_create(&proc, command, argv, fs->envp, procattr, tp))
goto CLEANUP;
process->handle = proc.hproc;
CLEANUP:
if (fs->socket_path && listen_handle != INVALID_HANDLE_VALUE)
{
CloseHandle(listen_handle);
}
if (i)
{
fs->envp[i - 1] = NULL;
}
ap_destroy_pool(tp);
return proc.pid;
#else /* WIN32 && !APACHE2 */
/* Adapted from Apache's util_script.c ap_call_exec() */
char *interpreter = NULL;
char *quoted_filename;
char *pCommand;
char *pEnvBlock, *pNext;
int i = 0;
int iEnvBlockLen = 1;
file_type_e fileType;
STARTUPINFO si;
PROCESS_INFORMATION pi;
request_rec r;
pid_t pid = -1;
pool * tp = ap_make_sub_pool(fcgi_config_pool);
HANDLE listen_handle = INVALID_HANDLE_VALUE;
char * termination_env_string = NULL;
process->terminationEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
if (process->terminationEvent == NULL)
{
ap_log_error(FCGI_LOG_CRIT, fcgi_apache_main_server,
"FastCGI: can't create termination event for server \"%s\", "
"CreateEvent() failed", fs->fs_path);
goto CLEANUP;
}
SetHandleInformation(process->terminationEvent, HANDLE_FLAG_INHERIT, TRUE);
termination_env_string = ap_psprintf(tp,
"_FCGI_SHUTDOWN_EVENT_=%ld", process->terminationEvent);
if (fs->socket_path)
{
SECURITY_ATTRIBUTES sa;
sa.lpSecurityDescriptor = NULL;
sa.bInheritHandle = TRUE;
sa.nLength = sizeof(sa);
listen_handle = CreateNamedPipe(fs->socket_path,
PIPE_ACCESS_DUPLEX,
PIPE_TYPE_BYTE | PIPE_READMODE_BYTE | PIPE_WAIT,
PIPE_UNLIMITED_INSTANCES, 4096, 4096, 0, &sa);
if (listen_handle == INVALID_HANDLE_VALUE)
{
ap_log_error(FCGI_LOG_CRIT, fcgi_apache_main_server,
"FastCGI: can't exec server \"%s\", CreateNamedPipe() failed", fs->fs_path);
goto CLEANUP;
}
}
else
{
listen_handle = (HANDLE) fs->listenFd;
}
memset(&si, 0, sizeof(si));
memset(&pi, 0, sizeof(pi));
memset(&r, 0, sizeof(r));
/* Can up a fake request to pass to ap_get_win32_interpreter() */
r.per_dir_config = fcgi_apache_main_server->lookup_defaults;
r.server = fcgi_apache_main_server;
r.filename = (char *) fs->fs_path;
r.pool = tp;
fileType = ap_get_win32_interpreter(&r, &interpreter);
if (fileType == eFileTypeUNKNOWN) {
ap_log_error(FCGI_LOG_ERR_NOERRNO, fcgi_apache_main_server,
"FastCGI: %s is not executable; ensure interpreted scripts have "
"\"#!\" as their first line",
fs->fs_path);
ap_destroy_pool(tp);
goto CLEANUP;
}
/*
* We have the interpreter (if there is one) and we have
* the arguments (if there are any).
* Build the command string to pass to CreateProcess.
*/
quoted_filename = ap_pstrcat(tp, "\"", fs->fs_path, "\"", NULL);
if (interpreter && *interpreter) {
pCommand = ap_pstrcat(tp, interpreter, " ", quoted_filename, NULL);
}
else {
pCommand = quoted_filename;
}
/*
* Make child process use hPipeOutputWrite as standard out,
* and make sure it does not show on screen.
*/
si.cb = sizeof(si);
si.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;
si.wShowWindow = SW_HIDE;
si.hStdInput = listen_handle;
/* XXX These should be open to the error_log */
si.hStdOutput = INVALID_HANDLE_VALUE;
si.hStdError = INVALID_HANDLE_VALUE;
/*
* Win32's CreateProcess call requires that the environment
* be passed in an environment block, a null terminated block of
* null terminated strings.
* @todo we should store the env in this format for win32.
*/
while (fs->envp[i])
{
iEnvBlockLen += strlen(fs->envp[i]) + 1;
i++;
}
iEnvBlockLen += strlen(termination_env_string) + 1;
iEnvBlockLen += strlen(fs->mutex_env_string) + 1;
pEnvBlock = (char *) ap_pcalloc(tp, iEnvBlockLen);
i = 0;
pNext = pEnvBlock;
while (fs->envp[i])
{
strcpy(pNext, fs->envp[i]);
pNext += strlen(pNext) + 1;
i++;
}
strcpy(pNext, termination_env_string);
pNext += strlen(pNext) + 1;
strcpy(pNext, fs->mutex_env_string);
if (CreateProcess(NULL, pCommand, NULL, NULL, TRUE,
0,
pEnvBlock,
ap_make_dirstr_parent(tp, fs->fs_path),
&si, &pi))
{
/* Hack to get 16-bit CGI's working. It works for all the
* standard modules shipped with Apache. pi.dwProcessId is 0
* for 16-bit CGIs and all the Unix specific code that calls
* ap_call_exec interprets this as a failure case. And we can't
* use -1 either because it is mapped to 0 by the caller.
*/
pid = (fileType == eFileTypeEXE16) ? -2 : pi.dwProcessId;
process->handle = pi.hProcess;
CloseHandle(pi.hThread);
}
CLEANUP:
if (fs->socket_path && listen_handle != INVALID_HANDLE_VALUE)
{
CloseHandle(listen_handle);
}
ap_destroy_pool(tp);
return pid;
#endif /* !APACHE2 */
#endif /* WIN32 */
}
#ifndef WIN32
static void reduce_privileges(void)
{
const char *name;
if (geteuid() != 0)
return;
#ifndef __EMX__
/* Get username if passed as a uid */
if (ap_user_name[0] == '#') {
uid_t uid = atoi(&ap_user_name[1]);
struct passwd *ent = getpwuid(uid);
if (ent == NULL) {
ap_log_error(FCGI_LOG_ALERT, fcgi_apache_main_server,
"FastCGI: process manager exiting, getpwuid(%u) couldn't determine user name, "
"you probably need to modify the User directive", (unsigned)uid);
exit(1);
}
name = ent->pw_name;
}
else
name = ap_user_name;
/* Change Group */
if (setgid(ap_group_id) == -1) {
ap_log_error(FCGI_LOG_ALERT, fcgi_apache_main_server,
"FastCGI: process manager exiting, setgid(%u) failed", (unsigned)ap_group_id);
exit(1);
}
/* See Apache PR2580. Until its resolved, do it the same way CGI is done.. */
/* Initialize supplementary groups */
if (initgroups(name, ap_group_id) == -1) {
ap_log_error(FCGI_LOG_ALERT, fcgi_apache_main_server,
"FastCGI: process manager exiting, initgroups(%s,%u) failed",
name, (unsigned)ap_group_id);
exit(1);
}
#endif /* __EMX__ */
/* Change User */
if (fcgi_wrapper) {
if (seteuid_user() == -1) {
ap_log_error(FCGI_LOG_ALERT_NOERRNO, fcgi_apache_main_server,
"FastCGI: process manager exiting, failed to reduce privileges");
exit(1);
}
}
else {
if (setuid(ap_user_id) == -1) {
ap_log_error(FCGI_LOG_ALERT, fcgi_apache_main_server,
"FastCGI: process manager exiting, setuid(%u) failed", (unsigned)ap_user_id);
exit(1);
}
}
}
/*************
* Change the name of this process - best we can easily.
*/
static void change_process_name(const char * const name)
{
/* under Apache2, ap_server_argv0 is const */
strncpy((char *) ap_server_argv0, name, strlen(ap_server_argv0));
}
#endif /* !WIN32 */
static void schedule_start(fcgi_server *s, int proc)
{
/* If we've started one recently, don't register another */
time_t time_passed = now - s->restartTime;
if ((s->procs[proc].pid && (time_passed < (int) s->restartDelay))
|| ((s->procs[proc].pid == 0) && (time_passed < s->initStartDelay)))
{
FCGIDBG6("ignore_job: slot=%d, pid=%ld, time_passed=%ld, initStartDelay=%ld, restartDelay=%ld", proc, (long) s->procs[proc].pid, time_passed, s->initStartDelay, s->restartDelay);
return;
}
FCGIDBG3("scheduling_start: %s (%d)", s->fs_path, proc);
s->procs[proc].state = FCGI_START_STATE;
if (proc == dynamicMaxClassProcs - 1) {
ap_log_error(FCGI_LOG_WARN_NOERRNO, fcgi_apache_main_server,
"FastCGI: scheduled the %sstart of the last (dynamic) server "
"\"%s\" process: reached dynamicMaxClassProcs (%d)",
s->procs[proc].pid ? "re" : "", s->fs_path, dynamicMaxClassProcs);
}
}
/*
*----------------------------------------------------------------------
*
* dynamic_read_msgs
*
* Removes the records written by request handlers and decodes them.
* We also update the data structures to reflect the changes.
*
*----------------------------------------------------------------------
*/
static void dynamic_read_msgs(int read_ready)
{
fcgi_server *s;
int rc;
#ifndef WIN32
static int buflen = 0;
static char buf[FCGI_MSGS_BUFSIZE + 1];
char *ptr1, *ptr2, opcode;
char execName[FCGI_MAXPATH + 1];
char user[MAX_USER_NAME_LEN + 2];
char group[MAX_GID_CHAR_LEN + 1];
unsigned long q_usec = 0UL, req_usec = 0UL;
#else
fcgi_pm_job *joblist = NULL;
fcgi_pm_job *cjob = NULL;
#endif
pool *sp = NULL, *tp;
#ifndef WIN32
user[MAX_USER_NAME_LEN + 1] = group[MAX_GID_CHAR_LEN] = '\0';
#endif
/*
* To prevent the idle application from running indefinitely, we
* check the timer and if it is expired, we recompute the values
* for each running application class. Then, when FCGI_REQUEST_COMPLETE_JOB
* message is received, only updates are made to the data structures.
*/
if (fcgi_dynamic_last_analyzed == 0) {
fcgi_dynamic_last_analyzed = now;
}
if ((now - fcgi_dynamic_last_analyzed) >= (int)dynamicUpdateInterval) {
for (s = fcgi_servers; s != NULL; s = s->next) {
if (s->directive != APP_CLASS_DYNAMIC)
break;
/* Advance the last analyzed timestamp by the elapsed time since
* it was last set. Round the increase down to the nearest
* multiple of dynamicUpdateInterval */
fcgi_dynamic_last_analyzed += (((long)(now-fcgi_dynamic_last_analyzed)/dynamicUpdateInterval)*dynamicUpdateInterval);
s->smoothConnTime = (unsigned long) ((1.0-dynamicGain)*s->smoothConnTime + dynamicGain*s->totalConnTime);
s->totalConnTime = 0UL;
s->totalQueueTime = 0UL;
}
}
if (read_ready <= 0) {
return;
}
#ifndef WIN32
rc = read(fcgi_pm_pipe[0], (void *)(buf + buflen), FCGI_MSGS_BUFSIZE - buflen);
if (rc <= 0) {
if (!caughtSigTerm) {
ap_log_error(FCGI_LOG_ALERT, fcgi_apache_main_server,
"FastCGI: read() from pipe failed (%d)", rc);
if (rc == 0) {
ap_log_error(FCGI_LOG_ALERT, fcgi_apache_main_server,
"FastCGI: the PM is shutting down, Apache seems to have disappeared - bye");
caughtSigTerm = TRUE;
}
}
return;
}
buflen += rc;
buf[buflen] = '\0';
#else
/* dynamic_read_msgs() is called when a MBOX_EVENT is received (a
* request to do something) and/or when a timeout expires.
* There really should be no reason why this wait would get stuck
* but there's no point in waiting forever. */
rc = WaitForSingleObject(fcgi_dynamic_mbox_mutex, FCGI_MBOX_MUTEX_TIMEOUT);
if (rc != WAIT_OBJECT_0 && rc != WAIT_ABANDONED)
{
ap_log_error(FCGI_LOG_ALERT, fcgi_apache_main_server,
"FastCGI: failed to aquire the dynamic mbox mutex - something is broke?!");
return;
}
joblist = fcgi_dynamic_mbox;
fcgi_dynamic_mbox = NULL;
if (! ReleaseMutex(fcgi_dynamic_mbox_mutex))
{
ap_log_error(FCGI_LOG_ALERT, fcgi_apache_main_server,
"FastCGI: failed to release the dynamic mbox mutex - something is broke?!");
}
cjob = joblist;
#endif
#ifdef APACHE2
apr_pool_create(&tp, fcgi_config_pool);
#else
tp = ap_make_sub_pool(fcgi_config_pool);
#endif
#ifndef WIN32
for (ptr1 = buf; ptr1; ptr1 = ptr2) {
int scan_failed = 0;