-
Notifications
You must be signed in to change notification settings - Fork 280
/
gw_backend.c
3095 lines (2678 loc) · 110 KB
/
gw_backend.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
/*
* gw_backend - gateway backend code shared by dynamic socket backends
*
* Copyright(c) 2017 Glenn Strauss gstrauss()gluelogic.com All rights reserved
* License: BSD 3-clause (same as lighttpd)
*/
#include "first.h"
#include "gw_backend.h"
#include <sys/types.h>
#include "sys-socket.h"
#include "sys-stat.h"
#include "sys-unistd.h" /* <unistd.h> */
#include "sys-wait.h"
#ifdef HAVE_SYS_UIO_H
#include <sys/uio.h>
#endif
#include <errno.h>
#include <fcntl.h>
#include <limits.h>
#include <stdint.h>
#include <stdlib.h>
#include <signal.h>
#include <string.h>
#ifndef SIGKILL
#define SIGKILL 9
#endif
#include "base.h"
#include "algo_md.h"
#include "array.h"
#include "buffer.h"
#include "chunk.h"
#include "fdevent.h"
#include "http_header.h"
#include "log.h"
#include "sock_addr.h"
__attribute_noinline__
static int * gw_status_get_counter(gw_host *host, gw_proc *proc, const char *tag, size_t tlen) {
/*(At the cost of some memory, could prepare strings for host and for proc
* so that here we would copy ready made string for proc (or if NULL,
* for host), and then append tag to produce key)*/
/*("gw.backend." 11, host->id <=128, proc->id <=10+1, static tag <=11)*/
char label[288];
size_t llen = sizeof("gw.backend.")-1, len;
memcpy(label, "gw.backend.", llen);
len = buffer_clen(host->id);
if (len) {
#ifdef __COVERITY__
force_assert(len < sizeof(label) - llen);
#endif
memcpy(label+llen, host->id->ptr, len);
llen += len;
}
if (proc) {
#ifdef __COVERITY__
force_assert(llen < sizeof(label) - (LI_ITOSTRING_LENGTH + 1));
#endif
label[llen++] = '.';
len = li_utostrn(label+llen, LI_ITOSTRING_LENGTH, proc->id);
llen += len;
}
#ifdef __COVERITY__
force_assert(tlen < sizeof(label) - llen);
#endif
memcpy(label+llen, tag, tlen);
llen += tlen;
label[llen] = '\0';
return plugin_stats_get_ptr(label, llen);
}
static void gw_proc_tag_inc(gw_host *host, gw_proc *proc, const char *tag, size_t len) {
++(*gw_status_get_counter(host, proc, tag, len));
}
static void gw_proc_connected_inc(gw_host *host, gw_proc *proc) {
UNUSED(host);
++(*proc->stats_connected); /* "gw.backend...connected" */
}
static void gw_proc_load_inc(gw_host *host, gw_proc *proc) {
*proc->stats_load = ++proc->load; /* "gw.backend...load" */
++(*host->stats_global_active); /* "gw.active-requests" */
}
static void gw_proc_load_dec(gw_host *host, gw_proc *proc) {
*proc->stats_load = --proc->load; /* "gw.backend...load" */
--(*host->stats_global_active); /* "gw.active-requests" */
}
static void gw_host_assign(gw_host *host) {
*host->stats_load = ++host->load; /* "gw.backend...load" */
}
static void gw_host_reset(gw_host *host) {
*host->stats_load = --host->load; /* "gw.backend...load" */
}
static void gw_status_init_proc(gw_host *host, gw_proc *proc) {
*gw_status_get_counter(host, proc, CONST_STR_LEN(".disabled")) = 0;
*gw_status_get_counter(host, proc, CONST_STR_LEN(".died")) = 0;
*gw_status_get_counter(host, proc, CONST_STR_LEN(".overloaded")) = 0;
proc->stats_connected =
gw_status_get_counter(host, proc, CONST_STR_LEN(".connected"));
*proc->stats_connected = 0;
proc->stats_load =
gw_status_get_counter(host, proc, CONST_STR_LEN(".load"));
*proc->stats_load = 0;
}
static void gw_status_init_host(gw_host *host) {
host->stats_load =
gw_status_get_counter(host, NULL, CONST_STR_LEN(".load"));
*host->stats_load = 0;
host->stats_global_active =
plugin_stats_get_ptr("gw.active-requests",sizeof("gw.active-requests")-1);
}
__attribute_cold__
static void gw_proc_set_state(gw_host *host, gw_proc *proc, int state) {
if ((int)proc->state == state) return;
if (proc->state == PROC_STATE_RUNNING) {
--host->active_procs;
} else if (state == PROC_STATE_RUNNING) {
++host->active_procs;
}
proc->state = state;
}
__attribute_cold__
__attribute_noinline__
static void gw_proc_init_portpath(gw_host *host, gw_proc *proc) {
if (!host->unixsocket) {
proc->port = host->port + proc->id;
return;
}
if (!proc->unixsocket)
proc->unixsocket = buffer_init();
if (!host->bin_path)
buffer_copy_buffer(proc->unixsocket, host->unixsocket);
else {
buffer_clear(proc->unixsocket);
buffer_append_str2(proc->unixsocket, BUF_PTR_LEN(host->unixsocket),
CONST_STR_LEN("-"));
buffer_append_int(proc->unixsocket, proc->id);
}
}
__attribute_cold__
__attribute_noinline__
__attribute_returns_nonnull__
static gw_proc *gw_proc_init(gw_host *host) {
gw_proc *proc = ck_calloc(1, sizeof(*proc));
/*proc->unixsocket = buffer_init();*//*(init on demand)*/
proc->connection_name = buffer_init();
proc->prev = NULL;
proc->next = NULL;
proc->state = PROC_STATE_DIED;
proc->id = host->max_id++;
gw_status_init_proc(host, proc); /*(proc->id must be set)*/
gw_proc_init_portpath(host, proc);
return proc;
}
__attribute_cold__
__attribute_noinline__
static void gw_proc_free(gw_proc *proc) {
if (!proc) return;
gw_proc_free(proc->next);
buffer_free(proc->unixsocket);
buffer_free(proc->connection_name);
free(proc->saddr);
free(proc);
}
__attribute_malloc__
__attribute_returns_nonnull__
static gw_host *gw_host_init(void) {
return ck_calloc(1, sizeof(gw_host));
}
static void gw_host_free(gw_host *h) {
if (!h) return;
if (h->refcount) {
--h->refcount;
return;
}
gw_proc_free(h->first);
gw_proc_free(h->unused_procs);
for (uint32_t i = 0; i < h->args.used; ++i) free(h->args.ptr[i]);
free(h->args.ptr);
free(h);
}
__attribute_malloc__
__attribute_returns_nonnull__
static gw_exts *gw_extensions_init(void) {
return ck_calloc(1, sizeof(gw_exts));
}
static void gw_extensions_free(gw_exts *f) {
if (!f) return;
for (uint32_t i = 0; i < f->used; ++i) {
gw_extension *fe = f->exts+i;
for (uint32_t j = 0; j < fe->used; ++j) {
gw_host_free(fe->hosts[j]);
}
free(fe->hosts);
}
free(f->exts);
free(f);
}
static int gw_extension_insert(gw_exts *ext, const buffer *key, gw_host *fh) {
gw_extension *fe = NULL;
for (uint32_t i = 0; i < ext->used; ++i) {
if (buffer_is_equal(key, &ext->exts[i].key)) {
fe = ext->exts+i;
break;
}
}
if (NULL == fe) {
if (!(ext->used & (8-1))) {
ck_realloc_u32((void **)&ext->exts,ext->used,8,sizeof(*ext->exts));
memset((void *)(ext->exts + ext->used), 0, 8 * sizeof(*ext->exts));
}
fe = ext->exts + ext->used++;
fe->last_used_ndx = -1;
buffer *b;
*(const buffer **)&b = &fe->key;
memcpy(b, key, sizeof(buffer)); /*(copy; not later free'd)*/
}
if (!(fe->used & (4-1)))
ck_realloc_u32((void **)&fe->hosts, fe->used, 4, sizeof(*fe->hosts));
fe->hosts[fe->used++] = fh;
return 0;
}
static void gw_proc_connect_success(gw_host *host, gw_proc *proc, int debug, request_st * const r) {
gw_proc_connected_inc(host, proc); /*(".connected")*/
proc->last_used = log_monotonic_secs;
if (debug) {
log_debug(r->conf.errh, __FILE__, __LINE__,
"got proc: pid: %d socket: %s load: %d",
proc->pid, proc->connection_name->ptr, proc->load);
}
}
__attribute_cold__
static void gw_proc_connect_error(request_st * const r, gw_host *host, gw_proc *proc, pid_t pid, int errnum, int debug) {
const unix_time64_t cur_ts = log_monotonic_secs;
log_error_st * const errh = r->conf.errh;
#ifdef _WIN32
WSASetLastError(errnum); /*(for log_perror()/log_serror())*/
if (errnum == WSAEWOULDBLOCK) errnum = EAGAIN;
#else
errno = errnum; /*(for log_perror()/log_serror())*/
#endif
log_serror(errh, __FILE__, __LINE__,
"establishing connection failed: socket: %s", proc->connection_name->ptr);
if (!proc->is_local) {
proc->disabled_until = cur_ts + host->disable_time;
gw_proc_set_state(host, proc, PROC_STATE_OVERLOADED);
}
else if (proc->pid == pid && proc->state == PROC_STATE_RUNNING) {
/* several requests from lighttpd might reference the same proc
*
* Only one of them should mark the proc
* and all other ones should just take a new one.
*
* If a new proc was started with the old struct, this might
* otherwise lead to marking a perfectly good proc as dead
*/
log_error(errh, __FILE__, __LINE__,
"backend error; we'll disable for %d"
"secs and send the request to another backend instead:"
"load: %d", host->disable_time, host->load);
if (EAGAIN == errnum) {
/* - EAGAIN: cool down the backend; it is overloaded */
#ifdef __linux__
log_error(errh, __FILE__, __LINE__,
"If this happened on Linux: You have run out of local ports. "
"Check the manual, section Performance how to handle this.");
#endif
if (debug) {
log_debug(errh, __FILE__, __LINE__,
"This means that you have more incoming requests than your "
"FastCGI backend can handle in parallel. It might help to "
"spawn more FastCGI backends or PHP children; if not, "
"decrease server.max-connections. The load for this FastCGI "
"backend %s is %d", proc->connection_name->ptr, proc->load);
}
proc->disabled_until = cur_ts + host->disable_time;
gw_proc_set_state(host, proc, PROC_STATE_OVERLOADED);
}
else {
/* we got a hard error from the backend like
* - ECONNREFUSED for tcp-ip sockets
* - ENOENT for unix-domain-sockets
*/
#if 0
gw_proc_set_state(host, proc, PROC_STATE_DIED_WAIT_FOR_PID);
#else /* treat as overloaded (future: unless we send kill() signal)*/
proc->disabled_until = cur_ts + host->disable_time;
gw_proc_set_state(host, proc, PROC_STATE_OVERLOADED);
#endif
}
}
if (EAGAIN == errnum) {
gw_proc_tag_inc(host, proc, CONST_STR_LEN(".overloaded"));
}
else {
gw_proc_tag_inc(host, proc, CONST_STR_LEN(".died"));
}
}
static void gw_proc_release(gw_host *host, gw_proc *proc, int debug, log_error_st *errh) {
gw_proc_load_dec(host, proc);
if (debug) {
log_debug(errh, __FILE__, __LINE__,
"released proc: pid: %d socket: %s load: %u",
proc->pid, proc->connection_name->ptr, proc->load);
}
}
__attribute_cold__
static void gw_proc_check_enable(gw_host * const host, gw_proc * const proc, log_error_st * const errh) {
if (log_monotonic_secs <= proc->disabled_until) return;
if (proc->state != PROC_STATE_OVERLOADED) return;
gw_proc_set_state(host, proc, PROC_STATE_RUNNING);
log_error(errh, __FILE__, __LINE__,
"gw-server re-enabled: %s %s %hu %s",
proc->connection_name->ptr,
host->host ? host->host->ptr : "", host->port,
host->unixsocket ? host->unixsocket->ptr : "");
}
__attribute_cold__
static void gw_proc_waitpid_log(const gw_host * const host, const gw_proc * const proc, log_error_st * const errh, const int status) {
if (WIFEXITED(status)) {
if (proc->state != PROC_STATE_KILLED) {
log_error(errh, __FILE__, __LINE__,
"child exited: %d %s",
WEXITSTATUS(status), proc->connection_name->ptr);
}
} else if (WIFSIGNALED(status)) {
if (WTERMSIG(status) != SIGTERM && WTERMSIG(status) != SIGINT
&& WTERMSIG(status) != host->kill_signal) {
log_error(errh, __FILE__, __LINE__,
"child signalled: %d", WTERMSIG(status));
}
} else {
log_error(errh, __FILE__, __LINE__,
"child died somehow: %d", status);
}
}
static int gw_proc_waitpid(gw_host *host, gw_proc *proc, log_error_st *errh) {
pid_t rc;
int status;
if (!proc->is_local) return 0;
if (proc->pid <= 0) return 0;
rc = fdevent_waitpid(proc->pid, &status, 1);
if (0 == rc) return 0; /* child still running */
/* child terminated */
if (-1 == rc) {
/* EINVAL or ECHILD no child processes */
/* should not happen; someone else has cleaned up for us */
log_perror(errh, __FILE__, __LINE__,
"pid %d %d not found", proc->pid, proc->state);
}
else {
gw_proc_waitpid_log(host, proc, errh, status);
}
proc->pid = 0;
if (proc->state != PROC_STATE_KILLED)
proc->disabled_until = log_monotonic_secs;
gw_proc_set_state(host, proc, PROC_STATE_DIED);
return 1;
}
__attribute_cold__
static int gw_proc_sockaddr_init(gw_host * const host, gw_proc * const proc, log_error_st * const errh) {
sock_addr addr;
socklen_t addrlen;
if (proc->unixsocket) {
if (1 != sock_addr_from_str_hints(&addr,&addrlen,proc->unixsocket->ptr,
AF_UNIX, 0, errh)) {
errno = EINVAL;
return -1;
}
buffer_clear(proc->connection_name);
buffer_append_str2(proc->connection_name,
CONST_STR_LEN("unix:"),
BUF_PTR_LEN(proc->unixsocket));
}
else {
#ifdef __COVERITY__
force_assert(host->host); /*(not NULL if !host->unixsocket)*/
#endif
/*(note: name resolution here is *blocking* if IP string not supplied)*/
if (1 != sock_addr_from_str_hints(&addr, &addrlen, host->host->ptr,
0, proc->port, errh)) {
errno = EINVAL;
return -1;
}
else if (host->host->size) {
/*(skip if constant string set in gw_set_defaults_backend())*/
/* overwrite host->host buffer with IP addr string so that
* any further use of gw_host does not block on DNS lookup */
buffer *h;
*(const buffer **)&h = host->host;
sock_addr_inet_ntop_copy_buffer(h, &addr);
host->family = sock_addr_get_family(&addr);
}
buffer_clear(proc->connection_name);
buffer_append_str3(proc->connection_name,
CONST_STR_LEN("tcp:"),
BUF_PTR_LEN(host->host),
CONST_STR_LEN(":"));
buffer_append_int(proc->connection_name, proc->port);
}
if (NULL != proc->saddr && proc->saddrlen < addrlen) {
free(proc->saddr);
proc->saddr = NULL;
}
if (NULL == proc->saddr) {
proc->saddr = (struct sockaddr *)ck_malloc(addrlen);
}
proc->saddrlen = addrlen;
memcpy(proc->saddr, &addr, addrlen);
return 0;
}
static int env_add(char_array *env, const char *key, size_t key_len, const char *val, size_t val_len) {
char *dst;
if (!key || !val) return -1;
dst = ck_malloc(key_len + val_len + 2);
memcpy(dst, key, key_len);
dst[key_len] = '=';
memcpy(dst + key_len + 1, val, val_len + 1); /* add the \0 from the value */
for (uint32_t i = 0; i < env->used; ++i) {
#ifdef __COVERITY__
force_assert(env->ptr); /*(non-NULL if env->used != 0)*/
#endif
if (0 == strncmp(dst, env->ptr[i], key_len + 1)) {
free(env->ptr[i]);
env->ptr[i] = dst;
return 0;
}
}
if (!(env->used & (16-1)))
ck_realloc_u32((void **)&env->ptr, env->used, 16, sizeof(*env->ptr));
env->ptr[env->used++] = dst;
return 0;
}
__attribute_cold__
static int gw_spawn_connection(gw_host * const host, gw_proc * const proc, log_error_st * const errh, int debug) {
int gw_fd;
int status;
if (debug) {
log_debug(errh, __FILE__, __LINE__,
"new proc, socket: %hu %s",
proc->port, proc->unixsocket ? proc->unixsocket->ptr : "");
}
gw_fd = fdevent_socket_cloexec(proc->saddr->sa_family, SOCK_STREAM, 0);
if (-1 == gw_fd) {
log_serror(errh, __FILE__, __LINE__, "socket()");
return -1;
}
do {
status = connect(gw_fd, proc->saddr, proc->saddrlen);
}
#ifdef _WIN32
while (-1 == status && WSAGetLastError() == WSAEINTR);
#else
while (-1 == status && errno == EINTR);
#endif
/* _WIN32 WSAGetLastError() WSAECONNRESET or WSAECONNREFUSED might
* or might not indicate presence of socket, so try to unlink unixsocket */
if (-1 == status && errno != ENOENT && proc->unixsocket) {
log_serror(errh, __FILE__, __LINE__,
"connect() %s", proc->unixsocket->ptr);
unlink(proc->unixsocket->ptr);
}
fdio_close_socket(gw_fd);
if (-1 == status) {
/* server is not up, spawn it */
char_array env;
uint32_t i;
/* reopen socket */
#ifdef _WIN32
/* Note: not using WSA_FLAG_OVERLAPPED
* because we are assigning to hStdInput of child process */
gw_fd = WSASocketA(proc->saddr->sa_family, SOCK_STREAM, 0, NULL, 0,
WSA_FLAG_NO_HANDLE_INHERIT);
#else
gw_fd = fdevent_socket_cloexec(proc->saddr->sa_family, SOCK_STREAM, 0);
#endif
if (-1 == gw_fd) {
log_serror(errh, __FILE__, __LINE__, "socket()");
return -1;
}
if (fdevent_set_so_reuseaddr(gw_fd, 1) < 0) {
log_serror(errh, __FILE__, __LINE__, "socketsockopt()");
fdio_close_socket(gw_fd);
return -1;
}
/* create socket */
if (-1 == bind(gw_fd, proc->saddr, proc->saddrlen)) {
log_serror(errh, __FILE__, __LINE__,
"bind() %s", proc->connection_name->ptr);
fdio_close_socket(gw_fd);
return -1;
}
if (-1 == listen(gw_fd, host->listen_backlog)) {
log_serror(errh, __FILE__, __LINE__, "listen()");
fdio_close_socket(gw_fd);
return -1;
}
{
/* create environment */
env.ptr = NULL;
env.used = 0;
/* build clean environment */
if (host->bin_env_copy && host->bin_env_copy->used) {
for (i = 0; i < host->bin_env_copy->used; ++i) {
data_string *ds=(data_string *)host->bin_env_copy->data[i];
char *ge;
if (NULL != (ge = getenv(ds->value.ptr))) {
env_add(&env, BUF_PTR_LEN(&ds->value), ge, strlen(ge));
}
}
} else {
char ** const e = fdevent_environ();
for (i = 0; e[i]; ++i) {
char *eq;
if (NULL != (eq = strchr(e[i], '='))) {
env_add(&env, e[i], eq - e[i], eq+1, strlen(eq+1));
}
}
}
/* create environment */
if (host->bin_env) {
for (i = 0; i < host->bin_env->used; ++i) {
data_string *ds = (data_string *)host->bin_env->data[i];
env_add(&env, BUF_PTR_LEN(&ds->key),
BUF_PTR_LEN(&ds->value));
}
}
for (i = 0; i < env.used; ++i) {
/* search for PHP_FCGI_CHILDREN */
if (0 == strncmp(env.ptr[i], "PHP_FCGI_CHILDREN=",
sizeof("PHP_FCGI_CHILDREN=")-1)) {
break;
}
}
/* not found, add a default */
if (i == env.used) {
env_add(&env, CONST_STR_LEN("PHP_FCGI_CHILDREN"),
CONST_STR_LEN("1"));
}
if (!(env.used & (16-1)))
ck_realloc_u32((void **)&env.ptr,env.used,1,sizeof(*env.ptr));
env.ptr[env.used] = NULL;
}
#ifdef _WIN32
int dfd = -2; /*(flag to chdir to script dir on _WIN32)*/
proc->pid =
fdevent_createprocess(host->args.ptr,
env.ptr, (intptr_t)gw_fd, -1, -1, dfd);
#else
int dfd = fdevent_open_dirname(host->args.ptr[0], 1);/*permit symlinks*/
if (-1 == dfd) {
log_perror(errh, __FILE__, __LINE__,
"open dirname failed: %s", host->args.ptr[0]);
}
/*(FCGI_LISTENSOCK_FILENO == STDIN_FILENO == 0)*/
proc->pid = (dfd >= 0)
? fdevent_fork_execve(host->args.ptr[0], host->args.ptr,
env.ptr, gw_fd, -1, -1, dfd)
: -1;
#endif
if (-1 == proc->pid)
log_perror(errh, __FILE__, __LINE__,
"gw-backend failed to start: %s", host->bin_path->ptr);
for (i = 0; i < env.used; ++i) free(env.ptr[i]);
free(env.ptr);
if (dfd >= 0) close(dfd);
fdio_close_socket(gw_fd);
if (-1 == proc->pid) {
proc->pid = 0;
proc->disabled_until = log_monotonic_secs;
return -1;
}
/* register process */
proc->last_used = log_monotonic_secs;
proc->is_local = 1;
/* wait */
struct timeval tv = { 0, 1000 };
select(0, NULL, NULL, NULL, &tv);
if (0 != gw_proc_waitpid(host, proc, errh)) {
log_error(errh, __FILE__, __LINE__,
"gw-backend failed to start: %s", host->bin_path->ptr);
log_error(errh, __FILE__, __LINE__,
"If you're trying to run your app as a FastCGI backend, make "
"sure you're using the FastCGI-enabled version. If this is PHP "
"on Gentoo, add 'fastcgi' to the USE flags. If this is PHP, try "
"removing the bytecode caches for now and try again.");
return -1;
}
} else {
proc->is_local = 0;
proc->pid = 0;
if (debug) {
log_debug(errh, __FILE__, __LINE__,
"(debug) socket is already used; won't spawn: %s",
proc->connection_name->ptr);
}
}
gw_proc_set_state(host, proc, PROC_STATE_RUNNING);
return 0;
}
__attribute_cold__
static void gw_proc_spawn(gw_host * const host, log_error_st * const errh, const int debug) {
gw_proc *proc;
for (proc = host->unused_procs; proc; proc = proc->next) {
/* (proc->pid <= 0 indicates PROC_STATE_DIED, not PROC_STATE_KILLED) */
if (proc->pid > 0) continue;
/* (do not attempt to spawn another proc if a proc just exited) */
if (proc->disabled_until >= log_monotonic_secs) return;
break;
}
if (proc) {
if (proc == host->unused_procs)
host->unused_procs = proc->next;
else
proc->prev->next = proc->next;
if (proc->next) {
proc->next->prev = proc->prev;
proc->next = NULL;
}
proc->prev = NULL;
gw_proc_init_portpath(host, proc);
} else {
proc = gw_proc_init(host);
}
if (0 != gw_proc_sockaddr_init(host, proc, errh)) {
/*(should not happen if host->host validated at startup,
* and translated from name to IP address at startup)*/
log_error(errh, __FILE__, __LINE__,
"ERROR: spawning backend failed.");
if (proc->id == host->max_id-1) --host->max_id;
gw_proc_free(proc);
} else if (gw_spawn_connection(host, proc, errh, debug)) {
log_error(errh, __FILE__, __LINE__,
"ERROR: spawning backend failed.");
proc->next = host->unused_procs;
if (host->unused_procs)
host->unused_procs->prev = proc;
host->unused_procs = proc;
} else {
proc->next = host->first;
if (host->first)
host->first->prev = proc;
host->first = proc;
++host->num_procs;
}
}
__attribute_cold__
static void gw_proc_kill(gw_host *host, gw_proc *proc) {
if (proc->next) proc->next->prev = proc->prev;
if (proc->prev) proc->prev->next = proc->next;
else host->first = proc->next;
--host->num_procs;
proc->prev = NULL;
proc->next = host->unused_procs;
proc->disabled_until = 0;
if (host->unused_procs)
host->unused_procs->prev = proc;
host->unused_procs = proc;
fdevent_kill(proc->pid, host->kill_signal);
gw_proc_set_state(host, proc, PROC_STATE_KILLED);
}
#ifdef HAVE_SYS_UN_H
__attribute_pure__
static gw_host * unixsocket_is_dup(gw_plugin_data *p, const buffer *unixsocket) {
if (NULL == p->cvlist) return NULL;
/* (init i to 0 if global context; to 1 to skip empty global context) */
for (int i = !p->cvlist[0].v.u2[1], used = p->nconfig; i < used; ++i) {
config_plugin_value_t *cpv = p->cvlist + p->cvlist[i].v.u2[0];
gw_plugin_config *conf = NULL;
for (; -1 != cpv->k_id; ++cpv) {
switch (cpv->k_id) {
case 0: /* xxxxx.server */
if (cpv->vtype == T_CONFIG_LOCAL) conf = cpv->v.v;
break;
default:
break;
}
}
if (NULL == conf || NULL == conf->exts) continue;
gw_exts *exts = conf->exts;
for (uint32_t j = 0; j < exts->used; ++j) {
gw_extension *ex = exts->exts+j;
for (uint32_t n = 0; n < ex->used; ++n) {
gw_host *host = ex->hosts[n];
if (host->unixsocket
&& buffer_is_equal(host->unixsocket, unixsocket)
&& host->bin_path)
return host;
}
}
}
return NULL;
}
#endif
static void parse_binpath(char_array *env, const buffer *b) {
char *start = b->ptr;
char c;
/* search for spaces */
for (size_t i = 0, used = buffer_clen(b); i < used; ++i) {
switch(b->ptr[i]) {
case ' ':
case '\t':
/* a WS, stop here and copy the argument */
if (!(env->used & (4-1)))
ck_realloc_u32((void**)&env->ptr,env->used,4,sizeof(*env->ptr));
c = b->ptr[i];
b->ptr[i] = '\0';
env->ptr[env->used++] = strdup(start);
b->ptr[i] = c;
start = b->ptr + i + 1;
break;
default:
break;
}
}
if (!(env->used & (4-1)) || !((env->used+1) & (4-1)))
ck_realloc_u32((void **)&env->ptr, env->used, 2, sizeof(*env->ptr));
env->ptr[env->used++] = strdup(start);
env->ptr[env->used] = NULL;
#ifdef _WIN32
/* lighttpd cygwin test environment does not include ".exe" extension */
if (NULL == getenv("CYGROOT")) return; /* set in tests/Lighttpd.pm */
struct stat st;
char *arg0 = env->ptr[0];
size_t len = strlen(arg0);
if ((len < 4 || 0 != memcmp(arg0+len-4, ".exe", 4))
&& 0 != stat(arg0, &st) && errno == ENOENT) {
ck_realloc_u32((void **)&env->ptr[0], len, 5, 1);
memcpy(env->ptr[0]+len, ".exe", 5);
}
#endif
}
enum {
GW_BALANCE_LEAST_CONNECTION,
GW_BALANCE_RR,
GW_BALANCE_HASH,
GW_BALANCE_STICKY
};
__attribute_noinline__
__attribute_pure__
static uint32_t
gw_hash(const char *str, const uint32_t len, uint32_t hash)
{
return djbhash(str, len, hash);
}
static gw_host * gw_host_get(request_st * const r, gw_extension *extension, int balance, int debug) {
int ndx = -1;
const int ext_used = (int)extension->used;
if (ext_used <= 1) {
if (1 == ext_used && extension->hosts[0]->active_procs > 0)
ndx = 0;
}
else {
switch(balance) {
case GW_BALANCE_LEAST_CONNECTION:
{ /* fair balancing */
for (int k = 0, max_usage = INT_MAX; k < ext_used; ++k) {
const gw_host * const host = extension->hosts[k];
if (0 == host->active_procs) continue;
if (host->load < max_usage) {
max_usage = host->load;
ndx = k;
}
}
break;
}
case GW_BALANCE_RR:
{ /* round robin */
const gw_host *host = extension->hosts[0];
/* Use last_used_ndx from first host in list */
int k = extension->last_used_ndx;
ndx = k + 1; /* use next host after the last one */
if (ndx < 0) ndx = 0;
/* Search first active host after last_used_ndx */
while (ndx < ext_used
&& 0 == (host = extension->hosts[ndx])->active_procs) ++ndx;
if (ndx >= ext_used) {
/* didn't find a higher id, wrap to the start */
for (ndx = 0; ndx <= (int) k; ++ndx) {
host = extension->hosts[ndx];
if (0 != host->active_procs) break;
}
/* No active host found */
if (0 == host->active_procs) ndx = -1;
}
/* Save new index for next round */
extension->last_used_ndx = ndx;
break;
}
case GW_BALANCE_HASH:
case GW_BALANCE_STICKY:
{ /* hash balancing or source sticky balancing */
const uint32_t base_hash = (balance == GW_BALANCE_HASH)
? gw_hash(BUF_PTR_LEN(&r->uri.authority),
gw_hash(BUF_PTR_LEN(&r->uri.path), DJBHASH_INIT))
: gw_hash(BUF_PTR_LEN(r->dst_addr_buf), DJBHASH_INIT);
uint32_t last_max = 0;
for (int k = 0; k < ext_used; ++k) {
const gw_host * const host = extension->hosts[k];
if (0 == host->active_procs) continue;
const uint32_t cur_max = base_hash ^ host->gw_hash;
if (last_max <= cur_max) {
last_max = cur_max;
ndx = k;
}
}
break;
}
default:
break;
}
}
if (__builtin_expect( (-1 != ndx), 1)) {
/* found a server */
if (debug) {
gw_host * const host = extension->hosts[ndx];
log_debug(r->conf.errh, __FILE__, __LINE__,
"gw - found a host %s %hu",
host->host ? host->host->ptr : "", host->port);
return host;
}
return extension->hosts[ndx];
} else if (0 == r->con->srv->srvconf.max_worker) {
/* special-case adaptive spawning and 0 == host->min_procs */
for (int k = 0; k < ext_used; ++k) {
gw_host * const host = extension->hosts[k];
if (0 == host->min_procs && 0 == host->num_procs && host->bin_path){
gw_proc_spawn(host, r->con->srv->errh, debug);
if (host->num_procs) return host;
}
}
}
/* all hosts are down */
/* sorry, we don't have a server alive for this ext */
r->http_status = 503; /* Service Unavailable */
r->handler_module = NULL;
/* only send the 'no handler' once */
if (!extension->note_is_sent) {
extension->note_is_sent = 1;
log_error(r->conf.errh, __FILE__, __LINE__,
"all handlers for %s?%.*s on %s are down.",
r->uri.path.ptr, BUFFER_INTLEN_PTR(&r->uri.query),
extension->key.ptr);
}
return NULL;
}
static int gw_establish_connection(request_st * const r, gw_host *host, gw_proc *proc, pid_t pid, int gw_fd, int debug) {
if (-1 == connect(gw_fd, proc->saddr, proc->saddrlen)) {
#ifdef _WIN32
/* MS returns WSAEWOULDBLOCK instead of WSAEINPROGRESS for connect()
* if socket is configured nonblocking */
int errnum = WSAGetLastError();
if (errnum == WSAEINPROGRESS || errnum == WSAEALREADY
|| errnum == WSAEWOULDBLOCK || errnum == WSAEINTR)
#else
int errnum = errno;
if (errnum == EINPROGRESS || errnum == EALREADY || errnum == EINTR
|| (errnum == EAGAIN && host->unixsocket))
#endif
{
if (debug > 2) {
log_debug(r->conf.errh, __FILE__, __LINE__,
"connect delayed; will continue later: %s",
proc->connection_name->ptr);
}
return 1;