-
Notifications
You must be signed in to change notification settings - Fork 41
/
Copy pathpen.c
2622 lines (2428 loc) · 66 KB
/
pen.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
Copyright (C) 2000-2016 Ulric Eriksson <ulric@siag.nu>
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, 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.
*/
#include "config.h"
#include <stdio.h>
#include <inttypes.h>
#include <ctype.h>
#include <errno.h>
#include <sys/types.h>
#include <assert.h>
#ifndef WINDOWS
#include <netdb.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#include <arpa/inet.h>
#include <sys/wait.h>
#include <sys/resource.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <syslog.h>
#include <pwd.h>
#endif
#include <signal.h>
#include <stdlib.h>
#include <stdarg.h>
#include <ctype.h>
#include <time.h>
#ifdef TIME_WITH_SYS_TIME
#include <sys/time.h>
#endif
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
#include "ssl.h"
#include "pen.h"
#include "acl.h"
#include "client.h"
#include "conn.h"
#include "diag.h"
#include "dlist.h"
#include "dsr.h"
#include "event.h"
#include "idlers.h"
#include "memory.h"
#include "netconv.h"
#include "pen_epoll.h"
#include "pen_kqueue.h"
#include "pen_poll.h"
#include "pen_select.h"
#include "server.h"
#include "settings.h"
#include "windows.h"
#define BUFFER_MAX (32*1024)
#define KEEP_MAX 100 /* how much to keep from the URI */
#define DUMMY_MSG "Ulric was here."
static int dummy = 0; /* use pen as a test target */
time_t now;
static int tcp_nodelay = 0;
static int listen_queue = CONNECTIONS_MAX;
static int asciidump;
static int loopflag;
static int exit_enabled = 0;
static int hupcounter = 0;
#ifndef WINDOWS
static int stats_flag = 0;
static int restart_log_flag = 0;
#endif
static int http = 0;
static char *cfgfile = NULL;
static char *logfile = NULL;
static FILE *logfp = NULL;
static struct sockaddr_in logserver;
static int logsock = -1;
static char *pidfile = NULL;
static FILE *pidfp = NULL;
static char *webfile = NULL;
static char listenport[1000];
static int port;
static int peek = 0;
static int control_acl;
static char *ctrlport = NULL;
int listenfd = -1;
static int ctrlfd = -1;
static char *jail = NULL;
static char *user = NULL;
static char *dsr_if, *dsr_ip;
struct sockaddr_storage *source = NULL;
#ifdef WINDOWS
/* because Windows scribbles over errno in an uncalled-for manner */
static int saved_errno;
#define SAVE_ERRNO (saved_errno = socket_errno)
#define USE_ERRNO (saved_errno)
#else /* not windows */
#define WOULD_BLOCK(err) (err == EAGAIN || err == EWOULDBLOCK)
#ifndef HAVE_ACCEPT4
static void make_nonblocking(int fd)
{
int fl;
DEBUG(2, "make_nonblocking(%d)", fd);
if ((fl = fcntl(fd, F_GETFL, 0)) == -1)
error("Can't fcntl, errno = %d", errno);
if (fl & O_NONBLOCK) {
DEBUG(3, "fd %d is already nonblocking", fd);
} else {
DEBUG(4, "fd %d is not nonblocking", fd);
if (fcntl(fd, F_SETFL, fl | O_NONBLOCK) == -1) {
error("Can't fcntl, errno = %d", errno);
}
}
}
#endif
#define SAVE_ERRNO
#define USE_ERRNO (socket_errno)
#endif
/* enable/disable with "tcp_nodelay/no tcp_nodelay" */
static void tcp_nodelay_on(int s)
{
#ifdef TCP_NODELAY
int one = 1;
int n = setsockopt(s, IPPROTO_TCP, TCP_NODELAY, (void *)&one, sizeof one);
DEBUG(2, "setsockopt(%d, %d, %d, %p, %d) returns %d",
s, IPPROTO_TCP, TCP_NODELAY, &one, sizeof one, n);
#else
debug("You don't have TCP_NODELAY");
#endif
}
/* save a few syscalls for modern Linux and BSD */
int socket_nb(int domain, int type, int protocol)
{
#ifdef SOCK_NONBLOCK
int s = socket(domain, type|SOCK_NONBLOCK, protocol);
SAVE_ERRNO;
DEBUG(2, "socket returns %d, socket_errno=%d", s, USE_ERRNO);
if (s == -1) error("Error opening socket: %s", strerror(USE_ERRNO));
#else
int s = socket(domain, type, protocol);
SAVE_ERRNO;
DEBUG(2, "socket returns %d, socket_errno=%d", s, USE_ERRNO);
if (s == -1) error("Error opening socket: %s", strerror(USE_ERRNO));
make_nonblocking(s);
#endif
if (tcp_nodelay) tcp_nodelay_on(s);
return s;
}
/* and a few more */
extern int accept4(int, struct sockaddr *, socklen_t *, int);
static int accept_nb(int sockfd, struct sockaddr *addr, socklen_t *addrlen)
{
#ifdef HAVE_ACCEPT4
return accept4(sockfd, addr, addrlen, SOCK_NONBLOCK);
#else
int s = accept(sockfd, addr, addrlen);
if (s != -1) make_nonblocking(sockfd);
return s;
#endif
if (tcp_nodelay) tcp_nodelay_on(sockfd);
}
#ifndef WINDOWS
static struct sigaction alrmaction, hupaction, termaction, usr1action, usr2action;
#endif
static int pen_strncasecmp(const char *p, const char *q, size_t n)
{
size_t i = 0;
int c = 0;
while ((i < n) && !(c = toupper((unsigned char)*p)-toupper((unsigned char)*q)) && *p) {
p++;
q++;
i++;
}
return c;
}
static char *pen_strcasestr(const char *haystack, const char *needle)
{
char *p = (char *)haystack;
int n = strlen(needle);
while (*p) {
if (!pen_strncasecmp(p, needle, n)) return p;
p++;
}
return NULL;
}
static int webstats(void)
{
FILE *fp;
int i;
time_t now;
struct tm *nowtm;
char nowstr[80];
if (webfile == NULL) {
debug("Don't know where to write web stats; see -w option");
return 0;
}
fp = fopen(webfile, "w");
if (fp == NULL) {
debug("Can't write to %s", webfile);
return 0;
}
now=time(NULL);
nowtm = localtime(&now);
strftime(nowstr, sizeof(nowstr), "%Y-%m-%d %H:%M:%S", nowtm);
fprintf(fp,
"<html>\n"
"<head>\n"
"<title>Pen status page</title>\n"
"</head>\n"
"<body bgcolor=\"#ffffff\">"
"<h1>Pen status page</h1>\n");
fprintf(fp,
"Time %s, %d servers, %d current<p>\n",
nowstr, nservers, current);
fprintf(fp,
"<table bgcolor=\"#c0c0c0\">\n"
"<tr>\n"
"<td bgcolor=\"#80f080\">server</td>\n"
"<td bgcolor=\"#80f080\">address</td>\n"
"<td bgcolor=\"#80f080\">status</td>\n"
"<td bgcolor=\"#80f080\">port</td>\n"
"<td bgcolor=\"#80f080\">connections</td>\n"
"<td bgcolor=\"#80f080\">max soft</td>\n"
"<td bgcolor=\"#80f080\">max hard</td>\n"
"<td bgcolor=\"#80f080\">sent</td>\n"
"<td bgcolor=\"#80f080\">received</td>\n"
"<td bgcolor=\"#80f080\">weight</td>\n"
"<td bgcolor=\"#80f080\">prio</td>\n"
"</tr>\n");
for (i = 0; i < nservers; i++) {
fprintf(fp,
"<tr>\n"
"<td>%d</td>\n"
"<td>%s</td>\n"
"<td>%d</td>\n"
"<td>%d</td>\n"
"<td>%d</td>\n"
"<td>%d</td>\n"
"<td>%d</td>\n"
"<td>%" PRIu64 "</td>\n"
"<td>%" PRIu64 "</td>\n"
"<td>%d</td>\n"
"<td>%d</td>\n"
"</tr>\n",
i, pen_ntoa(&servers[i].addr),
servers[i].status, pen_getport(&servers[i].addr),
servers[i].c, servers[i].maxc, servers[i].hard,
servers[i].sx, servers[i].rx,
servers[i].weight, servers[i].prio);
}
fprintf(fp, "</table>\n");
fprintf(fp, "<h2>Active clients</h2>");
fprintf(fp, "Max number of clients: %d<p>", clients_max);
fprintf(fp,
"<table bgcolor=\"#c0c0c0\">\n"
"<tr>\n"
"<td bgcolor=\"#80f080\">client</td>\n"
"<td bgcolor=\"#80f080\">address</td>\n"
"<td bgcolor=\"#80f080\">age(secs)</td>\n"
"<td bgcolor=\"#80f080\">last server</td>\n"
"<td bgcolor=\"#80f080\">connects</td>\n"
"<td bgcolor=\"#80f080\">sent</td>\n"
"<td bgcolor=\"#80f080\">received</td>\n"
"</tr>\n");
for (i = 0; i < clients_max; i++) {
if (clients[i].last == 0) continue;
fprintf(fp,
"<tr>\n"
"<td>%d</td>\n"
"<td>%s</td>\n"
"<td>%ld</td>\n"
"<td>%d</td>\n"
"<td>%ld</td>\n"
"<td>%" PRIu64 "</td>\n"
"<td>%" PRIu64 "</td>\n"
"</tr>\n",
i, pen_ntoa(&clients[i].addr),
(long)(now-clients[i].last), clients[i].server, clients[i].connects,
clients[i].csx, clients[i].crx);
}
fprintf(fp, "</table>\n");
fprintf(fp, "<h2>Active connections</h2>");
fprintf(fp, "Number of connections: %d max, %d used, %d last<p>",
connections_max, connections_used, connections_last);
fprintf(fp,
"<table bgcolor=\"#c0c0c0\">\n"
"<tr>\n"
"<td bgcolor=\"#80f080\">connection</td>\n"
"<td bgcolor=\"#80f080\">downfd</td>\n"
"<td bgcolor=\"#80f080\">upfd</td>\n"
"<td bgcolor=\"#80f080\">pending data down</td>\n"
"<td bgcolor=\"#80f080\">pending data up</td>\n"
"<td bgcolor=\"#80f080\">client</td>\n"
"<td bgcolor=\"#80f080\">server</td>\n"
"</tr>\n");
for (i = 0; i < connections_max; i++) {
if (conns[i].downfd == -1) continue;
fprintf(fp,
"<tr>\n"
"<td>%d</td>\n"
"<td>%d</td>\n"
"<td>%d</td>\n"
"<td>%d</td>\n"
"<td>%d</td>\n"
"<td>%d</td>\n"
"<td>%d</td>\n"
"</tr>\n",
i, conns[i].downfd, conns[i].upfd,
conns[i].downn, conns[i].upn,
conns[i].client, conns[i].server);
}
fprintf(fp, "</table>\n");
fprintf(fp,
"</body>\n"
"</html>\n");
fclose(fp);
return 1;
}
#ifndef WINDOWS
static void textstats(void)
{
int i;
time_t now;
struct tm *nowtm;
char nowstr[80];
now=time(NULL);
nowtm = localtime(&now);
strftime(nowstr, sizeof(nowstr), "%Y-%m-%d %H:%M:%S", nowtm);
debug("Time %s, %d servers, %d current",
nowstr, nservers, current);
for (i = 0; i < nservers; i++) {
debug("Server %d status:\n"
"address %s\n"
"%d\n"
"port %d\n"
"%d connections (%d soft, %d hard)\n"
"%llu sent, %llu received\n",
i, pen_ntoa(&servers[i].addr),
servers[i].status, pen_getport(&servers[i].addr),
servers[i].c, servers[i].maxc, servers[i].hard,
servers[i].sx, servers[i].rx);
}
debug("Max number of clients: %d", clients_max);
debug("Active clients:");
for (i = 0; i < clients_max; i++) {
if (clients[i].last == 0) continue;
debug("Client %d status:\n"
"address %s\n"
"last used %ld\n"
"last server %d\n",
"connects %ld\n",
"sent %llu\n",
"received %llu\n",
i, pen_ntoa(&clients[i].addr),
(long)(now-clients[i].last), clients[i].server, clients[i].connects,
clients[i].csx, clients[i].crx);
}
debug("Max number of connections: %d", connections_max);
debug("Active connections:");
for (i = 0; i < connections_max; i++) {
if (conns[i].downfd == -1) continue;
debug("Connection %d status:\n"
"downfd = %d, upfd = %d\n"
"pending data %d down, %d up\n"
"client %d, server %d\n",
i, conns[i].downfd, conns[i].upfd,
conns[i].downn, conns[i].upn,
conns[i].client, conns[i].server);
}
}
static void stats(int dummy)
{
DEBUG(1, "Caught USR1, will save stats");
stats_flag=1;
sigaction(SIGUSR1, &usr1action, NULL);
}
static void restart_log(int dummy)
{
DEBUG(1, "Caught HUP, will read cfg");
restart_log_flag=1;
sigaction(SIGHUP, &hupaction, NULL);
}
#endif
static void quit(int dummy)
{
DEBUG(1, "Quitting\nRead configuration %d times", hupcounter);
loopflag = 0;
}
#ifndef WINDOWS
static void die(int dummy)
{
abort();
}
#endif
static void dump(unsigned char *p, int n)
{
int i;
fprintf(stderr, "%d: ", n);
for (i = 0; i < n; i++) {
if (asciidump) {
fprintf(stderr, "%c",
(isprint(p[i])||isspace(p[i]))?p[i]:'.');
} else {
fprintf(stderr, "%02x ", (int)p[i]);
}
}
fprintf(stderr, "\n");
}
/* Log format is:
+ client_ip server_ip request
*/
static void netlog(int fd, int i, unsigned char *r, int n)
{
int j, k;
char b[1024];
DEBUG(2, "netlog(%d, %d, %p, %d)", fd, i, r, n);
strncpy(b, "+ ", sizeof b);
k = 2;
strncpy(b+k, pen_ntoa(&clients[conns[i].client].addr), (sizeof b)-k);
k += strlen(b+k);
b[k++] = ' ';
strncpy(b+k, pen_ntoa(&servers[conns[i].server].addr), (sizeof b)-k);
k += strlen(b+k);
b[k++] = ' ';
/* We have already used k bytes from b. This means that we want
no more than (sizeof b-(k+1)) bytes from r. The +1 is for the
trailing newline.
*/
j = sizeof b-(k+1);
if (n > j) n = j;
for (j = 0; j < n && r[j] != '\r' && r[j] != '\n'; j++) {
b[k++] = r[j];
}
b[k++] = '\n';
sendto(fd, b, k, 0, (struct sockaddr *)&logserver, sizeof logserver);
}
/* Log format is:
client_ip timestamp server_ip request
*/
static void log_request(FILE *fp, int i, unsigned char *b, int n)
{
int j;
if (n > KEEP_MAX) n = KEEP_MAX;
fprintf(fp, "%s ", pen_ntoa(&clients[conns[i].client].addr));
fprintf(fp, "%ld ", (long)now);
fprintf(fp, "%s ", pen_ntoa(&servers[conns[i].server].addr));
for (j = 0; j < n && b[j] != '\r' && b[j] != '\n'; j++) {
fprintf(fp, "%c", isascii(b[j])?b[j]:'.');
}
fprintf(fp, "\n");
}
static int rewrite_request(int i, int n, char *b)
{
char *q;
char p[BUFFER_MAX];
int pl;
b[n] = '\0';
DEBUG(2, "rewrite_request(%d, %d, %s)", i, n, b);
if (pen_strncasecmp(b, "GET ", 4) &&
pen_strncasecmp(b, "POST ", 5) &&
pen_strncasecmp(b, "HEAD ", 5)) {
return n; /* You can't touch this */
}
DEBUG(2, "Looking for CRLFCRLF");
q = strstr(b, "\r\n\r\n");
/* Steve Hall <steveh@intrapower.com.au> tells me that
apparently some clients send \n\n instead */
if (!q) {
DEBUG(2, "Looking for LFLF");
q = strstr(b, "\n\n");
}
if (!q) return n; /* not a header */
/* Look for existing X-Forwarded-For */
DEBUG(2, "Looking for X-Forwarded-For");
if (!pen_strcasestr(b, "\nX-Forwarded-For:"))
{
DEBUG(2, "Adding X-Forwarded-For");
/* Didn't find one, add our own */
snprintf(p, sizeof p, "\r\nX-Forwarded-For: %s",
pen_ntoa(&clients[conns[i].client].addr));
pl=strlen(p);
if (n+pl > BUFFER_MAX) return n;
memmove(q+pl, q, b+n-q);
memmove(q, p, pl);
n += pl;
}
b[n] = '\0';
if (!pen_strcasestr(b, "\nX-Forwarded-Proto:")){
DEBUG(2, "Adding X-Forwarded-Proto");
/* Didn't find one, add our own */
#ifdef HAVE_LIBSSL
snprintf(p, sizeof p, "\r\nX-Forwarded-Proto: %s",
(conns[i].ssl)?"https":"http");
#else
snprintf(p, sizeof p, "\r\nX-Forwarded-Proto: %s","http");
#endif /* HAVE_LIBSSL */
pl=strlen(p);
if (n+pl > BUFFER_MAX) return n;
memmove(q+pl, q, b+n-q);
memmove(q, p, pl);
n += pl;
}
return n;
}
static void change_events(int i)
{
int up_events = 0, down_events = 0;
int state = conns[i].state;
if (state & CS_IN_PROGRESS) {
DEBUG(2, "waiting for connect() to complete");
up_events |= EVENT_WRITE;
} else if (state & CS_CONNECTED) {
/* we are never interested in additional udp data from the client */
if (!udp) {
if (conns[i].upn == 0) {
if (!(state & CS_CLOSED_DOWN)) {
DEBUG(2, "interested in reading from downstream socket %d of connection %d", conns[i].downfd, i);
down_events |= EVENT_READ;
}
} else {
DEBUG(2, "interested in writing %d bytes to upstream socket %d of connection %d", conns[i].upn, conns[i].upfd, i);
up_events |= EVENT_WRITE;
}
}
/* tcp and udp processing upstream is handled the same here */
if (conns[i].downn == 0) {
if (!(state & CS_CLOSED_UP)) {
DEBUG(2, "interested in reading from upstream socket %d of connection %d", conns[i].upfd, i);
up_events |= EVENT_READ;
}
} else {
DEBUG(2, "interested in writing %d bytes to downstream socket %d of connection %d", conns[i].downn, conns[i].downfd, i);
down_events |= EVENT_WRITE;
}
}
/* We know that if down_events == up_events == 0, the connection
will be closed. Not doing anything here shaves off two syscalls.
*/
if (down_events || up_events) {
if (conns[i].downfd != -1) event_arm(conns[i].downfd, down_events);
if (conns[i].upfd != -1) event_arm(conns[i].upfd, up_events);
}
}
static int my_recv(int fd, void *buf, size_t len, int flags)
{
return recvfrom(fd, buf, len, flags, NULL, 0);
}
static int my_send(int fd, const void *buf, size_t len, int flags)
{
if (fd == -1) return len; /* idler */
return sendto(fd, buf, len, flags, NULL, 0);
}
static void add_dummy_reply(int conn)
{
char msg[1024];
DEBUG(2, "add_dummy_reply(%d)", conn);
snprintf(msg, sizeof msg,
"HTTP/1.1 200 OK\r\n"
"Content-Length: %d\r\n"
"Content-Type: text/html\r\n\r\n%s",
(int)strlen(DUMMY_MSG), DUMMY_MSG);
conns[conn].downn = strlen(msg);
conns[conn].downbptr = conns[conn].downb = pen_malloc(conns[conn].downn);
memcpy(conns[conn].downb, msg, conns[conn].downn);
change_events(conn);
}
static int copy_up(int i)
{
int n, rc, err = 0;
int from = conns[i].downfd;
int to = conns[i].upfd;
int serverindex = conns[i].server;
unsigned char b[BUFFER_MAX];
#ifdef HAVE_LIBSSL
SSL *ssl = conns[i].ssl;
if (ssl) {
rc = SSL_read(ssl, b, BUFFER_MAX);
DEBUG(2, "SSL_read returns %d\n", rc);
if (rc < 0) {
err = SSL_get_error(ssl, rc);
DEBUG(2, "SSL_read returns %d (SSL error %d)\n", rc, err);
if (err == SSL_ERROR_WANT_READ ||
err == SSL_ERROR_WANT_WRITE) {
return 0;
}
}
} else {
rc = my_recv(from, b, BUFFER_MAX, 0);
err = socket_errno;
}
#else
rc = my_recv(from, b, BUFFER_MAX, 0);
err = socket_errno;
#endif /* HAVE_LIBSSL */
DEBUG(2, "copy_up: recv(%d, %p, %d, 0) returns %d, errno = %d, socket_errno = %d", \
from, b, BUFFER_MAX, rc, errno, socket_errno);
if (rc == 0) { /* orderly shutdown */
DEBUG(2, "orderly shutdown of socket downfd=%d", from);
conns[i].state |= CS_CLOSED_DOWN;
/* no need to bother with any of this
if the connection will be closed anyway
*/
if (closing_time(i)) return -1;
change_events(i); /* so we stop reading from downfd */
if (!(conns[i].state & CS_CLOSED_UP)) {
/* proceed telling upfd about the close */
n = shutdown(to, SHUT_WR);
if (n == -1) {
err = socket_errno;
DEBUG(2, "shutdown(upfd=%d, SHUT_WR) returns %d, socket_errno=%d", to, n, err);
if (err != ENOTCONN) conns[i].state |= CS_CLOSED; /* because of the error */
}
}
return -1; /* the connection was successfully half-closed, wait for upstream to act */
} else if (rc == -1) {
if (WOULD_BLOCK(err)) return 0;
conns[i].state |= CS_CLOSED; /* because of the error */
return -1;
} else {
if (http) {
rc = rewrite_request(i, rc, (char *)b);
}
if (debuglevel > 2) dump(b, rc);
if (logfp) {
log_request(logfp, i, b, rc);
if (debuglevel > 2) log_request(stderr, i, b, rc);
}
if (logsock != -1) {
netlog(logsock, i, b, rc);
}
n = my_send(to, b, rc, 0); /* no ssl here */
conns[i].state &= ~CS_HALFDEAD;
SAVE_ERRNO;
DEBUG(2, "copy_up: send(%d, %p, %d, 0) returns %d, socket_errno = %d",
to, b, rc, n, USE_ERRNO);
if (n == -1) {
if (!WOULD_BLOCK(USE_ERRNO)) {
conns[i].state |= CS_CLOSED;
return -1;
}
n = 0;
}
if (n != rc) {
DEBUG(2, "copy_up saving %d bytes in up buffer", rc-n);
conns[i].upn = rc-n; /* remaining to be copied */
conns[i].upbptr = conns[i].upb = pen_malloc(rc-n);
memcpy(conns[i].upb, b+n, rc-n);
change_events(i);
}
#if 0
These could be simplified, no? Just store them in conn and update
servers and clients from close_conn.
#endif
servers[serverindex].sx += rc; /* That's not right? Should be n */
clients[conns[i].client].crx += rc;
conns[i].crx += rc; /* rewritten bytes read from client */
conns[i].ssx += n; /* actual bytes written to server */
if (dummy) add_dummy_reply(i);
}
return 0;
}
/* this function may have to deal with udp */
static int copy_down(int i)
{
int n, rc, err = 0;
int from = conns[i].upfd;
int to = conns[i].downfd;
int serverindex = conns[i].server;
#ifdef HAVE_LIBSSL
SSL *ssl = conns[i].ssl;
#endif
unsigned char b[BUFFER_MAX];
/* we called connect from add_client, so this works for udp and tcp */
rc = my_recv(from, b, BUFFER_MAX, 0); /* no ssl here */
DEBUG(2, "copy_down: recv(%d, %p, %d, %d) returns %d", from, b, BUFFER_MAX, 0, rc);
if (debuglevel > 2) dump(b, rc);
if (rc == 0) {
DEBUG(2, "orderly shutdown of socket %d", from);
conns[i].state |= CS_CLOSED_UP;
/* no need to bother with any of this
if the connection will be closed anyway
*/
if (closing_time(i)) return -1;
change_events(i); /* so we stop reading from upfd */
if (!(conns[i].state & CS_CLOSED_DOWN)) {
n = shutdown(to, SHUT_WR);
if (n == -1) {
err = socket_errno;
DEBUG(2, "shutdown(downfd=%d, SHUT_WR) returns %d, socket_errno=%d", to, n, err);
if (err != ENOTCONN) conns[i].state |= CS_CLOSED; /* because of the error */
}
}
return -1;
} else if (rc == -1) {
DEBUG(2, "socket_errno = %d", socket_errno);
conns[i].state |= CS_CLOSED; /* because of the error */
return -1;
} else {
int n;
if (udp) {
n = send(to, (void *)b, rc, 0);
conns[i].state = CS_CONNECTED;
return 0;
}
#ifdef HAVE_LIBSSL
if (ssl) {
/* We can't SSL_write here, because the auto buffer we're using now
won't be around if we need to retry the write.
Therefore don't write anything here but let flush_down do it. */
n = 0;
} else {
n = my_send(to, b, rc, 0);
err = socket_errno;
DEBUG(2, "copy_down: send(%d, %p, %d, %d) returns %d", to, b, rc, 0, n);
}
#else
n = my_send(to, b, rc, 0);
err = socket_errno;
DEBUG(2, "copy_down: send(%d, %p, %d, %d) returns %d", to, b, rc, 0, n);
#endif
if (n == -1) {
DEBUG(2, "errno = %d, socket_errno = %d", errno, socket_errno);
if (!WOULD_BLOCK(err)) {
conns[i].state |= CS_CLOSED;
return -1;
}
n = 0;
}
if (n != rc) {
DEBUG(2, "copy_down saving %d bytes in down buffer", rc-n);
conns[i].downn = rc-n;
conns[i].downbptr = conns[i].downb = pen_malloc(rc-n);
memcpy(conns[i].downb, b+n, rc-n);
change_events(i);
}
servers[serverindex].rx += rc;
clients[conns[i].client].csx += n;
conns[i].srx += rc;
conns[i].csx += n;
}
return 0;
}
#ifndef WINDOWS
static void alarm_handler(int dummy)
{
DEBUG(2, "alarm_handler(%d)", dummy);
}
#endif
static void usage(void)
{
printf("usage:\n"
" pen [-C addr:port] [-X] [-b sec] [-c N] [-e host[:port]] \\\n"
" [-t sec] [-x N] [-w dir] [-UHPWadfhrs] \\\n"
" [-o option] \\\n"
#ifdef HAVE_LIBSSL
" [-E certfile] [-K keyfile] \\\n"
" [-G cacertfile] [-A cacertdir] \\\n"
" [-Z] [-R] [-L protocol] \\\n"
#endif
" [host:]port h1[:p1[:maxc1[:hard1[:weight1[:prio1]]]]] [h2[:p2[:maxc2[:hard2[:weight2[:prio2]]]]]] ...\n"
"\n"
" -B host:port abuse server for naughty clients\n"
" -C port control port\n"
" -T sec tracking time in seconds (0 = forever) [%d]\n"
" -H add X-Forwarded-For header in http requests\n"
" -U use udp protocol support\n"
" -N use hash for initial server selection without save server\n"
" -O option use option in penctl format\n"
" -P use poll() rather than select()\n"
" -Q use kqueue to manage events (BSD)\n"
" -W use weight for server selection\n"
" -X enable 'exit' command for control port\n"
" -a debugging dumps in ascii format\n"
" -b sec blacklist time in seconds [%d]\n"
" -c N max number of clients [%d]\n"
" -d debugging on (repeat -d for more)\n"
" -e host:port emergency server of last resort\n"
" -f stay in foregound\n"
" -h use hash for initial server selection\n"
" -j dir run in chroot\n"
" -F file name of configuration file\n"
" -l file logging on\n"
" -r bypass client tracking in server selection\n"
" -s stubborn selection, i.e. don't fail over\n"
" -t sec connect timeout in seconds [%d]\n"
" -u user run as alternative user\n"
" -p file write pid to file\n"
" -x N max number of simultaneous connections [%d]\n"
" -w file save statistics in HTML format in a file\n"
" -o option use option in penctl format\n"
#ifdef HAVE_LIBSSL
" -E certfile use the given certificate in PEM format\n"
" -K keyfile use the given key in PEM format (may be contained in cert)\n"
" -G cacertfile file containing the CA's certificate\n"
" -A cacertdir directory containing CA certificates in hashed format\n"
" -Z use SSL compatibility mode\n"
" -R require valid peer certificate\n"
" -L protocol ssl23 (default), ssl2, ssl3 or tls1\n"
#endif
"\n"
"example:\n"
" pen smtp mailhost1:smtp mailhost2:25 mailhost3\n"
"\n",
TRACKING_TIME, BLACKLIST_TIME, CLIENTS_MAX, TIMEOUT, CONNECTIONS_MAX);
exit(0);
}
#ifndef WINDOWS
static void background(void)
{
#ifdef HAVE_DAEMON
daemon(0, 0);
#else
int childpid;
if ((childpid = fork()) < 0) {
error("Can't fork");
} else {
if (childpid > 0) {
exit(0); /* parent */
}
}
int devnull_fd = open("/dev/null", O_RDWR);
dup2(devnull_fd,0); /* stdin */
dup2(devnull_fd,1); /* stdout */
dup2(devnull_fd,2); /* stderr */
setsid();
signal(SIGCHLD, SIG_IGN);
#endif
}
#endif
static void init(int argc, char **argv)
{
int i;
int server;
int proto;
DEBUG(2, "init(%d, %p); port = %d", argc, argv, port);
debug("Before: conns = %p, connections_max = %d, clients = %p, clients_max = %d",
conns, connections_max, clients, clients_max);
if (connections_max == 0) expand_conntable(CONNECTIONS_MAX);
if (clients_max == 0) expand_clienttable(CLIENTS_MAX);
debug("After: conns = %p, connections_max = %d, clients = %p, clients_max = %d",
conns, connections_max, clients, clients_max);
current = 0;
server = 0;
if (udp) proto = SOCK_DGRAM;
else proto = SOCK_STREAM;
for (i = 1; i < argc; i++) {
DEBUG(2, "server[%d] = %s", server, argv[i]);
expand_servertable(server+1);
servers[server].status = 0;
servers[server].c = 0; /* connections... */
setaddress(server, argv[i], port, proto);
servers[server].sx = 0;
servers[server].rx = 0;
server++;
}
if (e_server) {
DEBUG(2, "Emergency server = %s", e_server);
expand_servertable(EMERGENCY_SERVER+1);
emerg_server = EMERGENCY_SERVER;
servers[EMERGENCY_SERVER].status = 0;
servers[EMERGENCY_SERVER].c = 0; /* connections... */
setaddress(EMERGENCY_SERVER, e_server, port, proto);
servers[EMERGENCY_SERVER].sx = 0;
servers[EMERGENCY_SERVER].rx = 0;
server++;
}
if (a_server) {
DEBUG(2, "Abuse server = %s", a_server);
expand_servertable(ABUSE_SERVER+1);
abuse_server = ABUSE_SERVER;
servers[ABUSE_SERVER].status = 0;
servers[ABUSE_SERVER].c = 0; /* connections... */
setaddress(ABUSE_SERVER, a_server, port, proto);
servers[ABUSE_SERVER].sx = 0;
servers[ABUSE_SERVER].rx = 0;
server++;
}
for (i = 0; i < clients_max; i++) {
clients[i].last = 0;
memset(&clients[i].addr, 0, sizeof(clients[i].addr));
clients[i].server = 0;
clients[i].connects = 0;
clients[i].csx = 0;
clients[i].crx = 0;
}
if (debuglevel) {
debug("%s starting", PACKAGE_STRING);
debug("servers:");
for (i = 0; i < nservers; i++) {
debug("%2d %s:%d:%d:%d:%d:%d", i,