]> git.ipfire.org Git - thirdparty/git.git/blame - http.c
Git 1.8.3
[thirdparty/git.git] / http.c
CommitLineData
29508e1e 1#include "http.h"
2264dfa5 2#include "pack.h"
de1a2fdd 3#include "sideband.h"
fe72d420 4#include "run-command.h"
f39f72d8 5#include "url.h"
148bb6a7 6#include "credential.h"
745c7c8e 7#include "version.h"
047ec602 8#include "pkt-line.h"
29508e1e 9
4251ccbd 10int active_requests;
e9176745 11int http_is_verbose;
de1a2fdd 12size_t http_post_buffer = 16 * LARGE_PACKET_MAX;
29508e1e 13
b8ac9230
MS
14#if LIBCURL_VERSION_NUM >= 0x070a06
15#define LIBCURL_CAN_HANDLE_AUTH_ANY
16#endif
17
ad75ebe5
TRC
18static int min_curl_sessions = 1;
19static int curl_session_count;
29508e1e 20#ifdef USE_CURL_MULTI
cc3530e8
MH
21static int max_requests = -1;
22static CURLM *curlm;
29508e1e
NH
23#endif
24#ifndef NO_CURL_EASY_DUPHANDLE
cc3530e8 25static CURL *curl_default;
29508e1e 26#endif
5424bc55
TRC
27
28#define PREV_BUF_SIZE 4096
29#define RANGE_HEADER_SIZE 30
30
29508e1e
NH
31char curl_errorstr[CURL_ERROR_SIZE];
32
cc3530e8 33static int curl_ssl_verify = -1;
4bc444eb 34static int curl_ssl_try;
4251ccbd 35static const char *ssl_cert;
ef52aafa 36#if LIBCURL_VERSION_NUM >= 0x070903
4251ccbd 37static const char *ssl_key;
29508e1e
NH
38#endif
39#if LIBCURL_VERSION_NUM >= 0x070908
4251ccbd 40static const char *ssl_capath;
29508e1e 41#endif
4251ccbd 42static const char *ssl_cainfo;
cc3530e8
MH
43static long curl_low_speed_limit = -1;
44static long curl_low_speed_time = -1;
4251ccbd
JH
45static int curl_ftp_no_epsv;
46static const char *curl_http_proxy;
bcfb95dd 47static const char *curl_cookie_file;
148bb6a7 48static struct credential http_auth = CREDENTIAL_INIT;
a4ddbc33 49static int http_proactive_auth;
b1d1058c 50static const char *user_agent;
29508e1e 51
30dd9163
ML
52#if LIBCURL_VERSION_NUM >= 0x071700
53/* Use CURLOPT_KEYPASSWD as is */
54#elif LIBCURL_VERSION_NUM >= 0x070903
55#define CURLOPT_KEYPASSWD CURLOPT_SSLKEYPASSWD
56#else
57#define CURLOPT_KEYPASSWD CURLOPT_SSLCERTPASSWD
58#endif
59
148bb6a7 60static struct credential cert_auth = CREDENTIAL_INIT;
30dd9163
ML
61static int ssl_cert_password_required;
62
cc3530e8 63static struct curl_slist *pragma_header;
5424bc55 64static struct curl_slist *no_pragma_header;
e9176745 65
4251ccbd 66static struct active_request_slot *active_queue_head;
29508e1e 67
a04ff3ec 68size_t fread_buffer(char *ptr, size_t eltsize, size_t nmemb, void *buffer_)
29508e1e
NH
69{
70 size_t size = eltsize * nmemb;
f444e528
JH
71 struct buffer *buffer = buffer_;
72
028c2976
MH
73 if (size > buffer->buf.len - buffer->posn)
74 size = buffer->buf.len - buffer->posn;
75 memcpy(ptr, buffer->buf.buf + buffer->posn, size);
29508e1e 76 buffer->posn += size;
028c2976 77
29508e1e
NH
78 return size;
79}
80
3944ba0c
MS
81#ifndef NO_CURL_IOCTL
82curlioerr ioctl_buffer(CURL *handle, int cmd, void *clientp)
83{
84 struct buffer *buffer = clientp;
85
86 switch (cmd) {
87 case CURLIOCMD_NOP:
88 return CURLIOE_OK;
89
90 case CURLIOCMD_RESTARTREAD:
91 buffer->posn = 0;
92 return CURLIOE_OK;
93
94 default:
95 return CURLIOE_UNKNOWNCMD;
96 }
97}
98#endif
99
a04ff3ec 100size_t fwrite_buffer(char *ptr, size_t eltsize, size_t nmemb, void *buffer_)
29508e1e
NH
101{
102 size_t size = eltsize * nmemb;
f444e528
JH
103 struct strbuf *buffer = buffer_;
104
028c2976 105 strbuf_add(buffer, ptr, size);
29508e1e
NH
106 return size;
107}
108
a04ff3ec 109size_t fwrite_null(char *ptr, size_t eltsize, size_t nmemb, void *strbuf)
29508e1e 110{
29508e1e
NH
111 return eltsize * nmemb;
112}
113
29508e1e
NH
114#ifdef USE_CURL_MULTI
115static void process_curl_messages(void)
116{
117 int num_messages;
118 struct active_request_slot *slot;
119 CURLMsg *curl_message = curl_multi_info_read(curlm, &num_messages);
120
121 while (curl_message != NULL) {
122 if (curl_message->msg == CURLMSG_DONE) {
123 int curl_result = curl_message->data.result;
124 slot = active_queue_head;
125 while (slot != NULL &&
126 slot->curl != curl_message->easy_handle)
127 slot = slot->next;
128 if (slot != NULL) {
129 curl_multi_remove_handle(curlm, slot->curl);
130 slot->curl_result = curl_result;
131 finish_active_slot(slot);
132 } else {
133 fprintf(stderr, "Received DONE message for unknown request!\n");
134 }
135 } else {
136 fprintf(stderr, "Unknown CURL message received: %d\n",
137 (int)curl_message->msg);
138 }
139 curl_message = curl_multi_info_read(curlm, &num_messages);
140 }
141}
142#endif
143
ef90d6d4 144static int http_options(const char *var, const char *value, void *cb)
29508e1e
NH
145{
146 if (!strcmp("http.sslverify", var)) {
7059cd99 147 curl_ssl_verify = git_config_bool(var, value);
29508e1e
NH
148 return 0;
149 }
7059cd99
JH
150 if (!strcmp("http.sslcert", var))
151 return git_config_string(&ssl_cert, var, value);
ef52aafa 152#if LIBCURL_VERSION_NUM >= 0x070903
7059cd99
JH
153 if (!strcmp("http.sslkey", var))
154 return git_config_string(&ssl_key, var, value);
29508e1e
NH
155#endif
156#if LIBCURL_VERSION_NUM >= 0x070908
7059cd99
JH
157 if (!strcmp("http.sslcapath", var))
158 return git_config_string(&ssl_capath, var, value);
29508e1e 159#endif
7059cd99
JH
160 if (!strcmp("http.sslcainfo", var))
161 return git_config_string(&ssl_cainfo, var, value);
754ae192
ML
162 if (!strcmp("http.sslcertpasswordprotected", var)) {
163 if (git_config_bool(var, value))
164 ssl_cert_password_required = 1;
165 return 0;
166 }
4bc444eb
MV
167 if (!strcmp("http.ssltry", var)) {
168 curl_ssl_try = git_config_bool(var, value);
169 return 0;
170 }
ad75ebe5
TRC
171 if (!strcmp("http.minsessions", var)) {
172 min_curl_sessions = git_config_int(var, value);
173#ifndef USE_CURL_MULTI
174 if (min_curl_sessions > 1)
175 min_curl_sessions = 1;
176#endif
177 return 0;
178 }
a6080a0a 179#ifdef USE_CURL_MULTI
29508e1e 180 if (!strcmp("http.maxrequests", var)) {
7059cd99 181 max_requests = git_config_int(var, value);
29508e1e
NH
182 return 0;
183 }
184#endif
29508e1e 185 if (!strcmp("http.lowspeedlimit", var)) {
7059cd99 186 curl_low_speed_limit = (long)git_config_int(var, value);
29508e1e
NH
187 return 0;
188 }
189 if (!strcmp("http.lowspeedtime", var)) {
7059cd99 190 curl_low_speed_time = (long)git_config_int(var, value);
29508e1e
NH
191 return 0;
192 }
193
3ea099d4
SK
194 if (!strcmp("http.noepsv", var)) {
195 curl_ftp_no_epsv = git_config_bool(var, value);
196 return 0;
197 }
7059cd99
JH
198 if (!strcmp("http.proxy", var))
199 return git_config_string(&curl_http_proxy, var, value);
3ea099d4 200
bcfb95dd
DB
201 if (!strcmp("http.cookiefile", var))
202 return git_config_string(&curl_cookie_file, var, value);
203
de1a2fdd
SP
204 if (!strcmp("http.postbuffer", var)) {
205 http_post_buffer = git_config_int(var, value);
206 if (http_post_buffer < LARGE_PACKET_MAX)
207 http_post_buffer = LARGE_PACKET_MAX;
208 return 0;
209 }
210
b1d1058c
SO
211 if (!strcmp("http.useragent", var))
212 return git_config_string(&user_agent, var, value);
213
29508e1e 214 /* Fall back on the default ones */
ef90d6d4 215 return git_default_config(var, value, cb);
29508e1e
NH
216}
217
c33976cb
JH
218static void init_curl_http_auth(CURL *result)
219{
6f4c347c
JK
220 if (!http_auth.username)
221 return;
222
223 credential_fill(&http_auth);
224
225#if LIBCURL_VERSION_NUM >= 0x071301
226 curl_easy_setopt(result, CURLOPT_USERNAME, http_auth.username);
227 curl_easy_setopt(result, CURLOPT_PASSWORD, http_auth.password);
228#else
229 {
aa0834a0 230 static struct strbuf up = STRBUF_INIT;
aa0834a0 231 strbuf_reset(&up);
148bb6a7
JK
232 strbuf_addf(&up, "%s:%s",
233 http_auth.username, http_auth.password);
aa0834a0 234 curl_easy_setopt(result, CURLOPT_USERPWD, up.buf);
c33976cb 235 }
6f4c347c 236#endif
c33976cb
JH
237}
238
30dd9163
ML
239static int has_cert_password(void)
240{
30dd9163
ML
241 if (ssl_cert == NULL || ssl_cert_password_required != 1)
242 return 0;
148bb6a7
JK
243 if (!cert_auth.password) {
244 cert_auth.protocol = xstrdup("cert");
75e9a405 245 cert_auth.username = xstrdup("");
148bb6a7
JK
246 cert_auth.path = xstrdup(ssl_cert);
247 credential_fill(&cert_auth);
248 }
249 return 1;
30dd9163
ML
250}
251
4251ccbd 252static CURL *get_curl_handle(void)
11979b98 253{
4251ccbd 254 CURL *result = curl_easy_init();
11979b98 255
a5ccc597
JH
256 if (!curl_ssl_verify) {
257 curl_easy_setopt(result, CURLOPT_SSL_VERIFYPEER, 0);
258 curl_easy_setopt(result, CURLOPT_SSL_VERIFYHOST, 0);
259 } else {
260 /* Verify authenticity of the peer's certificate */
261 curl_easy_setopt(result, CURLOPT_SSL_VERIFYPEER, 1);
262 /* The name in the cert must match whom we tried to connect */
263 curl_easy_setopt(result, CURLOPT_SSL_VERIFYHOST, 2);
264 }
265
11979b98
JH
266#if LIBCURL_VERSION_NUM >= 0x070907
267 curl_easy_setopt(result, CURLOPT_NETRC, CURL_NETRC_OPTIONAL);
268#endif
b8ac9230 269#ifdef LIBCURL_CAN_HANDLE_AUTH_ANY
525ecd26 270 curl_easy_setopt(result, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
b8ac9230 271#endif
11979b98 272
a4ddbc33
JK
273 if (http_proactive_auth)
274 init_curl_http_auth(result);
275
11979b98
JH
276 if (ssl_cert != NULL)
277 curl_easy_setopt(result, CURLOPT_SSLCERT, ssl_cert);
30dd9163 278 if (has_cert_password())
148bb6a7 279 curl_easy_setopt(result, CURLOPT_KEYPASSWD, cert_auth.password);
ef52aafa 280#if LIBCURL_VERSION_NUM >= 0x070903
11979b98
JH
281 if (ssl_key != NULL)
282 curl_easy_setopt(result, CURLOPT_SSLKEY, ssl_key);
283#endif
284#if LIBCURL_VERSION_NUM >= 0x070908
285 if (ssl_capath != NULL)
286 curl_easy_setopt(result, CURLOPT_CAPATH, ssl_capath);
287#endif
288 if (ssl_cainfo != NULL)
289 curl_easy_setopt(result, CURLOPT_CAINFO, ssl_cainfo);
11979b98
JH
290
291 if (curl_low_speed_limit > 0 && curl_low_speed_time > 0) {
292 curl_easy_setopt(result, CURLOPT_LOW_SPEED_LIMIT,
293 curl_low_speed_limit);
294 curl_easy_setopt(result, CURLOPT_LOW_SPEED_TIME,
295 curl_low_speed_time);
296 }
297
298 curl_easy_setopt(result, CURLOPT_FOLLOWLOCATION, 1);
311e2ea0
TRC
299#if LIBCURL_VERSION_NUM >= 0x071301
300 curl_easy_setopt(result, CURLOPT_POSTREDIR, CURL_REDIR_POST_ALL);
301#elif LIBCURL_VERSION_NUM >= 0x071101
302 curl_easy_setopt(result, CURLOPT_POST301, 1);
303#endif
11979b98 304
7982d74e
MW
305 if (getenv("GIT_CURL_VERBOSE"))
306 curl_easy_setopt(result, CURLOPT_VERBOSE, 1);
307
b1d1058c 308 curl_easy_setopt(result, CURLOPT_USERAGENT,
745c7c8e 309 user_agent ? user_agent : git_user_agent());
20fc9bc5 310
3ea099d4
SK
311 if (curl_ftp_no_epsv)
312 curl_easy_setopt(result, CURLOPT_FTP_USE_EPSV, 0);
313
4bc444eb
MV
314#ifdef CURLOPT_USE_SSL
315 if (curl_ssl_try)
316 curl_easy_setopt(result, CURLOPT_USE_SSL, CURLUSESSL_TRY);
317#endif
318
dd613997 319 if (curl_http_proxy) {
9c5665aa 320 curl_easy_setopt(result, CURLOPT_PROXY, curl_http_proxy);
dd613997
NBL
321 curl_easy_setopt(result, CURLOPT_PROXYAUTH, CURLAUTH_ANY);
322 }
9c5665aa 323
11979b98
JH
324 return result;
325}
326
7059cd99
JH
327static void set_from_env(const char **var, const char *envname)
328{
329 const char *val = getenv(envname);
330 if (val)
331 *var = val;
332}
333
a4ddbc33 334void http_init(struct remote *remote, const char *url, int proactive_auth)
29508e1e
NH
335{
336 char *low_speed_limit;
337 char *low_speed_time;
338
e9176745
TRC
339 http_is_verbose = 0;
340
7059cd99
JH
341 git_config(http_options, NULL);
342
29508e1e
NH
343 curl_global_init(CURL_GLOBAL_ALL);
344
a4ddbc33
JK
345 http_proactive_auth = proactive_auth;
346
9fc6440d
MH
347 if (remote && remote->http_proxy)
348 curl_http_proxy = xstrdup(remote->http_proxy);
349
29508e1e 350 pragma_header = curl_slist_append(pragma_header, "Pragma: no-cache");
e9176745 351 no_pragma_header = curl_slist_append(no_pragma_header, "Pragma:");
29508e1e
NH
352
353#ifdef USE_CURL_MULTI
354 {
355 char *http_max_requests = getenv("GIT_HTTP_MAX_REQUESTS");
356 if (http_max_requests != NULL)
357 max_requests = atoi(http_max_requests);
358 }
359
360 curlm = curl_multi_init();
361 if (curlm == NULL) {
362 fprintf(stderr, "Error creating curl multi handle.\n");
363 exit(1);
364 }
365#endif
366
367 if (getenv("GIT_SSL_NO_VERIFY"))
368 curl_ssl_verify = 0;
369
7059cd99 370 set_from_env(&ssl_cert, "GIT_SSL_CERT");
ef52aafa 371#if LIBCURL_VERSION_NUM >= 0x070903
7059cd99 372 set_from_env(&ssl_key, "GIT_SSL_KEY");
29508e1e
NH
373#endif
374#if LIBCURL_VERSION_NUM >= 0x070908
7059cd99 375 set_from_env(&ssl_capath, "GIT_SSL_CAPATH");
29508e1e 376#endif
7059cd99 377 set_from_env(&ssl_cainfo, "GIT_SSL_CAINFO");
29508e1e 378
b1d1058c
SO
379 set_from_env(&user_agent, "GIT_HTTP_USER_AGENT");
380
29508e1e
NH
381 low_speed_limit = getenv("GIT_HTTP_LOW_SPEED_LIMIT");
382 if (low_speed_limit != NULL)
383 curl_low_speed_limit = strtol(low_speed_limit, NULL, 10);
384 low_speed_time = getenv("GIT_HTTP_LOW_SPEED_TIME");
385 if (low_speed_time != NULL)
386 curl_low_speed_time = strtol(low_speed_time, NULL, 10);
387
29508e1e
NH
388 if (curl_ssl_verify == -1)
389 curl_ssl_verify = 1;
390
ad75ebe5 391 curl_session_count = 0;
29508e1e
NH
392#ifdef USE_CURL_MULTI
393 if (max_requests < 1)
394 max_requests = DEFAULT_MAX_REQUESTS;
395#endif
396
3ea099d4
SK
397 if (getenv("GIT_CURL_FTP_NO_EPSV"))
398 curl_ftp_no_epsv = 1;
399
deba4937 400 if (url) {
148bb6a7 401 credential_from_url(&http_auth, url);
754ae192
ML
402 if (!ssl_cert_password_required &&
403 getenv("GIT_SSL_CERT_PASSWORD_PROTECTED") &&
deba4937 404 !prefixcmp(url, "https://"))
30dd9163
ML
405 ssl_cert_password_required = 1;
406 }
c33976cb 407
29508e1e
NH
408#ifndef NO_CURL_EASY_DUPHANDLE
409 curl_default = get_curl_handle();
410#endif
411}
412
413void http_cleanup(void)
414{
415 struct active_request_slot *slot = active_queue_head;
29508e1e
NH
416
417 while (slot != NULL) {
3278cd0a 418 struct active_request_slot *next = slot->next;
f23d1f76 419 if (slot->curl != NULL) {
29508e1e 420#ifdef USE_CURL_MULTI
f23d1f76 421 curl_multi_remove_handle(curlm, slot->curl);
29508e1e 422#endif
29508e1e 423 curl_easy_cleanup(slot->curl);
f23d1f76 424 }
3278cd0a
SP
425 free(slot);
426 slot = next;
29508e1e 427 }
3278cd0a 428 active_queue_head = NULL;
29508e1e
NH
429
430#ifndef NO_CURL_EASY_DUPHANDLE
431 curl_easy_cleanup(curl_default);
432#endif
433
434#ifdef USE_CURL_MULTI
435 curl_multi_cleanup(curlm);
436#endif
437 curl_global_cleanup();
b3ca4e4e
NH
438
439 curl_slist_free_all(pragma_header);
3278cd0a 440 pragma_header = NULL;
9fc6440d 441
e9176745
TRC
442 curl_slist_free_all(no_pragma_header);
443 no_pragma_header = NULL;
444
9fc6440d 445 if (curl_http_proxy) {
e4a80ecf 446 free((void *)curl_http_proxy);
9fc6440d
MH
447 curl_http_proxy = NULL;
448 }
30dd9163 449
148bb6a7
JK
450 if (cert_auth.password != NULL) {
451 memset(cert_auth.password, 0, strlen(cert_auth.password));
452 free(cert_auth.password);
453 cert_auth.password = NULL;
30dd9163
ML
454 }
455 ssl_cert_password_required = 0;
29508e1e
NH
456}
457
29508e1e
NH
458struct active_request_slot *get_active_slot(void)
459{
460 struct active_request_slot *slot = active_queue_head;
461 struct active_request_slot *newslot;
462
463#ifdef USE_CURL_MULTI
464 int num_transfers;
465
466 /* Wait for a slot to open up if the queue is full */
467 while (active_requests >= max_requests) {
468 curl_multi_perform(curlm, &num_transfers);
4251ccbd 469 if (num_transfers < active_requests)
29508e1e 470 process_curl_messages();
29508e1e
NH
471 }
472#endif
473
4251ccbd 474 while (slot != NULL && slot->in_use)
29508e1e 475 slot = slot->next;
4251ccbd 476
29508e1e
NH
477 if (slot == NULL) {
478 newslot = xmalloc(sizeof(*newslot));
479 newslot->curl = NULL;
480 newslot->in_use = 0;
481 newslot->next = NULL;
482
483 slot = active_queue_head;
484 if (slot == NULL) {
485 active_queue_head = newslot;
486 } else {
4251ccbd 487 while (slot->next != NULL)
29508e1e 488 slot = slot->next;
29508e1e
NH
489 slot->next = newslot;
490 }
491 slot = newslot;
492 }
493
494 if (slot->curl == NULL) {
495#ifdef NO_CURL_EASY_DUPHANDLE
496 slot->curl = get_curl_handle();
497#else
498 slot->curl = curl_easy_duphandle(curl_default);
499#endif
ad75ebe5 500 curl_session_count++;
29508e1e
NH
501 }
502
503 active_requests++;
504 slot->in_use = 1;
c8568e13 505 slot->results = NULL;
baa7b67d 506 slot->finished = NULL;
29508e1e
NH
507 slot->callback_data = NULL;
508 slot->callback_func = NULL;
bcfb95dd 509 curl_easy_setopt(slot->curl, CURLOPT_COOKIEFILE, curl_cookie_file);
29508e1e 510 curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, pragma_header);
29508e1e 511 curl_easy_setopt(slot->curl, CURLOPT_ERRORBUFFER, curl_errorstr);
9094950d
NH
512 curl_easy_setopt(slot->curl, CURLOPT_CUSTOMREQUEST, NULL);
513 curl_easy_setopt(slot->curl, CURLOPT_READFUNCTION, NULL);
514 curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION, NULL);
1e41827d 515 curl_easy_setopt(slot->curl, CURLOPT_POSTFIELDS, NULL);
9094950d
NH
516 curl_easy_setopt(slot->curl, CURLOPT_UPLOAD, 0);
517 curl_easy_setopt(slot->curl, CURLOPT_HTTPGET, 1);
b793acf1 518 curl_easy_setopt(slot->curl, CURLOPT_FAILONERROR, 1);
dfa1725a
JK
519 if (http_auth.password)
520 init_curl_http_auth(slot->curl);
29508e1e
NH
521
522 return slot;
523}
524
525int start_active_slot(struct active_request_slot *slot)
526{
527#ifdef USE_CURL_MULTI
528 CURLMcode curlm_result = curl_multi_add_handle(curlm, slot->curl);
45c17412 529 int num_transfers;
29508e1e
NH
530
531 if (curlm_result != CURLM_OK &&
532 curlm_result != CURLM_CALL_MULTI_PERFORM) {
533 active_requests--;
534 slot->in_use = 0;
535 return 0;
536 }
45c17412
DB
537
538 /*
539 * We know there must be something to do, since we just added
540 * something.
541 */
542 curl_multi_perform(curlm, &num_transfers);
29508e1e
NH
543#endif
544 return 1;
545}
546
547#ifdef USE_CURL_MULTI
fc57b6aa
DB
548struct fill_chain {
549 void *data;
550 int (*fill)(void *);
551 struct fill_chain *next;
552};
553
4251ccbd 554static struct fill_chain *fill_cfg;
fc57b6aa
DB
555
556void add_fill_function(void *data, int (*fill)(void *))
557{
e8eec71d 558 struct fill_chain *new = xmalloc(sizeof(*new));
fc57b6aa
DB
559 struct fill_chain **linkp = &fill_cfg;
560 new->data = data;
561 new->fill = fill;
562 new->next = NULL;
563 while (*linkp)
564 linkp = &(*linkp)->next;
565 *linkp = new;
566}
567
45c17412
DB
568void fill_active_slots(void)
569{
570 struct active_request_slot *slot = active_queue_head;
571
fc57b6aa
DB
572 while (active_requests < max_requests) {
573 struct fill_chain *fill;
574 for (fill = fill_cfg; fill; fill = fill->next)
575 if (fill->fill(fill->data))
576 break;
577
578 if (!fill)
45c17412 579 break;
fc57b6aa 580 }
45c17412
DB
581
582 while (slot != NULL) {
ad75ebe5
TRC
583 if (!slot->in_use && slot->curl != NULL
584 && curl_session_count > min_curl_sessions) {
45c17412
DB
585 curl_easy_cleanup(slot->curl);
586 slot->curl = NULL;
ad75ebe5 587 curl_session_count--;
45c17412
DB
588 }
589 slot = slot->next;
590 }
591}
592
29508e1e
NH
593void step_active_slots(void)
594{
595 int num_transfers;
596 CURLMcode curlm_result;
597
598 do {
599 curlm_result = curl_multi_perform(curlm, &num_transfers);
600 } while (curlm_result == CURLM_CALL_MULTI_PERFORM);
601 if (num_transfers < active_requests) {
602 process_curl_messages();
603 fill_active_slots();
604 }
605}
606#endif
607
608void run_active_slot(struct active_request_slot *slot)
609{
610#ifdef USE_CURL_MULTI
29508e1e
NH
611 fd_set readfds;
612 fd_set writefds;
613 fd_set excfds;
614 int max_fd;
615 struct timeval select_timeout;
baa7b67d 616 int finished = 0;
29508e1e 617
baa7b67d
NH
618 slot->finished = &finished;
619 while (!finished) {
29508e1e
NH
620 step_active_slots();
621
df26c471 622 if (slot->in_use) {
eb56c821
MF
623#if LIBCURL_VERSION_NUM >= 0x070f04
624 long curl_timeout;
625 curl_multi_timeout(curlm, &curl_timeout);
626 if (curl_timeout == 0) {
627 continue;
628 } else if (curl_timeout == -1) {
629 select_timeout.tv_sec = 0;
630 select_timeout.tv_usec = 50000;
631 } else {
632 select_timeout.tv_sec = curl_timeout / 1000;
633 select_timeout.tv_usec = (curl_timeout % 1000) * 1000;
634 }
635#else
636 select_timeout.tv_sec = 0;
637 select_timeout.tv_usec = 50000;
638#endif
29508e1e 639
6f9dd67f 640 max_fd = -1;
29508e1e
NH
641 FD_ZERO(&readfds);
642 FD_ZERO(&writefds);
643 FD_ZERO(&excfds);
6f9dd67f 644 curl_multi_fdset(curlm, &readfds, &writefds, &excfds, &max_fd);
eb56c821 645
7202b81f
SZ
646 /*
647 * It can happen that curl_multi_timeout returns a pathologically
648 * long timeout when curl_multi_fdset returns no file descriptors
649 * to read. See commit message for more details.
650 */
651 if (max_fd < 0 &&
652 (select_timeout.tv_sec > 0 ||
653 select_timeout.tv_usec > 50000)) {
654 select_timeout.tv_sec = 0;
655 select_timeout.tv_usec = 50000;
656 }
657
6f9dd67f 658 select(max_fd+1, &readfds, &writefds, &excfds, &select_timeout);
29508e1e
NH
659 }
660 }
661#else
662 while (slot->in_use) {
663 slot->curl_result = curl_easy_perform(slot->curl);
664 finish_active_slot(slot);
665 }
666#endif
667}
668
53f31389 669static void closedown_active_slot(struct active_request_slot *slot)
29508e1e 670{
028c2976
MH
671 active_requests--;
672 slot->in_use = 0;
53f31389
MW
673}
674
83e41e2e 675static void release_active_slot(struct active_request_slot *slot)
53f31389
MW
676{
677 closedown_active_slot(slot);
ad75ebe5 678 if (slot->curl && curl_session_count > min_curl_sessions) {
b3ca4e4e 679#ifdef USE_CURL_MULTI
53f31389 680 curl_multi_remove_handle(curlm, slot->curl);
b3ca4e4e 681#endif
53f31389
MW
682 curl_easy_cleanup(slot->curl);
683 slot->curl = NULL;
ad75ebe5 684 curl_session_count--;
53f31389 685 }
b3ca4e4e 686#ifdef USE_CURL_MULTI
53f31389 687 fill_active_slots();
b3ca4e4e 688#endif
53f31389
MW
689}
690
de1a2fdd 691void finish_active_slot(struct active_request_slot *slot)
53f31389
MW
692{
693 closedown_active_slot(slot);
028c2976 694 curl_easy_getinfo(slot->curl, CURLINFO_HTTP_CODE, &slot->http_code);
c8568e13 695
baa7b67d
NH
696 if (slot->finished != NULL)
697 (*slot->finished) = 1;
698
c8568e13
NH
699 /* Store slot results so they can be read after the slot is reused */
700 if (slot->results != NULL) {
701 slot->results->curl_result = slot->curl_result;
702 slot->results->http_code = slot->http_code;
703 }
704
028c2976 705 /* Run callback if appropriate */
4251ccbd 706 if (slot->callback_func != NULL)
028c2976 707 slot->callback_func(slot->callback_data);
29508e1e
NH
708}
709
710void finish_all_active_slots(void)
711{
712 struct active_request_slot *slot = active_queue_head;
713
714 while (slot != NULL)
715 if (slot->in_use) {
716 run_active_slot(slot);
717 slot = active_queue_head;
718 } else {
719 slot = slot->next;
720 }
721}
d7e92806 722
5ace994f 723/* Helpers for modifying and creating URLs */
d7e92806
MH
724static inline int needs_quote(int ch)
725{
726 if (((ch >= 'A') && (ch <= 'Z'))
727 || ((ch >= 'a') && (ch <= 'z'))
728 || ((ch >= '0') && (ch <= '9'))
729 || (ch == '/')
730 || (ch == '-')
731 || (ch == '.'))
732 return 0;
733 return 1;
734}
735
d7e92806
MH
736static char *quote_ref_url(const char *base, const char *ref)
737{
113106e0 738 struct strbuf buf = STRBUF_INIT;
d7e92806 739 const char *cp;
113106e0 740 int ch;
d7e92806 741
5ace994f 742 end_url_with_slash(&buf, base);
113106e0
TRC
743
744 for (cp = ref; (ch = *cp) != 0; cp++)
d7e92806 745 if (needs_quote(ch))
113106e0 746 strbuf_addf(&buf, "%%%02x", ch);
d7e92806 747 else
113106e0 748 strbuf_addch(&buf, *cp);
d7e92806 749
113106e0 750 return strbuf_detach(&buf, NULL);
d7e92806
MH
751}
752
5424bc55
TRC
753void append_remote_object_url(struct strbuf *buf, const char *url,
754 const char *hex,
755 int only_two_digit_prefix)
756{
800324c3
TRC
757 end_url_with_slash(buf, url);
758
759 strbuf_addf(buf, "objects/%.*s/", 2, hex);
5424bc55
TRC
760 if (!only_two_digit_prefix)
761 strbuf_addf(buf, "%s", hex+2);
762}
763
764char *get_remote_object_url(const char *url, const char *hex,
765 int only_two_digit_prefix)
766{
767 struct strbuf buf = STRBUF_INIT;
768 append_remote_object_url(&buf, url, hex, only_two_digit_prefix);
769 return strbuf_detach(&buf, NULL);
770}
771
1960897e 772int handle_curl_result(struct slot_results *results)
88097030 773{
6d052d78
JK
774 /*
775 * If we see a failing http code with CURLE_OK, we have turned off
776 * FAILONERROR (to keep the server's custom error response), and should
777 * translate the code into failure here.
778 */
779 if (results->curl_result == CURLE_OK &&
780 results->http_code >= 400) {
781 results->curl_result = CURLE_HTTP_RETURNED_ERROR;
782 /*
783 * Normally curl will already have put the "reason phrase"
784 * from the server into curl_errorstr; unfortunately without
785 * FAILONERROR it is lost, so we can give only the numeric
786 * status code.
787 */
788 snprintf(curl_errorstr, sizeof(curl_errorstr),
789 "The requested URL returned error: %ld",
790 results->http_code);
791 }
792
88097030
JK
793 if (results->curl_result == CURLE_OK) {
794 credential_approve(&http_auth);
795 return HTTP_OK;
796 } else if (missing_target(results))
797 return HTTP_MISSING_TARGET;
798 else if (results->http_code == 401) {
799 if (http_auth.username && http_auth.password) {
800 credential_reject(&http_auth);
801 return HTTP_NOAUTH;
802 } else {
803 credential_fill(&http_auth);
88097030
JK
804 return HTTP_REAUTH;
805 }
806 } else {
3503e9ab 807#if LIBCURL_VERSION_NUM >= 0x070c00
88097030
JK
808 if (!curl_errorstr[0])
809 strlcpy(curl_errorstr,
810 curl_easy_strerror(results->curl_result),
811 sizeof(curl_errorstr));
3503e9ab 812#endif
88097030
JK
813 return HTTP_ERROR;
814 }
815}
816
e929cd20
MH
817/* http_request() targets */
818#define HTTP_REQUEST_STRBUF 0
819#define HTTP_REQUEST_FILE 1
820
4656bf47
SP
821static int http_request(const char *url, struct strbuf *type,
822 void *result, int target, int options)
e929cd20
MH
823{
824 struct active_request_slot *slot;
825 struct slot_results results;
826 struct curl_slist *headers = NULL;
827 struct strbuf buf = STRBUF_INIT;
828 int ret;
829
830 slot = get_active_slot();
831 slot->results = &results;
832 curl_easy_setopt(slot->curl, CURLOPT_HTTPGET, 1);
833
834 if (result == NULL) {
835 curl_easy_setopt(slot->curl, CURLOPT_NOBODY, 1);
836 } else {
837 curl_easy_setopt(slot->curl, CURLOPT_NOBODY, 0);
838 curl_easy_setopt(slot->curl, CURLOPT_FILE, result);
839
840 if (target == HTTP_REQUEST_FILE) {
841 long posn = ftell(result);
842 curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION,
843 fwrite);
844 if (posn > 0) {
845 strbuf_addf(&buf, "Range: bytes=%ld-", posn);
846 headers = curl_slist_append(headers, buf.buf);
847 strbuf_reset(&buf);
848 }
e929cd20
MH
849 } else
850 curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION,
851 fwrite_buffer);
852 }
853
854 strbuf_addstr(&buf, "Pragma:");
855 if (options & HTTP_NO_CACHE)
856 strbuf_addstr(&buf, " no-cache");
6d052d78
JK
857 if (options & HTTP_KEEP_ERROR)
858 curl_easy_setopt(slot->curl, CURLOPT_FAILONERROR, 0);
e929cd20
MH
859
860 headers = curl_slist_append(headers, buf.buf);
861
862 curl_easy_setopt(slot->curl, CURLOPT_URL, url);
863 curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, headers);
aa90b969 864 curl_easy_setopt(slot->curl, CURLOPT_ENCODING, "gzip");
e929cd20
MH
865
866 if (start_active_slot(slot)) {
867 run_active_slot(slot);
1960897e 868 ret = handle_curl_result(&results);
e929cd20 869 } else {
67d2a7b5
JK
870 snprintf(curl_errorstr, sizeof(curl_errorstr),
871 "failed to start HTTP request");
e929cd20
MH
872 ret = HTTP_START_FAILED;
873 }
874
4656bf47
SP
875 if (type) {
876 char *t;
3443db51 877 strbuf_reset(type);
4656bf47
SP
878 curl_easy_getinfo(slot->curl, CURLINFO_CONTENT_TYPE, &t);
879 if (t)
880 strbuf_addstr(type, t);
881 }
882
e929cd20
MH
883 curl_slist_free_all(headers);
884 strbuf_release(&buf);
885
886 return ret;
887}
888
4656bf47
SP
889static int http_request_reauth(const char *url,
890 struct strbuf *type,
891 void *result, int target,
8d677edc
JK
892 int options)
893{
4656bf47 894 int ret = http_request(url, type, result, target, options);
8d677edc
JK
895 if (ret != HTTP_REAUTH)
896 return ret;
6d052d78
JK
897
898 /*
899 * If we are using KEEP_ERROR, the previous request may have
900 * put cruft into our output stream; we should clear it out before
901 * making our next request. We only know how to do this for
902 * the strbuf case, but that is enough to satisfy current callers.
903 */
904 if (options & HTTP_KEEP_ERROR) {
905 switch (target) {
906 case HTTP_REQUEST_STRBUF:
907 strbuf_reset(result);
908 break;
909 default:
910 die("BUG: HTTP_KEEP_ERROR is only supported with strbufs");
911 }
912 }
4656bf47 913 return http_request(url, type, result, target, options);
8d677edc
JK
914}
915
4656bf47
SP
916int http_get_strbuf(const char *url,
917 struct strbuf *type,
918 struct strbuf *result, int options)
e929cd20 919{
4656bf47
SP
920 return http_request_reauth(url, type, result,
921 HTTP_REQUEST_STRBUF, options);
e929cd20
MH
922}
923
83e41e2e 924/*
a7793a74 925 * Downloads a URL and stores the result in the given file.
83e41e2e
JH
926 *
927 * If a previous interrupted download is detected (i.e. a previous temporary
928 * file is still around) the download is resumed.
929 */
930static int http_get_file(const char *url, const char *filename, int options)
e929cd20
MH
931{
932 int ret;
933 struct strbuf tmpfile = STRBUF_INIT;
934 FILE *result;
935
936 strbuf_addf(&tmpfile, "%s.temp", filename);
937 result = fopen(tmpfile.buf, "a");
938 if (! result) {
939 error("Unable to open local file %s", tmpfile.buf);
940 ret = HTTP_ERROR;
941 goto cleanup;
942 }
943
4656bf47 944 ret = http_request_reauth(url, NULL, result, HTTP_REQUEST_FILE, options);
e929cd20
MH
945 fclose(result);
946
947 if ((ret == HTTP_OK) && move_temp_to_file(tmpfile.buf, filename))
948 ret = HTTP_ERROR;
949cleanup:
950 strbuf_release(&tmpfile);
951 return ret;
952}
953
c13b2633 954int http_fetch_ref(const char *base, struct ref *ref)
d7e92806
MH
955{
956 char *url;
957 struct strbuf buffer = STRBUF_INIT;
0d5896e1 958 int ret = -1;
d7e92806 959
c13b2633 960 url = quote_ref_url(base, ref->name);
4656bf47 961 if (http_get_strbuf(url, NULL, &buffer, HTTP_NO_CACHE) == HTTP_OK) {
0d5896e1
MH
962 strbuf_rtrim(&buffer);
963 if (buffer.len == 40)
964 ret = get_sha1_hex(buffer.buf, ref->old_sha1);
965 else if (!prefixcmp(buffer.buf, "ref: ")) {
966 ref->symref = xstrdup(buffer.buf + 5);
967 ret = 0;
d7e92806 968 }
d7e92806
MH
969 }
970
971 strbuf_release(&buffer);
972 free(url);
973 return ret;
974}
b8caac2b
TRC
975
976/* Helpers for fetching packs */
750ef425 977static char *fetch_pack_index(unsigned char *sha1, const char *base_url)
b8caac2b 978{
750ef425 979 char *url, *tmp;
b8caac2b 980 struct strbuf buf = STRBUF_INIT;
b8caac2b 981
b8caac2b 982 if (http_is_verbose)
162eb5f8 983 fprintf(stderr, "Getting index for pack %s\n", sha1_to_hex(sha1));
b8caac2b
TRC
984
985 end_url_with_slash(&buf, base_url);
162eb5f8 986 strbuf_addf(&buf, "objects/pack/pack-%s.idx", sha1_to_hex(sha1));
b8caac2b
TRC
987 url = strbuf_detach(&buf, NULL);
988
750ef425
SP
989 strbuf_addf(&buf, "%s.temp", sha1_pack_index_name(sha1));
990 tmp = strbuf_detach(&buf, NULL);
991
992 if (http_get_file(url, tmp, 0) != HTTP_OK) {
82247e9b 993 error("Unable to get pack index %s", url);
750ef425
SP
994 free(tmp);
995 tmp = NULL;
996 }
b8caac2b 997
b8caac2b 998 free(url);
750ef425 999 return tmp;
b8caac2b
TRC
1000}
1001
1002static int fetch_and_setup_pack_index(struct packed_git **packs_head,
1003 unsigned char *sha1, const char *base_url)
1004{
1005 struct packed_git *new_pack;
750ef425
SP
1006 char *tmp_idx = NULL;
1007 int ret;
b8caac2b 1008
750ef425
SP
1009 if (has_pack_index(sha1)) {
1010 new_pack = parse_pack_index(sha1, NULL);
1011 if (!new_pack)
1012 return -1; /* parse_pack_index() already issued error message */
1013 goto add_pack;
1014 }
1015
1016 tmp_idx = fetch_pack_index(sha1, base_url);
1017 if (!tmp_idx)
b8caac2b
TRC
1018 return -1;
1019
750ef425
SP
1020 new_pack = parse_pack_index(sha1, tmp_idx);
1021 if (!new_pack) {
1022 unlink(tmp_idx);
1023 free(tmp_idx);
1024
b8caac2b 1025 return -1; /* parse_pack_index() already issued error message */
750ef425
SP
1026 }
1027
1028 ret = verify_pack_index(new_pack);
1029 if (!ret) {
1030 close_pack_index(new_pack);
1031 ret = move_temp_to_file(tmp_idx, sha1_pack_index_name(sha1));
1032 }
1033 free(tmp_idx);
1034 if (ret)
1035 return -1;
1036
1037add_pack:
b8caac2b
TRC
1038 new_pack->next = *packs_head;
1039 *packs_head = new_pack;
1040 return 0;
1041}
1042
1043int http_get_info_packs(const char *base_url, struct packed_git **packs_head)
1044{
1045 int ret = 0, i = 0;
1046 char *url, *data;
1047 struct strbuf buf = STRBUF_INIT;
1048 unsigned char sha1[20];
1049
1050 end_url_with_slash(&buf, base_url);
1051 strbuf_addstr(&buf, "objects/info/packs");
1052 url = strbuf_detach(&buf, NULL);
1053
4656bf47 1054 ret = http_get_strbuf(url, NULL, &buf, HTTP_NO_CACHE);
b8caac2b
TRC
1055 if (ret != HTTP_OK)
1056 goto cleanup;
1057
1058 data = buf.buf;
1059 while (i < buf.len) {
1060 switch (data[i]) {
1061 case 'P':
1062 i++;
1063 if (i + 52 <= buf.len &&
1064 !prefixcmp(data + i, " pack-") &&
1065 !prefixcmp(data + i + 46, ".pack\n")) {
1066 get_sha1_hex(data + i + 6, sha1);
1067 fetch_and_setup_pack_index(packs_head, sha1,
1068 base_url);
1069 i += 51;
1070 break;
1071 }
1072 default:
1073 while (i < buf.len && data[i] != '\n')
1074 i++;
1075 }
1076 i++;
1077 }
1078
1079cleanup:
1080 free(url);
1081 return ret;
1082}
2264dfa5
TRC
1083
1084void release_http_pack_request(struct http_pack_request *preq)
1085{
1086 if (preq->packfile != NULL) {
1087 fclose(preq->packfile);
1088 preq->packfile = NULL;
2264dfa5
TRC
1089 }
1090 if (preq->range_header != NULL) {
1091 curl_slist_free_all(preq->range_header);
1092 preq->range_header = NULL;
1093 }
1094 preq->slot = NULL;
1095 free(preq->url);
1096}
1097
1098int finish_http_pack_request(struct http_pack_request *preq)
1099{
2264dfa5 1100 struct packed_git **lst;
021ab6f0 1101 struct packed_git *p = preq->target;
fe72d420
SP
1102 char *tmp_idx;
1103 struct child_process ip;
1104 const char *ip_argv[8];
2264dfa5 1105
fe72d420 1106 close_pack_index(p);
2264dfa5 1107
3065274c
SP
1108 fclose(preq->packfile);
1109 preq->packfile = NULL;
2264dfa5
TRC
1110
1111 lst = preq->lst;
021ab6f0 1112 while (*lst != p)
2264dfa5
TRC
1113 lst = &((*lst)->next);
1114 *lst = (*lst)->next;
1115
fe72d420
SP
1116 tmp_idx = xstrdup(preq->tmpfile);
1117 strcpy(tmp_idx + strlen(tmp_idx) - strlen(".pack.temp"),
1118 ".idx.temp");
1119
1120 ip_argv[0] = "index-pack";
1121 ip_argv[1] = "-o";
1122 ip_argv[2] = tmp_idx;
1123 ip_argv[3] = preq->tmpfile;
1124 ip_argv[4] = NULL;
1125
1126 memset(&ip, 0, sizeof(ip));
1127 ip.argv = ip_argv;
1128 ip.git_cmd = 1;
1129 ip.no_stdin = 1;
1130 ip.no_stdout = 1;
1131
1132 if (run_command(&ip)) {
1133 unlink(preq->tmpfile);
1134 unlink(tmp_idx);
1135 free(tmp_idx);
2264dfa5 1136 return -1;
fe72d420
SP
1137 }
1138
1139 unlink(sha1_pack_index_name(p->sha1));
2264dfa5 1140
fe72d420
SP
1141 if (move_temp_to_file(preq->tmpfile, sha1_pack_name(p->sha1))
1142 || move_temp_to_file(tmp_idx, sha1_pack_index_name(p->sha1))) {
1143 free(tmp_idx);
2264dfa5 1144 return -1;
fe72d420 1145 }
2264dfa5 1146
fe72d420
SP
1147 install_packed_git(p);
1148 free(tmp_idx);
2264dfa5
TRC
1149 return 0;
1150}
1151
1152struct http_pack_request *new_http_pack_request(
1153 struct packed_git *target, const char *base_url)
1154{
2264dfa5
TRC
1155 long prev_posn = 0;
1156 char range[RANGE_HEADER_SIZE];
1157 struct strbuf buf = STRBUF_INIT;
1158 struct http_pack_request *preq;
1159
ec99c9a8 1160 preq = xcalloc(1, sizeof(*preq));
2264dfa5 1161 preq->target = target;
2264dfa5
TRC
1162
1163 end_url_with_slash(&buf, base_url);
1164 strbuf_addf(&buf, "objects/pack/pack-%s.pack",
1165 sha1_to_hex(target->sha1));
bb99190e 1166 preq->url = strbuf_detach(&buf, NULL);
2264dfa5 1167
90d05713
TRC
1168 snprintf(preq->tmpfile, sizeof(preq->tmpfile), "%s.temp",
1169 sha1_pack_name(target->sha1));
2264dfa5
TRC
1170 preq->packfile = fopen(preq->tmpfile, "a");
1171 if (!preq->packfile) {
1172 error("Unable to open local file %s for pack",
1173 preq->tmpfile);
1174 goto abort;
1175 }
1176
1177 preq->slot = get_active_slot();
2264dfa5
TRC
1178 curl_easy_setopt(preq->slot->curl, CURLOPT_FILE, preq->packfile);
1179 curl_easy_setopt(preq->slot->curl, CURLOPT_WRITEFUNCTION, fwrite);
bb99190e 1180 curl_easy_setopt(preq->slot->curl, CURLOPT_URL, preq->url);
2264dfa5
TRC
1181 curl_easy_setopt(preq->slot->curl, CURLOPT_HTTPHEADER,
1182 no_pragma_header);
1183
1184 /*
1185 * If there is data present from a previous transfer attempt,
1186 * resume where it left off
1187 */
1188 prev_posn = ftell(preq->packfile);
1189 if (prev_posn>0) {
1190 if (http_is_verbose)
1191 fprintf(stderr,
1192 "Resuming fetch of pack %s at byte %ld\n",
1193 sha1_to_hex(target->sha1), prev_posn);
1194 sprintf(range, "Range: bytes=%ld-", prev_posn);
1195 preq->range_header = curl_slist_append(NULL, range);
1196 curl_easy_setopt(preq->slot->curl, CURLOPT_HTTPHEADER,
1197 preq->range_header);
1198 }
1199
1200 return preq;
1201
1202abort:
bb99190e 1203 free(preq->url);
5ae9ebfd 1204 free(preq);
2264dfa5
TRC
1205 return NULL;
1206}
5424bc55
TRC
1207
1208/* Helpers for fetching objects (loose) */
a04ff3ec 1209static size_t fwrite_sha1_file(char *ptr, size_t eltsize, size_t nmemb,
5424bc55
TRC
1210 void *data)
1211{
1212 unsigned char expn[4096];
1213 size_t size = eltsize * nmemb;
1214 int posn = 0;
1215 struct http_object_request *freq =
1216 (struct http_object_request *)data;
1217 do {
1218 ssize_t retval = xwrite(freq->localfile,
1219 (char *) ptr + posn, size - posn);
1220 if (retval < 0)
1221 return posn;
1222 posn += retval;
1223 } while (posn < size);
1224
1225 freq->stream.avail_in = size;
a04ff3ec 1226 freq->stream.next_in = (void *)ptr;
5424bc55
TRC
1227 do {
1228 freq->stream.next_out = expn;
1229 freq->stream.avail_out = sizeof(expn);
1230 freq->zret = git_inflate(&freq->stream, Z_SYNC_FLUSH);
1231 git_SHA1_Update(&freq->c, expn,
1232 sizeof(expn) - freq->stream.avail_out);
1233 } while (freq->stream.avail_in && freq->zret == Z_OK);
5424bc55
TRC
1234 return size;
1235}
1236
1237struct http_object_request *new_http_object_request(const char *base_url,
1238 unsigned char *sha1)
1239{
1240 char *hex = sha1_to_hex(sha1);
1241 char *filename;
1242 char prevfile[PATH_MAX];
5424bc55 1243 int prevlocal;
a04ff3ec 1244 char prev_buf[PREV_BUF_SIZE];
5424bc55
TRC
1245 ssize_t prev_read = 0;
1246 long prev_posn = 0;
1247 char range[RANGE_HEADER_SIZE];
1248 struct curl_slist *range_header = NULL;
1249 struct http_object_request *freq;
1250
ec99c9a8 1251 freq = xcalloc(1, sizeof(*freq));
5424bc55
TRC
1252 hashcpy(freq->sha1, sha1);
1253 freq->localfile = -1;
1254
1255 filename = sha1_file_name(sha1);
5424bc55
TRC
1256 snprintf(freq->tmpfile, sizeof(freq->tmpfile),
1257 "%s.temp", filename);
1258
1259 snprintf(prevfile, sizeof(prevfile), "%s.prev", filename);
1260 unlink_or_warn(prevfile);
1261 rename(freq->tmpfile, prevfile);
1262 unlink_or_warn(freq->tmpfile);
1263
1264 if (freq->localfile != -1)
1265 error("fd leakage in start: %d", freq->localfile);
1266 freq->localfile = open(freq->tmpfile,
1267 O_WRONLY | O_CREAT | O_EXCL, 0666);
1268 /*
1269 * This could have failed due to the "lazy directory creation";
1270 * try to mkdir the last path component.
1271 */
1272 if (freq->localfile < 0 && errno == ENOENT) {
1273 char *dir = strrchr(freq->tmpfile, '/');
1274 if (dir) {
1275 *dir = 0;
1276 mkdir(freq->tmpfile, 0777);
1277 *dir = '/';
1278 }
1279 freq->localfile = open(freq->tmpfile,
1280 O_WRONLY | O_CREAT | O_EXCL, 0666);
1281 }
1282
1283 if (freq->localfile < 0) {
0da8b2e7
SP
1284 error("Couldn't create temporary file %s: %s",
1285 freq->tmpfile, strerror(errno));
5424bc55
TRC
1286 goto abort;
1287 }
1288
5424bc55
TRC
1289 git_inflate_init(&freq->stream);
1290
1291 git_SHA1_Init(&freq->c);
1292
bb99190e 1293 freq->url = get_remote_object_url(base_url, hex, 0);
5424bc55
TRC
1294
1295 /*
1296 * If a previous temp file is present, process what was already
1297 * fetched.
1298 */
1299 prevlocal = open(prevfile, O_RDONLY);
1300 if (prevlocal != -1) {
1301 do {
1302 prev_read = xread(prevlocal, prev_buf, PREV_BUF_SIZE);
1303 if (prev_read>0) {
1304 if (fwrite_sha1_file(prev_buf,
1305 1,
1306 prev_read,
1307 freq) == prev_read) {
1308 prev_posn += prev_read;
1309 } else {
1310 prev_read = -1;
1311 }
1312 }
1313 } while (prev_read > 0);
1314 close(prevlocal);
1315 }
1316 unlink_or_warn(prevfile);
1317
1318 /*
1319 * Reset inflate/SHA1 if there was an error reading the previous temp
1320 * file; also rewind to the beginning of the local file.
1321 */
1322 if (prev_read == -1) {
1323 memset(&freq->stream, 0, sizeof(freq->stream));
1324 git_inflate_init(&freq->stream);
1325 git_SHA1_Init(&freq->c);
1326 if (prev_posn>0) {
1327 prev_posn = 0;
1328 lseek(freq->localfile, 0, SEEK_SET);
0c4f21e4 1329 if (ftruncate(freq->localfile, 0) < 0) {
0da8b2e7
SP
1330 error("Couldn't truncate temporary file %s: %s",
1331 freq->tmpfile, strerror(errno));
0c4f21e4
JL
1332 goto abort;
1333 }
5424bc55
TRC
1334 }
1335 }
1336
1337 freq->slot = get_active_slot();
1338
1339 curl_easy_setopt(freq->slot->curl, CURLOPT_FILE, freq);
1340 curl_easy_setopt(freq->slot->curl, CURLOPT_WRITEFUNCTION, fwrite_sha1_file);
1341 curl_easy_setopt(freq->slot->curl, CURLOPT_ERRORBUFFER, freq->errorstr);
bb99190e 1342 curl_easy_setopt(freq->slot->curl, CURLOPT_URL, freq->url);
5424bc55
TRC
1343 curl_easy_setopt(freq->slot->curl, CURLOPT_HTTPHEADER, no_pragma_header);
1344
1345 /*
1346 * If we have successfully processed data from a previous fetch
1347 * attempt, only fetch the data we don't already have.
1348 */
1349 if (prev_posn>0) {
1350 if (http_is_verbose)
1351 fprintf(stderr,
1352 "Resuming fetch of object %s at byte %ld\n",
1353 hex, prev_posn);
1354 sprintf(range, "Range: bytes=%ld-", prev_posn);
1355 range_header = curl_slist_append(range_header, range);
1356 curl_easy_setopt(freq->slot->curl,
1357 CURLOPT_HTTPHEADER, range_header);
1358 }
1359
1360 return freq;
1361
5424bc55 1362abort:
bb99190e 1363 free(freq->url);
5424bc55
TRC
1364 free(freq);
1365 return NULL;
1366}
1367
1368void process_http_object_request(struct http_object_request *freq)
1369{
1370 if (freq->slot == NULL)
1371 return;
1372 freq->curl_result = freq->slot->curl_result;
1373 freq->http_code = freq->slot->http_code;
1374 freq->slot = NULL;
1375}
1376
1377int finish_http_object_request(struct http_object_request *freq)
1378{
1379 struct stat st;
1380
1381 close(freq->localfile);
1382 freq->localfile = -1;
1383
1384 process_http_object_request(freq);
1385
1386 if (freq->http_code == 416) {
bd757c18 1387 warning("requested range invalid; we may already have all the data.");
5424bc55
TRC
1388 } else if (freq->curl_result != CURLE_OK) {
1389 if (stat(freq->tmpfile, &st) == 0)
1390 if (st.st_size == 0)
1391 unlink_or_warn(freq->tmpfile);
1392 return -1;
1393 }
1394
1395 git_inflate_end(&freq->stream);
1396 git_SHA1_Final(freq->real_sha1, &freq->c);
1397 if (freq->zret != Z_STREAM_END) {
1398 unlink_or_warn(freq->tmpfile);
1399 return -1;
1400 }
1401 if (hashcmp(freq->sha1, freq->real_sha1)) {
1402 unlink_or_warn(freq->tmpfile);
1403 return -1;
1404 }
1405 freq->rename =
0da8b2e7 1406 move_temp_to_file(freq->tmpfile, sha1_file_name(freq->sha1));
5424bc55
TRC
1407
1408 return freq->rename;
1409}
1410
1411void abort_http_object_request(struct http_object_request *freq)
1412{
1413 unlink_or_warn(freq->tmpfile);
1414
1415 release_http_object_request(freq);
1416}
1417
1418void release_http_object_request(struct http_object_request *freq)
1419{
1420 if (freq->localfile != -1) {
1421 close(freq->localfile);
1422 freq->localfile = -1;
1423 }
1424 if (freq->url != NULL) {
1425 free(freq->url);
1426 freq->url = NULL;
1427 }
4b9fa0e3
TRC
1428 if (freq->slot != NULL) {
1429 freq->slot->callback_func = NULL;
1430 freq->slot->callback_data = NULL;
1431 release_active_slot(freq->slot);
1432 freq->slot = NULL;
1433 }
5424bc55 1434}