-
Notifications
You must be signed in to change notification settings - Fork 0
/
phttpget.c
1567 lines (1347 loc) · 53.8 KB
/
phttpget.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 2005, 2016, 2018 Colin Percival, Felix Weinrank
* All rights reserved
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted providing that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
* IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#ifdef __linux__
#define _GNU_SOURCE
#define OFF_MAX LONG_MAX
#define _XOPEN_SOURCE 600
#include <sys/select.h>
#endif
#include <sys/types.h>
#include <sys/time.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netinet/sctp.h>
#include <arpa/inet.h>
#include <ctype.h>
#include <err.h>
#include <errno.h>
#include <fcntl.h>
#include <limits.h>
#include <netdb.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sysexits.h>
#include <unistd.h>
#include <sys/queue.h>
#include <stdarg.h>
#include <stdlib.h>
#include <string.h>
#include <sys/time.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <strings.h>
/* maximum SCTP streams */
#define FIFO_BUFFER_SIZE 1024
#define RESPONSE_BUFFER_SIZE 1048576
#define LOG_PRG 0
#define LOG_ERR 1
#define LOG_INF 2
#define LOG_DBG 3
static const char * env_HTTP_USER_AGENT;
static char * env_HTTP_TIMEOUT;
static char * env_HTTP_TRANSPORT_PROTOCOL;
static char * env_HTTP_SCTP_UDP_ENCAPS_PORT;
static char * env_HTTP_DEBUG;
static char * env_HTTP_PIPE;
static char * env_HTTP_USE_PIPELINING;
static char * env_HTTP_SCTP_MAX_STREAMS;
static char * env_HTTP_IP_PROTOCOL;
static struct timeval timo = {0, 0};
static uint8_t log_level = LOG_ERR; /* 0 = none | 1 = error | 2 = verbose | 3 = very verbose */
static in_port_t udp_encaps_port = 0;
static int protocol = IPPROTO_SCTP;
static uint16_t sctp_num_streams = 0;
static uint8_t *sctp_stream_status;
static uint32_t sctp_last_stream = 0; /* Last SCTP stream read from */
static char *servername; /* Name of server to connect with */
static uint8_t sctp_streams_busy = 0; /* Indicator if all streams are busy */
static struct timeval tv_init;
static uint8_t use_stdin = 0; /* read requests from stdin */
static uint8_t use_pipe = 0; /* read requests from pipe */
static uint8_t use_pipelining = 1; /* allow pipelining */
static uint8_t save_file = 0; /* save received data to file */
static uint16_t sctp_max_streams = 100; /* limit number of SCTP streams */
static int ip_protocol = AF_UNSPEC; /* 0 = both | 4 = IPv4 | 6 = IPv6 */
/* STATS */
static uint32_t stat_bytes_header = 0;
static uint32_t stat_bytes_payload = 0;
static uint32_t stat_status_200 = 0;
static uint32_t stat_status_404 = 0;
static uint32_t stat_status_other = 0;
int fifo_in_fd = -1;
int fifo_out_fd = -1;
char *fifo_in_name = "/tmp/phttpget-in";
char *fifo_out_name = "/tmp/phttpget-out";
enum stream_status {STREAM_FREE, STREAM_USED};
struct sctp_pipe_data {
uint32_t id;
uint32_t path_len;
uint32_t cookie_len;
uint32_t header_len;
uint32_t payload_len;
char path[FIFO_BUFFER_SIZE];
} __attribute__ ((packed));
struct request {
uint32_t id;
char *cookie;
char *url;
struct sctp_pipe_data pipe_data;
TAILQ_ENTRY(request) entries;
};
TAILQ_HEAD(request_queue, request);
struct request_queue requests_open;
struct request_queue requests_pending;
#define MAX(a,b) (((a)>(b))?(a):(b))
#define MIN(a,b) (((a)<(b))?(a):(b))
#ifndef __FreeBSD__
/* Locate a substring in a string */
char *
strnstr(const char *s, const char *find, size_t slen)
{
char c, sc;
size_t len;
if ((c = *find++) != '\0') {
len = strlen(find);
do {
do {
if (slen-- < 1 || (sc = *s++) == '\0')
return (NULL);
} while (sc != c);
if (len > slen)
return (NULL);
} while (strncmp(s, find, len) != 0);
s--;
}
return ((char *)s);
}
#endif
static const char *bytes2human(uint64_t bytes)
{
char *suffix[] = {"", "K", "M", "G", "T"};
char suffix_length = sizeof(suffix) / sizeof(suffix[0]);
int i = 0;
double human_size = bytes;
static char output[200];
if (bytes > 1024) {
for (i = 0; (bytes / 1024) > 0 && i < suffix_length - 1; i++) {
human_size = bytes / 1024.0;
bytes /= 1024;
}
}
snprintf(output, sizeof(output), "%.02lf %s", human_size, suffix[i]);
return output;
}
/*
* Write log entry
*/
static void
mylog(uint8_t level, const char* format, ...)
{
struct timeval tv_now, tv_diff;
// skip unwanted loglevels
if (log_level < level) {
return;
}
gettimeofday(&tv_now, NULL);
tv_diff.tv_sec = tv_now.tv_sec - tv_init.tv_sec;
if (tv_init.tv_usec < tv_now.tv_usec) {
tv_diff.tv_usec = tv_now.tv_usec - tv_init.tv_usec;
} else {
tv_diff.tv_sec -= 1;
tv_diff.tv_usec = 1000000 + tv_now.tv_usec - tv_init.tv_usec;
}
fprintf(stderr, "[%4ld.%06ld]", (long)tv_diff.tv_sec, (long)tv_diff.tv_usec);
switch (level) {
case 0:
fprintf(stderr, "[PRG] ");
break;
case 1:
fprintf(stderr, "[ERR] ");
break;
case 2:
fprintf(stderr, "[INF] ");
break;
case 3:
fprintf(stderr, "[DBG] ");
break;
}
va_list argptr;
va_start(argptr, format);
vfprintf(stderr, format, argptr);
va_end(argptr);
fprintf(stderr, "\n"); // xxx:ugly solution...
}
/* Print usage and exit */
static void
usage(void)
{
mylog(LOG_PRG, "usage: phttpget server [file1 file2 filnen]\n");
exit(EX_USAGE);
}
/* Read environment variables */
static void
readenv(void)
{
char *p;
long http_timeout;
long sctp_max_streams_temp;
long ip_protocol_temp;
env_HTTP_USER_AGENT = getenv("HTTP_USER_AGENT");
if (env_HTTP_USER_AGENT == NULL) {
env_HTTP_USER_AGENT = "phttpget/0.2";
}
env_HTTP_TIMEOUT = getenv("HTTP_TIMEOUT");
if (env_HTTP_TIMEOUT != NULL) {
http_timeout = strtol(env_HTTP_TIMEOUT, &p, 10);
if ((*env_HTTP_TIMEOUT == '\0') || (*p != '\0') || (http_timeout < 0)) {
mylog(LOG_ERR, "HTTP_TIMEOUT (%s) is not a positive integer", env_HTTP_TIMEOUT);
exit(EXIT_FAILURE);
} else {
timo.tv_sec = http_timeout;
}
}
mylog(LOG_PRG, "Settings - timeout : %d", timo.tv_sec);
env_HTTP_TRANSPORT_PROTOCOL = getenv("HTTP_TRANSPORT_PROTOCOL");
if (env_HTTP_TRANSPORT_PROTOCOL != NULL) {
if (strncasecmp(env_HTTP_TRANSPORT_PROTOCOL, "TCP", 3) == 0) {
protocol = IPPROTO_TCP;
} else if (strncasecmp(env_HTTP_TRANSPORT_PROTOCOL, "SCTP", 4) == 0) {
protocol = IPPROTO_SCTP;
} else {
mylog(LOG_ERR, "HTTP_TRANSPORT_PROTOCOL (%s) not supported", env_HTTP_TRANSPORT_PROTOCOL);
exit(EXIT_FAILURE);
}
}
mylog(LOG_PRG, "Settings - protocol : %s", (protocol == IPPROTO_TCP) ? "TCP" : "SCTP");
env_HTTP_SCTP_UDP_ENCAPS_PORT = getenv("HTTP_SCTP_UDP_ENCAPS_PORT");
if (env_HTTP_SCTP_UDP_ENCAPS_PORT != NULL) {
udp_encaps_port = (in_port_t) strtol(env_HTTP_SCTP_UDP_ENCAPS_PORT, &p, 10);
}
mylog(LOG_PRG, "Settings - SCTP UDP encaps port : %d (%s)", udp_encaps_port, (udp_encaps_port > 0) ? "enabled" : "disabled");
env_HTTP_DEBUG = getenv("HTTP_DEBUG");
if (env_HTTP_DEBUG != NULL) {
if (strncasecmp(env_HTTP_DEBUG, "LOG_PRG", 7) == 0) {
log_level = LOG_PRG;
} else if (strncasecmp(env_HTTP_DEBUG, "LOG_ERR", 7) == 0) {
log_level = LOG_ERR;
} else if (strncasecmp(env_HTTP_DEBUG, "LOG_INF", 7) == 0) {
log_level = LOG_INF;
} else if (strncasecmp(env_HTTP_DEBUG, "LOG_DBG", 7) == 0) {
log_level = LOG_DBG;
} else {
mylog(LOG_ERR, "unknown debug level");
exit(EXIT_FAILURE);
}
}
env_HTTP_PIPE = getenv("HTTP_PIPE");
if (env_HTTP_PIPE != NULL) {
use_pipe = 1;
mylog(LOG_INF, "Using pipes for requests/reposnses");
}
env_HTTP_USE_PIPELINING = getenv("HTTP_USE_PIPELINING");
if (env_HTTP_USE_PIPELINING != NULL) {
if (strncasecmp(env_HTTP_USE_PIPELINING, "YES", 3) == 0) {
use_pipelining = 1;
} else if (strncasecmp(env_HTTP_USE_PIPELINING, "NO", 2) == 0) {
use_pipelining = 0;
} else {
mylog(LOG_ERR, "invalid settings for pipelining support");
exit(EXIT_FAILURE);
}
}
mylog(LOG_PRG, "Settings - pipelining : %s", (use_pipelining == 1) ? "enabled" : "disabled");
env_HTTP_SCTP_MAX_STREAMS = getenv("HTTP_SCTP_MAX_STREAMS");
if (env_HTTP_SCTP_MAX_STREAMS != NULL) {
sctp_max_streams_temp = strtol(env_HTTP_SCTP_MAX_STREAMS, NULL, 10);
if (sctp_max_streams_temp < 1 || sctp_max_streams_temp > 65536) {
mylog(LOG_ERR, "sctp_max_streams out of range");
exit(EXIT_FAILURE);
}
sctp_max_streams = (uint16_t) sctp_max_streams_temp;
}
env_HTTP_IP_PROTOCOL = getenv("HTTP_IP_PROTOCOL");
if (env_HTTP_IP_PROTOCOL != NULL) {
ip_protocol_temp = strtol(env_HTTP_IP_PROTOCOL, NULL, 10);
switch (ip_protocol_temp) {
case 0:
ip_protocol = AF_UNSPEC;
mylog(LOG_PRG, "Settings - ip_protocol : AF_UNSPEC");
break;
case 4:
ip_protocol = AF_INET;
mylog(LOG_PRG, "Settings - ip_protocol : AF_INET");
break;
case 6:
ip_protocol = AF_INET6;
mylog(LOG_PRG, "Settings - ip_protocol : AF_INET6");
break;
default:
mylog(LOG_ERR, "ip_protocol out of range - shoud be 0/4/6");
exit(EXIT_FAILURE);
}
}
if (protocol == IPPROTO_SCTP && use_pipelining) {
mylog(LOG_PRG, "Settings - max SCTP streams : %d", sctp_max_streams);
}
}
static int
setup_connection(struct addrinfo *res, int *sd) {
int i = 0;
struct sctp_initmsg initmsg; /* To signal die number of incoming and outgoing streams */
int val; /* Value used for setsockopt call */
struct sctp_status status; /* To reuest SCTP status information */
#ifdef SCTP_REMOTE_UDP_ENCAPS_PORT
struct sctp_udpencaps encaps; /* SCTP/UDP information */
#endif
#ifdef __linux__
struct sctp_event_subscribe subscribe;
#endif
socklen_t statuslen = 0;
/* No addresses left to try :-( */
if (res == NULL) {
mylog(LOG_ERR, "[%d][%s] - Could not connect to %s", __LINE__, __func__, servername);
exit(EXIT_FAILURE);
}
char addr_str[INET6_ADDRSTRLEN];
struct sockaddr_in* saddr = (struct sockaddr_in*)res->ai_addr;
struct sockaddr_in6* saddr6 = (struct sockaddr_in6*)res->ai_addr;
if (res->ai_family == AF_INET) {
inet_ntop(res->ai_family, &saddr->sin_addr, addr_str, sizeof(addr_str));
} else if (res->ai_family == AF_INET6) {
inet_ntop(res->ai_family, &saddr6->sin6_addr, addr_str, sizeof(addr_str));
} else {
mylog(LOG_ERR, "[%d][%s] - Unsupported address family", __LINE__, __func__);
exit(EXIT_FAILURE);
}
mylog(LOG_PRG, "[%d][%s] - Candidate : %s %d", __LINE__, __func__, addr_str , res->ai_family);
if (res->ai_family == AF_INET || res->ai_family == AF_INET6) {
mylog(LOG_PRG, "[%d][%s] - Using IPv%d", __LINE__, __func__, (res->ai_family == AF_INET) ? (4) : (6));
} else {
mylog(LOG_ERR, "[%d][%s] - unknown address family", __LINE__, __func__);
exit(EXIT_FAILURE);
}
/* Create a socket... */
*sd = socket(res->ai_family, res->ai_socktype, protocol);
if (*sd == -1) {
/* reatry... */
mylog(LOG_ERR, "[%d][%s] - socket() failed", __LINE__, __func__);
return -1;
}
/* ... set timeouts ... */
setsockopt(*sd, SOL_SOCKET, SO_SNDTIMEO, (void *)&timo, (socklen_t)sizeof(timo));
setsockopt(*sd, SOL_SOCKET, SO_RCVTIMEO, (void *)&timo, (socklen_t)sizeof(timo));
/* set SCTP specific options */
if (protocol == IPPROTO_SCTP) {
/* Ensure an appropriate number of stream will be negotated. */
initmsg.sinit_num_ostreams = sctp_max_streams;
initmsg.sinit_max_instreams = sctp_max_streams;
initmsg.sinit_max_attempts = 0; /* Use default */
initmsg.sinit_max_init_timeo = 0; /* Use default */
if (setsockopt(*sd, IPPROTO_SCTP, SCTP_INITMSG, (char*) &initmsg, sizeof(initmsg)) < 0) {
mylog(LOG_ERR, "[%d][%s] - setsockopt() failed", __LINE__, __func__);
exit(EXIT_FAILURE);
}
val = 1;
if (setsockopt(*sd, IPPROTO_SCTP, SCTP_NODELAY, (char*) &val, sizeof(val)) < 0) {
mylog(LOG_ERR, "[%d][%s] - setsockopt() failed", __LINE__, __func__);
exit(EXIT_FAILURE);
}
#if defined(__FreeBSD__) || defined(__APPLE__)
/* Enable RCVINFO delivery */
if (setsockopt(*sd, IPPROTO_SCTP, SCTP_RECVRCVINFO, (char*) &val, sizeof(val)) < 0) {
mylog(LOG_ERR, "[%d][%s] - setsockopt() failed", __LINE__, __func__);
exit(EXIT_FAILURE);
}
#elif defined(__linux__)
/* sorry michael ... i know this must hurt you! :) */
memset(&subscribe, 0, sizeof(subscribe));
subscribe.sctp_data_io_event = val;
/* subscribe.sctp_association_event = val; */
if (setsockopt(*sd, SOL_SCTP, SCTP_EVENTS, (char *)&subscribe, sizeof(subscribe)) < 0) {
mylog(LOG_ERR, "[%d][%s] - setsockopt() failed", __LINE__, __func__);
exit(EXIT_FAILURE);
}
#endif
if (udp_encaps_port > 0) {
#ifdef SCTP_REMOTE_UDP_ENCAPS_PORT
/* Use UDP encapsulation for SCTP */
memset(&encaps, 0, sizeof(encaps));
encaps.sue_address.ss_family = res->ai_family;
encaps.sue_address.ss_len = res->ai_addrlen;
encaps.sue_port = htons(udp_encaps_port);
if (setsockopt(*sd, IPPROTO_SCTP, SCTP_REMOTE_UDP_ENCAPS_PORT, (void *)&encaps, (socklen_t)sizeof(encaps))) {
mylog(LOG_ERR, "[%d][%s] - setsockopt() failed", __LINE__, __func__);
exit(EXIT_FAILURE);
}
mylog(LOG_PRG, "Settings - UDP encapsulation port : %d", udp_encaps_port);
#else
mylog(LOG_ERR, "[%d][%s] - UDP encapsulation unsupported", __LINE__, __func__);
exit(EXIT_FAILURE);
#endif
}
}
#ifdef SO_NOSIGPIPE
/* ... disable SIGPIPE generation ... */
val = 1;
setsockopt(*sd, SOL_SOCKET, SO_NOSIGPIPE, (void *)&val, sizeof(int));
#endif
val = 2 << 19;
if (setsockopt(*sd, SOL_SOCKET, SO_RCVBUF, &val, sizeof(val)) < 0) {
mylog(LOG_ERR, "[%d][%s] - setsockopt() failed", __LINE__, __func__);
exit(EXIT_FAILURE);
}
/* ... and connect to the server. */
if (connect(*sd, res->ai_addr, res->ai_addrlen)) {
close(*sd);
*sd = -1;
mylog(LOG_ERR, "[%d][%s] - connect() failed", __LINE__, __func__);
return -1;
}
statuslen = sizeof(val);
if (getsockopt(*sd, SOL_SOCKET, SO_RCVBUF, &val, &statuslen) < 0) {
mylog(LOG_ERR, "[%d][%s] - getsockopt() failed", __LINE__, __func__);
exit(EXIT_FAILURE);
}
mylog(LOG_INF, "[%d][%s] - SO_RCVBUG: %d", __LINE__, __func__, val);
if (protocol == IPPROTO_SCTP) {
/* Get the actual number of outgoing streams. */
statuslen = sizeof(status);
memset(&status, 0, sizeof(status));
if (getsockopt(*sd, IPPROTO_SCTP, SCTP_STATUS, &status, &statuslen) < 0) {
mylog(LOG_ERR, "[%d][%s] - setsockopt() failed", __LINE__, __func__);
exit(EXIT_FAILURE);
}
sctp_num_streams = MIN(status.sstat_instrms, status.sstat_outstrms);
/* Allocate stream status array */
if ((sctp_stream_status = malloc(sizeof(uint8_t) * sctp_num_streams)) == NULL) {
mylog(LOG_ERR, "[%d][%s] - malloc failed", __LINE__, __func__);
exit(EXIT_FAILURE);
}
/* Initialize the stream status array */
for (i = 0; i < sctp_num_streams; i++) {
sctp_stream_status[i] = STREAM_FREE;
}
mylog(LOG_INF, "[%d][%s] - SCTP available Streams: %d IN - %d OUT - using: %d", __LINE__, __func__, status.sstat_instrms, status.sstat_outstrms, sctp_num_streams);
}
mylog(LOG_INF, "[%d][%s] - connected", __LINE__, __func__);
return 0;
}
static int
readln(int sd, char *resbuf, int *resbuflen, int *resbufpos)
{
ssize_t len = 0;
struct msghdr msg;
struct iovec iov;
struct cmsghdr *scmsg;
#if defined(__FreeBSD__) || defined(__APPLE__)
char cmsgbuf[CMSG_SPACE(sizeof(struct sctp_rcvinfo))];
struct sctp_rcvinfo *rcvinfo;
memset(cmsgbuf, 0, CMSG_SPACE(sizeof(struct sctp_rcvinfo)));
#elif defined(__linux__)
char cmsgbuf[CMSG_SPACE(sizeof(struct sctp_sndrcvinfo))];
struct sctp_sndrcvinfo *rcvinfo;
memset(cmsgbuf, 0, CMSG_SPACE(sizeof(struct sctp_sndrcvinfo)));
#endif
while (strnstr(resbuf + *resbufpos, "\r\n", *resbuflen - *resbufpos) == NULL) {
/* Move buffered data to the start of the buffer */
if (*resbufpos != 0) {
memmove(resbuf, resbuf + *resbufpos, *resbuflen - *resbufpos);
*resbuflen -= *resbufpos;
*resbufpos = 0;
}
/* If the buffer is full, complain */
if (*resbuflen == RESPONSE_BUFFER_SIZE) {
mylog(LOG_INF, "[%d][%s] - buffer is full", __LINE__, __func__);
exit(EXIT_FAILURE);
return -1;
}
/* message orientated protocol - new message : new response */
if (protocol == IPPROTO_SCTP) {
*resbuflen = 0;
*resbufpos = 0;
}
/* Read more data into the buffer */
iov.iov_base = resbuf + *resbuflen;
iov.iov_len = RESPONSE_BUFFER_SIZE - *resbuflen;
msg.msg_name = NULL;
msg.msg_namelen = 0;
msg.msg_iov = &iov;
msg.msg_iovlen = 1;
msg.msg_control = cmsgbuf;
msg.msg_controllen = sizeof(cmsgbuf);
len = recvmsg(sd, &msg, 0);
if ((MSG_NOTIFICATION & msg.msg_flags)) {
mylog(LOG_ERR, "[%d][%s] - recvmsg - got notification - fixme", __LINE__, __func__);
exit(EXIT_FAILURE);
}
/* If recvmsg returned 0 or -1 (no interrupt) - we stop reading */
if ((len == 0) || ((len == -1) && (errno != EINTR))) {
mylog(LOG_ERR, "[%d][%s] - recvmsg returned %d - %s", __LINE__, __func__, len, strerror(errno));
return -1;
} else if (len > 0) {
*resbuflen += len;
}
if (protocol == IPPROTO_SCTP) {
/* Stream we received data from */
scmsg = CMSG_FIRSTHDR(&msg);
if (scmsg == NULL) {
mylog(LOG_ERR, "[%d][%s] - CMSG_FIRSTHDR() failed - len %d", __LINE__, __func__, len);
exit(EXIT_FAILURE);
}
#if defined(__FreeBSD__) || defined(__APPLE__)
rcvinfo = (struct sctp_rcvinfo *)CMSG_DATA(scmsg);
sctp_last_stream = rcvinfo->rcv_sid;
#elif defined(__linux__)
rcvinfo = (struct sctp_sndrcvinfo *)CMSG_DATA(scmsg);
sctp_last_stream = rcvinfo->sinfo_stream;
#endif
}
}
return 0;
}
/* Copy bytes from one sd fd to sd fd */
static int
copybytes(int sd, int fd, off_t copylen, char *resbuf, int *resbuflen, int *resbufpos)
{
ssize_t len;
struct msghdr msg;
struct iovec iov;
#if defined(__FreeBSD__) || defined(__APPLE__)
char cmsgbuf[CMSG_SPACE(sizeof(struct sctp_rcvinfo))];
memset(cmsgbuf, 0, CMSG_SPACE(sizeof(struct sctp_rcvinfo)));
#elif defined(__linux__)
char cmsgbuf[CMSG_SPACE(sizeof(struct sctp_sndrcvinfo))];
memset(cmsgbuf, 0, CMSG_SPACE(sizeof(struct sctp_sndrcvinfo)));
#endif
while (copylen) {
/* Write data from resbuf to fd */
len = *resbuflen - *resbufpos;
if (copylen < len) {
len = copylen;
}
/* Write to file until resbuf is "empty" before calling recvmsg */
if (len > 0) {
/* fd is unset so we just discard data */
if (fd == -1) {
mylog(LOG_DBG, "[%d][%s] - fd == -1 - discarding", __LINE__, __func__);
/* we have valid fd - so write to file */
} else if ((len = write(fd, resbuf + *resbufpos, len)) == -1) {
mylog(LOG_ERR, "[%d][%s] - write() failed - fix it!", __LINE__, __func__);
exit(EXIT_FAILURE);
}
*resbufpos += len;
copylen -= len;
stat_bytes_payload += len;
continue;
}
iov.iov_base = resbuf;
iov.iov_len = RESPONSE_BUFFER_SIZE;
msg.msg_name = NULL;
msg.msg_namelen = 0;
msg.msg_iov = &iov;
msg.msg_iovlen = 1;
msg.msg_control = cmsgbuf;
msg.msg_controllen = sizeof(cmsgbuf);
/* Read more data into buffer */
if ((len = recvmsg(sd, &msg, 0)) == -1) {
if (errno == EINTR) {
continue;
}
mylog(LOG_ERR, "[%d][%s] - recvmsg() failed : %s", __LINE__, __func__, strerror(errno));
return -1;
} else if (len == 0) {
mylog(LOG_ERR, "[%d][%s] - recvmsg() returned 0", __LINE__, __func__);
return -2;
} else {
mylog(LOG_DBG, "[%d][%s] - read %d bytes ", __LINE__, __func__, len);
*resbuflen = len;
*resbufpos = 0;
}
}
return 0;
}
static int
send_request(int sd, char *reqbuf, int *reqbuflen, int *reqbufpos) {
#if defined(__FreeBSD__) || defined(__APPLE__)
char* cmsgbuf[CMSG_SPACE(sizeof(struct sctp_sndinfo))];
struct sctp_sndinfo *sndinfo;
#elif defined(__linux__)
char cmsgbuf[CMSG_SPACE(sizeof(struct sctp_sndrcvinfo))];
struct sctp_sndrcvinfo *sndinfo;
#endif
struct iovec iov;
struct msghdr msghdr;
struct cmsghdr *cmsg;
int len;
int i;
/* initialize */
memset(cmsgbuf, 0, sizeof(cmsgbuf));
memset(&msghdr, 0, sizeof(struct msghdr));
memset(&iov, 0, sizeof(struct iovec));
msghdr.msg_iov = &iov;
msghdr.msg_iovlen = 1;
mylog(LOG_DBG, "[%d][%s] - %s", __LINE__, __func__, reqbuf + *reqbufpos);
/* if using SCTP, append control msg to define outgoing stream */
if (protocol == IPPROTO_SCTP) {
msghdr.msg_control = cmsgbuf;
msghdr.msg_controllen = sizeof(cmsgbuf);
cmsg = CMSG_FIRSTHDR(&msghdr);
cmsg->cmsg_level = IPPROTO_SCTP;
cmsg->cmsg_len = sizeof(cmsgbuf);
#if defined(__FreeBSD__) || defined(__APPLE__)
cmsg->cmsg_type = SCTP_SNDINFO;
sndinfo = (struct sctp_sndinfo*) CMSG_DATA(cmsg);
#elif defined(__linux__)
cmsg->cmsg_type = SCTP_SNDRCV;
sndinfo = (struct sctp_sndrcvinfo*) CMSG_DATA(cmsg);
#endif
sctp_streams_busy = 1;
/* lookup next free stream - if all streams busy return with -2 */
for (i = 0; i < sctp_num_streams; i++) {
if (sctp_stream_status[i] == STREAM_FREE) {
sctp_stream_status[i] = STREAM_USED;
#if defined(__FreeBSD__) || defined(__APPLE__)
sndinfo->snd_sid = i;
#elif defined(__linux__)
sndinfo->sinfo_stream = i;
#endif
sctp_streams_busy = 0;
break;
}
}
if (sctp_streams_busy == 1) {
mylog(LOG_INF, "[%d][%s] - all SCTP streams are busy...", __LINE__, __func__);
return 0;
}
}
/* send until we reached the end of the buffer... */
while (*reqbufpos < *reqbuflen) {
iov.iov_base = reqbuf + *reqbufpos;
iov.iov_len = *reqbuflen - *reqbufpos;
len = sendmsg(sd, &msghdr, 0);
/* sendmsg failed - but don't worry - non-blocking :) */
if (len == -1) {
if (errno == EWOULDBLOCK || errno == EAGAIN) {
mylog(LOG_DBG, "[%d][%s] - sendmsg() failed - EWOULDBLOCK", __LINE__, __func__);
break;
} else {
return -1;
}
}
/* move reqbufpos by sent bytes */
*reqbufpos += len;
}
return 0;
}
static int
handle_response(int *sd, int *fd, char *resbuf, int *resbuflen, int *resbufpos, struct request *request, int *keepalive, int *pipelined)
{
int error = 0;
char * hln; /* Pointer within header line */
char * eolp; /* Pointer to "\r\n" within resbuf */
int statuscode = 0; /* HTTP Status code */
off_t contentlength = -1; /* Value from Content-Length header */
int chunked = 0; /* != if transfer-encoding is chunked */
off_t clen; /* Chunk length */
char * fname = NULL; /* Name of downloaded file */
uint32_t bytes_header_tmp = stat_bytes_header;
uint32_t bytes_payload_tmp = stat_bytes_payload;
int len = 0;
int len_left = 0;
char * bufptr = NULL;
*keepalive = 0;
if (protocol == IPPROTO_SCTP) {
*resbufpos = 0;
*resbuflen = 0;
/* Get a header line - only once for SCTP */
if (readln(*sd, resbuf, resbuflen, resbufpos)) {
mylog(LOG_ERR, "[%d][%s] - readln() failed", __LINE__, __func__);
return -1;
}
}
do {
if (protocol == IPPROTO_TCP) {
/* Get a header line - stream based TCP*/
if (readln(*sd, resbuf, resbuflen, resbufpos)) {
mylog(LOG_ERR, "[%d][%s] - readln() failed", __LINE__, __func__);
return -1;
}
}
hln = resbuf + *resbufpos;
eolp = strnstr(hln, "\r\n", *resbuflen - *resbufpos);
*resbufpos = (eolp - resbuf) + 2;
*eolp = '\0';
stat_bytes_header += strlen(hln) + 2;
mylog(LOG_DBG, "[%d][%s] - %s", __LINE__, __func__, hln);
/* Make sure it doesn't contain a NUL character */
if (strchr(hln, '\0') != eolp) {
return -1;
}
if (statuscode == 0) {
/* The first line MUST be HTTP/1.x xxx ... */
if ((strncmp(hln, "HTTP/1.", 7) != 0) || !isdigit(hln[7])) {
return -1;
}
/*
* If the minor version number isn't zero,
* then we can assume that pipelining our
* requests is OK -- as long as we don't
* see a "Connection: close" line later
* and we either have a Content-Length or
* Transfer-Encoding: chunked header to
* tell us the length.
*/
if (hln[7] != '0' && use_pipelining) {
*pipelined = 1;
}
/* Skip over the minor version number */
hln = strchr(hln + 7, ' ');
if (hln == NULL) {
return -1;
} else {
hln++;
}
/* Read the status code */
while (isdigit(*hln)) {
statuscode = statuscode * 10 + *hln - '0';
hln++;
}
if (statuscode < 100 || statuscode > 599) {
return -1;
}
/* Ignore the rest of the line */
continue;
}
/* Check for "Connection: close" or "Connection: Keep-Alive" header */
if (strncasecmp(hln, "Connection:", 11) == 0) {
hln += 11;
if (strcasestr(hln, "close") != NULL) {
*pipelined = 0;
}
if (strcasestr(hln, "Keep-Alive") != NULL) {
*keepalive = 1;
}
mylog(LOG_DBG, "[%d][%s] - Keep-Alive : %d - Pipelined : %d", __LINE__, __func__, *keepalive, *pipelined);
/* Next header... */
continue;
}
/* Check for "Content-Length:" header */
if (strncasecmp(hln, "Content-Length:", 15) == 0) {
hln += 15;
contentlength = 0;
/* Find the start of the length */
while (!isdigit(*hln) && (*hln != '\0')) {
hln++;
}
/* Compute the length */
while (isdigit(*hln)) {
if (contentlength >= OFF_MAX / 10) {
/* Nasty people... */
return -1;
}
contentlength = contentlength * 10 + *hln - '0';
hln++;
}
/* Next header... */
continue;
}
/* Check for "Transfer-Encoding: chunked" header */
if (strncasecmp(hln, "Transfer-Encoding:", 18) == 0) {
hln += 18;
if (strcasestr(hln, "chunked") != NULL) {
chunked = 1;
}
/* Next header... */
continue;
}
/* We blithely ignore any other header lines */
/* No more header lines */
if (strlen(hln) == 0) {
/*
* If the status code was 1xx, then there will
* be a real header later. Servers may emit
* 1xx header blocks at will, but since we
* don't expect one, we should just ignore it.
*/
if (100 <= statuscode && statuscode <= 199) {
statuscode = 0;
continue;
}
/* End of header; message body follows */
break;
}
} while (1);
/* No message body for 204 or 304 */
if (statuscode == 204 || statuscode == 304) {
return 0;
}
/*
* There should be a message body coming, but we only want
* to send it to a file if the status code is 200
*/
if (statuscode == 200 && save_file == 1) {
/* Generate a file name for the download */
fname = strrchr(request->url, '/');
if (fname == NULL) {
fname = request->url;
} else {
fname++;
}
if (strlen(fname) == 0) {
mylog(LOG_ERR, "[%d][%s] - Cannot optain file name", __LINE__, __func__);
exit(EXIT_FAILURE);
}
/* Open file for writing */
if ((*fd = open(fname, O_CREAT | O_TRUNC | O_WRONLY, 0644)) == -1) {
mylog(LOG_ERR, "[%d][%s] - Failed to open file for writing", __LINE__, __func__);
exit(EXIT_FAILURE);
}
};
/* Read the message and send data to fd if appropriate */
if (chunked) {
/* Handle a chunked-encoded entity */
/* Read chunks */
do {
error = readln(*sd, resbuf, resbuflen, resbufpos);
if (error) {
return -1;
}
hln = resbuf + *resbufpos;
eolp = strstr(hln, "\r\n");
*resbufpos = (eolp - resbuf) + 2;
clen = 0;
while (isxdigit(*hln)) {
if (clen >= OFF_MAX / 16) {
/* Nasty people... */
return -1;
}
if (isdigit(*hln)) {
clen = clen * 16 + *hln - '0';
} else {
clen = clen * 16 + 10 + tolower(*hln) - 'a';
}
hln++;
}
if (copybytes(*sd, *fd, clen, resbuf, resbuflen, resbufpos)) {
mylog(LOG_ERR, "[%d][%s] - copybytes failed", __LINE__, __func__);
*keepalive = 0;
return -1;
}
} while (clen != 0);
/* Read trailer and final CRLF */
do {
error = readln(*sd, resbuf, resbuflen, resbufpos);
if (error) {