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