forked from mboye/webperf
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhurl_core.c
2253 lines (2035 loc) · 74.8 KB
/
hurl_core.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
#include <arpa/inet.h>
#include <assert.h>
#include <ctype.h>
#include <errno.h>
#include <fcntl.h>
#include <limits.h>
#include <math.h>
#include <netdb.h>
#include <poll.h>
#include <signal.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <strings.h>
#include <sys/socket.h>
#include <sys/time.h>
#include <sys/types.h>
#include <unistd.h>
#include "hurl_core.h"
#ifndef HURL_NO_SSL
#include <openssl/ssl.h>
#include <openssl/err.h>
#include <openssl/rand.h>
#include <openssl/x509v3.h>
#endif
void *hurl_connection_exec(void *connection_ptr);
HURLPath *hurl_server_dequeue(HURLServer *server);
int hurl_connection_response(HURLConnection *connection, HURLPath *path, char **buffer, size_t *buffer_len, size_t *data_len,
enum HTTPFeatureSupport *feature_persistence);
int hurl_connection_request(HURLConnection *connection, HURLPath *path);
void hurl_resolve(HURLDomain *domain); /* Default DNS resolution. */
int hurl_header_str(HURLHeader *headers, char *buffer, size_t buffer_len);
HURLHeader *hurl_headers_copy(HURLHeader *headers);
/* unsigned int hurl_domain_nrof_paths(HURLDomain *domain); */
ssize_t hurl_send(HURLConnection *connection, char *buffer, size_t buffer_len);
ssize_t hurl_recv(HURLConnection *connection, char *buffer, size_t buffer_len);
int hurl_connect(HURLConnection *connection);
void hurl_connection_close(HURLConnection *connection, enum HURLConnectionState state);
int hurl_verify_ssl_scope(char *expected_domain, char *actual_domain);
unsigned char split_domain_name(char *name, char *labels[]);
int hurl_parse_response_code(char *line, char **code_text);
HURLManager *hurl_manager_init() {
HURLManager *manager;
/* Ignore SIGPIPE */
signal(SIGPIPE, SIG_IGN);
if ((manager = calloc(1, sizeof(HURLManager))) != NULL) {
manager->feature_pipelining = SUPPORTED;
manager->feature_tls = SUPPORTED;
manager->max_connections = HURL_MAX_CONNECTIONS;
manager->max_domain_connections = HURL_MAX_DOMAIN_CONNECTIONS;
manager->max_pipeline = HURL_MAX_PIPELINE_REQUESTS;
manager->keep_alive = HURL_KEEP_ALIVE; /* Keep-alive is currently not supported. */
manager->max_retries = HURL_MAX_RETRIES;
manager->connect_timeout = HURL_TIMEOUT;
manager->send_timeout = HURL_TIMEOUT;
manager->recv_timeout = HURL_TIMEOUT;
manager->recv_buffer_len = 0;
manager->http_version = 1.1f;
manager->follow_redirect = 1;
manager->max_redirects = HURL_MAX_REDIRECTS;
pthread_mutex_init(&manager->lock, NULL);
pthread_cond_init(&manager->condition, NULL);
#ifndef HURL_NO_SSL
/* Initialize OpenSSL */
SSL_load_error_strings();
ERR_load_crypto_strings();
SSL_library_init();
manager->ca_path = NULL;
manager->ca_file = NULL;
#endif
return manager;
} else {
return NULL;
}
}
void hurl_debug(const char *func, const char *msg, ...) {
#ifndef NDEBUG
char template[1024];
va_list args;
snprintf(template, sizeof template, "[%u] %s(): %s\n", (unsigned int) pthread_self(), func, msg);
va_start(args, msg);
vfprintf(stderr, template, args);
va_end(args);
fflush(stderr);
#endif
}
char *hurl_allocstrcpy(char *str, size_t str_len, unsigned int alloc_padding) {
char *newstr;
if (str != NULL) {
if ((newstr = calloc(str_len + alloc_padding, sizeof(char))) == NULL) {
exit(EXIT_FAILURE);
}
memcpy(newstr, str, str_len);
return newstr;
} else {
return NULL;
}
}
HURLDomain *hurl_get_domain(HURLManager *manager, char *domain) {
HURLDomain *d, *last;
d = manager->domains;
last = NULL;
/* Find domain. */
while (d != NULL) {
if (strcasecmp(d->domain, domain) == 0) {
/* Match found, so stop searching. */
return d;
}
last = d;
d = d->next;
}
/* The domain does not exist, so create it. */
if ((d = calloc(1, sizeof(HURLDomain))) == NULL) {
/* Out of memory. */
return NULL;
}
if ((d->domain = hurl_allocstrcpy(domain, strlen(domain), 1)) == NULL) {
/* Out of memory. */
return NULL;
}
d->manager = manager;
pthread_mutex_init(&d->dns_lock, NULL);
/* Add server to linked list. */
if (last != NULL) {
last->next = d;
} else {
/* This is the first item in the list. */
manager->domains = d;
}
/* Increment number of unique domains. */
manager->nrof_domains++;
/* At this points the domain exists. */
return d;
}
HURLServer *hurl_get_server(HURLDomain *domain, unsigned short port, int tls) {
HURLServer *s, *last = NULL;
/* Find server with matching port number. */
s = domain->servers;
while (s != NULL) {
if (s->port == port && s->tls == tls) {
/* Match found, so stop searching. */
return s;
}
last = s;
s = s->next;
}
/* The server does not exists, so create it. */
if ((s = calloc(1, sizeof(HURLServer))) == NULL) {
return NULL;
}
s->domain = domain;
s->port = port;
s->tls = tls;
s->pipeline_errors = 0;
/* Add server to linked list. */
if (last != NULL) {
last->next = s;
s->previous = last;
} else {
/* This is the first item in the list. */
domain->servers = s;
}
/* At this point the server has been created. */
return s;
}
HURLPath *hurl_add_url(HURLManager *manager, int allow_duplicate, char *url, void *tag) {
HURLParsedURL *parsed_url;
HURLDomain *domain;
HURLServer *server;
HURLPath *path, *p = NULL, *last = NULL;
int tls;
if (!hurl_parse_url(url, &parsed_url)) {
/* Failed to parse URL. */
return NULL;
}
/* Check if connection should use TLS. */
tls = strcmp(parsed_url->protocol, "https") == 0 ? 1 : 0;
/* Get lock. */
pthread_mutex_lock(&manager->lock);
hurl_debug(__func__, "Thread %u got lock.", (unsigned int) pthread_self());
/* Get domain */
if ((domain = hurl_get_domain(manager, parsed_url->hostname)) == NULL) {
/* Release lock. */
pthread_mutex_unlock(&manager->lock);
hurl_debug(__func__, "Thread %u released lock.", (unsigned int) pthread_self());
hurl_parsed_url_free(parsed_url);
return NULL;
}
/* Get server */
if ((server = hurl_get_server(domain, parsed_url->port, tls)) == NULL) {
/* Release lock. */
pthread_mutex_unlock(&manager->lock);
hurl_debug(__func__, "Thread %u released lock.", (unsigned int) pthread_self());
hurl_parsed_url_free(parsed_url);
return NULL;
}
/* Check for duplicates */
if (!allow_duplicate) {
p = server->paths;
while (p != NULL) {
if (strcasecmp(p->path, parsed_url->path) == 0) {
/* Duplicate path found */
hurl_debug(__func__, "Duplicate path detected. Ignoring it...");
hurl_parsed_url_free(parsed_url);
pthread_mutex_unlock(&manager->lock);
return NULL;
}
last = p;
p = p->next;
}
}
/* Create path structure */
if ((path = calloc(1, sizeof(HURLPath))) == NULL) {
/* Out of memory. */
/* Release lock. */
pthread_mutex_unlock(&manager->lock);
hurl_debug(__func__, "Thread %u released lock.", (unsigned int) pthread_self());
hurl_parsed_url_free(parsed_url);
return NULL;
}
/* Copy path */
if ((path->path = hurl_allocstrcpy(parsed_url->path, strlen(parsed_url->path), 1)) == NULL) {
/* Out of memory. */
/* Release lock. */
pthread_mutex_unlock(&manager->lock);
hurl_debug(__func__, "Thread %u released lock.", (unsigned int) pthread_self());
hurl_parsed_url_free(parsed_url);
return NULL;
}
/* Set reverse pointer to domain structure. */
path->server = server;
path->state = DOWNLOAD_STATE_PENDING;
/* Set tag pointer */
path->tag = tag;
/* Find last path in linked list. */
p = server->paths;
while (p != NULL) {
last = p;
p = p->next;
}
if (last != NULL) {
last->next = path;
path->previous = last;
} else {
/* This is the first item in the list. */
server->paths = path;
}
/* Increment number of paths for the server and domain. */
server->nrof_paths++;
domain->nrof_paths++;
/* Release lock. */
pthread_mutex_unlock(&manager->lock);
hurl_debug(__func__, "Thread %u released lock.", (unsigned int) pthread_self());
hurl_parsed_url_free(parsed_url);
return path;
}
int hurl_domain_nrof_paths(HURLDomain *domain, enum HURLDownloadState state) {
HURLServer *s;
HURLPath *p;
int count = 0;
s = domain->servers;
while (s != NULL) {
p = s->paths;
while (p != NULL) {
if (p->state == state) {
count++;
}
p = p->next;
}
s = s->next;
}
return count;
}
int hurl_nrof_paths(HURLManager *manager, enum HURLDownloadState state) {
HURLDomain *d;
int count = 0;
d = manager->domains;
while (d != NULL) {
count += hurl_domain_nrof_paths(d, state);
d = d->next;
}
return count;
}
int hurl_exec(HURLManager *manager) {
void *thread_result_ptr;
int nrof_domain_paths = 0, nrof_paths = 0;
HURLDomain *domain;
struct timeval eof_exec, exec_time;
gettimeofday(&manager->bgof_exec, NULL);
hurl_debug(__func__, "Began execution @ %f", timeval_to_msec(&manager->bgof_exec));
/* Loop until everything has been downloaded. */
for (;;) {
/* Get lock. */
pthread_mutex_lock(&manager->lock);
hurl_debug(__func__, "Thread %u got lock.", (unsigned int) pthread_self());
nrof_paths = hurl_nrof_paths(manager, DOWNLOAD_STATE_PENDING);
if (nrof_paths == 0) {
pthread_mutex_unlock(&manager->lock);
hurl_debug(__func__, "Thread %u released lock.", (unsigned int) pthread_self());
break;
}
hurl_debug(__func__, "Remaining paths: %u", nrof_paths);
/* Calculate connection limit per domain. */
domain = manager->domains;
while (domain != NULL) {
if ((nrof_domain_paths = hurl_domain_nrof_paths(domain, DOWNLOAD_STATE_PENDING)) > 0) {
domain->max_connections = (unsigned int) roundf((((float) nrof_domain_paths / (float) nrof_paths)) * (float) manager->max_connections);
if (domain->max_connections <= 0) {
/* Always allow one connection. */
domain->max_connections = 1;
}
/* Set connection limit to number of files if more connections were allowed. */
if (domain->max_connections > domain->nrof_paths) {
domain->max_connections = domain->nrof_paths;
}
/* Enforce per domain connection limit. */
if (domain->max_connections > manager->max_domain_connections) {
domain->max_connections = manager->max_domain_connections;
}
hurl_debug(__func__, "Max connections: %s => %u", domain->domain, domain->max_connections);
} else {
/* Prevent a connection thread from being started for this domain. */
domain->max_connections = 0;
}
domain = domain->next;
}
/* Initialize thread synchronization condition: Global number of connections. */
pthread_cond_init(&manager->condition, NULL);
/* Release lock. */
pthread_mutex_unlock(&manager->lock);
hurl_debug(__func__, "Thread %u released lock.", (unsigned int) pthread_self());
/* Start domain managers. */
domain = manager->domains;
while (domain != NULL) {
if (domain->max_connections > 0) {
if (pthread_create(&domain->thread, NULL, hurl_domain_exec, domain) != 0) {
/* Failed to start thread. */
hurl_debug(__func__, "Failed to create thread for '%s'", domain->domain);
} else {
domain->thread_running = 1;
}
}
domain = domain->next;
}
/* Wait for all domain execution threads to finish. */
domain = manager->domains;
while (domain != NULL) {
if (domain->thread_running) {
pthread_join(domain->thread, &thread_result_ptr);
domain->thread_running = 0;
hurl_debug(__func__, "Thread %s joined.", domain->domain);
}
domain = domain->next;
}
hurl_debug(__func__, "Completed: %d", hurl_nrof_paths(manager, DOWNLOAD_STATE_COMPLETED));
hurl_debug(__func__, "In progress: %d", hurl_nrof_paths(manager, DOWNLOAD_STATE_IN_PROGRESS));
}
gettimeofday(&eof_exec, NULL);
timersub(&eof_exec, &manager->bgof_exec, &exec_time);
manager->exec_time = timeval_to_msec(&exec_time);
return 1;
}
void *hurl_domain_exec(void *domain_ptr) {
HURLDomain *domain = (HURLDomain *) domain_ptr;
HURLConnection *connection = NULL, *last_connection = NULL, *next;
HURLServer *server;
void *thread_result_ptr;
int i;
hurl_debug(__func__, "[ %s ] Domain thread started.", domain->domain);
/* Start connection controllers for servers. */
server = domain->servers;
while (server != NULL) {
/* Calculate the number of connections to allow for this server.*/
server->max_connections = (unsigned int) roundf((((float) server->nrof_paths / (float) domain->nrof_paths)) * (float) domain->max_connections);
if (server->max_connections <= 0) {
server->max_connections = 1;
}
hurl_debug(__func__, "[ %s:%u ] max. connections = %u", server->domain->domain, server->port, server->max_connections);
for (i = 0; i < (int) server->max_connections; i++) {
/* Create connection for server. */
if ((connection = calloc(1, sizeof(HURLConnection))) == NULL) {
/* Out of memory. */
return 0;
}
connection->server = server;
/* Add connection to linked list */
if (last_connection != NULL) {
last_connection->next = connection;
connection->previous = last_connection;
} else {
server->connections = connection;
}
last_connection = connection;
/* Start connection thread. */
pthread_create(&connection->thread, NULL, hurl_connection_exec, connection);
connection = connection->next;
}
server = server->next;
}
/* Wait for all connection execution threads to finnish. */
server = domain->servers;
while (server != NULL) {
connection = server->connections;
while (connection != NULL) {
next = connection->next;
pthread_join(connection->thread, &thread_result_ptr);
hurl_debug(__func__, "[%s] Domain thread ended.", connection->server->domain->domain);
hurl_connection_free(connection);
connection = next;
}
server = server->next;
}
pthread_exit(NULL);
}
void *hurl_connection_exec(void *connection_ptr) {
HURLConnection *connection = (HURLConnection *) connection_ptr;
HURLServer *server = connection->server;
HURLDomain *domain = server->domain;
HURLManager *manager = domain->manager;
HURLPath *path = NULL;
int connect_retval;
char *buffer = NULL;
size_t buffer_len = 0, data_len = 0;
enum HTTPFeatureSupport feature_persistence = UNKNOWN_SUPPORT, feature_pipelining = UNKNOWN_SUPPORT;
unsigned int i;
HURLPath **queue;
unsigned int queue_len = 0;
unsigned int max_pipeline = domain->manager->max_pipeline;
int response_retval;
struct timeval eof_resolution, resolution_time;
hurl_debug(__func__, "[ %s:%u ] Connection thread started.", domain->domain, server->port);
/* Enforce global connection limit. */
pthread_mutex_lock(&manager->lock);
hurl_debug(__func__, "Thread %u got lock.", (unsigned int) pthread_self());
/* Wait for permission to establish connection. */
while (domain->manager->connections >= domain->manager->max_connections) {
pthread_cond_wait(&manager->condition, &manager->lock);
/* hurl_debug(__func__, "CONDITIONAL LOCK: Checking active connections counter."); */
}
/* Increment number of global connections. */
domain->manager->connections++;
hurl_debug(__func__, "[ %s:%u ] %d out of %d connections in use.", domain->domain, server->port, manager->connections, manager->max_connections);
/* Check if there are any files left to download. */
if ((path = hurl_server_dequeue(server)) == NULL) {
/* Nothing for this connection thread to do. */
hurl_debug(__func__, "[ %s:%u ] No files left to download.", domain->domain, server->port);
/* Decrement active connections counter ** We already have the lock ** . */
hurl_debug(__func__, "Thread %u got lock.", (unsigned int) pthread_self());
domain->manager->connections--;
pthread_mutex_unlock(&manager->lock);
hurl_debug(__func__, "Thread %u released lock.", (unsigned int) pthread_self());
hurl_connection_close(connection, CONNECTION_STATE_CLOSED);
pthread_exit(NULL);
}
pthread_mutex_unlock(&manager->lock);
hurl_debug(__func__, "Thread %u released lock.", (unsigned int) pthread_self());
/* Get DNS lock. */
pthread_mutex_lock(&domain->dns_lock);
hurl_debug(__func__, "Thread %u got DNS lock.", (unsigned int) pthread_self());
/* Resolve domain name. */
if (domain->dns_state == DNS_STATE_UNRESOLVED) {
hurl_debug(__func__, "Resolving domain name.");
assert(domain->dns_trigger == NULL);
domain->dns_trigger = path;
gettimeofday(&domain->bgof_resolution, NULL);
if (manager->hook_resolve != NULL) {
/* Override DNS resolution. */
manager->hook_resolve(domain, path);
} else {
/* Use default DNS resolution. */
hurl_resolve(domain);
}
/* Calculate resolution time */
gettimeofday(&eof_resolution, NULL);
timersub(&eof_resolution, &domain->bgof_resolution, &resolution_time);
domain->resolution_time = timeval_to_msec(&resolution_time);
hurl_debug(__func__, "[ %s:%u ] Domain name resolved in %f ms", domain->domain, server->port, domain->resolution_time);
} else {
hurl_debug(__func__, "[ %s:%u ] Domain name has already been resolved.", domain->domain, server->port);
}
/* Release DNS lock. */
pthread_mutex_unlock(&domain->dns_lock);
hurl_debug(__func__, "Thread %u released DNS lock.", (unsigned int) pthread_self());
/* Abort if DNS resolution failed. */
if (domain->dns_state == DNS_STATE_ERROR) {
hurl_debug(__func__, "[ %s:%u ] DNS resolution failed. Aborting...", domain->domain, server->port);
pthread_mutex_lock(&manager->lock);
/* Decrement active connections counter. */
domain->manager->connections--;
/* Mark file as failed. */
path->state = DOWNLOAD_STATE_ERROR;
/* Call transfer failed hook. */
if (manager->hook_transfer_complete) {
manager->hook_transfer_complete(path, connection, HURL_XFER_DNS, 0, 0);
}
pthread_mutex_unlock(&manager->lock);
pthread_exit(NULL);
}
/* As long as there are files to download. */
while (path != NULL) {
/* Call pre-connect hook */
if (manager->hook_pre_connect != NULL && !manager->hook_pre_connect(path, connection)) {
/* Do not connect to this server. */
path = hurl_server_dequeue(server);
continue;
}
/* Connect to server. */
if ((connect_retval = hurl_connect(connection)) != CONNECTION_ERROR) {
/* Call post connect hook */
if (manager->hook_post_connect != NULL) {
manager->hook_post_connect(path, connection, connect_retval);
}
/* Is pipelining supported? */
if (domain->manager->feature_pipelining == SUPPORTED && feature_persistence == SUPPORTED && feature_pipelining != UNSUPPORTED) {
/* Try to pipeline requests over persistent connection. */
queue = calloc(max_pipeline, sizeof(HURLPath *));
hurl_debug(__func__, "[ %s:%u ] Attempting to pipeline requests.", domain->domain, server->port);
/* Get lock. */
pthread_mutex_lock(&server->domain->manager->lock);
hurl_debug(__func__, "Thread %u got lock.", (unsigned int) pthread_self());
/* Create pipeline queue. */
queue_len = 0;
while (queue_len < max_pipeline && path != NULL) {
/* Call pre-request hook */
if (manager->hook_send_request == NULL || (manager->hook_send_request != NULL && manager->hook_send_request(path, connection, 1))) {
/* Add path to queue. */
queue[queue_len++] = path;
}
/* Get next file to download. */
if (queue_len + 1 < max_pipeline) {
path = hurl_server_dequeue(server);
}
}
/* Release lock. */
pthread_mutex_unlock(&server->domain->manager->lock);
hurl_debug(__func__, "Thread %u released lock.", (unsigned int) pthread_self());
/* Send pipelined requests. */
for (i = 0; i < queue_len; i++) {
path = queue[i];
/* Attempt to send request. */
if (!hurl_connection_request(connection, path)) {
/* Change state of path to retry download. */
path->state = DOWNLOAD_STATE_PENDING;
break;
}
}
/* Receive pipelined responses. */
for (i = 0; i < queue_len; i++) {
path = queue[i];
/* Receive pipelined response. */
if ((response_retval = hurl_connection_response(connection, path, &buffer, &buffer_len, &data_len, &feature_persistence)) > 0) {
/* The entire response was received. */
gettimeofday(&path->response_received, NULL);
hurl_debug(__func__, "[ %s:%u%.32s ] Response received. ", domain->domain, server->port, path->path);
} else if (response_retval == 0) {
/* The file was received and the server closed the connection. */
gettimeofday(&path->response_received, NULL);
if (i < queue_len) {
/* This was not the last request, so something went wrong. */
hurl_debug(__func__, "[ %s:%u%.32s ] Connection closed by server.", domain->domain, server->port, path->path);
}
break;
} else {
gettimeofday(&path->response_received, NULL);
/* Error */
hurl_debug(__func__, "[ %s:%u%.32s ] Error. ", domain->domain, server->port, path->path);
break;
}
}
/* Get lock. */
pthread_mutex_lock(&manager->lock);
hurl_debug(__func__, "Thread %u got lock.", (unsigned int) pthread_self());
/* Update download states. */
for (i = 0; i < queue_len; i++) {
path = queue[i];
if (path->state == DOWNLOAD_STATE_IN_PROGRESS) {
/* All pipelined requests were not answered. */
server->pipeline_errors++;
feature_pipelining = UNSUPPORTED;
path->state = DOWNLOAD_STATE_PENDING;
}
}
/* Get next file to download. */
path = hurl_server_dequeue(server);
/* Free queue */
free(queue);
/* Release lock. */
pthread_mutex_unlock(&manager->lock);
hurl_debug(__func__, "Thread %u released lock.", (unsigned int) pthread_self());
continue;
} else {
/* Send single requets over persistent or non-persistent connection. */
/* Send HTTP request. */
if (manager->hook_send_request == NULL || (manager->hook_send_request != NULL && manager->hook_send_request(path, connection, 0))) {
if (hurl_connection_request(connection, path)) {
/* Receive HTTP response. */
if (hurl_connection_response(connection, path, &buffer, &buffer_len, &data_len, &feature_persistence) >= 0) {
gettimeofday(&path->response_received, NULL);
if (domain->manager->feature_persistence == UNSUPPORTED || feature_persistence == UNSUPPORTED) {
/* Persistent connections not allowed: close connection */
hurl_connection_close(connection, CONNECTION_STATE_CLOSED);
hurl_debug(__func__, "[ %s:%u ] Connection closed by client.", domain->domain, server->port);
}
/* Get lock. */
pthread_mutex_lock(&manager->lock);
hurl_debug(__func__, "Thread %u got lock.", (unsigned int) pthread_self());
/* Get next file to download. */
path = hurl_server_dequeue(server);
/* Release lock. */
pthread_mutex_unlock(&manager->lock);
hurl_debug(__func__, "Thread %u released lock.", (unsigned int) pthread_self());
continue;
}
} else {
/* Failed to send request */
/* TODO: Handle failed request transmission. */
}
} else {
/* We were not allowed to send the request */
pthread_mutex_lock(&manager->lock);
path->state = DOWNLOAD_STATE_ERROR;
pthread_mutex_unlock(&manager->lock);
/* Call transfer failed hook. */
if (manager->hook_transfer_complete) {
manager->hook_transfer_complete(path, connection, HURL_XFER_HOOK, 0, 0);
}
}
}
} else {
/* Call post connect hook */
if (manager->hook_post_connect != NULL) {
manager->hook_post_connect(path, connection, connect_retval);
}
/* Fatal error: Could not connect to any servers. */
hurl_debug(__func__, "[ %s:%u ] Failed to connect.", domain->domain, connection->server->port);
/* Get lock, update download state, and release lock. */
pthread_mutex_lock(&manager->lock);
hurl_debug(__func__, "Thread %u got lock.", (unsigned int) pthread_self());
path->state = DOWNLOAD_STATE_ERROR;
/* Call transfer failed hook. */
if (manager->hook_transfer_complete) {
manager->hook_transfer_complete(path, connection, HURL_XFER_CONNECT, 0, 0);
}
pthread_mutex_unlock(&manager->lock);
hurl_debug(__func__, "Thread %u released lock.", (unsigned int) pthread_self());
}
/* Get next file to download. */
pthread_mutex_lock(&manager->lock);
path = hurl_server_dequeue(server);
pthread_mutex_unlock(&manager->lock);
}
/* Decrement active connections counter. */
pthread_mutex_lock(&manager->lock);
hurl_debug(__func__, "Thread %u got lock.", (unsigned int) pthread_self());
domain->manager->connections--;
/* Notify waiting threads of change in number of connections. */
pthread_cond_broadcast(&domain->manager->condition);
pthread_mutex_unlock(&manager->lock);
hurl_debug(__func__, "Thread %u released lock.", (unsigned int) pthread_self());
/* Free memory */
free(buffer);
/* End connection thread. */
pthread_exit(NULL);
}
int hurl_connect(HURLConnection *connection) {
struct sockaddr address;
unsigned int address_len;
int sock_flags;
struct pollfd poll_sock;
int sock_errno;
unsigned int sock_errno_len;
int timeout = connection->server->domain->manager->connect_timeout;
HURLServer *server = connection->server;
HURLDomain *domain = connection->server->domain;
int i;
int connect_retval;
HURLManager *manager = connection->server->domain->manager;
unsigned int sockopt_len = sizeof(manager->recv_buffer_len);
struct timeval end_connect, connect_time;
struct timeval ssl_begin_connect, ssl_end_connect, connect_time_ssl;
int poll_retval;
#ifndef HURL_NO_SSL
int ssl_error;
int ssl_connected = 0;
char ssl_error_str[256];
X509 *server_cert;
X509_NAME *subject_name;
STACK_OF(GENERAL_NAME) *san_names = NULL;
int san_names_nb;
char common_name[256];
int certificate_ok = 0;
#endif
/* Zero SSL timing. */
bzero(&ssl_begin_connect, sizeof(struct timeval));
bzero(&ssl_end_connect, sizeof(struct timeval));
#ifdef HURL_NO_SSL
if(connection->server->tls) {
hurl_debug(__func__, "Cannot connect: no SSL support.");
return CONNECTION_ERROR;
}
#endif
/* Check if a connection is already open. */
if (connection->state == CONNECTION_STATE_CONNECTED) {
hurl_debug(__func__, "[ %s:%u ] Reusing connection.", domain->domain, server->port);
connection->reused = 1;
return CONNECTION_REUSED;
}
if (connection->state == CONNECTION_STATE_ERROR) {
hurl_debug(__func__, "[ %s:%u ] Previous attempts to connect to this server have failed. Aborting...", domain->domain, server->port);
return CONNECTION_ERROR;
}
/* Change connection state. */
connection->state = CONNECTION_STATE_IN_PROGRESS;
connection->reused = 0;
for (i = 0; i < (int) domain->nrof_addresses; i++) {
/* Ignore IP addresses where connect() failed. */
if (domain->addresses[i] == NULL) {
continue;
}
/* Copy address to we can fix the port number before calling connect() */
memcpy(&address, domain->addresses[i], sizeof(struct sockaddr));
/* Create socket and connect to server. */
if (address.sa_family == AF_INET) {
address_len = sizeof(struct sockaddr_in);
/* IPv4 */
if ((connection->sock = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
hurl_debug(__func__, "[%s][%u] Failed to create socket: %s", domain->domain, server->port, strerror(errno));
continue;
}
/* Set port number. */
((struct sockaddr_in*) &address)->sin_port = htons(server->port);
} else {
assert(address.sa_family == AF_INET6);
address_len = sizeof(struct sockaddr_in6);
/* IPv6 */
if ((connection->sock = socket(AF_INET6, SOCK_STREAM, 0)) < 0) {
hurl_debug(__func__, "[%s][%u] Failed to create IPv6 socket: %s", domain->domain, server->port, strerror(errno));
continue;
}
/* Set port number. */
((struct sockaddr_in6 *) &address)->sin6_port = htons(server->port);
}
/* Get socket flags. */
if ((sock_flags = fcntl(connection->sock, F_GETFL, 0)) < 0) {
hurl_debug(__func__, "Failed to get socket flags - %s.", strerror(
errno));
continue;
}
/* Change socket to use non-blocking IO. */
if ((fcntl(connection->sock, F_SETFL, sock_flags | O_NONBLOCK)) < 0) {
hurl_debug(__func__, "Failed to switch socket to non-blocking mode - %s.", strerror(errno));
continue;
}
/* Connect to server. */
hurl_debug(__func__, "[ %s:%u ] Connecting to server...", domain->domain, server->port);
gettimeofday(&connection->begin_connect, NULL);
if (connect(connection->sock, &address, address_len) < 0) {
if (errno != EINPROGRESS) {
hurl_debug(__func__, "[ %s:%u ] Failed to connect: %s", domain->domain, server->port, strerror(errno));
continue;
}
}
/* Setup polling parameters. */
bzero(&poll_sock, sizeof(struct pollfd));
poll_sock.fd = connection->sock;
poll_sock.events = POLLOUT;
/* Wait for connection to become ready. */
switch ((poll_retval = poll(&poll_sock, 1, (int) timeout))) {
case -1:
/* Poll failed. */
hurl_debug(__func__, "[ %s:%u ] Failed to poll with retval %d - %s", domain->domain, server->port, poll_retval, strerror(errno));
continue;
default:
case 0:
/* Poll timed out. */
hurl_debug(__func__, "[ %s:%u ] The connection timed out.", domain->domain, server->port);
continue;
case 1:
/* The socket is ready to send data. */
if (poll_sock.revents & POLLOUT) {
/* Check if an error occurred. */
sock_errno_len = sizeof(sock_errno);
if (getsockopt(connection->sock, SOL_SOCKET, SO_ERROR, &sock_errno, &sock_errno_len) < 0) {
/* Failed to retrieve socket status. */
hurl_debug(__func__, "[ %s:%u ] Failed to get socket status - %s", domain->domain, server->port, strerror(errno));
continue;
} else {
if (sock_errno != 0) {
/* Failed to connect. */
hurl_debug(__func__, "[ %s:%u ] Failed to connect: %s", domain->domain, server->port, strerror(sock_errno));
continue;
}
}
}
break;
}
hurl_debug(__func__, "[ %s:%u ] Connected to server.", domain->domain, server->port);
#ifndef HURL_NO_SSL
/* Switch to secure connection? */
if (connection->server->tls) {
hurl_debug(__func__, "Switching to TLS.");
gettimeofday(&ssl_begin_connect, NULL);
/* Context is SSL v. 2 or 3. */
connection->ssl_context = SSL_CTX_new(SSLv23_client_method());
if (connection->ssl_context == NULL) {
hurl_connection_close(connection, CONNECTION_STATE_CLOSED);
return CONNECTION_ERROR;;
}
/* Enable verification of server certificate. */
if (!SSL_CTX_load_verify_locations(connection->ssl_context, connection->server->domain->manager->ca_file,
connection->server->domain->manager->ca_path)) {
hurl_debug(__func__, "Failed to load SSL certificates.");
hurl_connection_close(connection, CONNECTION_STATE_ERROR);
return CONNECTION_ERROR;
}
SSL_CTX_set_verify(connection->ssl_context,
SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, 0);
/* Create SSL handle for connection. */
connection->ssl_handle = SSL_new(connection->ssl_context);
if (connection->ssl_handle == NULL) {
hurl_debug(__func__, "SSL error.");
hurl_connection_close(connection, CONNECTION_STATE_CLOSED);
return CONNECTION_ERROR;
}
/* Associate SSL handle with open TCP connection. */
if (!SSL_set_fd(connection->ssl_handle, connection->sock)) {
hurl_connection_close(connection, CONNECTION_STATE_CLOSED);
return CONNECTION_ERROR;
}
poll_sock.events = POLLIN | POLLOUT;
while (!ssl_connected) {
switch (poll(&poll_sock, 1, (int) server->domain->manager->connect_timeout)) {
case -1:
/* Poll failed. */
hurl_debug(__func__, "Failed to poll - %s\n", strerror(errno));
hurl_connection_close(connection, CONNECTION_STATE_CLOSED);
return CONNECTION_ERROR;
default:
case 0:
/* Poll timed out. */
hurl_debug(__func__, "The connection timed out.\n");
hurl_connection_close(connection, CONNECTION_STATE_CLOSED);
return CONNECTION_ERROR;
case 1:
/* The socket is ready. */
/* Establish SSL connection on top of TCP connection. */
if ((connect_retval = SSL_connect(connection->ssl_handle)) != 1) {
ssl_error = SSL_get_error(connection->ssl_handle, connect_retval);
if (ssl_error == SSL_ERROR_WANT_READ) {
poll_sock.events = POLLIN;
/* hurl_debug(__func__, "SSL wants READ"); */
} else if (ssl_error == SSL_ERROR_WANT_WRITE) {
poll_sock.events = POLLOUT;
/* hurl_debug(__func__, "SSL wants WRITE"); */
} else {
ERR_error_string_n((unsigned long) ssl_error, ssl_error_str, sizeof(ssl_error_str));
hurl_debug(__func__, "SSL connect error: %s", ssl_error_str);
hurl_connection_close(connection, CONNECTION_STATE_CLOSED);
return CONNECTION_ERROR;
}
} else {
hurl_debug(__func__, "The SSL connection is ready.");
ssl_connected = 1;
}
}
}
/* Verify common name of certificate. */
/* TODO: Dont verify certificate for URLs with IP addresses. */
server_cert = SSL_get_peer_certificate(connection->ssl_handle);
subject_name = X509_get_subject_name(server_cert);
if (X509_NAME_get_text_by_NID(subject_name, NID_commonName, common_name, sizeof(common_name)) != -1) {
hurl_debug(__func__, "Checking certificate common name.");
/* Check if common name is *.domain.com */
if (hurl_verify_ssl_scope(connection->server->domain->domain, common_name)) {
certificate_ok = 1;
} else {
hurl_debug(__func__, "SSL: Expected %s but got %s", connection->server->domain->domain, common_name);
}
} else {
hurl_debug(__func__, "Could not get common name of certificate.");
}
if (!certificate_ok) {
/* Check "Subject Alternative Name" */
if ((san_names = X509_get_ext_d2i(server_cert,
NID_subject_alt_name, NULL, NULL)) != NULL) {
hurl_debug(__func__, "Checking certificate for Subject Alternative Names");