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