coccinelle: make use of the "type" FREE_AND_NULL() rule
[git] / http.c
1 #include "git-compat-util.h"
2 #include "http.h"
3 #include "pack.h"
4 #include "sideband.h"
5 #include "run-command.h"
6 #include "url.h"
7 #include "urlmatch.h"
8 #include "credential.h"
9 #include "version.h"
10 #include "pkt-line.h"
11 #include "gettext.h"
12 #include "transport.h"
13
14 static struct trace_key trace_curl = TRACE_KEY_INIT(CURL);
15 #if LIBCURL_VERSION_NUM >= 0x070a08
16 long int git_curl_ipresolve = CURL_IPRESOLVE_WHATEVER;
17 #else
18 long int git_curl_ipresolve;
19 #endif
20 int active_requests;
21 int http_is_verbose;
22 ssize_t http_post_buffer = 16 * LARGE_PACKET_MAX;
23
24 #if LIBCURL_VERSION_NUM >= 0x070a06
25 #define LIBCURL_CAN_HANDLE_AUTH_ANY
26 #endif
27
28 static int min_curl_sessions = 1;
29 static int curl_session_count;
30 #ifdef USE_CURL_MULTI
31 static int max_requests = -1;
32 static CURLM *curlm;
33 #endif
34 #ifndef NO_CURL_EASY_DUPHANDLE
35 static CURL *curl_default;
36 #endif
37
38 #define PREV_BUF_SIZE 4096
39
40 char curl_errorstr[CURL_ERROR_SIZE];
41
42 static int curl_ssl_verify = -1;
43 static int curl_ssl_try;
44 static const char *ssl_cert;
45 static const char *ssl_cipherlist;
46 static const char *ssl_version;
47 static struct {
48         const char *name;
49         long ssl_version;
50 } sslversions[] = {
51         { "sslv2", CURL_SSLVERSION_SSLv2 },
52         { "sslv3", CURL_SSLVERSION_SSLv3 },
53         { "tlsv1", CURL_SSLVERSION_TLSv1 },
54 #if LIBCURL_VERSION_NUM >= 0x072200
55         { "tlsv1.0", CURL_SSLVERSION_TLSv1_0 },
56         { "tlsv1.1", CURL_SSLVERSION_TLSv1_1 },
57         { "tlsv1.2", CURL_SSLVERSION_TLSv1_2 },
58 #endif
59 };
60 #if LIBCURL_VERSION_NUM >= 0x070903
61 static const char *ssl_key;
62 #endif
63 #if LIBCURL_VERSION_NUM >= 0x070908
64 static const char *ssl_capath;
65 #endif
66 #if LIBCURL_VERSION_NUM >= 0x072c00
67 static const char *ssl_pinnedkey;
68 #endif
69 static const char *ssl_cainfo;
70 static long curl_low_speed_limit = -1;
71 static long curl_low_speed_time = -1;
72 static int curl_ftp_no_epsv;
73 static const char *curl_http_proxy;
74 static const char *curl_no_proxy;
75 static const char *http_proxy_authmethod;
76 static struct {
77         const char *name;
78         long curlauth_param;
79 } proxy_authmethods[] = {
80         { "basic", CURLAUTH_BASIC },
81         { "digest", CURLAUTH_DIGEST },
82         { "negotiate", CURLAUTH_GSSNEGOTIATE },
83         { "ntlm", CURLAUTH_NTLM },
84 #ifdef LIBCURL_CAN_HANDLE_AUTH_ANY
85         { "anyauth", CURLAUTH_ANY },
86 #endif
87         /*
88          * CURLAUTH_DIGEST_IE has no corresponding command-line option in
89          * curl(1) and is not included in CURLAUTH_ANY, so we leave it out
90          * here, too
91          */
92 };
93 #if LIBCURL_VERSION_NUM >= 0x071600
94 static const char *curl_deleg;
95 static struct {
96         const char *name;
97         long curl_deleg_param;
98 } curl_deleg_levels[] = {
99         { "none", CURLGSSAPI_DELEGATION_NONE },
100         { "policy", CURLGSSAPI_DELEGATION_POLICY_FLAG },
101         { "always", CURLGSSAPI_DELEGATION_FLAG },
102 };
103 #endif
104
105 static struct credential proxy_auth = CREDENTIAL_INIT;
106 static const char *curl_proxyuserpwd;
107 static const char *curl_cookie_file;
108 static int curl_save_cookies;
109 struct credential http_auth = CREDENTIAL_INIT;
110 static int http_proactive_auth;
111 static const char *user_agent;
112 static int curl_empty_auth = -1;
113
114 enum http_follow_config http_follow_config = HTTP_FOLLOW_INITIAL;
115
116 #if LIBCURL_VERSION_NUM >= 0x071700
117 /* Use CURLOPT_KEYPASSWD as is */
118 #elif LIBCURL_VERSION_NUM >= 0x070903
119 #define CURLOPT_KEYPASSWD CURLOPT_SSLKEYPASSWD
120 #else
121 #define CURLOPT_KEYPASSWD CURLOPT_SSLCERTPASSWD
122 #endif
123
124 static struct credential cert_auth = CREDENTIAL_INIT;
125 static int ssl_cert_password_required;
126 #ifdef LIBCURL_CAN_HANDLE_AUTH_ANY
127 static unsigned long http_auth_methods = CURLAUTH_ANY;
128 static int http_auth_methods_restricted;
129 /* Modes for which empty_auth cannot actually help us. */
130 static unsigned long empty_auth_useless =
131         CURLAUTH_BASIC
132 #ifdef CURLAUTH_DIGEST_IE
133         | CURLAUTH_DIGEST_IE
134 #endif
135         | CURLAUTH_DIGEST;
136 #endif
137
138 static struct curl_slist *pragma_header;
139 static struct curl_slist *no_pragma_header;
140 static struct curl_slist *extra_http_headers;
141
142 static struct active_request_slot *active_queue_head;
143
144 static char *cached_accept_language;
145
146 size_t fread_buffer(char *ptr, size_t eltsize, size_t nmemb, void *buffer_)
147 {
148         size_t size = eltsize * nmemb;
149         struct buffer *buffer = buffer_;
150
151         if (size > buffer->buf.len - buffer->posn)
152                 size = buffer->buf.len - buffer->posn;
153         memcpy(ptr, buffer->buf.buf + buffer->posn, size);
154         buffer->posn += size;
155
156         return size;
157 }
158
159 #ifndef NO_CURL_IOCTL
160 curlioerr ioctl_buffer(CURL *handle, int cmd, void *clientp)
161 {
162         struct buffer *buffer = clientp;
163
164         switch (cmd) {
165         case CURLIOCMD_NOP:
166                 return CURLIOE_OK;
167
168         case CURLIOCMD_RESTARTREAD:
169                 buffer->posn = 0;
170                 return CURLIOE_OK;
171
172         default:
173                 return CURLIOE_UNKNOWNCMD;
174         }
175 }
176 #endif
177
178 size_t fwrite_buffer(char *ptr, size_t eltsize, size_t nmemb, void *buffer_)
179 {
180         size_t size = eltsize * nmemb;
181         struct strbuf *buffer = buffer_;
182
183         strbuf_add(buffer, ptr, size);
184         return size;
185 }
186
187 size_t fwrite_null(char *ptr, size_t eltsize, size_t nmemb, void *strbuf)
188 {
189         return eltsize * nmemb;
190 }
191
192 static void closedown_active_slot(struct active_request_slot *slot)
193 {
194         active_requests--;
195         slot->in_use = 0;
196 }
197
198 static void finish_active_slot(struct active_request_slot *slot)
199 {
200         closedown_active_slot(slot);
201         curl_easy_getinfo(slot->curl, CURLINFO_HTTP_CODE, &slot->http_code);
202
203         if (slot->finished != NULL)
204                 (*slot->finished) = 1;
205
206         /* Store slot results so they can be read after the slot is reused */
207         if (slot->results != NULL) {
208                 slot->results->curl_result = slot->curl_result;
209                 slot->results->http_code = slot->http_code;
210 #if LIBCURL_VERSION_NUM >= 0x070a08
211                 curl_easy_getinfo(slot->curl, CURLINFO_HTTPAUTH_AVAIL,
212                                   &slot->results->auth_avail);
213 #else
214                 slot->results->auth_avail = 0;
215 #endif
216
217                 curl_easy_getinfo(slot->curl, CURLINFO_HTTP_CONNECTCODE,
218                         &slot->results->http_connectcode);
219         }
220
221         /* Run callback if appropriate */
222         if (slot->callback_func != NULL)
223                 slot->callback_func(slot->callback_data);
224 }
225
226 static void xmulti_remove_handle(struct active_request_slot *slot)
227 {
228 #ifdef USE_CURL_MULTI
229         curl_multi_remove_handle(curlm, slot->curl);
230 #endif
231 }
232
233 #ifdef USE_CURL_MULTI
234 static void process_curl_messages(void)
235 {
236         int num_messages;
237         struct active_request_slot *slot;
238         CURLMsg *curl_message = curl_multi_info_read(curlm, &num_messages);
239
240         while (curl_message != NULL) {
241                 if (curl_message->msg == CURLMSG_DONE) {
242                         int curl_result = curl_message->data.result;
243                         slot = active_queue_head;
244                         while (slot != NULL &&
245                                slot->curl != curl_message->easy_handle)
246                                 slot = slot->next;
247                         if (slot != NULL) {
248                                 xmulti_remove_handle(slot);
249                                 slot->curl_result = curl_result;
250                                 finish_active_slot(slot);
251                         } else {
252                                 fprintf(stderr, "Received DONE message for unknown request!\n");
253                         }
254                 } else {
255                         fprintf(stderr, "Unknown CURL message received: %d\n",
256                                 (int)curl_message->msg);
257                 }
258                 curl_message = curl_multi_info_read(curlm, &num_messages);
259         }
260 }
261 #endif
262
263 static int http_options(const char *var, const char *value, void *cb)
264 {
265         if (!strcmp("http.sslverify", var)) {
266                 curl_ssl_verify = git_config_bool(var, value);
267                 return 0;
268         }
269         if (!strcmp("http.sslcipherlist", var))
270                 return git_config_string(&ssl_cipherlist, var, value);
271         if (!strcmp("http.sslversion", var))
272                 return git_config_string(&ssl_version, var, value);
273         if (!strcmp("http.sslcert", var))
274                 return git_config_string(&ssl_cert, var, value);
275 #if LIBCURL_VERSION_NUM >= 0x070903
276         if (!strcmp("http.sslkey", var))
277                 return git_config_string(&ssl_key, var, value);
278 #endif
279 #if LIBCURL_VERSION_NUM >= 0x070908
280         if (!strcmp("http.sslcapath", var))
281                 return git_config_pathname(&ssl_capath, var, value);
282 #endif
283         if (!strcmp("http.sslcainfo", var))
284                 return git_config_pathname(&ssl_cainfo, var, value);
285         if (!strcmp("http.sslcertpasswordprotected", var)) {
286                 ssl_cert_password_required = git_config_bool(var, value);
287                 return 0;
288         }
289         if (!strcmp("http.ssltry", var)) {
290                 curl_ssl_try = git_config_bool(var, value);
291                 return 0;
292         }
293         if (!strcmp("http.minsessions", var)) {
294                 min_curl_sessions = git_config_int(var, value);
295 #ifndef USE_CURL_MULTI
296                 if (min_curl_sessions > 1)
297                         min_curl_sessions = 1;
298 #endif
299                 return 0;
300         }
301 #ifdef USE_CURL_MULTI
302         if (!strcmp("http.maxrequests", var)) {
303                 max_requests = git_config_int(var, value);
304                 return 0;
305         }
306 #endif
307         if (!strcmp("http.lowspeedlimit", var)) {
308                 curl_low_speed_limit = (long)git_config_int(var, value);
309                 return 0;
310         }
311         if (!strcmp("http.lowspeedtime", var)) {
312                 curl_low_speed_time = (long)git_config_int(var, value);
313                 return 0;
314         }
315
316         if (!strcmp("http.noepsv", var)) {
317                 curl_ftp_no_epsv = git_config_bool(var, value);
318                 return 0;
319         }
320         if (!strcmp("http.proxy", var))
321                 return git_config_string(&curl_http_proxy, var, value);
322
323         if (!strcmp("http.proxyauthmethod", var))
324                 return git_config_string(&http_proxy_authmethod, var, value);
325
326         if (!strcmp("http.cookiefile", var))
327                 return git_config_pathname(&curl_cookie_file, var, value);
328         if (!strcmp("http.savecookies", var)) {
329                 curl_save_cookies = git_config_bool(var, value);
330                 return 0;
331         }
332
333         if (!strcmp("http.postbuffer", var)) {
334                 http_post_buffer = git_config_ssize_t(var, value);
335                 if (http_post_buffer < 0)
336                         warning(_("negative value for http.postbuffer; defaulting to %d"), LARGE_PACKET_MAX);
337                 if (http_post_buffer < LARGE_PACKET_MAX)
338                         http_post_buffer = LARGE_PACKET_MAX;
339                 return 0;
340         }
341
342         if (!strcmp("http.useragent", var))
343                 return git_config_string(&user_agent, var, value);
344
345         if (!strcmp("http.emptyauth", var)) {
346                 if (value && !strcmp("auto", value))
347                         curl_empty_auth = -1;
348                 else
349                         curl_empty_auth = git_config_bool(var, value);
350                 return 0;
351         }
352
353         if (!strcmp("http.delegation", var)) {
354 #if LIBCURL_VERSION_NUM >= 0x071600
355                 return git_config_string(&curl_deleg, var, value);
356 #else
357                 warning(_("Delegation control is not supported with cURL < 7.22.0"));
358                 return 0;
359 #endif
360         }
361
362         if (!strcmp("http.pinnedpubkey", var)) {
363 #if LIBCURL_VERSION_NUM >= 0x072c00
364                 return git_config_pathname(&ssl_pinnedkey, var, value);
365 #else
366                 warning(_("Public key pinning not supported with cURL < 7.44.0"));
367                 return 0;
368 #endif
369         }
370
371         if (!strcmp("http.extraheader", var)) {
372                 if (!value) {
373                         return config_error_nonbool(var);
374                 } else if (!*value) {
375                         curl_slist_free_all(extra_http_headers);
376                         extra_http_headers = NULL;
377                 } else {
378                         extra_http_headers =
379                                 curl_slist_append(extra_http_headers, value);
380                 }
381                 return 0;
382         }
383
384         if (!strcmp("http.followredirects", var)) {
385                 if (value && !strcmp(value, "initial"))
386                         http_follow_config = HTTP_FOLLOW_INITIAL;
387                 else if (git_config_bool(var, value))
388                         http_follow_config = HTTP_FOLLOW_ALWAYS;
389                 else
390                         http_follow_config = HTTP_FOLLOW_NONE;
391                 return 0;
392         }
393
394         /* Fall back on the default ones */
395         return git_default_config(var, value, cb);
396 }
397
398 static int curl_empty_auth_enabled(void)
399 {
400         if (curl_empty_auth >= 0)
401                 return curl_empty_auth;
402
403 #ifndef LIBCURL_CAN_HANDLE_AUTH_ANY
404         /*
405          * Our libcurl is too old to do AUTH_ANY in the first place;
406          * just default to turning the feature off.
407          */
408 #else
409         /*
410          * In the automatic case, kick in the empty-auth
411          * hack as long as we would potentially try some
412          * method more exotic than "Basic" or "Digest".
413          *
414          * But only do this when this is our second or
415          * subsequent request, as by then we know what
416          * methods are available.
417          */
418         if (http_auth_methods_restricted &&
419             (http_auth_methods & ~empty_auth_useless))
420                 return 1;
421 #endif
422         return 0;
423 }
424
425 static void init_curl_http_auth(CURL *result)
426 {
427         if (!http_auth.username || !*http_auth.username) {
428                 if (curl_empty_auth_enabled())
429                         curl_easy_setopt(result, CURLOPT_USERPWD, ":");
430                 return;
431         }
432
433         credential_fill(&http_auth);
434
435 #if LIBCURL_VERSION_NUM >= 0x071301
436         curl_easy_setopt(result, CURLOPT_USERNAME, http_auth.username);
437         curl_easy_setopt(result, CURLOPT_PASSWORD, http_auth.password);
438 #else
439         {
440                 static struct strbuf up = STRBUF_INIT;
441                 /*
442                  * Note that we assume we only ever have a single set of
443                  * credentials in a given program run, so we do not have
444                  * to worry about updating this buffer, only setting its
445                  * initial value.
446                  */
447                 if (!up.len)
448                         strbuf_addf(&up, "%s:%s",
449                                 http_auth.username, http_auth.password);
450                 curl_easy_setopt(result, CURLOPT_USERPWD, up.buf);
451         }
452 #endif
453 }
454
455 /* *var must be free-able */
456 static void var_override(const char **var, char *value)
457 {
458         if (value) {
459                 free((void *)*var);
460                 *var = xstrdup(value);
461         }
462 }
463
464 static void set_proxyauth_name_password(CURL *result)
465 {
466 #if LIBCURL_VERSION_NUM >= 0x071301
467                 curl_easy_setopt(result, CURLOPT_PROXYUSERNAME,
468                         proxy_auth.username);
469                 curl_easy_setopt(result, CURLOPT_PROXYPASSWORD,
470                         proxy_auth.password);
471 #else
472                 struct strbuf s = STRBUF_INIT;
473
474                 strbuf_addstr_urlencode(&s, proxy_auth.username, 1);
475                 strbuf_addch(&s, ':');
476                 strbuf_addstr_urlencode(&s, proxy_auth.password, 1);
477                 curl_proxyuserpwd = strbuf_detach(&s, NULL);
478                 curl_easy_setopt(result, CURLOPT_PROXYUSERPWD, curl_proxyuserpwd);
479 #endif
480 }
481
482 static void init_curl_proxy_auth(CURL *result)
483 {
484         if (proxy_auth.username) {
485                 if (!proxy_auth.password)
486                         credential_fill(&proxy_auth);
487                 set_proxyauth_name_password(result);
488         }
489
490         var_override(&http_proxy_authmethod, getenv("GIT_HTTP_PROXY_AUTHMETHOD"));
491
492 #if LIBCURL_VERSION_NUM >= 0x070a07 /* CURLOPT_PROXYAUTH and CURLAUTH_ANY */
493         if (http_proxy_authmethod) {
494                 int i;
495                 for (i = 0; i < ARRAY_SIZE(proxy_authmethods); i++) {
496                         if (!strcmp(http_proxy_authmethod, proxy_authmethods[i].name)) {
497                                 curl_easy_setopt(result, CURLOPT_PROXYAUTH,
498                                                 proxy_authmethods[i].curlauth_param);
499                                 break;
500                         }
501                 }
502                 if (i == ARRAY_SIZE(proxy_authmethods)) {
503                         warning("unsupported proxy authentication method %s: using anyauth",
504                                         http_proxy_authmethod);
505                         curl_easy_setopt(result, CURLOPT_PROXYAUTH, CURLAUTH_ANY);
506                 }
507         }
508         else
509                 curl_easy_setopt(result, CURLOPT_PROXYAUTH, CURLAUTH_ANY);
510 #endif
511 }
512
513 static int has_cert_password(void)
514 {
515         if (ssl_cert == NULL || ssl_cert_password_required != 1)
516                 return 0;
517         if (!cert_auth.password) {
518                 cert_auth.protocol = xstrdup("cert");
519                 cert_auth.username = xstrdup("");
520                 cert_auth.path = xstrdup(ssl_cert);
521                 credential_fill(&cert_auth);
522         }
523         return 1;
524 }
525
526 #if LIBCURL_VERSION_NUM >= 0x071900
527 static void set_curl_keepalive(CURL *c)
528 {
529         curl_easy_setopt(c, CURLOPT_TCP_KEEPALIVE, 1);
530 }
531
532 #elif LIBCURL_VERSION_NUM >= 0x071000
533 static int sockopt_callback(void *client, curl_socket_t fd, curlsocktype type)
534 {
535         int ka = 1;
536         int rc;
537         socklen_t len = (socklen_t)sizeof(ka);
538
539         if (type != CURLSOCKTYPE_IPCXN)
540                 return 0;
541
542         rc = setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, (void *)&ka, len);
543         if (rc < 0)
544                 warning_errno("unable to set SO_KEEPALIVE on socket");
545
546         return 0; /* CURL_SOCKOPT_OK only exists since curl 7.21.5 */
547 }
548
549 static void set_curl_keepalive(CURL *c)
550 {
551         curl_easy_setopt(c, CURLOPT_SOCKOPTFUNCTION, sockopt_callback);
552 }
553
554 #else
555 static void set_curl_keepalive(CURL *c)
556 {
557         /* not supported on older curl versions */
558 }
559 #endif
560
561 static void redact_sensitive_header(struct strbuf *header)
562 {
563         const char *sensitive_header;
564
565         if (skip_prefix(header->buf, "Authorization:", &sensitive_header) ||
566             skip_prefix(header->buf, "Proxy-Authorization:", &sensitive_header)) {
567                 /* The first token is the type, which is OK to log */
568                 while (isspace(*sensitive_header))
569                         sensitive_header++;
570                 while (*sensitive_header && !isspace(*sensitive_header))
571                         sensitive_header++;
572                 /* Everything else is opaque and possibly sensitive */
573                 strbuf_setlen(header,  sensitive_header - header->buf);
574                 strbuf_addstr(header, " <redacted>");
575         }
576 }
577
578 static void curl_dump_header(const char *text, unsigned char *ptr, size_t size, int hide_sensitive_header)
579 {
580         struct strbuf out = STRBUF_INIT;
581         struct strbuf **headers, **header;
582
583         strbuf_addf(&out, "%s, %10.10ld bytes (0x%8.8lx)\n",
584                 text, (long)size, (long)size);
585         trace_strbuf(&trace_curl, &out);
586         strbuf_reset(&out);
587         strbuf_add(&out, ptr, size);
588         headers = strbuf_split_max(&out, '\n', 0);
589
590         for (header = headers; *header; header++) {
591                 if (hide_sensitive_header)
592                         redact_sensitive_header(*header);
593                 strbuf_insert((*header), 0, text, strlen(text));
594                 strbuf_insert((*header), strlen(text), ": ", 2);
595                 strbuf_rtrim((*header));
596                 strbuf_addch((*header), '\n');
597                 trace_strbuf(&trace_curl, (*header));
598         }
599         strbuf_list_free(headers);
600         strbuf_release(&out);
601 }
602
603 static void curl_dump_data(const char *text, unsigned char *ptr, size_t size)
604 {
605         size_t i;
606         struct strbuf out = STRBUF_INIT;
607         unsigned int width = 60;
608
609         strbuf_addf(&out, "%s, %10.10ld bytes (0x%8.8lx)\n",
610                 text, (long)size, (long)size);
611         trace_strbuf(&trace_curl, &out);
612
613         for (i = 0; i < size; i += width) {
614                 size_t w;
615
616                 strbuf_reset(&out);
617                 strbuf_addf(&out, "%s: ", text);
618                 for (w = 0; (w < width) && (i + w < size); w++) {
619                         unsigned char ch = ptr[i + w];
620
621                         strbuf_addch(&out,
622                                        (ch >= 0x20) && (ch < 0x80)
623                                        ? ch : '.');
624                 }
625                 strbuf_addch(&out, '\n');
626                 trace_strbuf(&trace_curl, &out);
627         }
628         strbuf_release(&out);
629 }
630
631 static int curl_trace(CURL *handle, curl_infotype type, char *data, size_t size, void *userp)
632 {
633         const char *text;
634         enum { NO_FILTER = 0, DO_FILTER = 1 };
635
636         switch (type) {
637         case CURLINFO_TEXT:
638                 trace_printf_key(&trace_curl, "== Info: %s", data);
639         default:                /* we ignore unknown types by default */
640                 return 0;
641
642         case CURLINFO_HEADER_OUT:
643                 text = "=> Send header";
644                 curl_dump_header(text, (unsigned char *)data, size, DO_FILTER);
645                 break;
646         case CURLINFO_DATA_OUT:
647                 text = "=> Send data";
648                 curl_dump_data(text, (unsigned char *)data, size);
649                 break;
650         case CURLINFO_SSL_DATA_OUT:
651                 text = "=> Send SSL data";
652                 curl_dump_data(text, (unsigned char *)data, size);
653                 break;
654         case CURLINFO_HEADER_IN:
655                 text = "<= Recv header";
656                 curl_dump_header(text, (unsigned char *)data, size, NO_FILTER);
657                 break;
658         case CURLINFO_DATA_IN:
659                 text = "<= Recv data";
660                 curl_dump_data(text, (unsigned char *)data, size);
661                 break;
662         case CURLINFO_SSL_DATA_IN:
663                 text = "<= Recv SSL data";
664                 curl_dump_data(text, (unsigned char *)data, size);
665                 break;
666         }
667         return 0;
668 }
669
670 void setup_curl_trace(CURL *handle)
671 {
672         if (!trace_want(&trace_curl))
673                 return;
674         curl_easy_setopt(handle, CURLOPT_VERBOSE, 1L);
675         curl_easy_setopt(handle, CURLOPT_DEBUGFUNCTION, curl_trace);
676         curl_easy_setopt(handle, CURLOPT_DEBUGDATA, NULL);
677 }
678
679 static long get_curl_allowed_protocols(int from_user)
680 {
681         long allowed_protocols = 0;
682
683         if (is_transport_allowed("http", from_user))
684                 allowed_protocols |= CURLPROTO_HTTP;
685         if (is_transport_allowed("https", from_user))
686                 allowed_protocols |= CURLPROTO_HTTPS;
687         if (is_transport_allowed("ftp", from_user))
688                 allowed_protocols |= CURLPROTO_FTP;
689         if (is_transport_allowed("ftps", from_user))
690                 allowed_protocols |= CURLPROTO_FTPS;
691
692         return allowed_protocols;
693 }
694
695 static CURL *get_curl_handle(void)
696 {
697         CURL *result = curl_easy_init();
698
699         if (!result)
700                 die("curl_easy_init failed");
701
702         if (!curl_ssl_verify) {
703                 curl_easy_setopt(result, CURLOPT_SSL_VERIFYPEER, 0);
704                 curl_easy_setopt(result, CURLOPT_SSL_VERIFYHOST, 0);
705         } else {
706                 /* Verify authenticity of the peer's certificate */
707                 curl_easy_setopt(result, CURLOPT_SSL_VERIFYPEER, 1);
708                 /* The name in the cert must match whom we tried to connect */
709                 curl_easy_setopt(result, CURLOPT_SSL_VERIFYHOST, 2);
710         }
711
712 #if LIBCURL_VERSION_NUM >= 0x070907
713         curl_easy_setopt(result, CURLOPT_NETRC, CURL_NETRC_OPTIONAL);
714 #endif
715 #ifdef LIBCURL_CAN_HANDLE_AUTH_ANY
716         curl_easy_setopt(result, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
717 #endif
718
719 #if LIBCURL_VERSION_NUM >= 0x071600
720         if (curl_deleg) {
721                 int i;
722                 for (i = 0; i < ARRAY_SIZE(curl_deleg_levels); i++) {
723                         if (!strcmp(curl_deleg, curl_deleg_levels[i].name)) {
724                                 curl_easy_setopt(result, CURLOPT_GSSAPI_DELEGATION,
725                                                 curl_deleg_levels[i].curl_deleg_param);
726                                 break;
727                         }
728                 }
729                 if (i == ARRAY_SIZE(curl_deleg_levels))
730                         warning("Unknown delegation method '%s': using default",
731                                 curl_deleg);
732         }
733 #endif
734
735         if (http_proactive_auth)
736                 init_curl_http_auth(result);
737
738         if (getenv("GIT_SSL_VERSION"))
739                 ssl_version = getenv("GIT_SSL_VERSION");
740         if (ssl_version && *ssl_version) {
741                 int i;
742                 for (i = 0; i < ARRAY_SIZE(sslversions); i++) {
743                         if (!strcmp(ssl_version, sslversions[i].name)) {
744                                 curl_easy_setopt(result, CURLOPT_SSLVERSION,
745                                                  sslversions[i].ssl_version);
746                                 break;
747                         }
748                 }
749                 if (i == ARRAY_SIZE(sslversions))
750                         warning("unsupported ssl version %s: using default",
751                                 ssl_version);
752         }
753
754         if (getenv("GIT_SSL_CIPHER_LIST"))
755                 ssl_cipherlist = getenv("GIT_SSL_CIPHER_LIST");
756         if (ssl_cipherlist != NULL && *ssl_cipherlist)
757                 curl_easy_setopt(result, CURLOPT_SSL_CIPHER_LIST,
758                                 ssl_cipherlist);
759
760         if (ssl_cert != NULL)
761                 curl_easy_setopt(result, CURLOPT_SSLCERT, ssl_cert);
762         if (has_cert_password())
763                 curl_easy_setopt(result, CURLOPT_KEYPASSWD, cert_auth.password);
764 #if LIBCURL_VERSION_NUM >= 0x070903
765         if (ssl_key != NULL)
766                 curl_easy_setopt(result, CURLOPT_SSLKEY, ssl_key);
767 #endif
768 #if LIBCURL_VERSION_NUM >= 0x070908
769         if (ssl_capath != NULL)
770                 curl_easy_setopt(result, CURLOPT_CAPATH, ssl_capath);
771 #endif
772 #if LIBCURL_VERSION_NUM >= 0x072c00
773         if (ssl_pinnedkey != NULL)
774                 curl_easy_setopt(result, CURLOPT_PINNEDPUBLICKEY, ssl_pinnedkey);
775 #endif
776         if (ssl_cainfo != NULL)
777                 curl_easy_setopt(result, CURLOPT_CAINFO, ssl_cainfo);
778
779         if (curl_low_speed_limit > 0 && curl_low_speed_time > 0) {
780                 curl_easy_setopt(result, CURLOPT_LOW_SPEED_LIMIT,
781                                  curl_low_speed_limit);
782                 curl_easy_setopt(result, CURLOPT_LOW_SPEED_TIME,
783                                  curl_low_speed_time);
784         }
785
786         curl_easy_setopt(result, CURLOPT_MAXREDIRS, 20);
787 #if LIBCURL_VERSION_NUM >= 0x071301
788         curl_easy_setopt(result, CURLOPT_POSTREDIR, CURL_REDIR_POST_ALL);
789 #elif LIBCURL_VERSION_NUM >= 0x071101
790         curl_easy_setopt(result, CURLOPT_POST301, 1);
791 #endif
792 #if LIBCURL_VERSION_NUM >= 0x071304
793         curl_easy_setopt(result, CURLOPT_REDIR_PROTOCOLS,
794                          get_curl_allowed_protocols(0));
795         curl_easy_setopt(result, CURLOPT_PROTOCOLS,
796                          get_curl_allowed_protocols(-1));
797 #else
798         warning("protocol restrictions not applied to curl redirects because\n"
799                 "your curl version is too old (>= 7.19.4)");
800 #endif
801         if (getenv("GIT_CURL_VERBOSE"))
802                 curl_easy_setopt(result, CURLOPT_VERBOSE, 1L);
803         setup_curl_trace(result);
804
805         curl_easy_setopt(result, CURLOPT_USERAGENT,
806                 user_agent ? user_agent : git_user_agent());
807
808         if (curl_ftp_no_epsv)
809                 curl_easy_setopt(result, CURLOPT_FTP_USE_EPSV, 0);
810
811 #ifdef CURLOPT_USE_SSL
812         if (curl_ssl_try)
813                 curl_easy_setopt(result, CURLOPT_USE_SSL, CURLUSESSL_TRY);
814 #endif
815
816         /*
817          * CURL also examines these variables as a fallback; but we need to query
818          * them here in order to decide whether to prompt for missing password (cf.
819          * init_curl_proxy_auth()).
820          *
821          * Unlike many other common environment variables, these are historically
822          * lowercase only. It appears that CURL did not know this and implemented
823          * only uppercase variants, which was later corrected to take both - with
824          * the exception of http_proxy, which is lowercase only also in CURL. As
825          * the lowercase versions are the historical quasi-standard, they take
826          * precedence here, as in CURL.
827          */
828         if (!curl_http_proxy) {
829                 if (http_auth.protocol && !strcmp(http_auth.protocol, "https")) {
830                         var_override(&curl_http_proxy, getenv("HTTPS_PROXY"));
831                         var_override(&curl_http_proxy, getenv("https_proxy"));
832                 } else {
833                         var_override(&curl_http_proxy, getenv("http_proxy"));
834                 }
835                 if (!curl_http_proxy) {
836                         var_override(&curl_http_proxy, getenv("ALL_PROXY"));
837                         var_override(&curl_http_proxy, getenv("all_proxy"));
838                 }
839         }
840
841         if (curl_http_proxy && curl_http_proxy[0] == '\0') {
842                 /*
843                  * Handle case with the empty http.proxy value here to keep
844                  * common code clean.
845                  * NB: empty option disables proxying at all.
846                  */
847                 curl_easy_setopt(result, CURLOPT_PROXY, "");
848         } else if (curl_http_proxy) {
849 #if LIBCURL_VERSION_NUM >= 0x071800
850                 if (starts_with(curl_http_proxy, "socks5h"))
851                         curl_easy_setopt(result,
852                                 CURLOPT_PROXYTYPE, CURLPROXY_SOCKS5_HOSTNAME);
853                 else if (starts_with(curl_http_proxy, "socks5"))
854                         curl_easy_setopt(result,
855                                 CURLOPT_PROXYTYPE, CURLPROXY_SOCKS5);
856                 else if (starts_with(curl_http_proxy, "socks4a"))
857                         curl_easy_setopt(result,
858                                 CURLOPT_PROXYTYPE, CURLPROXY_SOCKS4A);
859                 else if (starts_with(curl_http_proxy, "socks"))
860                         curl_easy_setopt(result,
861                                 CURLOPT_PROXYTYPE, CURLPROXY_SOCKS4);
862 #endif
863                 if (strstr(curl_http_proxy, "://"))
864                         credential_from_url(&proxy_auth, curl_http_proxy);
865                 else {
866                         struct strbuf url = STRBUF_INIT;
867                         strbuf_addf(&url, "http://%s", curl_http_proxy);
868                         credential_from_url(&proxy_auth, url.buf);
869                         strbuf_release(&url);
870                 }
871
872                 if (!proxy_auth.host)
873                         die("Invalid proxy URL '%s'", curl_http_proxy);
874
875                 curl_easy_setopt(result, CURLOPT_PROXY, proxy_auth.host);
876 #if LIBCURL_VERSION_NUM >= 0x071304
877                 var_override(&curl_no_proxy, getenv("NO_PROXY"));
878                 var_override(&curl_no_proxy, getenv("no_proxy"));
879                 curl_easy_setopt(result, CURLOPT_NOPROXY, curl_no_proxy);
880 #endif
881         }
882         init_curl_proxy_auth(result);
883
884         set_curl_keepalive(result);
885
886         return result;
887 }
888
889 static void set_from_env(const char **var, const char *envname)
890 {
891         const char *val = getenv(envname);
892         if (val)
893                 *var = val;
894 }
895
896 void http_init(struct remote *remote, const char *url, int proactive_auth)
897 {
898         char *low_speed_limit;
899         char *low_speed_time;
900         char *normalized_url;
901         struct urlmatch_config config = { STRING_LIST_INIT_DUP };
902
903         config.section = "http";
904         config.key = NULL;
905         config.collect_fn = http_options;
906         config.cascade_fn = git_default_config;
907         config.cb = NULL;
908
909         http_is_verbose = 0;
910         normalized_url = url_normalize(url, &config.url);
911
912         git_config(urlmatch_config_entry, &config);
913         free(normalized_url);
914
915         if (curl_global_init(CURL_GLOBAL_ALL) != CURLE_OK)
916                 die("curl_global_init failed");
917
918         http_proactive_auth = proactive_auth;
919
920         if (remote && remote->http_proxy)
921                 curl_http_proxy = xstrdup(remote->http_proxy);
922
923         if (remote)
924                 var_override(&http_proxy_authmethod, remote->http_proxy_authmethod);
925
926         pragma_header = curl_slist_append(http_copy_default_headers(),
927                 "Pragma: no-cache");
928         no_pragma_header = curl_slist_append(http_copy_default_headers(),
929                 "Pragma:");
930
931 #ifdef USE_CURL_MULTI
932         {
933                 char *http_max_requests = getenv("GIT_HTTP_MAX_REQUESTS");
934                 if (http_max_requests != NULL)
935                         max_requests = atoi(http_max_requests);
936         }
937
938         curlm = curl_multi_init();
939         if (!curlm)
940                 die("curl_multi_init failed");
941 #endif
942
943         if (getenv("GIT_SSL_NO_VERIFY"))
944                 curl_ssl_verify = 0;
945
946         set_from_env(&ssl_cert, "GIT_SSL_CERT");
947 #if LIBCURL_VERSION_NUM >= 0x070903
948         set_from_env(&ssl_key, "GIT_SSL_KEY");
949 #endif
950 #if LIBCURL_VERSION_NUM >= 0x070908
951         set_from_env(&ssl_capath, "GIT_SSL_CAPATH");
952 #endif
953         set_from_env(&ssl_cainfo, "GIT_SSL_CAINFO");
954
955         set_from_env(&user_agent, "GIT_HTTP_USER_AGENT");
956
957         low_speed_limit = getenv("GIT_HTTP_LOW_SPEED_LIMIT");
958         if (low_speed_limit != NULL)
959                 curl_low_speed_limit = strtol(low_speed_limit, NULL, 10);
960         low_speed_time = getenv("GIT_HTTP_LOW_SPEED_TIME");
961         if (low_speed_time != NULL)
962                 curl_low_speed_time = strtol(low_speed_time, NULL, 10);
963
964         if (curl_ssl_verify == -1)
965                 curl_ssl_verify = 1;
966
967         curl_session_count = 0;
968 #ifdef USE_CURL_MULTI
969         if (max_requests < 1)
970                 max_requests = DEFAULT_MAX_REQUESTS;
971 #endif
972
973         if (getenv("GIT_CURL_FTP_NO_EPSV"))
974                 curl_ftp_no_epsv = 1;
975
976         if (url) {
977                 credential_from_url(&http_auth, url);
978                 if (!ssl_cert_password_required &&
979                     getenv("GIT_SSL_CERT_PASSWORD_PROTECTED") &&
980                     starts_with(url, "https://"))
981                         ssl_cert_password_required = 1;
982         }
983
984 #ifndef NO_CURL_EASY_DUPHANDLE
985         curl_default = get_curl_handle();
986 #endif
987 }
988
989 void http_cleanup(void)
990 {
991         struct active_request_slot *slot = active_queue_head;
992
993         while (slot != NULL) {
994                 struct active_request_slot *next = slot->next;
995                 if (slot->curl != NULL) {
996                         xmulti_remove_handle(slot);
997                         curl_easy_cleanup(slot->curl);
998                 }
999                 free(slot);
1000                 slot = next;
1001         }
1002         active_queue_head = NULL;
1003
1004 #ifndef NO_CURL_EASY_DUPHANDLE
1005         curl_easy_cleanup(curl_default);
1006 #endif
1007
1008 #ifdef USE_CURL_MULTI
1009         curl_multi_cleanup(curlm);
1010 #endif
1011         curl_global_cleanup();
1012
1013         curl_slist_free_all(extra_http_headers);
1014         extra_http_headers = NULL;
1015
1016         curl_slist_free_all(pragma_header);
1017         pragma_header = NULL;
1018
1019         curl_slist_free_all(no_pragma_header);
1020         no_pragma_header = NULL;
1021
1022         if (curl_http_proxy) {
1023                 free((void *)curl_http_proxy);
1024                 curl_http_proxy = NULL;
1025         }
1026
1027         if (proxy_auth.password) {
1028                 memset(proxy_auth.password, 0, strlen(proxy_auth.password));
1029                 FREE_AND_NULL(proxy_auth.password);
1030         }
1031
1032         free((void *)curl_proxyuserpwd);
1033         curl_proxyuserpwd = NULL;
1034
1035         free((void *)http_proxy_authmethod);
1036         http_proxy_authmethod = NULL;
1037
1038         if (cert_auth.password != NULL) {
1039                 memset(cert_auth.password, 0, strlen(cert_auth.password));
1040                 FREE_AND_NULL(cert_auth.password);
1041         }
1042         ssl_cert_password_required = 0;
1043
1044         FREE_AND_NULL(cached_accept_language);
1045 }
1046
1047 struct active_request_slot *get_active_slot(void)
1048 {
1049         struct active_request_slot *slot = active_queue_head;
1050         struct active_request_slot *newslot;
1051
1052 #ifdef USE_CURL_MULTI
1053         int num_transfers;
1054
1055         /* Wait for a slot to open up if the queue is full */
1056         while (active_requests >= max_requests) {
1057                 curl_multi_perform(curlm, &num_transfers);
1058                 if (num_transfers < active_requests)
1059                         process_curl_messages();
1060         }
1061 #endif
1062
1063         while (slot != NULL && slot->in_use)
1064                 slot = slot->next;
1065
1066         if (slot == NULL) {
1067                 newslot = xmalloc(sizeof(*newslot));
1068                 newslot->curl = NULL;
1069                 newslot->in_use = 0;
1070                 newslot->next = NULL;
1071
1072                 slot = active_queue_head;
1073                 if (slot == NULL) {
1074                         active_queue_head = newslot;
1075                 } else {
1076                         while (slot->next != NULL)
1077                                 slot = slot->next;
1078                         slot->next = newslot;
1079                 }
1080                 slot = newslot;
1081         }
1082
1083         if (slot->curl == NULL) {
1084 #ifdef NO_CURL_EASY_DUPHANDLE
1085                 slot->curl = get_curl_handle();
1086 #else
1087                 slot->curl = curl_easy_duphandle(curl_default);
1088 #endif
1089                 curl_session_count++;
1090         }
1091
1092         active_requests++;
1093         slot->in_use = 1;
1094         slot->results = NULL;
1095         slot->finished = NULL;
1096         slot->callback_data = NULL;
1097         slot->callback_func = NULL;
1098         curl_easy_setopt(slot->curl, CURLOPT_COOKIEFILE, curl_cookie_file);
1099         if (curl_save_cookies)
1100                 curl_easy_setopt(slot->curl, CURLOPT_COOKIEJAR, curl_cookie_file);
1101         curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, pragma_header);
1102         curl_easy_setopt(slot->curl, CURLOPT_ERRORBUFFER, curl_errorstr);
1103         curl_easy_setopt(slot->curl, CURLOPT_CUSTOMREQUEST, NULL);
1104         curl_easy_setopt(slot->curl, CURLOPT_READFUNCTION, NULL);
1105         curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION, NULL);
1106         curl_easy_setopt(slot->curl, CURLOPT_POSTFIELDS, NULL);
1107         curl_easy_setopt(slot->curl, CURLOPT_UPLOAD, 0);
1108         curl_easy_setopt(slot->curl, CURLOPT_HTTPGET, 1);
1109         curl_easy_setopt(slot->curl, CURLOPT_FAILONERROR, 1);
1110         curl_easy_setopt(slot->curl, CURLOPT_RANGE, NULL);
1111
1112         /*
1113          * Default following to off unless "ALWAYS" is configured; this gives
1114          * callers a sane starting point, and they can tweak for individual
1115          * HTTP_FOLLOW_* cases themselves.
1116          */
1117         if (http_follow_config == HTTP_FOLLOW_ALWAYS)
1118                 curl_easy_setopt(slot->curl, CURLOPT_FOLLOWLOCATION, 1);
1119         else
1120                 curl_easy_setopt(slot->curl, CURLOPT_FOLLOWLOCATION, 0);
1121
1122 #if LIBCURL_VERSION_NUM >= 0x070a08
1123         curl_easy_setopt(slot->curl, CURLOPT_IPRESOLVE, git_curl_ipresolve);
1124 #endif
1125 #ifdef LIBCURL_CAN_HANDLE_AUTH_ANY
1126         curl_easy_setopt(slot->curl, CURLOPT_HTTPAUTH, http_auth_methods);
1127 #endif
1128         if (http_auth.password || curl_empty_auth_enabled())
1129                 init_curl_http_auth(slot->curl);
1130
1131         return slot;
1132 }
1133
1134 int start_active_slot(struct active_request_slot *slot)
1135 {
1136 #ifdef USE_CURL_MULTI
1137         CURLMcode curlm_result = curl_multi_add_handle(curlm, slot->curl);
1138         int num_transfers;
1139
1140         if (curlm_result != CURLM_OK &&
1141             curlm_result != CURLM_CALL_MULTI_PERFORM) {
1142                 warning("curl_multi_add_handle failed: %s",
1143                         curl_multi_strerror(curlm_result));
1144                 active_requests--;
1145                 slot->in_use = 0;
1146                 return 0;
1147         }
1148
1149         /*
1150          * We know there must be something to do, since we just added
1151          * something.
1152          */
1153         curl_multi_perform(curlm, &num_transfers);
1154 #endif
1155         return 1;
1156 }
1157
1158 #ifdef USE_CURL_MULTI
1159 struct fill_chain {
1160         void *data;
1161         int (*fill)(void *);
1162         struct fill_chain *next;
1163 };
1164
1165 static struct fill_chain *fill_cfg;
1166
1167 void add_fill_function(void *data, int (*fill)(void *))
1168 {
1169         struct fill_chain *new = xmalloc(sizeof(*new));
1170         struct fill_chain **linkp = &fill_cfg;
1171         new->data = data;
1172         new->fill = fill;
1173         new->next = NULL;
1174         while (*linkp)
1175                 linkp = &(*linkp)->next;
1176         *linkp = new;
1177 }
1178
1179 void fill_active_slots(void)
1180 {
1181         struct active_request_slot *slot = active_queue_head;
1182
1183         while (active_requests < max_requests) {
1184                 struct fill_chain *fill;
1185                 for (fill = fill_cfg; fill; fill = fill->next)
1186                         if (fill->fill(fill->data))
1187                                 break;
1188
1189                 if (!fill)
1190                         break;
1191         }
1192
1193         while (slot != NULL) {
1194                 if (!slot->in_use && slot->curl != NULL
1195                         && curl_session_count > min_curl_sessions) {
1196                         curl_easy_cleanup(slot->curl);
1197                         slot->curl = NULL;
1198                         curl_session_count--;
1199                 }
1200                 slot = slot->next;
1201         }
1202 }
1203
1204 void step_active_slots(void)
1205 {
1206         int num_transfers;
1207         CURLMcode curlm_result;
1208
1209         do {
1210                 curlm_result = curl_multi_perform(curlm, &num_transfers);
1211         } while (curlm_result == CURLM_CALL_MULTI_PERFORM);
1212         if (num_transfers < active_requests) {
1213                 process_curl_messages();
1214                 fill_active_slots();
1215         }
1216 }
1217 #endif
1218
1219 void run_active_slot(struct active_request_slot *slot)
1220 {
1221 #ifdef USE_CURL_MULTI
1222         fd_set readfds;
1223         fd_set writefds;
1224         fd_set excfds;
1225         int max_fd;
1226         struct timeval select_timeout;
1227         int finished = 0;
1228
1229         slot->finished = &finished;
1230         while (!finished) {
1231                 step_active_slots();
1232
1233                 if (slot->in_use) {
1234 #if LIBCURL_VERSION_NUM >= 0x070f04
1235                         long curl_timeout;
1236                         curl_multi_timeout(curlm, &curl_timeout);
1237                         if (curl_timeout == 0) {
1238                                 continue;
1239                         } else if (curl_timeout == -1) {
1240                                 select_timeout.tv_sec  = 0;
1241                                 select_timeout.tv_usec = 50000;
1242                         } else {
1243                                 select_timeout.tv_sec  =  curl_timeout / 1000;
1244                                 select_timeout.tv_usec = (curl_timeout % 1000) * 1000;
1245                         }
1246 #else
1247                         select_timeout.tv_sec  = 0;
1248                         select_timeout.tv_usec = 50000;
1249 #endif
1250
1251                         max_fd = -1;
1252                         FD_ZERO(&readfds);
1253                         FD_ZERO(&writefds);
1254                         FD_ZERO(&excfds);
1255                         curl_multi_fdset(curlm, &readfds, &writefds, &excfds, &max_fd);
1256
1257                         /*
1258                          * It can happen that curl_multi_timeout returns a pathologically
1259                          * long timeout when curl_multi_fdset returns no file descriptors
1260                          * to read.  See commit message for more details.
1261                          */
1262                         if (max_fd < 0 &&
1263                             (select_timeout.tv_sec > 0 ||
1264                              select_timeout.tv_usec > 50000)) {
1265                                 select_timeout.tv_sec  = 0;
1266                                 select_timeout.tv_usec = 50000;
1267                         }
1268
1269                         select(max_fd+1, &readfds, &writefds, &excfds, &select_timeout);
1270                 }
1271         }
1272 #else
1273         while (slot->in_use) {
1274                 slot->curl_result = curl_easy_perform(slot->curl);
1275                 finish_active_slot(slot);
1276         }
1277 #endif
1278 }
1279
1280 static void release_active_slot(struct active_request_slot *slot)
1281 {
1282         closedown_active_slot(slot);
1283         if (slot->curl) {
1284                 xmulti_remove_handle(slot);
1285                 if (curl_session_count > min_curl_sessions) {
1286                         curl_easy_cleanup(slot->curl);
1287                         slot->curl = NULL;
1288                         curl_session_count--;
1289                 }
1290         }
1291 #ifdef USE_CURL_MULTI
1292         fill_active_slots();
1293 #endif
1294 }
1295
1296 void finish_all_active_slots(void)
1297 {
1298         struct active_request_slot *slot = active_queue_head;
1299
1300         while (slot != NULL)
1301                 if (slot->in_use) {
1302                         run_active_slot(slot);
1303                         slot = active_queue_head;
1304                 } else {
1305                         slot = slot->next;
1306                 }
1307 }
1308
1309 /* Helpers for modifying and creating URLs */
1310 static inline int needs_quote(int ch)
1311 {
1312         if (((ch >= 'A') && (ch <= 'Z'))
1313                         || ((ch >= 'a') && (ch <= 'z'))
1314                         || ((ch >= '0') && (ch <= '9'))
1315                         || (ch == '/')
1316                         || (ch == '-')
1317                         || (ch == '.'))
1318                 return 0;
1319         return 1;
1320 }
1321
1322 static char *quote_ref_url(const char *base, const char *ref)
1323 {
1324         struct strbuf buf = STRBUF_INIT;
1325         const char *cp;
1326         int ch;
1327
1328         end_url_with_slash(&buf, base);
1329
1330         for (cp = ref; (ch = *cp) != 0; cp++)
1331                 if (needs_quote(ch))
1332                         strbuf_addf(&buf, "%%%02x", ch);
1333                 else
1334                         strbuf_addch(&buf, *cp);
1335
1336         return strbuf_detach(&buf, NULL);
1337 }
1338
1339 void append_remote_object_url(struct strbuf *buf, const char *url,
1340                               const char *hex,
1341                               int only_two_digit_prefix)
1342 {
1343         end_url_with_slash(buf, url);
1344
1345         strbuf_addf(buf, "objects/%.*s/", 2, hex);
1346         if (!only_two_digit_prefix)
1347                 strbuf_addstr(buf, hex + 2);
1348 }
1349
1350 char *get_remote_object_url(const char *url, const char *hex,
1351                             int only_two_digit_prefix)
1352 {
1353         struct strbuf buf = STRBUF_INIT;
1354         append_remote_object_url(&buf, url, hex, only_two_digit_prefix);
1355         return strbuf_detach(&buf, NULL);
1356 }
1357
1358 static int handle_curl_result(struct slot_results *results)
1359 {
1360         /*
1361          * If we see a failing http code with CURLE_OK, we have turned off
1362          * FAILONERROR (to keep the server's custom error response), and should
1363          * translate the code into failure here.
1364          *
1365          * Likewise, if we see a redirect (30x code), that means we turned off
1366          * redirect-following, and we should treat the result as an error.
1367          */
1368         if (results->curl_result == CURLE_OK &&
1369             results->http_code >= 300) {
1370                 results->curl_result = CURLE_HTTP_RETURNED_ERROR;
1371                 /*
1372                  * Normally curl will already have put the "reason phrase"
1373                  * from the server into curl_errorstr; unfortunately without
1374                  * FAILONERROR it is lost, so we can give only the numeric
1375                  * status code.
1376                  */
1377                 xsnprintf(curl_errorstr, sizeof(curl_errorstr),
1378                           "The requested URL returned error: %ld",
1379                           results->http_code);
1380         }
1381
1382         if (results->curl_result == CURLE_OK) {
1383                 credential_approve(&http_auth);
1384                 if (proxy_auth.password)
1385                         credential_approve(&proxy_auth);
1386                 return HTTP_OK;
1387         } else if (missing_target(results))
1388                 return HTTP_MISSING_TARGET;
1389         else if (results->http_code == 401) {
1390                 if (http_auth.username && http_auth.password) {
1391                         credential_reject(&http_auth);
1392                         return HTTP_NOAUTH;
1393                 } else {
1394 #ifdef LIBCURL_CAN_HANDLE_AUTH_ANY
1395                         http_auth_methods &= ~CURLAUTH_GSSNEGOTIATE;
1396                         if (results->auth_avail) {
1397                                 http_auth_methods &= results->auth_avail;
1398                                 http_auth_methods_restricted = 1;
1399                         }
1400 #endif
1401                         return HTTP_REAUTH;
1402                 }
1403         } else {
1404                 if (results->http_connectcode == 407)
1405                         credential_reject(&proxy_auth);
1406 #if LIBCURL_VERSION_NUM >= 0x070c00
1407                 if (!curl_errorstr[0])
1408                         strlcpy(curl_errorstr,
1409                                 curl_easy_strerror(results->curl_result),
1410                                 sizeof(curl_errorstr));
1411 #endif
1412                 return HTTP_ERROR;
1413         }
1414 }
1415
1416 int run_one_slot(struct active_request_slot *slot,
1417                  struct slot_results *results)
1418 {
1419         slot->results = results;
1420         if (!start_active_slot(slot)) {
1421                 xsnprintf(curl_errorstr, sizeof(curl_errorstr),
1422                           "failed to start HTTP request");
1423                 return HTTP_START_FAILED;
1424         }
1425
1426         run_active_slot(slot);
1427         return handle_curl_result(results);
1428 }
1429
1430 struct curl_slist *http_copy_default_headers(void)
1431 {
1432         struct curl_slist *headers = NULL, *h;
1433
1434         for (h = extra_http_headers; h; h = h->next)
1435                 headers = curl_slist_append(headers, h->data);
1436
1437         return headers;
1438 }
1439
1440 static CURLcode curlinfo_strbuf(CURL *curl, CURLINFO info, struct strbuf *buf)
1441 {
1442         char *ptr;
1443         CURLcode ret;
1444
1445         strbuf_reset(buf);
1446         ret = curl_easy_getinfo(curl, info, &ptr);
1447         if (!ret && ptr)
1448                 strbuf_addstr(buf, ptr);
1449         return ret;
1450 }
1451
1452 /*
1453  * Check for and extract a content-type parameter. "raw"
1454  * should be positioned at the start of the potential
1455  * parameter, with any whitespace already removed.
1456  *
1457  * "name" is the name of the parameter. The value is appended
1458  * to "out".
1459  */
1460 static int extract_param(const char *raw, const char *name,
1461                          struct strbuf *out)
1462 {
1463         size_t len = strlen(name);
1464
1465         if (strncasecmp(raw, name, len))
1466                 return -1;
1467         raw += len;
1468
1469         if (*raw != '=')
1470                 return -1;
1471         raw++;
1472
1473         while (*raw && !isspace(*raw) && *raw != ';')
1474                 strbuf_addch(out, *raw++);
1475         return 0;
1476 }
1477
1478 /*
1479  * Extract a normalized version of the content type, with any
1480  * spaces suppressed, all letters lowercased, and no trailing ";"
1481  * or parameters.
1482  *
1483  * Note that we will silently remove even invalid whitespace. For
1484  * example, "text / plain" is specifically forbidden by RFC 2616,
1485  * but "text/plain" is the only reasonable output, and this keeps
1486  * our code simple.
1487  *
1488  * If the "charset" argument is not NULL, store the value of any
1489  * charset parameter there.
1490  *
1491  * Example:
1492  *   "TEXT/PLAIN; charset=utf-8" -> "text/plain", "utf-8"
1493  *   "text / plain" -> "text/plain"
1494  */
1495 static void extract_content_type(struct strbuf *raw, struct strbuf *type,
1496                                  struct strbuf *charset)
1497 {
1498         const char *p;
1499
1500         strbuf_reset(type);
1501         strbuf_grow(type, raw->len);
1502         for (p = raw->buf; *p; p++) {
1503                 if (isspace(*p))
1504                         continue;
1505                 if (*p == ';') {
1506                         p++;
1507                         break;
1508                 }
1509                 strbuf_addch(type, tolower(*p));
1510         }
1511
1512         if (!charset)
1513                 return;
1514
1515         strbuf_reset(charset);
1516         while (*p) {
1517                 while (isspace(*p) || *p == ';')
1518                         p++;
1519                 if (!extract_param(p, "charset", charset))
1520                         return;
1521                 while (*p && !isspace(*p))
1522                         p++;
1523         }
1524
1525         if (!charset->len && starts_with(type->buf, "text/"))
1526                 strbuf_addstr(charset, "ISO-8859-1");
1527 }
1528
1529 static void write_accept_language(struct strbuf *buf)
1530 {
1531         /*
1532          * MAX_DECIMAL_PLACES must not be larger than 3. If it is larger than
1533          * that, q-value will be smaller than 0.001, the minimum q-value the
1534          * HTTP specification allows. See
1535          * http://tools.ietf.org/html/rfc7231#section-5.3.1 for q-value.
1536          */
1537         const int MAX_DECIMAL_PLACES = 3;
1538         const int MAX_LANGUAGE_TAGS = 1000;
1539         const int MAX_ACCEPT_LANGUAGE_HEADER_SIZE = 4000;
1540         char **language_tags = NULL;
1541         int num_langs = 0;
1542         const char *s = get_preferred_languages();
1543         int i;
1544         struct strbuf tag = STRBUF_INIT;
1545
1546         /* Don't add Accept-Language header if no language is preferred. */
1547         if (!s)
1548                 return;
1549
1550         /*
1551          * Split the colon-separated string of preferred languages into
1552          * language_tags array.
1553          */
1554         do {
1555                 /* collect language tag */
1556                 for (; *s && (isalnum(*s) || *s == '_'); s++)
1557                         strbuf_addch(&tag, *s == '_' ? '-' : *s);
1558
1559                 /* skip .codeset, @modifier and any other unnecessary parts */
1560                 while (*s && *s != ':')
1561                         s++;
1562
1563                 if (tag.len) {
1564                         num_langs++;
1565                         REALLOC_ARRAY(language_tags, num_langs);
1566                         language_tags[num_langs - 1] = strbuf_detach(&tag, NULL);
1567                         if (num_langs >= MAX_LANGUAGE_TAGS - 1) /* -1 for '*' */
1568                                 break;
1569                 }
1570         } while (*s++);
1571
1572         /* write Accept-Language header into buf */
1573         if (num_langs) {
1574                 int last_buf_len = 0;
1575                 int max_q;
1576                 int decimal_places;
1577                 char q_format[32];
1578
1579                 /* add '*' */
1580                 REALLOC_ARRAY(language_tags, num_langs + 1);
1581                 language_tags[num_langs++] = "*"; /* it's OK; this won't be freed */
1582
1583                 /* compute decimal_places */
1584                 for (max_q = 1, decimal_places = 0;
1585                      max_q < num_langs && decimal_places <= MAX_DECIMAL_PLACES;
1586                      decimal_places++, max_q *= 10)
1587                         ;
1588
1589                 xsnprintf(q_format, sizeof(q_format), ";q=0.%%0%dd", decimal_places);
1590
1591                 strbuf_addstr(buf, "Accept-Language: ");
1592
1593                 for (i = 0; i < num_langs; i++) {
1594                         if (i > 0)
1595                                 strbuf_addstr(buf, ", ");
1596
1597                         strbuf_addstr(buf, language_tags[i]);
1598
1599                         if (i > 0)
1600                                 strbuf_addf(buf, q_format, max_q - i);
1601
1602                         if (buf->len > MAX_ACCEPT_LANGUAGE_HEADER_SIZE) {
1603                                 strbuf_remove(buf, last_buf_len, buf->len - last_buf_len);
1604                                 break;
1605                         }
1606
1607                         last_buf_len = buf->len;
1608                 }
1609         }
1610
1611         /* free language tags -- last one is a static '*' */
1612         for (i = 0; i < num_langs - 1; i++)
1613                 free(language_tags[i]);
1614         free(language_tags);
1615 }
1616
1617 /*
1618  * Get an Accept-Language header which indicates user's preferred languages.
1619  *
1620  * Examples:
1621  *   LANGUAGE= -> ""
1622  *   LANGUAGE=ko:en -> "Accept-Language: ko, en; q=0.9, *; q=0.1"
1623  *   LANGUAGE=ko_KR.UTF-8:sr@latin -> "Accept-Language: ko-KR, sr; q=0.9, *; q=0.1"
1624  *   LANGUAGE=ko LANG=en_US.UTF-8 -> "Accept-Language: ko, *; q=0.1"
1625  *   LANGUAGE= LANG=en_US.UTF-8 -> "Accept-Language: en-US, *; q=0.1"
1626  *   LANGUAGE= LANG=C -> ""
1627  */
1628 static const char *get_accept_language(void)
1629 {
1630         if (!cached_accept_language) {
1631                 struct strbuf buf = STRBUF_INIT;
1632                 write_accept_language(&buf);
1633                 if (buf.len > 0)
1634                         cached_accept_language = strbuf_detach(&buf, NULL);
1635         }
1636
1637         return cached_accept_language;
1638 }
1639
1640 static void http_opt_request_remainder(CURL *curl, off_t pos)
1641 {
1642         char buf[128];
1643         xsnprintf(buf, sizeof(buf), "%"PRIuMAX"-", (uintmax_t)pos);
1644         curl_easy_setopt(curl, CURLOPT_RANGE, buf);
1645 }
1646
1647 /* http_request() targets */
1648 #define HTTP_REQUEST_STRBUF     0
1649 #define HTTP_REQUEST_FILE       1
1650
1651 static int http_request(const char *url,
1652                         void *result, int target,
1653                         const struct http_get_options *options)
1654 {
1655         struct active_request_slot *slot;
1656         struct slot_results results;
1657         struct curl_slist *headers = http_copy_default_headers();
1658         struct strbuf buf = STRBUF_INIT;
1659         const char *accept_language;
1660         int ret;
1661
1662         slot = get_active_slot();
1663         curl_easy_setopt(slot->curl, CURLOPT_HTTPGET, 1);
1664
1665         if (result == NULL) {
1666                 curl_easy_setopt(slot->curl, CURLOPT_NOBODY, 1);
1667         } else {
1668                 curl_easy_setopt(slot->curl, CURLOPT_NOBODY, 0);
1669                 curl_easy_setopt(slot->curl, CURLOPT_FILE, result);
1670
1671                 if (target == HTTP_REQUEST_FILE) {
1672                         off_t posn = ftello(result);
1673                         curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION,
1674                                          fwrite);
1675                         if (posn > 0)
1676                                 http_opt_request_remainder(slot->curl, posn);
1677                 } else
1678                         curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION,
1679                                          fwrite_buffer);
1680         }
1681
1682         accept_language = get_accept_language();
1683
1684         if (accept_language)
1685                 headers = curl_slist_append(headers, accept_language);
1686
1687         strbuf_addstr(&buf, "Pragma:");
1688         if (options && options->no_cache)
1689                 strbuf_addstr(&buf, " no-cache");
1690         if (options && options->keep_error)
1691                 curl_easy_setopt(slot->curl, CURLOPT_FAILONERROR, 0);
1692         if (options && options->initial_request &&
1693             http_follow_config == HTTP_FOLLOW_INITIAL)
1694                 curl_easy_setopt(slot->curl, CURLOPT_FOLLOWLOCATION, 1);
1695
1696         headers = curl_slist_append(headers, buf.buf);
1697
1698         curl_easy_setopt(slot->curl, CURLOPT_URL, url);
1699         curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, headers);
1700         curl_easy_setopt(slot->curl, CURLOPT_ENCODING, "gzip");
1701
1702         ret = run_one_slot(slot, &results);
1703
1704         if (options && options->content_type) {
1705                 struct strbuf raw = STRBUF_INIT;
1706                 curlinfo_strbuf(slot->curl, CURLINFO_CONTENT_TYPE, &raw);
1707                 extract_content_type(&raw, options->content_type,
1708                                      options->charset);
1709                 strbuf_release(&raw);
1710         }
1711
1712         if (options && options->effective_url)
1713                 curlinfo_strbuf(slot->curl, CURLINFO_EFFECTIVE_URL,
1714                                 options->effective_url);
1715
1716         curl_slist_free_all(headers);
1717         strbuf_release(&buf);
1718
1719         return ret;
1720 }
1721
1722 /*
1723  * Update the "base" url to a more appropriate value, as deduced by
1724  * redirects seen when requesting a URL starting with "url".
1725  *
1726  * The "asked" parameter is a URL that we asked curl to access, and must begin
1727  * with "base".
1728  *
1729  * The "got" parameter is the URL that curl reported to us as where we ended
1730  * up.
1731  *
1732  * Returns 1 if we updated the base url, 0 otherwise.
1733  *
1734  * Our basic strategy is to compare "base" and "asked" to find the bits
1735  * specific to our request. We then strip those bits off of "got" to yield the
1736  * new base. So for example, if our base is "http://example.com/foo.git",
1737  * and we ask for "http://example.com/foo.git/info/refs", we might end up
1738  * with "https://other.example.com/foo.git/info/refs". We would want the
1739  * new URL to become "https://other.example.com/foo.git".
1740  *
1741  * Note that this assumes a sane redirect scheme. It's entirely possible
1742  * in the example above to end up at a URL that does not even end in
1743  * "info/refs".  In such a case we die. There's not much we can do, such a
1744  * scheme is unlikely to represent a real git repository, and failing to
1745  * rewrite the base opens options for malicious redirects to do funny things.
1746  */
1747 static int update_url_from_redirect(struct strbuf *base,
1748                                     const char *asked,
1749                                     const struct strbuf *got)
1750 {
1751         const char *tail;
1752         size_t new_len;
1753
1754         if (!strcmp(asked, got->buf))
1755                 return 0;
1756
1757         if (!skip_prefix(asked, base->buf, &tail))
1758                 die("BUG: update_url_from_redirect: %s is not a superset of %s",
1759                     asked, base->buf);
1760
1761         new_len = got->len;
1762         if (!strip_suffix_mem(got->buf, &new_len, tail))
1763                 die(_("unable to update url base from redirection:\n"
1764                       "  asked for: %s\n"
1765                       "   redirect: %s"),
1766                     asked, got->buf);
1767
1768         strbuf_reset(base);
1769         strbuf_add(base, got->buf, new_len);
1770
1771         return 1;
1772 }
1773
1774 static int http_request_reauth(const char *url,
1775                                void *result, int target,
1776                                struct http_get_options *options)
1777 {
1778         int ret = http_request(url, result, target, options);
1779
1780         if (ret != HTTP_OK && ret != HTTP_REAUTH)
1781                 return ret;
1782
1783         if (options && options->effective_url && options->base_url) {
1784                 if (update_url_from_redirect(options->base_url,
1785                                              url, options->effective_url)) {
1786                         credential_from_url(&http_auth, options->base_url->buf);
1787                         url = options->effective_url->buf;
1788                 }
1789         }
1790
1791         if (ret != HTTP_REAUTH)
1792                 return ret;
1793
1794         /*
1795          * If we are using KEEP_ERROR, the previous request may have
1796          * put cruft into our output stream; we should clear it out before
1797          * making our next request. We only know how to do this for
1798          * the strbuf case, but that is enough to satisfy current callers.
1799          */
1800         if (options && options->keep_error) {
1801                 switch (target) {
1802                 case HTTP_REQUEST_STRBUF:
1803                         strbuf_reset(result);
1804                         break;
1805                 default:
1806                         die("BUG: HTTP_KEEP_ERROR is only supported with strbufs");
1807                 }
1808         }
1809
1810         credential_fill(&http_auth);
1811
1812         return http_request(url, result, target, options);
1813 }
1814
1815 int http_get_strbuf(const char *url,
1816                     struct strbuf *result,
1817                     struct http_get_options *options)
1818 {
1819         return http_request_reauth(url, result, HTTP_REQUEST_STRBUF, options);
1820 }
1821
1822 /*
1823  * Downloads a URL and stores the result in the given file.
1824  *
1825  * If a previous interrupted download is detected (i.e. a previous temporary
1826  * file is still around) the download is resumed.
1827  */
1828 static int http_get_file(const char *url, const char *filename,
1829                          struct http_get_options *options)
1830 {
1831         int ret;
1832         struct strbuf tmpfile = STRBUF_INIT;
1833         FILE *result;
1834
1835         strbuf_addf(&tmpfile, "%s.temp", filename);
1836         result = fopen(tmpfile.buf, "a");
1837         if (!result) {
1838                 error("Unable to open local file %s", tmpfile.buf);
1839                 ret = HTTP_ERROR;
1840                 goto cleanup;
1841         }
1842
1843         ret = http_request_reauth(url, result, HTTP_REQUEST_FILE, options);
1844         fclose(result);
1845
1846         if (ret == HTTP_OK && finalize_object_file(tmpfile.buf, filename))
1847                 ret = HTTP_ERROR;
1848 cleanup:
1849         strbuf_release(&tmpfile);
1850         return ret;
1851 }
1852
1853 int http_fetch_ref(const char *base, struct ref *ref)
1854 {
1855         struct http_get_options options = {0};
1856         char *url;
1857         struct strbuf buffer = STRBUF_INIT;
1858         int ret = -1;
1859
1860         options.no_cache = 1;
1861
1862         url = quote_ref_url(base, ref->name);
1863         if (http_get_strbuf(url, &buffer, &options) == HTTP_OK) {
1864                 strbuf_rtrim(&buffer);
1865                 if (buffer.len == 40)
1866                         ret = get_oid_hex(buffer.buf, &ref->old_oid);
1867                 else if (starts_with(buffer.buf, "ref: ")) {
1868                         ref->symref = xstrdup(buffer.buf + 5);
1869                         ret = 0;
1870                 }
1871         }
1872
1873         strbuf_release(&buffer);
1874         free(url);
1875         return ret;
1876 }
1877
1878 /* Helpers for fetching packs */
1879 static char *fetch_pack_index(unsigned char *sha1, const char *base_url)
1880 {
1881         char *url, *tmp;
1882         struct strbuf buf = STRBUF_INIT;
1883
1884         if (http_is_verbose)
1885                 fprintf(stderr, "Getting index for pack %s\n", sha1_to_hex(sha1));
1886
1887         end_url_with_slash(&buf, base_url);
1888         strbuf_addf(&buf, "objects/pack/pack-%s.idx", sha1_to_hex(sha1));
1889         url = strbuf_detach(&buf, NULL);
1890
1891         strbuf_addf(&buf, "%s.temp", sha1_pack_index_name(sha1));
1892         tmp = strbuf_detach(&buf, NULL);
1893
1894         if (http_get_file(url, tmp, NULL) != HTTP_OK) {
1895                 error("Unable to get pack index %s", url);
1896                 FREE_AND_NULL(tmp);
1897         }
1898
1899         free(url);
1900         return tmp;
1901 }
1902
1903 static int fetch_and_setup_pack_index(struct packed_git **packs_head,
1904         unsigned char *sha1, const char *base_url)
1905 {
1906         struct packed_git *new_pack;
1907         char *tmp_idx = NULL;
1908         int ret;
1909
1910         if (has_pack_index(sha1)) {
1911                 new_pack = parse_pack_index(sha1, sha1_pack_index_name(sha1));
1912                 if (!new_pack)
1913                         return -1; /* parse_pack_index() already issued error message */
1914                 goto add_pack;
1915         }
1916
1917         tmp_idx = fetch_pack_index(sha1, base_url);
1918         if (!tmp_idx)
1919                 return -1;
1920
1921         new_pack = parse_pack_index(sha1, tmp_idx);
1922         if (!new_pack) {
1923                 unlink(tmp_idx);
1924                 free(tmp_idx);
1925
1926                 return -1; /* parse_pack_index() already issued error message */
1927         }
1928
1929         ret = verify_pack_index(new_pack);
1930         if (!ret) {
1931                 close_pack_index(new_pack);
1932                 ret = finalize_object_file(tmp_idx, sha1_pack_index_name(sha1));
1933         }
1934         free(tmp_idx);
1935         if (ret)
1936                 return -1;
1937
1938 add_pack:
1939         new_pack->next = *packs_head;
1940         *packs_head = new_pack;
1941         return 0;
1942 }
1943
1944 int http_get_info_packs(const char *base_url, struct packed_git **packs_head)
1945 {
1946         struct http_get_options options = {0};
1947         int ret = 0, i = 0;
1948         char *url, *data;
1949         struct strbuf buf = STRBUF_INIT;
1950         unsigned char sha1[20];
1951
1952         end_url_with_slash(&buf, base_url);
1953         strbuf_addstr(&buf, "objects/info/packs");
1954         url = strbuf_detach(&buf, NULL);
1955
1956         options.no_cache = 1;
1957         ret = http_get_strbuf(url, &buf, &options);
1958         if (ret != HTTP_OK)
1959                 goto cleanup;
1960
1961         data = buf.buf;
1962         while (i < buf.len) {
1963                 switch (data[i]) {
1964                 case 'P':
1965                         i++;
1966                         if (i + 52 <= buf.len &&
1967                             starts_with(data + i, " pack-") &&
1968                             starts_with(data + i + 46, ".pack\n")) {
1969                                 get_sha1_hex(data + i + 6, sha1);
1970                                 fetch_and_setup_pack_index(packs_head, sha1,
1971                                                       base_url);
1972                                 i += 51;
1973                                 break;
1974                         }
1975                 default:
1976                         while (i < buf.len && data[i] != '\n')
1977                                 i++;
1978                 }
1979                 i++;
1980         }
1981
1982 cleanup:
1983         free(url);
1984         return ret;
1985 }
1986
1987 void release_http_pack_request(struct http_pack_request *preq)
1988 {
1989         if (preq->packfile != NULL) {
1990                 fclose(preq->packfile);
1991                 preq->packfile = NULL;
1992         }
1993         preq->slot = NULL;
1994         free(preq->url);
1995         free(preq);
1996 }
1997
1998 int finish_http_pack_request(struct http_pack_request *preq)
1999 {
2000         struct packed_git **lst;
2001         struct packed_git *p = preq->target;
2002         char *tmp_idx;
2003         size_t len;
2004         struct child_process ip = CHILD_PROCESS_INIT;
2005         const char *ip_argv[8];
2006
2007         close_pack_index(p);
2008
2009         fclose(preq->packfile);
2010         preq->packfile = NULL;
2011
2012         lst = preq->lst;
2013         while (*lst != p)
2014                 lst = &((*lst)->next);
2015         *lst = (*lst)->next;
2016
2017         if (!strip_suffix(preq->tmpfile, ".pack.temp", &len))
2018                 die("BUG: pack tmpfile does not end in .pack.temp?");
2019         tmp_idx = xstrfmt("%.*s.idx.temp", (int)len, preq->tmpfile);
2020
2021         ip_argv[0] = "index-pack";
2022         ip_argv[1] = "-o";
2023         ip_argv[2] = tmp_idx;
2024         ip_argv[3] = preq->tmpfile;
2025         ip_argv[4] = NULL;
2026
2027         ip.argv = ip_argv;
2028         ip.git_cmd = 1;
2029         ip.no_stdin = 1;
2030         ip.no_stdout = 1;
2031
2032         if (run_command(&ip)) {
2033                 unlink(preq->tmpfile);
2034                 unlink(tmp_idx);
2035                 free(tmp_idx);
2036                 return -1;
2037         }
2038
2039         unlink(sha1_pack_index_name(p->sha1));
2040
2041         if (finalize_object_file(preq->tmpfile, sha1_pack_name(p->sha1))
2042          || finalize_object_file(tmp_idx, sha1_pack_index_name(p->sha1))) {
2043                 free(tmp_idx);
2044                 return -1;
2045         }
2046
2047         install_packed_git(p);
2048         free(tmp_idx);
2049         return 0;
2050 }
2051
2052 struct http_pack_request *new_http_pack_request(
2053         struct packed_git *target, const char *base_url)
2054 {
2055         off_t prev_posn = 0;
2056         struct strbuf buf = STRBUF_INIT;
2057         struct http_pack_request *preq;
2058
2059         preq = xcalloc(1, sizeof(*preq));
2060         preq->target = target;
2061
2062         end_url_with_slash(&buf, base_url);
2063         strbuf_addf(&buf, "objects/pack/pack-%s.pack",
2064                 sha1_to_hex(target->sha1));
2065         preq->url = strbuf_detach(&buf, NULL);
2066
2067         snprintf(preq->tmpfile, sizeof(preq->tmpfile), "%s.temp",
2068                 sha1_pack_name(target->sha1));
2069         preq->packfile = fopen(preq->tmpfile, "a");
2070         if (!preq->packfile) {
2071                 error("Unable to open local file %s for pack",
2072                       preq->tmpfile);
2073                 goto abort;
2074         }
2075
2076         preq->slot = get_active_slot();
2077         curl_easy_setopt(preq->slot->curl, CURLOPT_FILE, preq->packfile);
2078         curl_easy_setopt(preq->slot->curl, CURLOPT_WRITEFUNCTION, fwrite);
2079         curl_easy_setopt(preq->slot->curl, CURLOPT_URL, preq->url);
2080         curl_easy_setopt(preq->slot->curl, CURLOPT_HTTPHEADER,
2081                 no_pragma_header);
2082
2083         /*
2084          * If there is data present from a previous transfer attempt,
2085          * resume where it left off
2086          */
2087         prev_posn = ftello(preq->packfile);
2088         if (prev_posn>0) {
2089                 if (http_is_verbose)
2090                         fprintf(stderr,
2091                                 "Resuming fetch of pack %s at byte %"PRIuMAX"\n",
2092                                 sha1_to_hex(target->sha1), (uintmax_t)prev_posn);
2093                 http_opt_request_remainder(preq->slot->curl, prev_posn);
2094         }
2095
2096         return preq;
2097
2098 abort:
2099         free(preq->url);
2100         free(preq);
2101         return NULL;
2102 }
2103
2104 /* Helpers for fetching objects (loose) */
2105 static size_t fwrite_sha1_file(char *ptr, size_t eltsize, size_t nmemb,
2106                                void *data)
2107 {
2108         unsigned char expn[4096];
2109         size_t size = eltsize * nmemb;
2110         int posn = 0;
2111         struct http_object_request *freq = data;
2112         struct active_request_slot *slot = freq->slot;
2113
2114         if (slot) {
2115                 CURLcode c = curl_easy_getinfo(slot->curl, CURLINFO_HTTP_CODE,
2116                                                 &slot->http_code);
2117                 if (c != CURLE_OK)
2118                         die("BUG: curl_easy_getinfo for HTTP code failed: %s",
2119                                 curl_easy_strerror(c));
2120                 if (slot->http_code >= 300)
2121                         return size;
2122         }
2123
2124         do {
2125                 ssize_t retval = xwrite(freq->localfile,
2126                                         (char *) ptr + posn, size - posn);
2127                 if (retval < 0)
2128                         return posn;
2129                 posn += retval;
2130         } while (posn < size);
2131
2132         freq->stream.avail_in = size;
2133         freq->stream.next_in = (void *)ptr;
2134         do {
2135                 freq->stream.next_out = expn;
2136                 freq->stream.avail_out = sizeof(expn);
2137                 freq->zret = git_inflate(&freq->stream, Z_SYNC_FLUSH);
2138                 git_SHA1_Update(&freq->c, expn,
2139                                 sizeof(expn) - freq->stream.avail_out);
2140         } while (freq->stream.avail_in && freq->zret == Z_OK);
2141         return size;
2142 }
2143
2144 struct http_object_request *new_http_object_request(const char *base_url,
2145         unsigned char *sha1)
2146 {
2147         char *hex = sha1_to_hex(sha1);
2148         const char *filename;
2149         char prevfile[PATH_MAX];
2150         int prevlocal;
2151         char prev_buf[PREV_BUF_SIZE];
2152         ssize_t prev_read = 0;
2153         off_t prev_posn = 0;
2154         struct http_object_request *freq;
2155
2156         freq = xcalloc(1, sizeof(*freq));
2157         hashcpy(freq->sha1, sha1);
2158         freq->localfile = -1;
2159
2160         filename = sha1_file_name(sha1);
2161         snprintf(freq->tmpfile, sizeof(freq->tmpfile),
2162                  "%s.temp", filename);
2163
2164         snprintf(prevfile, sizeof(prevfile), "%s.prev", filename);
2165         unlink_or_warn(prevfile);
2166         rename(freq->tmpfile, prevfile);
2167         unlink_or_warn(freq->tmpfile);
2168
2169         if (freq->localfile != -1)
2170                 error("fd leakage in start: %d", freq->localfile);
2171         freq->localfile = open(freq->tmpfile,
2172                                O_WRONLY | O_CREAT | O_EXCL, 0666);
2173         /*
2174          * This could have failed due to the "lazy directory creation";
2175          * try to mkdir the last path component.
2176          */
2177         if (freq->localfile < 0 && errno == ENOENT) {
2178                 char *dir = strrchr(freq->tmpfile, '/');
2179                 if (dir) {
2180                         *dir = 0;
2181                         mkdir(freq->tmpfile, 0777);
2182                         *dir = '/';
2183                 }
2184                 freq->localfile = open(freq->tmpfile,
2185                                        O_WRONLY | O_CREAT | O_EXCL, 0666);
2186         }
2187
2188         if (freq->localfile < 0) {
2189                 error_errno("Couldn't create temporary file %s", freq->tmpfile);
2190                 goto abort;
2191         }
2192
2193         git_inflate_init(&freq->stream);
2194
2195         git_SHA1_Init(&freq->c);
2196
2197         freq->url = get_remote_object_url(base_url, hex, 0);
2198
2199         /*
2200          * If a previous temp file is present, process what was already
2201          * fetched.
2202          */
2203         prevlocal = open(prevfile, O_RDONLY);
2204         if (prevlocal != -1) {
2205                 do {
2206                         prev_read = xread(prevlocal, prev_buf, PREV_BUF_SIZE);
2207                         if (prev_read>0) {
2208                                 if (fwrite_sha1_file(prev_buf,
2209                                                      1,
2210                                                      prev_read,
2211                                                      freq) == prev_read) {
2212                                         prev_posn += prev_read;
2213                                 } else {
2214                                         prev_read = -1;
2215                                 }
2216                         }
2217                 } while (prev_read > 0);
2218                 close(prevlocal);
2219         }
2220         unlink_or_warn(prevfile);
2221
2222         /*
2223          * Reset inflate/SHA1 if there was an error reading the previous temp
2224          * file; also rewind to the beginning of the local file.
2225          */
2226         if (prev_read == -1) {
2227                 memset(&freq->stream, 0, sizeof(freq->stream));
2228                 git_inflate_init(&freq->stream);
2229                 git_SHA1_Init(&freq->c);
2230                 if (prev_posn>0) {
2231                         prev_posn = 0;
2232                         lseek(freq->localfile, 0, SEEK_SET);
2233                         if (ftruncate(freq->localfile, 0) < 0) {
2234                                 error_errno("Couldn't truncate temporary file %s",
2235                                             freq->tmpfile);
2236                                 goto abort;
2237                         }
2238                 }
2239         }
2240
2241         freq->slot = get_active_slot();
2242
2243         curl_easy_setopt(freq->slot->curl, CURLOPT_FILE, freq);
2244         curl_easy_setopt(freq->slot->curl, CURLOPT_FAILONERROR, 0);
2245         curl_easy_setopt(freq->slot->curl, CURLOPT_WRITEFUNCTION, fwrite_sha1_file);
2246         curl_easy_setopt(freq->slot->curl, CURLOPT_ERRORBUFFER, freq->errorstr);
2247         curl_easy_setopt(freq->slot->curl, CURLOPT_URL, freq->url);
2248         curl_easy_setopt(freq->slot->curl, CURLOPT_HTTPHEADER, no_pragma_header);
2249
2250         /*
2251          * If we have successfully processed data from a previous fetch
2252          * attempt, only fetch the data we don't already have.
2253          */
2254         if (prev_posn>0) {
2255                 if (http_is_verbose)
2256                         fprintf(stderr,
2257                                 "Resuming fetch of object %s at byte %"PRIuMAX"\n",
2258                                 hex, (uintmax_t)prev_posn);
2259                 http_opt_request_remainder(freq->slot->curl, prev_posn);
2260         }
2261
2262         return freq;
2263
2264 abort:
2265         free(freq->url);
2266         free(freq);
2267         return NULL;
2268 }
2269
2270 void process_http_object_request(struct http_object_request *freq)
2271 {
2272         if (freq->slot == NULL)
2273                 return;
2274         freq->curl_result = freq->slot->curl_result;
2275         freq->http_code = freq->slot->http_code;
2276         freq->slot = NULL;
2277 }
2278
2279 int finish_http_object_request(struct http_object_request *freq)
2280 {
2281         struct stat st;
2282
2283         close(freq->localfile);
2284         freq->localfile = -1;
2285
2286         process_http_object_request(freq);
2287
2288         if (freq->http_code == 416) {
2289                 warning("requested range invalid; we may already have all the data.");
2290         } else if (freq->curl_result != CURLE_OK) {
2291                 if (stat(freq->tmpfile, &st) == 0)
2292                         if (st.st_size == 0)
2293                                 unlink_or_warn(freq->tmpfile);
2294                 return -1;
2295         }
2296
2297         git_inflate_end(&freq->stream);
2298         git_SHA1_Final(freq->real_sha1, &freq->c);
2299         if (freq->zret != Z_STREAM_END) {
2300                 unlink_or_warn(freq->tmpfile);
2301                 return -1;
2302         }
2303         if (hashcmp(freq->sha1, freq->real_sha1)) {
2304                 unlink_or_warn(freq->tmpfile);
2305                 return -1;
2306         }
2307         freq->rename =
2308                 finalize_object_file(freq->tmpfile, sha1_file_name(freq->sha1));
2309
2310         return freq->rename;
2311 }
2312
2313 void abort_http_object_request(struct http_object_request *freq)
2314 {
2315         unlink_or_warn(freq->tmpfile);
2316
2317         release_http_object_request(freq);
2318 }
2319
2320 void release_http_object_request(struct http_object_request *freq)
2321 {
2322         if (freq->localfile != -1) {
2323                 close(freq->localfile);
2324                 freq->localfile = -1;
2325         }
2326         if (freq->url != NULL) {
2327                 FREE_AND_NULL(freq->url);
2328         }
2329         if (freq->slot != NULL) {
2330                 freq->slot->callback_func = NULL;
2331                 freq->slot->callback_data = NULL;
2332                 release_active_slot(freq->slot);
2333                 freq->slot = NULL;
2334         }
2335 }