-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathproxy.c
2859 lines (2518 loc) · 71.7 KB
/
proxy.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
/*
* This is the main module of the CNTLM
*
* CNTLM 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.
*
* CNTLM 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., 51 Franklin
* St, Fifth Floor, Boston, MA 02110-1301, USA.
*
* Copyright (c) 2007 David Kubicek
*
*/
#include <pthread.h>
#include <stdio.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/time.h>
#include <sys/select.h>
#include <sys/stat.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <signal.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <strings.h>
#include <netdb.h>
#include <regex.h>
#include <ctype.h>
#include <pwd.h>
#include <fcntl.h>
#include <syslog.h>
#include <termios.h>
#include <fnmatch.h>
/*
* Some helping routines like linked list manipulation substr(), memory
* allocation, NTLM authentication routines, etc.
*/
#include "config/config.h"
#include "socket.h"
#include "utils.h"
#include "ntlm.h"
#include "spnego.h"
#include "swap.h"
#include "config.h"
#include "acl.h"
#include "auth.h"
#include "http.h"
#include "pages.c"
#define DEFAULT_PORT "3128"
#define SAMPLE 4096
#define STACK_SIZE sizeof(void *)*8*1024
#define PLUG_NONE 0x0000
#define PLUG_SENDHEAD 0x0001
#define PLUG_SENDDATA 0x0002
#define PLUG_ERROR 0x8000
#define PLUG_ALL 0x7FFF
/*
* A couple of shortcuts for if statements
*/
#define CONNECT(data) (data && data->req && !strcasecmp("CONNECT", data->method))
#define HEAD(data) (data && data->req && !strcasecmp("HEAD", data->method))
#define GET(data) (data && data->req && !strcasecmp("GET", data->method))
/*
* Global "read-only" data initialized in main(). Comments list funcs. which use
* them. Having these global avoids the need to pass them to each thread and
* from there again a few times to inner calls.
*/
int debug = 0; /* all debug printf's and possibly external modules */
static struct auth_s *creds = NULL; /* throughout the whole module */
static int quit = 0; /* sighandler() */
static int asdaemon = 1; /* myexit() */
static int ntlmbasic = 0; /* proxy_thread() */
static int use_spnego = 1;
static char *spnego_spn = "";
static int serialize = 0;
static int scanner_plugin = 0;
static long scanner_plugin_maxsize = 0;
static int precache = 0;
static int active_conns = 0;
static pthread_mutex_t active_mtx = PTHREAD_MUTEX_INITIALIZER;
/*
* List of finished threads. Each thread proxy_thread() adds itself to it when
* finished. Main regularly joins and removes all tid's in there.
*/
static plist_t threads_list = NULL;
static pthread_mutex_t threads_mtx = PTHREAD_MUTEX_INITIALIZER;
/*
* List of cached connections. Accessed by each thread proxy_thread().
*/
static plist_t connection_list = NULL;
static pthread_mutex_t connection_mtx = PTHREAD_MUTEX_INITIALIZER;
/*
* List of available proxies and current proxy id for proxy_connect().
*/
static int parent_count = 0;
static int parent_curr = 0;
static pthread_mutex_t parent_mtx = PTHREAD_MUTEX_INITIALIZER;
static plist_t parent_list = NULL;
typedef struct {
struct in_addr host;
int port;
} proxy_t;
/*
* List of custom header substitutions, SOCKS5 proxy users and
* UserAgents for the scanner plugin.
*/
static hlist_t header_list = NULL; /* proxy_thread() */
static hlist_t users_list = NULL; /* socks5_thread() */
static plist_t scanner_agent_list = NULL; /* scanner_hook() */
/*
* General signal handler. If in debug mode, quit immediately.
*/
void sighandler(int p) {
if (!quit)
syslog(LOG_INFO, "Signal %d received, issuing clean shutdown\n", p);
else
syslog(LOG_INFO, "Signal %d received, forcing shutdown\n", p);
if (quit++ || debug)
quit++;
}
void myexit(int rc) {
if (rc)
fprintf(stderr, "Exitting with error. Check daemon logs or run with -v.\n");
exit(rc);
}
/*
* Keep count of active connections (trasferring data)
*/
void update_active(int i) {
pthread_mutex_lock(&active_mtx);
active_conns += i;
pthread_mutex_unlock(&active_mtx);
}
/*
* Retur/ count of active connections (trasferring data)
*/
int check_active(void) {
int r;
pthread_mutex_lock(&active_mtx);
r = active_conns;
pthread_mutex_unlock(&active_mtx);
return r;
}
/*
* Connect to the selected proxy. If the request fails, pick next proxy
* in the line. Each request scans the whole list until all items are tried
* or a working proxy is found, in which case it is selected and used by
* all threads until it stops working. Then the search starts again.
*/
int proxy_connect(void) {
proxy_t *aux;
int i, prev;
plist_t list, tmp;
int loop = 0;
prev = parent_curr;
pthread_mutex_lock(&parent_mtx);
if (parent_curr == 0) {
aux = (proxy_t *)plist_get(parent_list, ++parent_curr);
syslog(LOG_INFO, "Using proxy %s:%d\n", inet_ntoa(aux->host), aux->port);
}
pthread_mutex_unlock(&parent_mtx);
do {
aux = (proxy_t *)plist_get(parent_list, parent_curr);
i = so_connect(aux->host, aux->port);
if (i <= 0) {
pthread_mutex_lock(&parent_mtx);
if (parent_curr >= parent_count)
parent_curr = 0;
aux = (proxy_t *)plist_get(parent_list, ++parent_curr);
pthread_mutex_unlock(&parent_mtx);
syslog(LOG_ERR, "Proxy connect failed, will try %s:%d\n", inet_ntoa(aux->host), aux->port);
}
} while (i <= 0 && ++loop < parent_count);
if (i <= 0 && loop >= parent_count)
syslog(LOG_ERR, "No proxy on the list works. You lose.\n");
/*
* We have to invalidate the cached connections if we moved to a different proxy
*/
if (prev != parent_curr) {
pthread_mutex_lock(&connection_mtx);
list = connection_list;
while (list) {
tmp = list->next;
close(list->key);
list = tmp;
}
plist_free(connection_list);
pthread_mutex_unlock(&connection_mtx);
}
return i;
}
/*
* Parse proxy parameter and add it to the global list.
*/
int parent_add(char *parent, int port) {
int len, i;
char *proxy;
proxy_t *aux;
struct in_addr host;
/*
* Check format and parse it.
*/
proxy = strdup(parent);
len = strlen(proxy);
i = strcspn(proxy, ": ");
if (i != len) {
proxy[i++] = 0;
while (i < len && (proxy[i] == ' ' || proxy[i] == '\t'))
i++;
if (i >= len) {
free(proxy);
return 0;
}
port = atoi(proxy+i);
}
/*
* No port argument and not parsed from proxy?
*/
if (!port) {
syslog(LOG_ERR, "Invalid proxy specification %s.\n", parent);
free(proxy);
myexit(1);
}
/*
* Try to resolve proxy address
*/
if (debug)
syslog(LOG_INFO, "Resolving proxy %s...\n", proxy);
if (!so_resolv(&host, proxy)) {
syslog(LOG_ERR, "Cannot resolve proxy %s, discarding.\n", parent);
free(proxy);
return 0;
}
aux = (proxy_t *)new(sizeof(proxy_t));
aux->host = host;
aux->port = port;
parent_list = plist_add(parent_list, ++parent_count, (char *)aux);
free(proxy);
return 1;
}
/*
* Register and bind new proxy service port.
*/
void listen_add(const char *service, plist_t *list, char *spec, int gateway) {
struct in_addr source;
int i, p, len, port;
char *tmp;
len = strlen(spec);
p = strcspn(spec, ":");
if (p < len-1) {
tmp = substr(spec, 0, p);
if (!so_resolv(&source, tmp)) {
syslog(LOG_ERR, "Cannot resolve listen address %s\n", tmp);
myexit(1);
}
free(tmp);
port = atoi(tmp = spec+p+1);
} else {
source.s_addr = htonl(gateway ? INADDR_ANY : INADDR_LOOPBACK);
port = atoi(tmp = spec);
}
if (!port) {
syslog(LOG_ERR, "Invalid listen port %s.\n", tmp);
myexit(1);
}
i = so_listen(port, source);
if (i > 0) {
*list = plist_add(*list, i, NULL);
syslog(LOG_INFO, "%s listening on %s:%d\n", service, inet_ntoa(source), port);
}
}
/*
* Register a new tunnel definition, bind service port.
*/
void tunnel_add(plist_t *list, char *spec, int gateway) {
struct in_addr source;
int i, len, count, pos, port;
char *field[4];
char *tmp;
spec = strdup(spec);
len = strlen(spec);
field[0] = spec;
for (count = 1, i = 0; i < len; ++i)
if (spec[i] == ':') {
spec[i] = 0;
field[count++] = spec+i+1;
}
pos = 0;
if (count == 4) {
if (!so_resolv(&source, field[pos])) {
syslog(LOG_ERR, "Cannot resolve tunel listen address: %s\n", field[pos]);
myexit(1);
}
pos++;
} else
source.s_addr = htonl(gateway ? INADDR_ANY : INADDR_LOOPBACK);
if (count-pos == 3) {
port = atoi(field[pos]);
if (port == 0) {
syslog(LOG_ERR, "Invalid tunnel local port: %s\n", field[pos]);
myexit(1);
}
if (!strlen(field[pos+1]) || !strlen(field[pos+2])) {
syslog(LOG_ERR, "Invalid tunnel target: %s:%s\n", field[pos+1], field[pos+2]);
myexit(1);
}
tmp = new(strlen(field[pos+1]) + strlen(field[pos+2]) + 2 + 1);
strcpy(tmp, field[pos+1]);
strcat(tmp, ":");
strcat(tmp, field[pos+2]);
i = so_listen(port, source);
if (i > 0) {
*list = plist_add(*list, i, tmp);
syslog(LOG_INFO, "New tunnel from %s:%d to %s\n", inet_ntoa(source), port, tmp);
} else
free(tmp);
} else {
printf("Tunnel specification incorrect ([laddress:]lport:rserver:rport).\n");
myexit(1);
}
free(spec);
}
/*
* Duplicate client request headers, change requested method to HEAD
* (so we avoid any body transfers during NTLM negotiation), and add
* proxy authentication request headers.
*
* Read the reply, if it contains NTLM challenge, generate final
* NTLM auth message and insert it into the original client header,
* which is then processed by caller himself.
*
* If the proxy closes the connection for some reason, we notify our
* caller by setting closed to 1. Otherwise, it is set to 0.
* If closed == NULL, we do not signal anything.
*/
int authenticate_spnego(int sd, rr_data_t request, int *closed) {
char *tmp, *buf, *challenge;
rr_data_t auth;
int len, rc;
void *creds, *ctxt;
if (closed)
*closed = 0;
buf = new(BUFSIZE);
strcpy(buf, "Negotiate ");
len = spnego_request(spnego_spn, &tmp, &creds, &ctxt);
to_base64(MEM(buf, unsigned char, 0xA), MEM(tmp, unsigned char, 0), len, BUFSIZE-0xA);
free(tmp);
auth = dup_rr_data(request);
/*
* If the request is CONNECT, we have to keep it unmodified
*/
if (!CONNECT(request)) {
free(auth->method);
auth->method = strdup("GET");
}
auth->headers = hlist_mod(auth->headers, "Proxy-Authorization", buf, 1);
auth->headers = hlist_del(auth->headers, "Content-Length");
if (debug) {
printf("\nSending auth request...\n");
hlist_dump(auth->headers);
}
if (!headers_send(sd, auth)) {
rc = 0;
goto bailout;
}
free_rr_data(auth);
auth = new_rr_data();
if (debug) {
printf("Reading auth response...\n");
}
if (!headers_recv(sd, auth)) {
rc = 0;
goto bailout;
}
if (debug)
hlist_dump(auth->headers);
tmp = hlist_get(auth->headers, "Content-Length");
if (tmp && (len = atoi(tmp))) {
if (debug)
printf("Got %d too many bytes.\n", len);
data_drop(sd, len);
}
/*
* Should auth continue?
*/
if (auth->code == 407) {
tmp = hlist_get(auth->headers, "Proxy-Authenticate");
if (tmp) {
challenge = new(strlen(tmp));
len = from_base64(challenge, tmp+0xA );
if (len > 0) {
len = spnego_response(spnego, challenge, len, creds, ctxt, &tmp);
if (len > 0) {
strcpy(buf, "Negotiate ");
to_base64(MEM(buf, unsigned char, 0xA), MEM(tmp, unsigned char, 0), len, BUFSIZE-0xA);
request->headers = hlist_mod(request->headers, "Proxy-Authorization", buf, 1);
free(tmp);
} else {
syslog(LOG_ERR, "Invalid negotiate response!\n");
rc = 0;
free(challenge);
goto bailout;
}
} else {
syslog(LOG_ERR, "Proxy returning invalid challenge!\n");
rc = 0;
free(challenge);
goto bailout;
}
free(challenge);
} else {
syslog(LOG_WARNING, "No Proxy-Authenticate received! Negotiate not supported?\n");
}
} else if (auth->code >= 500 && auth->code <= 599) {
/*
* Proxy didn't like the request, close connection and don't try again.
*/
syslog(LOG_WARNING, "The request was denied!\n");
close(sd);
rc = 500;
goto bailout;
} else {
/*
* No auth was neccessary, let the caller make the request again.
*/
if (closed)
*closed = 1;
}
/*
* Does proxy intend to close the connection? E.g. it didn't require auth
* at all or there was some problem. If so, let caller know that it should
* reconnect!
*/
if (closed && hlist_subcmp(auth->headers, "Proxy-Connection", "close")) {
if (debug)
printf("Proxy signals it's closing the connection.\n");
*closed = 1;
}
rc = 1;
bailout:
free_rr_data(auth);
free(buf);
spnego_free(&creds, &ctxt);
return rc;
}
int authenticate_ntlm(int sd, rr_data_t request, struct auth_s *creds, int *closed) {
char *tmp, *buf, *challenge;
rr_data_t auth;
int len, rc;
if (closed)
*closed = 0;
buf = new(BUFSIZE);
strcpy(buf, "NTLM ");
len = ntlm_request(&tmp, creds);
to_base64(MEM(buf, unsigned char, 5), MEM(tmp, unsigned char, 0), len, BUFSIZE-5);
free(tmp);
auth = dup_rr_data(request);
/*
* If the request is CONNECT, we have to keep it unmodified
*/
if (!CONNECT(request)) {
free(auth->method);
auth->method = strdup("GET");
}
auth->headers = hlist_mod(auth->headers, "Proxy-Authorization", buf, 1);
auth->headers = hlist_del(auth->headers, "Content-Length");
if (debug) {
printf("\nSending auth request...\n");
hlist_dump(auth->headers);
}
if (!headers_send(sd, auth)) {
rc = 0;
goto bailout;
}
free_rr_data(auth);
auth = new_rr_data();
if (debug) {
printf("Reading auth response...\n");
}
if (!headers_recv(sd, auth)) {
rc = 0;
goto bailout;
}
if (debug)
hlist_dump(auth->headers);
tmp = hlist_get(auth->headers, "Content-Length");
if (tmp && (len = atoi(tmp))) {
if (debug)
printf("Got %d too many bytes.\n", len);
data_drop(sd, len);
}
/*
* Should auth continue?
*/
if (auth->code == 407) {
tmp = hlist_get(auth->headers, "Proxy-Authenticate");
if (tmp) {
challenge = new(strlen(tmp));
len = from_base64(challenge, tmp+5);
if (len > NTLM_CHALLENGE_MIN) {
len = ntlm_response(&tmp, challenge, len, creds);
if (len > 0) {
strcpy(buf, "NTLM ");
to_base64(MEM(buf, unsigned char, 5), MEM(tmp, unsigned char, 0), len, BUFSIZE-5);
request->headers = hlist_mod(request->headers, "Proxy-Authorization", buf, 1);
free(tmp);
} else {
syslog(LOG_ERR, "No target info block. Cannot do NTLMv2!\n");
rc = 0;
free(challenge);
goto bailout;
}
} else {
syslog(LOG_ERR, "Proxy returning invalid challenge!\n");
rc = 0;
free(challenge);
goto bailout;
}
free(challenge);
} else {
syslog(LOG_WARNING, "No Proxy-Authenticate received! NTLM not supported?\n");
}
} else if (auth->code >= 500 && auth->code <= 599) {
/*
* Proxy didn't like the request, close connection and don't try again.
*/
syslog(LOG_WARNING, "The request was denied!\n");
close(sd);
rc = 500;
goto bailout;
} else {
/*
* No auth was neccessary, let the caller make the request again.
*/
if (closed)
*closed = 1;
}
/*
* Does proxy intend to close the connection? E.g. it didn't require auth
* at all or there was some problem. If so, let caller know that it should
* reconnect!
*/
if (closed && hlist_subcmp(auth->headers, "Proxy-Connection", "close")) {
if (debug)
printf("Proxy signals it's closing the connection.\n");
*closed = 1;
}
rc = 1;
bailout:
free_rr_data(auth);
free(buf);
return rc;
}
/*
* Auth connection "sd" and try to return negotiated CONNECT
* connection to a remote host:port (thost).
*
* Return 0 for success, -1 for proxy negotiation error and
* -HTTP_CODE in case the request failed.
*/
int make_connect(int sd, const char *thost) {
rr_data_t data1, data2;
int ret, closed;
if (!sd || !thost || !strlen(thost))
return -1;
data1 = new_rr_data();
data2 = new_rr_data();
data1->req = 1;
data1->method = strdup("CONNECT");
data1->url = strdup(thost);
data1->http = strdup("0");
data1->headers = hlist_mod(data1->headers, "Proxy-Connection", "Keep-Alive", 1);
if (debug)
printf("Starting authentication...\n");
if (use_spnego)
ret = authenticate_spnego(sd, data1, &closed);
else
ret = authenticate_ntlm(sd, data1, creds, &closed);
if (ret && ret != 500) {
if (closed || so_closed(sd)) {
close(sd);
sd = proxy_connect();
if (sd <= 0) {
ret = -1;
goto bailout;
}
}
if (debug) {
printf("Sending real request:\n");
hlist_dump(data1->headers);
}
if (headers_send(sd, data1)) {
if (debug)
printf("Reading real response:\n");
if (headers_recv(sd, data2)) {
if (debug)
hlist_dump(data2->headers);
if (data2->code == 200) {
if (debug)
printf("Ok CONNECT response. Tunneling...\n");
ret = 0;
goto bailout;
} else if (data2->code == 407) {
syslog(LOG_ERR, "Authentication for tunnel %s failed!\n", thost);
} else {
syslog(LOG_ERR, "Request for CONNECT denied!\n");
}
ret = -data2->code;
} else {
if (debug)
printf("Reading response failed!\n");
ret = -1;
}
} else {
if (debug)
printf("Sending request failed!\n");
ret = -1;
}
} else {
if (ret == 500)
syslog(LOG_ERR, "Tunneling to %s not allowed!\n", thost);
else
syslog(LOG_ERR, "Authentication requests failed!\n");
ret = -500;
}
bailout:
free_rr_data(data1);
free_rr_data(data2);
return ret;
}
/*
* Return 0 if no body, -1 if until EOF, number if size known
*/
int has_body(rr_data_t request, rr_data_t response) {
rr_data_t current;
int length, nobody;
char *tmp;
/*
* Checking complete req+res conversation or just the
* first part when there's no response yet?
*/
current = (response->http ? response : request);
/*
* HTTP body length decisions. There MUST NOT be any body from
* server if the request was HEAD or reply is 1xx, 204 or 304.
* No body can be in GET request if direction is from client.
*/
if (current == response) {
nobody = (HEAD(request) ||
(response->code >= 100 && response->code < 200) ||
response->code == 204 ||
response->code == 304);
} else {
nobody = GET(request) || HEAD(request);
}
/*
* Otherwise consult Content-Length. If present, we forward exaclty
* that many bytes.
*
* If not present, but there is Transfer-Encoding or Content-Type
* (or a request to close connection, that is, end of data is signaled
* by remote close), we will forward until EOF.
*
* No C-L, no T-E, no C-T == no body.
*/
tmp = hlist_get(current->headers, "Content-Length");
if (!nobody && tmp == NULL && (hlist_in(current->headers, "Content-Type")
|| hlist_in(current->headers, "Transfer-Encoding")
|| (response->code == 200))) {
length = -1;
} else
length = (tmp == NULL || nobody ? 0 : atol(tmp));
return length;
}
int scanner_hook(rr_data_t *request, rr_data_t *response, int *cd, int *sd, long maxKBs) {
char *buf, *line, *pos, *tmp, *pat, *post, *isaid, *uurl;
int bsize, lsize, size, len, i, nc;
rr_data_t newreq, newres;
plist_t list;
int ok = 1;
int done = 0;
int headers_initiated = 0;
long c, progress = 0, filesize = 0;
if (!(*request)->method || !(*response)->http
|| has_body(*request, *response) != -1
|| hlist_subcmp((*response)->headers, "Transfer-Encoding", "chunked")
|| !hlist_subcmp((*response)->headers, "Proxy-Connection", "close"))
return PLUG_SENDHEAD | PLUG_SENDDATA;
tmp = hlist_get((*request)->headers, "User-Agent");
if (tmp) {
tmp = lowercase(strdup(tmp));
list = scanner_agent_list;
while (list) {
pat = lowercase(strdup(list->aux));
if (debug)
printf("scanner_hook: matching U-A header (%s) to %s\n", tmp, pat);
if (!fnmatch(pat, tmp, 0)) {
if (debug)
printf("scanner_hook: positive match!\n");
maxKBs = 0;
free(pat);
break;
}
free(pat);
list = list->next;
}
free(tmp);
}
bsize = SAMPLE;
buf = new(bsize);
len = 0;
do {
size = read(*sd, buf + len, SAMPLE - len - 1);
if (debug)
printf("scanner_hook: read %d of %d\n", size, SAMPLE - len);
if (size > 0)
len += size;
} while (size > 0 && len < SAMPLE - 1);
if (strstr(buf, "<title>Downloading status</title>") && (pos=strstr(buf, "ISAServerUniqueID=")) && (pos = strchr(pos, '"'))) {
pos++;
c = strlen(pos);
for (i = 0; i < c && pos[i] != '"'; ++i);
if (pos[i] == '"') {
isaid = substr(pos, 0, i);
if (debug)
printf("scanner_hook: ISA id = %s\n", isaid);
lsize = BUFSIZE;
line = new(lsize);
do {
i = so_recvln(*sd, &line, &lsize);
c = strlen(line);
if (len + c >= bsize) {
bsize *= 2;
tmp = realloc(buf, bsize);
if (tmp == NULL)
break;
else
buf = tmp;
}
strcat(buf, line);
len += c;
if (i > 0 && (!strncmp(line, " UpdatePage(", 12) || (done=!strncmp(line, "DownloadFinished(", 17)))) {
if (debug)
printf("scanner_hook: %s", line);
if ((pos=strstr(line, "To be downloaded"))) {
filesize = atol(pos+16);
if (debug)
printf("scanner_hook: file size detected: %ld KiBs (max: %ld)\n", filesize/1024, maxKBs);
if (maxKBs && (maxKBs == 1 || filesize/1024 > maxKBs))
break;
/*
* We have to send HTTP protocol ID so we can send the notification
* headers during downloading. Once we've done that, it cannot appear
* again, which it would if we returned PLUG_SENDHEAD, so we must
* remember to not include it.
*/
headers_initiated = 1;
tmp = new(MINIBUF_SIZE);
snprintf(tmp, MINIBUF_SIZE, "HTTP/1.%s 200 OK\r\n", (*request)->http);
write(*cd, tmp, strlen(tmp));
free(tmp);
}
if (!headers_initiated) {
if (debug)
printf("scanner_hook: Giving up, \"To be downloaded\" line not found!\n");
break;
}
/*
* Send a notification header to the client, just so it doesn't timeout
*/
if (!done) {
tmp = new(MINIBUF_SIZE);
progress = atol(line+12);
snprintf(tmp, MINIBUF_SIZE, "ISA-Scanner: %ld of %ld\r\n", progress, filesize);
write(*cd, tmp, strlen(tmp));
free(tmp);
}
/*
* If download size is unknown beforehand, stop when downloaded amount is over ISAScannerSize
*/
if (!filesize && maxKBs && maxKBs != 1 && progress/1024 > maxKBs)
break;
}
} while (i > 0 && !done);
if (i > 0 && done && (pos = strstr(line, "\",\"")+3) && (c = strchr(pos, '"')-pos) > 0) {
tmp = substr(pos, 0, c);
pos = urlencode(tmp);
free(tmp);
uurl = urlencode((*request)->url);
post = new(BUFSIZE);
snprintf(post, bsize, "%surl=%s&%sSaveToDisk=YES&%sOrig=%s", isaid, pos, isaid, isaid, uurl);
if (debug)
printf("scanner_hook: Getting file with URL data = %s\n", (*request)->url);
tmp = new(MINIBUF_SIZE);
snprintf(tmp, MINIBUF_SIZE, "%d", (int)strlen(post));
newres = new_rr_data();
newreq = dup_rr_data(*request);
free(newreq->method);
newreq->method = strdup("POST");
hlist_mod(newreq->headers, "Referer", (*request)->url, 1);
hlist_mod(newreq->headers, "Content-Type", "application/x-www-form-urlencoded", 1);
hlist_mod(newreq->headers, "Content-Length", tmp, 1);
free(tmp);
/*
* Try to use a cached connection or authenticate new.
*/
pthread_mutex_lock(&connection_mtx);
i = plist_pop(&connection_list);
pthread_mutex_unlock(&connection_mtx);
if (i) {
if (debug)
printf("scanner_hook: Found autenticated connection %d!\n", i);
nc = i;
} else {
nc = proxy_connect();
if (use_spnego)
c = authenticate_spnego(nc, newreq, NULL);
else
c = authenticate(nc, newreq, creds, NULL);
if (c > 0 && c != 500) {
if (debug)
printf("scanner_hook: Authentication OK, getting the file...\n");
} else {
if (debug)
printf("scanner_hook: Authentication failed\n");
nc = 0;
}
}
/*
* The POST request for the real file
*/
if (nc && headers_send(nc, newreq) && write(nc, post, strlen(post)) && headers_recv(nc, newres)) {
if (debug)
hlist_dump(newres->headers);
free_rr_data(*response);
/*
* We always know the filesize here. Send it to the client, because ISA doesn't!!!
* The clients progress bar doesn't work without it and it stinks!
*/
if (filesize || progress) {
tmp = new(20);
snprintf(tmp, 20, "%ld", filesize ? filesize : progress);
newres->headers = hlist_mod(newres->headers, "Content-Length", tmp, 1);
}
/*
* Here we remember if previous code already sent some headers
* to the client. In such case, do not include the HTTP/1.x ID.
*/
newres->skip_http = headers_initiated;
*response = dup_rr_data(newres);
*sd = nc;