-
Notifications
You must be signed in to change notification settings - Fork 11
/
simpleproxy.c
1442 lines (1254 loc) · 38.4 KB
/
simpleproxy.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$
* ---------------------------------------------------------------------
*
* Simple proxy daemon
* ====================
*
* Authors:
* --------
* Vadim Zaliva <lord@crocodile.org>
* Vlad Karpinsky <vlad@noir.crocodile.org>
* Vadim Tymchenko <verylong@noir.crocodile.org>
* Renzo Davoli <renzo@cs.unibo.it> (html probe & html basic authentication).
*
* Licence:
* --------
*
* Copyright (C) 1999 Vadim Zaliva
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*
*/
/* #define DEBUG 1 */
#include <stdio.h>
#include <sys/param.h>
#include <sys/types.h>
#if HAVE_SYS_WAIT_H
#include <sys/wait.h>
#endif
#include <sys/socket.h>
#ifndef _WIN32
# include <sys/un.h>
#endif
#include <sys/uio.h>
#if HAVE_UNISTD_H
#include <unistd.h>
#endif
#include <string.h>
#include <signal.h>
#include <stdlib.h>
#include <sys/time.h>
#include <sys/resource.h>
#include <stdarg.h>
#if HAVE_SYS_FILIO_H
# include <sys/filio.h>
#endif
#if HAVE_STROPTS_H
# include <stropts.h>
#endif
#include <sys/stat.h>
#if HAVE_SYSLOG_H
# include <syslog.h>
#endif
#include <netdb.h>
#if HAVE_FCNTL_H
#include <fcntl.h>
#endif
#if HAVE_TERMIO_H
# include <termio.h>
#endif
#include <errno.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <ctype.h>
#include <sys/socket.h>
#include <netdb.h>
#include "cfg.h"
#ifndef nil
# define nil NULL
#endif
#ifndef SAME
# define SAME 0
#endif
#define MBUFSIZ 8192
#define SELECT_TIMOEOUT_SEC 5
#define SELECT_TIMOEOUT_MSEC 0
static char *SIMPLEPROXY_VERSION = "simpleproxy v3.5 by lord@crocodile.org,vlad@noir.crocodile.org,verylong@noir.crocodile.org,renzo@cs.unibo.it";
static char *SIMPLEPROXY_USAGE = "simpleproxy -L <[host:]port> -R <host:port> [-d] [-v] [-V] [-7] [-i] [-u] [-p PID file] [-P <POP3 accounts list file>] [-f cfgfile] [-t tracefile] [-D delay in sec.] [-S <HTTPS proxy host:port> [-a <HTTPS Auth user>:<HTTPS Auth password>] ] [-A <HTTP Auth user>:<HTTP Auth password>]";
static char *PROXY_HEADER_FMT = "\r\nProxy-Authorization: Basic %s";
static char *PROXY_HEADER = "\r\nProxy-Authorization: Basic ";
static char AUTHMSG[]=
"HTTP/1.1 407 Proxy Authorization Required\r\n"
"Proxy-Authenticate: Basic realm=\"";
static char AUTHMSG2[]= "\"\r\n"
"Content-Type: text/html\r\n"
"\r\n"
"<HTML><HEAD>\r\n"
"<TITLE>407 Proxy Authorization Required</TITLE>\r\n"
"</HEAD><BODY>\r\n"
"<H1>Proxy Authorization Required</H1>\r\n"
"Login and Password required\r\n"
"<hr>\r\nSimpleProxy\r\n"
"</BODY></HTML>\r\n";
struct lst_record
{
char *s;
struct lst_record *next;
};
static void daemon_start(void);
static int writen(int fd, char *ptr, int nbytes);
static void pass_all(int fd, int client);
static int pass_out( int in, int out);
static int pass_in( int in, int out, int isHtmlProbe,char *authHash);
static int get_hostaddr(const char *name);
static int readln(int fd, char *buf, int siz);
static void firstword(char *str);
static struct lst_record * load_pop3_list(const char *popfile);
static int check_pop3_list(struct lst_record *lst, char *acc);
static int pop3_login(int remotefd,int newsockfd);
static int read_pop3_cmd(int s, char *buff, int max_buf, int strip);
static void child_dead( int stat );
static void write_pid( char* filename );
static int process_remote(const char *rhost, int rportn,const char *client_name);
static int open_remote(const char *rhost, int rportn,const char *client_name);
static void logopen(void);
static void logclose(void);
static void logmsg(int, char *format, ...);
static void ctrlc(int);
static int https_connect(int remoteFd, const char *remoteHost, int remotePort);
static int str2bool(char *s);
static void parse_host_port(const char *src, char **h_ptr, int *p_ptr);
static void replace_string(char **dst, const char*src);
static void fatal();
static char *base64_encode(char *plaintext);
static void trace(int fd, char *buf, int siz);
static int isVerbose = 0;
static int isDaemon = 0;
static int isStripping = 0;
static int isStartedFromInetd = 0;
static int isUsingHTTPSAuth = 0;
static int isHtmlProbe = 0;
static long Delay = 0;
static char *HTTPSProxyHost = nil;
static int HTTPSProxyPort = -1;
static char *HTTPSBasicAuthString = nil;
static char *HTTPAuthHash = nil;
static char *Tracefile = nil;
static int SockFD = -1,
SrcSockFD = -1,
DstSockFD = -1;
struct lst_record *POPList = nil;
int main(int ac, char **av)
{
socklen_t clien;
struct sockaddr_in cli_addr, serv_addr;
int lportn = -1, rportn = -1;
char *lhost = nil, *rhost = nil;
struct hostent *hp;
char *client_name;
extern char *optarg;
int c;
int errflg = 0;
char *cfgfile = nil;
char *popfile = nil;
static struct Cfg *cfg = nil;
char *pidfile = nil;
int rsp = 1;
char *https_auth = nil;
char *http_auth = nil;
char *HTTPSAuthHash = nil;
int len;
char hbuf[NI_MAXHOST];
/* Check for the arguments, and overwrite values from cfg file */
while((c = getopt(ac, av, "iVv7dhuL:R:H:f:p:P:D:S:s:a:A:t:")) != -1)
switch (c)
{
case 'v':
isVerbose++;
break;
case 'i':
isStartedFromInetd++;
break;
case 'd':
isDaemon++;
break;
case 'u':
isHtmlProbe++;
break;
case 'p':
replace_string(&pidfile, optarg);
break;
case 'f':
replace_string(&cfgfile, optarg);
if(cfgfile)
{
if((cfg=readcfg(cfgfile))==nil)
{
logmsg(LOG_ERR,"Error reading cfg file.");
return 1;
}
else
{
char *tmp;
/* let's process cfg file. Will cnage options only if they were not set already*/
if (!isVerbose)
isVerbose = str2bool(cfgfind("Verbose", cfg, 0));
if (!isStartedFromInetd)
isStartedFromInetd = str2bool(cfgfind("StartedFromInetd",cfg, 0));
if (!isDaemon)
isDaemon = str2bool(cfgfind("Daemon", cfg, 0));
if (!isStripping)
isStripping = str2bool(cfgfind("Strip8bit", cfg, 0));
if (!isHtmlProbe)
isHtmlProbe = str2bool(cfgfind("HtmlProbe", cfg, 0));
tmp = cfgfind("LocalPort", cfg, 0);
if (tmp && lportn == -1)
parse_host_port(tmp, nil, &lportn);
tmp = cfgfind("RemotePort", cfg, 0);
if (tmp && rportn == -1)
parse_host_port(tmp, nil, &rportn);
tmp = cfgfind("HTTPSProxyPort",cfg, 0);
if (tmp && HTTPSProxyPort == -1)
parse_host_port(tmp, nil, &HTTPSProxyPort);
tmp = cfgfind("PIDFile", cfg, 0);
if(tmp && !pidfile)
replace_string(&pidfile, tmp);
tmp = cfgfind("POP3File", cfg, 0);
if(tmp && !popfile)
replace_string(&popfile, tmp);
tmp = cfgfind("LocalHost", cfg, 0);
if(tmp && !rhost)
parse_host_port(tmp, &lhost, &lportn);
tmp = cfgfind("RemoteHost", cfg, 0);
if(tmp && !rhost)
parse_host_port(tmp, &rhost, &rportn);
tmp = cfgfind("HTTPSProxyHost",cfg, 0);
if(tmp && !HTTPSProxyHost)
parse_host_port(tmp, &HTTPSProxyHost, &HTTPSProxyPort);
tmp = cfgfind("TraceFile", cfg, 0);
if(tmp && !Tracefile)
replace_string(&Tracefile, tmp);
tmp = cfgfind("https_auth", cfg, 0);
if(tmp && !https_auth) {
isUsingHTTPSAuth = 1;
replace_string(&https_auth, tmp);
}
tmp = cfgfind("http_auth", cfg, 0);
if(tmp && !http_auth)
replace_string(&http_auth, tmp);
freecfg(cfg);
}
}
break;
case 'L':
parse_host_port(optarg, &lhost, &lportn);
break;
case 'P':
replace_string(&popfile, optarg);
break;
case 'R':
parse_host_port(optarg, &rhost, &rportn);
break;
case 'H':
replace_string(&rhost, optarg);
break;
case 'D':
Delay = atol(optarg);
break;
case '7':
isStripping = 1;
break;
case 'S':
parse_host_port(optarg, &HTTPSProxyHost, &HTTPSProxyPort);
break;
case 's':
parse_host_port(optarg, nil, &HTTPSProxyPort);
break;
case 'V':
fprintf(stderr, "%s\n", SIMPLEPROXY_VERSION);
exit(0);
case 'h':
errflg++; // to make it print 'Usage:...'
break;
case 'a':
if((HTTPSProxyHost == nil) && (HTTPSProxyPort == -1))
fprintf(stderr, "Warning! Proxy authorization (-a) meaningless without HTTPS parameters (-S)\n");
isUsingHTTPSAuth = 1;
replace_string(&https_auth,optarg);
break;
case 'A':
replace_string(&http_auth,optarg);
break;
case 't':
replace_string(&Tracefile, optarg);
break;
default:
errflg++;
}
/* let us check options compatibility and completness*/
if(isUsingHTTPSAuth)
{
HTTPSAuthHash = base64_encode(https_auth);
HTTPSBasicAuthString = malloc(strlen(HTTPSAuthHash) + strlen(PROXY_HEADER_FMT));
sprintf(HTTPSBasicAuthString,PROXY_HEADER_FMT,HTTPSAuthHash);
free(HTTPSAuthHash);
} else
{
HTTPSBasicAuthString = "";
}
if(http_auth)
HTTPAuthHash = base64_encode(http_auth);
if (isStartedFromInetd && lportn > 0)
errflg++;
if (!rhost ||
rportn <= 0 ||
(lportn <= 0 && !isStartedFromInetd) ||
(HTTPSProxyHost && HTTPSProxyPort <=0))
errflg++;
/* Do some options post-processing */
if(isStartedFromInetd)
isDaemon++; /* implies */
if(errflg)
{
(void)fprintf(stderr, "%s\n", SIMPLEPROXY_VERSION);
(void)fprintf(stderr, "Usage:\n\t%s\n", SIMPLEPROXY_USAGE);
exit(1);
}
logopen();
if(signal(SIGINT,ctrlc)==SIG_ERR)
logmsg(LOG_ERR,"Error installing interrupt handler.");
if(lportn <= 1024 && geteuid()!=0 && !isStartedFromInetd)
{
if(!isVerbose)
{
logopen();
isVerbose++;
}
logmsg(LOG_ERR,"You must be root to run SIMPLEPROXY on reserved port");
fatal();
}
if (popfile)
POPList = load_pop3_list(popfile);
if (!isStartedFromInetd)
{
/* Let's become a daemon */
if(isDaemon)
daemon_start();
if(pidfile)
write_pid(pidfile);
if((SockFD = socket(AF_INET,SOCK_STREAM,0)) < 0)
{
logmsg(LOG_ERR,"Error creating socket.");
fatal();
}
memset((void *)&serv_addr, 0, sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = ((lhost && *lhost)? get_hostaddr(lhost): htonl(INADDR_ANY));
serv_addr.sin_port = htons(lportn);
if (setsockopt(SockFD, SOL_SOCKET, SO_REUSEADDR, (void*)&rsp, sizeof(rsp)))
logmsg(LOG_ERR,"Error setting socket options");
if (bind(SockFD, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0)
{
logmsg(LOG_ERR,"Error binding socket.");
fatal();
}
logmsg(LOG_INFO,"Waiting for connections.");
if (listen(SockFD,5) < 0)
{
logmsg(LOG_ERR,"Error listening socket: %s", strerror(errno));
fatal();
}
while (1)
{
clien = sizeof(cli_addr);
SrcSockFD = accept(SockFD,(struct sockaddr *)&cli_addr, &clien);
if(SrcSockFD < 0)
{
if (errno == EINTR || errno == ECHILD) /* Interrupt after SIGCHLD */
continue;
logmsg(LOG_ERR, "accept error - %s", strerror(errno));
fatal();
}
signal(SIGCHLD, child_dead);
switch (fork())
{
case -1: /* fork error */
logmsg(LOG_ERR,"fork error - %s", strerror(errno));
break;
case 0: /* Child */
if (getnameinfo((const struct sockaddr *) &cli_addr, len,
hbuf, sizeof(hbuf), NULL, 0, 0) == 0)
client_name = strdup(hbuf);
else
client_name = inet_ntoa(cli_addr.sin_addr);
/*
* I don't know is that a bug, but on Irix 6.2 parent
* process will not be able to accept any new connection
* if SockFD is closed here. Vlad
*/
/* (void)shutdown(SockFD,2); */
/* (void)close(SockFD); */
/* Process connection */
logmsg(LOG_NOTICE,
"Connect from %s (%s:%d->%s:%d)",
client_name,
((lhost && *lhost)? lhost: "ANY"), lportn,
(rhost && *rhost)? rhost: "localhost", rportn);
if (process_remote(rhost, rportn, client_name))
fatal();
logmsg(LOG_NOTICE,
"Connect from %s (%s:%d->%s:%d) closed",
client_name,
((lhost && *lhost)? lhost: "ANY"), lportn,
(rhost && *rhost)? rhost: "localhost", rportn);
shutdown(SrcSockFD, 2);
close(SrcSockFD);
SrcSockFD = -1;
closelog();
return 0; // Exit
default:
/* Parent */
close(SrcSockFD);
SrcSockFD = -1;
}
}
}
else
{
/* Started from inetd */
SrcSockFD = 0; // stdin
logmsg(LOG_NOTICE,
"Connect (inetd->%s:%d)",
(rhost && *rhost)? rhost: "localhost", rportn);
process_remote(rhost, rportn, "inetd");
logmsg(LOG_NOTICE,
"Connect (inetd->%s:%d) closed",
(rhost && *rhost)? rhost: "localhost", rportn);
}
return 0;
}
/*
* Write "n" bytes to a descriptor.
* Use in place of write() when fd is a stream socket.
*/
static int writen(int fd, char *ptr, int nbytes)
{
int nleft, nwritten;
nleft = nbytes;
while (nleft > 0)
{
nwritten = write(fd, ptr, nleft);
if(nwritten <= 0)
return(nwritten); /* error */
nleft -= nwritten;
ptr += nwritten;
}
return(nbytes - nleft);
}
/*
* Detach a daemon process from login session context.
*/
static void daemon_start(void)
{
/* Maybe I should do 2 forks here? */
if(fork())
exit(0);
if(chdir("/")) {} /* supressing warn_unused_result */
umask(0);
(void) close(0);
(void) close(1);
(void) close(2);
(void) open("/", O_RDONLY);
(void) dup2(0, 1);
(void) dup2(0, 2);
setsid();
}
void pass_all( int fd, int client )
{
fd_set in;
struct timeval tv;
int nsock, retval;
nsock = ((fd > client)? fd: client) + 1;
while(1)
{
FD_ZERO(&in);
FD_SET(fd, &in);
FD_SET(client, &in);
tv.tv_sec = SELECT_TIMOEOUT_SEC;
tv.tv_usec = SELECT_TIMOEOUT_MSEC;
retval = select(nsock, &in, nil, nil, &tv);
switch (retval)
{
case 0 :
/* Nothing to receive */
break;
case -1:
/* Error occured */
logmsg(LOG_ERR, "i/o error - %s", strerror(errno));
return;
default:
if(FD_ISSET( fd, &in))
retval = pass_out(fd, client);
else if(FD_ISSET( client, &in))
retval = pass_in(client, fd, isHtmlProbe, HTTPAuthHash);
else
retval = -1;
if( retval < 0)
return;
if(Delay > 0)
sleep(Delay);
}
}
}
static int get_hostaddr(const char *name)
{
struct hostent *he;
int res = -1;
int a1,a2,a3,a4;
if (sscanf(name,"%d.%d.%d.%d",&a1,&a2,&a3,&a4) == 4)
res = inet_addr(name);
else
{
he = gethostbyname(name);
if (he)
memcpy(&res , he->h_addr , he->h_length);
}
return res;
}
/* credit: some code for html probe has been taken from dsniff (renzo davoli)*/
static int strrindex (const char *s, int c, int pos)
{
if (pos >= 0) {
pos--;
while (pos >= 0 && s[pos] != c)
pos--;
}
return pos;
}
static int
is_display_uri(char *uri)
{
static char *good_prefixes[] = { NULL };
static char *good_suffixes[] = { ".html", ".htm", "/", ".shtml",
".cgi", ".asp", ".php3", ".txt",".pdf",
".xml", ".asc", NULL };
#ifdef INSEARCH
static char *good_infixes[] = { ".cgi", ".asp", ".php3", NULL };
#endif
int len, slen, pos;
char **pp, *p;
/* printf("is_display_uri %s\n",uri);*/
/* Get URI length, without QUERY_INFO */
if ((p = strchr(uri, '?')) != NULL) {
len = p - uri;
}
/* Get URI length, without TAG */
else if ((p = strchr(uri, '#')) != NULL) {
len = p - uri;
}
else {
/* no '?', no '#', maybe dir */
len = strlen(uri);
pos=strrindex(uri,'/',len);
if (pos >= 0) {
if (strchr(&uri[pos+1],'.') == NULL &&
strchr(&uri[pos+1],'=') == NULL &&
strchr(&uri[pos+1],'&') == NULL)
return 1;
}
}
for (pp = good_suffixes; *pp != NULL; pp++) {
if (len < (slen = strlen(*pp))) continue;
if (strncasecmp(&uri[len - slen], *pp, slen) == 0)
return (1);
}
for (pp = good_prefixes; *pp != NULL; pp++) {
if (len < (slen = strlen(*pp))) continue;
if (strncasecmp(uri, *pp, slen) == 0)
return (1);
}
#ifdef INSEARCH
for (pp = good_infixes; *pp != NULL; pp++) {
for (pos = len; pos > (slen = strlen(*pp)); pos = strrindex(uri,'/',pos)) {
if (strncasecmp(&uri[pos - slen], *pp, slen) == 0)
return (1);
}
}
#endif
return (0);
}
static char *strxdup(const char *s, size_t n)
{
char *result=malloc(n+1);
if (result != NULL) {
memcpy(result,s,n);
result[n]=0;
}
return result;
}
static int
process_http_request(char *data, int len)
{
char *uri, *enduri;
data[len]=0;
//printf("process_http_request(%d)\n%s\nEND\n",getpid(),data);
if (strncmp(data, "GET ", 4)==0) {
uri = data+4;
if ((enduri=strchr(uri,' ')) != NULL) {
uri=strxdup(uri,(size_t)(enduri-uri));
//printf("uri %s\n",uri);
if (is_display_uri(uri)) {
printf("%s\n",uri);
fflush(stdout);
}
free(uri);
}
}
return 0;
}
static int pass_out( int in, int out)
{
int nread;
char buff[MBUFSIZ];
if ((nread = readln(in, buff,MBUFSIZ)) <= 0)
return -1;
else
{
if (isStripping)
{
char *bufp;
for (bufp = buff+nread-1; bufp >= buff; bufp--)
*bufp = *bufp&0177;
}
if(writen(out, buff, nread) != nread)
{
logmsg(LOG_ERR,"write error");
return -1;
}
}
return 0;
}
static int auth_check (char *buf, int len, char *http_authhash)
{
char *match;
if ((match=strstr(buf,PROXY_HEADER)) != NULL) {
int authlen=strlen(PROXY_HEADER)+strlen(http_authhash);
if (((match - buf)-authlen) <= len) {
if (strncmp(match+strlen(PROXY_HEADER),http_authhash,strlen(http_authhash))==0 &&
(*(match + authlen) == '\r' || *(match + authlen) == '\n')) {
memmove(match,match+authlen,(match-buf)-authlen);
return(len-authlen);
} else
return 0;
}
else
return 0;
} else
return 0;
}
static int pass_in( int in, int out , int htmlProbe, char *http_authhash)
{
int nread;
static char *buff=NULL;
static int size=0;
static int len=0;
/* printf("HASH %s|=== %d\n",http_authhash,getpid()); */
if ((size - len) == 0) {
if (size==0) size=MBUFSIZ;
else size *= 2;
buff = realloc(buff,size+1);
if (!buff)
return -1;
}
if ((nread = readln(in, buff+len, size-len)) <= 0)
return -1;
{
char *pos;
len+=nread;
buff[len]=0;
/* printf("R %d %d ==%s==\n",nread,len,buff); */
if (htmlProbe || http_authhash != NULL) {
/* http basic parsing (allowing persistent connections and pipelining) */
while ((pos=strstr(buff,"\r\n\r\n")) != NULL) {
int nout;
nout=nread=(pos-buff)+4;
/* printf("C %d %d ==%s==\n",nread,len,buff); */
if (isStripping)
{
char *bufp;
for (bufp = buff+nread-1; bufp >= buff; bufp--)
*bufp = *bufp&0177;
}
/* authentication management */
if (http_authhash != NULL && (nout = auth_check(buff,nread,http_authhash)) == 0) {
writen(in,AUTHMSG,sizeof(AUTHMSG));
writen(in,"SimpleProxy",11);
writen(in,AUTHMSG2,sizeof(AUTHMSG2));
return -1;
} else {
if(writen(out, buff, nout) != nout)
{
logmsg(LOG_ERR,"write error");
return -1;
}
/* probe: display on stdout significant URLs */
if (htmlProbe)
process_http_request(buff, nout);
}
len -= nread;
if (len>0)
memmove(buff,buff+nread,len);
else
*buff=0;
}
} else {
if (isStripping)
{
char *bufp;
for (bufp = buff+nread-1; bufp >= buff; bufp--)
*bufp = *bufp&0177;
}
if(writen(out, buff, len) != len)
{
logmsg(LOG_ERR,"write error");
return -1;
}
len -= nread;
*buff=0;
}
}
return 0;
}
void child_dead( int stat )
{
while(waitpid( -1, nil, WNOHANG ) > 0);
signal( SIGCHLD, child_dead );
}
void parse_host_port(const char *src, char ** h_ptr, int *p_ptr)
{
if(src)
{
struct servent *se;
/* Look for ':' separator */
const char *tmp = strrchr(src, ':');
if (tmp)
{
if (h_ptr)
{
replace_string(h_ptr, src);
/* This looks like host:port syntax */
*((*h_ptr) + (tmp - src)) = '\0';
}
tmp++;
}
else
tmp = src; /* to compensate future ++; */
*p_ptr = (isdigit(*tmp))?
atoi(tmp):
(((se = getservbyname(tmp, "tcp")) == nil)?
-1:
ntohs(se->s_port));
}
}
void write_pid( char* filename )
{
FILE *f;
if((f=fopen(filename,"w"))==nil)
{
logmsg(LOG_WARNING,"Can't open file '%s' to write PID",filename);
return;
}
fprintf( f,"%d",getpid());
fclose( f );
return;
}
/**
* Load list of allowed POP3 accounts from external file
* One per line
*/
static struct lst_record *load_pop3_list(const char *popfile)
{
FILE *f;
char str[2048];
struct lst_record *first = nil;
struct lst_record *last = nil;
if((f=fopen(popfile,"r"))==nil)
{
logmsg(LOG_ERR,"Can't open POP3 file: %s",popfile);
return nil;
}
while((str==fgets(str,2040,f)))
{
if(*str=='#') continue; /* comment */
firstword(str);
if(*str=='\0') continue;
logmsg(LOG_INFO,"Adding '%s' to POP3 users list",str);
if(first==nil)
{
first=(struct lst_record *)malloc(sizeof(struct lst_record));
last=first;
} else {
last->next=(struct lst_record *)malloc(sizeof(struct lst_record));
last=last->next;
}
last->s=strdup(str);
last->next=nil;
}
fclose(f);
return first;
}
/**
* Check if given account is OK to proxy
*/
static int check_pop3_list(struct lst_record *lst, char *acc)
{
while (lst)
{
if(strcmp(lst->s, acc) == 0)
return 1; /* found */
else
lst = lst->next;
}
return 0;
}
static void firstword(char *s)
{
s=strpbrk(s,"\n\t\r ");
if(s)
*s='\0';
}
static int readln(int fd, char *buf, int siz)
{
int nread;
nread = read(fd, buf, siz);
if(nread <= 0)
{
if(nread < 0)
logmsg(LOG_ERR,"read error");
return -1;
} else
{
if (Tracefile)
{
// do tracing;
trace(fd, buf, nread);
}
return nread;
}
}
/**
* . reads single POP3 command from socket.
* . strips \r and \n at the end
* . returns number of chars left or -1 in case of read error.
*/
static int read_pop3_cmd(int s, char *buff, int max_buf, int strip)
{
int n;
if((n=readln(s,buff,max_buf))<=0) return -1; /* read error */
do {
buff[n--]='\0';
} while((buff[n]=='\r' || buff[n]=='\n') && n>=0 && strip);
return n;
}
/*
* Pass USER command to remote end only if user is in the list
*
* See RFC1725 for details.
*/
static int pop3_login(int server,int user)
{
static char errmsg0[]={"-ERR Not allowed by proxy\r\n" };
static char errmsg1[]={"-ERR Can't get your user name\r\n"};
static char errmsg2[]={"-ERR USER or QUIT command expected\r\n" };
static char errmsg3[]={"-ERR PASS or QUIT command expected\r\n" };
char buff[MBUFSIZ];
char *s;
/* read +OK from server */
if(readln(server,buff,MBUFSIZ)<=0) return 1; /* read error */