remote-curl: let servers override http 404 advice
[git] / remote-curl.c
1 #include "cache.h"
2 #include "remote.h"
3 #include "strbuf.h"
4 #include "walker.h"
5 #include "http.h"
6 #include "exec_cmd.h"
7 #include "run-command.h"
8 #include "pkt-line.h"
9 #include "sideband.h"
10
11 static struct remote *remote;
12 static const char *url; /* always ends with a trailing slash */
13
14 struct options {
15         int verbosity;
16         unsigned long depth;
17         unsigned progress : 1,
18                 followtags : 1,
19                 dry_run : 1,
20                 thin : 1;
21 };
22 static struct options options;
23
24 static int set_option(const char *name, const char *value)
25 {
26         if (!strcmp(name, "verbosity")) {
27                 char *end;
28                 int v = strtol(value, &end, 10);
29                 if (value == end || *end)
30                         return -1;
31                 options.verbosity = v;
32                 return 0;
33         }
34         else if (!strcmp(name, "progress")) {
35                 if (!strcmp(value, "true"))
36                         options.progress = 1;
37                 else if (!strcmp(value, "false"))
38                         options.progress = 0;
39                 else
40                         return -1;
41                 return 0;
42         }
43         else if (!strcmp(name, "depth")) {
44                 char *end;
45                 unsigned long v = strtoul(value, &end, 10);
46                 if (value == end || *end)
47                         return -1;
48                 options.depth = v;
49                 return 0;
50         }
51         else if (!strcmp(name, "followtags")) {
52                 if (!strcmp(value, "true"))
53                         options.followtags = 1;
54                 else if (!strcmp(value, "false"))
55                         options.followtags = 0;
56                 else
57                         return -1;
58                 return 0;
59         }
60         else if (!strcmp(name, "dry-run")) {
61                 if (!strcmp(value, "true"))
62                         options.dry_run = 1;
63                 else if (!strcmp(value, "false"))
64                         options.dry_run = 0;
65                 else
66                         return -1;
67                 return 0;
68         }
69         else {
70                 return 1 /* unsupported */;
71         }
72 }
73
74 struct discovery {
75         const char *service;
76         char *buf_alloc;
77         char *buf;
78         size_t len;
79         struct ref *refs;
80         unsigned proto_git : 1;
81 };
82 static struct discovery *last_discovery;
83
84 static struct ref *parse_git_refs(struct discovery *heads, int for_push)
85 {
86         struct ref *list = NULL;
87         get_remote_heads(-1, heads->buf, heads->len, &list,
88                          for_push ? REF_NORMAL : 0, NULL);
89         return list;
90 }
91
92 static struct ref *parse_info_refs(struct discovery *heads)
93 {
94         char *data, *start, *mid;
95         char *ref_name;
96         int i = 0;
97
98         struct ref *refs = NULL;
99         struct ref *ref = NULL;
100         struct ref *last_ref = NULL;
101
102         data = heads->buf;
103         start = NULL;
104         mid = data;
105         while (i < heads->len) {
106                 if (!start) {
107                         start = &data[i];
108                 }
109                 if (data[i] == '\t')
110                         mid = &data[i];
111                 if (data[i] == '\n') {
112                         if (mid - start != 40)
113                                 die("%sinfo/refs not valid: is this a git repository?", url);
114                         data[i] = 0;
115                         ref_name = mid + 1;
116                         ref = xmalloc(sizeof(struct ref) +
117                                       strlen(ref_name) + 1);
118                         memset(ref, 0, sizeof(struct ref));
119                         strcpy(ref->name, ref_name);
120                         get_sha1_hex(start, ref->old_sha1);
121                         if (!refs)
122                                 refs = ref;
123                         if (last_ref)
124                                 last_ref->next = ref;
125                         last_ref = ref;
126                         start = NULL;
127                 }
128                 i++;
129         }
130
131         ref = alloc_ref("HEAD");
132         if (!http_fetch_ref(url, ref) &&
133             !resolve_remote_symref(ref, refs)) {
134                 ref->next = refs;
135                 refs = ref;
136         } else {
137                 free(ref);
138         }
139
140         return refs;
141 }
142
143 static void free_discovery(struct discovery *d)
144 {
145         if (d) {
146                 if (d == last_discovery)
147                         last_discovery = NULL;
148                 free(d->buf_alloc);
149                 free_refs(d->refs);
150                 free(d);
151         }
152 }
153
154 static int show_http_message(struct strbuf *type, struct strbuf *msg)
155 {
156         const char *p, *eol;
157
158         /*
159          * We only show text/plain parts, as other types are likely
160          * to be ugly to look at on the user's terminal.
161          *
162          * TODO should handle "; charset=XXX", and re-encode into
163          * logoutputencoding
164          */
165         if (strcasecmp(type->buf, "text/plain"))
166                 return -1;
167
168         strbuf_trim(msg);
169         if (!msg->len)
170                 return -1;
171
172         p = msg->buf;
173         do {
174                 eol = strchrnul(p, '\n');
175                 fprintf(stderr, "remote: %.*s\n", (int)(eol - p), p);
176                 p = eol + 1;
177         } while(*eol);
178         return 0;
179 }
180
181 static struct discovery* discover_refs(const char *service, int for_push)
182 {
183         struct strbuf exp = STRBUF_INIT;
184         struct strbuf type = STRBUF_INIT;
185         struct strbuf buffer = STRBUF_INIT;
186         struct discovery *last = last_discovery;
187         char *refs_url;
188         int http_ret, maybe_smart = 0;
189
190         if (last && !strcmp(service, last->service))
191                 return last;
192         free_discovery(last);
193
194         strbuf_addf(&buffer, "%sinfo/refs", url);
195         if ((!prefixcmp(url, "http://") || !prefixcmp(url, "https://")) &&
196              git_env_bool("GIT_SMART_HTTP", 1)) {
197                 maybe_smart = 1;
198                 if (!strchr(url, '?'))
199                         strbuf_addch(&buffer, '?');
200                 else
201                         strbuf_addch(&buffer, '&');
202                 strbuf_addf(&buffer, "service=%s", service);
203         }
204         refs_url = strbuf_detach(&buffer, NULL);
205
206         http_ret = http_get_strbuf(refs_url, &type, &buffer,
207                                    HTTP_NO_CACHE | HTTP_KEEP_ERROR);
208         switch (http_ret) {
209         case HTTP_OK:
210                 break;
211         case HTTP_MISSING_TARGET:
212                 if (!show_http_message(&type, &buffer))
213                         die("repository '%s' not found", url);
214                 die("%s not found: did you run git update-server-info on the"
215                     " server?", refs_url);
216         case HTTP_NOAUTH:
217                 show_http_message(&type, &buffer);
218                 die("Authentication failed");
219         default:
220                 show_http_message(&type, &buffer);
221                 http_error(refs_url, http_ret);
222                 die("HTTP request failed");
223         }
224
225         last= xcalloc(1, sizeof(*last_discovery));
226         last->service = service;
227         last->buf_alloc = strbuf_detach(&buffer, &last->len);
228         last->buf = last->buf_alloc;
229
230         strbuf_addf(&exp, "application/x-%s-advertisement", service);
231         if (maybe_smart &&
232             (5 <= last->len && last->buf[4] == '#') &&
233             !strbuf_cmp(&exp, &type)) {
234                 char *line;
235
236                 /*
237                  * smart HTTP response; validate that the service
238                  * pkt-line matches our request.
239                  */
240                 line = packet_read_line_buf(&last->buf, &last->len, NULL);
241
242                 strbuf_reset(&exp);
243                 strbuf_addf(&exp, "# service=%s", service);
244                 if (strcmp(line, exp.buf))
245                         die("invalid server response; got '%s'", line);
246                 strbuf_release(&exp);
247
248                 /* The header can include additional metadata lines, up
249                  * until a packet flush marker.  Ignore these now, but
250                  * in the future we might start to scan them.
251                  */
252                 while (packet_read_line_buf(&last->buf, &last->len, NULL))
253                         ;
254
255                 last->proto_git = 1;
256         }
257
258         if (last->proto_git)
259                 last->refs = parse_git_refs(last, for_push);
260         else
261                 last->refs = parse_info_refs(last);
262
263         free(refs_url);
264         strbuf_release(&exp);
265         strbuf_release(&type);
266         strbuf_release(&buffer);
267         last_discovery = last;
268         return last;
269 }
270
271 static struct ref *get_refs(int for_push)
272 {
273         struct discovery *heads;
274
275         if (for_push)
276                 heads = discover_refs("git-receive-pack", for_push);
277         else
278                 heads = discover_refs("git-upload-pack", for_push);
279
280         return heads->refs;
281 }
282
283 static void output_refs(struct ref *refs)
284 {
285         struct ref *posn;
286         for (posn = refs; posn; posn = posn->next) {
287                 if (posn->symref)
288                         printf("@%s %s\n", posn->symref, posn->name);
289                 else
290                         printf("%s %s\n", sha1_to_hex(posn->old_sha1), posn->name);
291         }
292         printf("\n");
293         fflush(stdout);
294 }
295
296 struct rpc_state {
297         const char *service_name;
298         const char **argv;
299         struct strbuf *stdin_preamble;
300         char *service_url;
301         char *hdr_content_type;
302         char *hdr_accept;
303         char *buf;
304         size_t alloc;
305         size_t len;
306         size_t pos;
307         int in;
308         int out;
309         struct strbuf result;
310         unsigned gzip_request : 1;
311         unsigned initial_buffer : 1;
312 };
313
314 static size_t rpc_out(void *ptr, size_t eltsize,
315                 size_t nmemb, void *buffer_)
316 {
317         size_t max = eltsize * nmemb;
318         struct rpc_state *rpc = buffer_;
319         size_t avail = rpc->len - rpc->pos;
320
321         if (!avail) {
322                 rpc->initial_buffer = 0;
323                 avail = packet_read(rpc->out, NULL, NULL, rpc->buf, rpc->alloc, 0);
324                 if (!avail)
325                         return 0;
326                 rpc->pos = 0;
327                 rpc->len = avail;
328         }
329
330         if (max < avail)
331                 avail = max;
332         memcpy(ptr, rpc->buf + rpc->pos, avail);
333         rpc->pos += avail;
334         return avail;
335 }
336
337 #ifndef NO_CURL_IOCTL
338 static curlioerr rpc_ioctl(CURL *handle, int cmd, void *clientp)
339 {
340         struct rpc_state *rpc = clientp;
341
342         switch (cmd) {
343         case CURLIOCMD_NOP:
344                 return CURLIOE_OK;
345
346         case CURLIOCMD_RESTARTREAD:
347                 if (rpc->initial_buffer) {
348                         rpc->pos = 0;
349                         return CURLIOE_OK;
350                 }
351                 fprintf(stderr, "Unable to rewind rpc post data - try increasing http.postBuffer\n");
352                 return CURLIOE_FAILRESTART;
353
354         default:
355                 return CURLIOE_UNKNOWNCMD;
356         }
357 }
358 #endif
359
360 static size_t rpc_in(char *ptr, size_t eltsize,
361                 size_t nmemb, void *buffer_)
362 {
363         size_t size = eltsize * nmemb;
364         struct rpc_state *rpc = buffer_;
365         write_or_die(rpc->in, ptr, size);
366         return size;
367 }
368
369 static int run_slot(struct active_request_slot *slot)
370 {
371         int err;
372         struct slot_results results;
373
374         slot->results = &results;
375         slot->curl_result = curl_easy_perform(slot->curl);
376         finish_active_slot(slot);
377
378         err = handle_curl_result(&results);
379         if (err != HTTP_OK && err != HTTP_REAUTH) {
380                 error("RPC failed; result=%d, HTTP code = %ld",
381                       results.curl_result, results.http_code);
382         }
383
384         return err;
385 }
386
387 static int probe_rpc(struct rpc_state *rpc)
388 {
389         struct active_request_slot *slot;
390         struct curl_slist *headers = NULL;
391         struct strbuf buf = STRBUF_INIT;
392         int err;
393
394         slot = get_active_slot();
395
396         headers = curl_slist_append(headers, rpc->hdr_content_type);
397         headers = curl_slist_append(headers, rpc->hdr_accept);
398
399         curl_easy_setopt(slot->curl, CURLOPT_NOBODY, 0);
400         curl_easy_setopt(slot->curl, CURLOPT_POST, 1);
401         curl_easy_setopt(slot->curl, CURLOPT_URL, rpc->service_url);
402         curl_easy_setopt(slot->curl, CURLOPT_ENCODING, NULL);
403         curl_easy_setopt(slot->curl, CURLOPT_POSTFIELDS, "0000");
404         curl_easy_setopt(slot->curl, CURLOPT_POSTFIELDSIZE, 4);
405         curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, headers);
406         curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION, fwrite_buffer);
407         curl_easy_setopt(slot->curl, CURLOPT_FILE, &buf);
408
409         err = run_slot(slot);
410
411         curl_slist_free_all(headers);
412         strbuf_release(&buf);
413         return err;
414 }
415
416 static int post_rpc(struct rpc_state *rpc)
417 {
418         struct active_request_slot *slot;
419         struct curl_slist *headers = NULL;
420         int use_gzip = rpc->gzip_request;
421         char *gzip_body = NULL;
422         size_t gzip_size = 0;
423         int err, large_request = 0;
424
425         /* Try to load the entire request, if we can fit it into the
426          * allocated buffer space we can use HTTP/1.0 and avoid the
427          * chunked encoding mess.
428          */
429         while (1) {
430                 size_t left = rpc->alloc - rpc->len;
431                 char *buf = rpc->buf + rpc->len;
432                 int n;
433
434                 if (left < LARGE_PACKET_MAX) {
435                         large_request = 1;
436                         use_gzip = 0;
437                         break;
438                 }
439
440                 n = packet_read(rpc->out, NULL, NULL, buf, left, 0);
441                 if (!n)
442                         break;
443                 rpc->len += n;
444         }
445
446         if (large_request) {
447                 do {
448                         err = probe_rpc(rpc);
449                 } while (err == HTTP_REAUTH);
450                 if (err != HTTP_OK)
451                         return -1;
452         }
453
454         headers = curl_slist_append(headers, rpc->hdr_content_type);
455         headers = curl_slist_append(headers, rpc->hdr_accept);
456         headers = curl_slist_append(headers, "Expect:");
457
458 retry:
459         slot = get_active_slot();
460
461         curl_easy_setopt(slot->curl, CURLOPT_NOBODY, 0);
462         curl_easy_setopt(slot->curl, CURLOPT_POST, 1);
463         curl_easy_setopt(slot->curl, CURLOPT_URL, rpc->service_url);
464         curl_easy_setopt(slot->curl, CURLOPT_ENCODING, "gzip");
465
466         if (large_request) {
467                 /* The request body is large and the size cannot be predicted.
468                  * We must use chunked encoding to send it.
469                  */
470                 headers = curl_slist_append(headers, "Transfer-Encoding: chunked");
471                 rpc->initial_buffer = 1;
472                 curl_easy_setopt(slot->curl, CURLOPT_READFUNCTION, rpc_out);
473                 curl_easy_setopt(slot->curl, CURLOPT_INFILE, rpc);
474 #ifndef NO_CURL_IOCTL
475                 curl_easy_setopt(slot->curl, CURLOPT_IOCTLFUNCTION, rpc_ioctl);
476                 curl_easy_setopt(slot->curl, CURLOPT_IOCTLDATA, rpc);
477 #endif
478                 if (options.verbosity > 1) {
479                         fprintf(stderr, "POST %s (chunked)\n", rpc->service_name);
480                         fflush(stderr);
481                 }
482
483         } else if (gzip_body) {
484                 /*
485                  * If we are looping to retry authentication, then the previous
486                  * run will have set up the headers and gzip buffer already,
487                  * and we just need to send it.
488                  */
489                 curl_easy_setopt(slot->curl, CURLOPT_POSTFIELDS, gzip_body);
490                 curl_easy_setopt(slot->curl, CURLOPT_POSTFIELDSIZE, gzip_size);
491
492         } else if (use_gzip && 1024 < rpc->len) {
493                 /* The client backend isn't giving us compressed data so
494                  * we can try to deflate it ourselves, this may save on.
495                  * the transfer time.
496                  */
497                 git_zstream stream;
498                 int ret;
499
500                 memset(&stream, 0, sizeof(stream));
501                 git_deflate_init_gzip(&stream, Z_BEST_COMPRESSION);
502                 gzip_size = git_deflate_bound(&stream, rpc->len);
503                 gzip_body = xmalloc(gzip_size);
504
505                 stream.next_in = (unsigned char *)rpc->buf;
506                 stream.avail_in = rpc->len;
507                 stream.next_out = (unsigned char *)gzip_body;
508                 stream.avail_out = gzip_size;
509
510                 ret = git_deflate(&stream, Z_FINISH);
511                 if (ret != Z_STREAM_END)
512                         die("cannot deflate request; zlib deflate error %d", ret);
513
514                 ret = git_deflate_end_gently(&stream);
515                 if (ret != Z_OK)
516                         die("cannot deflate request; zlib end error %d", ret);
517
518                 gzip_size = stream.total_out;
519
520                 headers = curl_slist_append(headers, "Content-Encoding: gzip");
521                 curl_easy_setopt(slot->curl, CURLOPT_POSTFIELDS, gzip_body);
522                 curl_easy_setopt(slot->curl, CURLOPT_POSTFIELDSIZE, gzip_size);
523
524                 if (options.verbosity > 1) {
525                         fprintf(stderr, "POST %s (gzip %lu to %lu bytes)\n",
526                                 rpc->service_name,
527                                 (unsigned long)rpc->len, (unsigned long)gzip_size);
528                         fflush(stderr);
529                 }
530         } else {
531                 /* We know the complete request size in advance, use the
532                  * more normal Content-Length approach.
533                  */
534                 curl_easy_setopt(slot->curl, CURLOPT_POSTFIELDS, rpc->buf);
535                 curl_easy_setopt(slot->curl, CURLOPT_POSTFIELDSIZE, rpc->len);
536                 if (options.verbosity > 1) {
537                         fprintf(stderr, "POST %s (%lu bytes)\n",
538                                 rpc->service_name, (unsigned long)rpc->len);
539                         fflush(stderr);
540                 }
541         }
542
543         curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, headers);
544         curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION, rpc_in);
545         curl_easy_setopt(slot->curl, CURLOPT_FILE, rpc);
546
547         err = run_slot(slot);
548         if (err == HTTP_REAUTH && !large_request)
549                 goto retry;
550         if (err != HTTP_OK)
551                 err = -1;
552
553         curl_slist_free_all(headers);
554         free(gzip_body);
555         return err;
556 }
557
558 static int rpc_service(struct rpc_state *rpc, struct discovery *heads)
559 {
560         const char *svc = rpc->service_name;
561         struct strbuf buf = STRBUF_INIT;
562         struct strbuf *preamble = rpc->stdin_preamble;
563         struct child_process client;
564         int err = 0;
565
566         memset(&client, 0, sizeof(client));
567         client.in = -1;
568         client.out = -1;
569         client.git_cmd = 1;
570         client.argv = rpc->argv;
571         if (start_command(&client))
572                 exit(1);
573         if (preamble)
574                 write_or_die(client.in, preamble->buf, preamble->len);
575         if (heads)
576                 write_or_die(client.in, heads->buf, heads->len);
577
578         rpc->alloc = http_post_buffer;
579         rpc->buf = xmalloc(rpc->alloc);
580         rpc->in = client.in;
581         rpc->out = client.out;
582         strbuf_init(&rpc->result, 0);
583
584         strbuf_addf(&buf, "%s%s", url, svc);
585         rpc->service_url = strbuf_detach(&buf, NULL);
586
587         strbuf_addf(&buf, "Content-Type: application/x-%s-request", svc);
588         rpc->hdr_content_type = strbuf_detach(&buf, NULL);
589
590         strbuf_addf(&buf, "Accept: application/x-%s-result", svc);
591         rpc->hdr_accept = strbuf_detach(&buf, NULL);
592
593         while (!err) {
594                 int n = packet_read(rpc->out, NULL, NULL, rpc->buf, rpc->alloc, 0);
595                 if (!n)
596                         break;
597                 rpc->pos = 0;
598                 rpc->len = n;
599                 err |= post_rpc(rpc);
600         }
601
602         close(client.in);
603         client.in = -1;
604         if (!err) {
605                 strbuf_read(&rpc->result, client.out, 0);
606         } else {
607                 char buf[4096];
608                 for (;;)
609                         if (xread(client.out, buf, sizeof(buf)) <= 0)
610                                 break;
611         }
612
613         close(client.out);
614         client.out = -1;
615
616         err |= finish_command(&client);
617         free(rpc->service_url);
618         free(rpc->hdr_content_type);
619         free(rpc->hdr_accept);
620         free(rpc->buf);
621         strbuf_release(&buf);
622         return err;
623 }
624
625 static int fetch_dumb(int nr_heads, struct ref **to_fetch)
626 {
627         struct walker *walker;
628         char **targets = xmalloc(nr_heads * sizeof(char*));
629         int ret, i;
630
631         if (options.depth)
632                 die("dumb http transport does not support --depth");
633         for (i = 0; i < nr_heads; i++)
634                 targets[i] = xstrdup(sha1_to_hex(to_fetch[i]->old_sha1));
635
636         walker = get_http_walker(url);
637         walker->get_all = 1;
638         walker->get_tree = 1;
639         walker->get_history = 1;
640         walker->get_verbosely = options.verbosity >= 3;
641         walker->get_recover = 0;
642         ret = walker_fetch(walker, nr_heads, targets, NULL, NULL);
643         walker_free(walker);
644
645         for (i = 0; i < nr_heads; i++)
646                 free(targets[i]);
647         free(targets);
648
649         return ret ? error("Fetch failed.") : 0;
650 }
651
652 static int fetch_git(struct discovery *heads,
653         int nr_heads, struct ref **to_fetch)
654 {
655         struct rpc_state rpc;
656         struct strbuf preamble = STRBUF_INIT;
657         char *depth_arg = NULL;
658         int argc = 0, i, err;
659         const char *argv[15];
660
661         argv[argc++] = "fetch-pack";
662         argv[argc++] = "--stateless-rpc";
663         argv[argc++] = "--stdin";
664         argv[argc++] = "--lock-pack";
665         if (options.followtags)
666                 argv[argc++] = "--include-tag";
667         if (options.thin)
668                 argv[argc++] = "--thin";
669         if (options.verbosity >= 3) {
670                 argv[argc++] = "-v";
671                 argv[argc++] = "-v";
672         }
673         if (!options.progress)
674                 argv[argc++] = "--no-progress";
675         if (options.depth) {
676                 struct strbuf buf = STRBUF_INIT;
677                 strbuf_addf(&buf, "--depth=%lu", options.depth);
678                 depth_arg = strbuf_detach(&buf, NULL);
679                 argv[argc++] = depth_arg;
680         }
681         argv[argc++] = url;
682         argv[argc++] = NULL;
683
684         for (i = 0; i < nr_heads; i++) {
685                 struct ref *ref = to_fetch[i];
686                 if (!ref->name || !*ref->name)
687                         die("cannot fetch by sha1 over smart http");
688                 packet_buf_write(&preamble, "%s\n", ref->name);
689         }
690         packet_buf_flush(&preamble);
691
692         memset(&rpc, 0, sizeof(rpc));
693         rpc.service_name = "git-upload-pack",
694         rpc.argv = argv;
695         rpc.stdin_preamble = &preamble;
696         rpc.gzip_request = 1;
697
698         err = rpc_service(&rpc, heads);
699         if (rpc.result.len)
700                 write_or_die(1, rpc.result.buf, rpc.result.len);
701         strbuf_release(&rpc.result);
702         strbuf_release(&preamble);
703         free(depth_arg);
704         return err;
705 }
706
707 static int fetch(int nr_heads, struct ref **to_fetch)
708 {
709         struct discovery *d = discover_refs("git-upload-pack", 0);
710         if (d->proto_git)
711                 return fetch_git(d, nr_heads, to_fetch);
712         else
713                 return fetch_dumb(nr_heads, to_fetch);
714 }
715
716 static void parse_fetch(struct strbuf *buf)
717 {
718         struct ref **to_fetch = NULL;
719         struct ref *list_head = NULL;
720         struct ref **list = &list_head;
721         int alloc_heads = 0, nr_heads = 0;
722
723         do {
724                 if (!prefixcmp(buf->buf, "fetch ")) {
725                         char *p = buf->buf + strlen("fetch ");
726                         char *name;
727                         struct ref *ref;
728                         unsigned char old_sha1[20];
729
730                         if (strlen(p) < 40 || get_sha1_hex(p, old_sha1))
731                                 die("protocol error: expected sha/ref, got %s'", p);
732                         if (p[40] == ' ')
733                                 name = p + 41;
734                         else if (!p[40])
735                                 name = "";
736                         else
737                                 die("protocol error: expected sha/ref, got %s'", p);
738
739                         ref = alloc_ref(name);
740                         hashcpy(ref->old_sha1, old_sha1);
741
742                         *list = ref;
743                         list = &ref->next;
744
745                         ALLOC_GROW(to_fetch, nr_heads + 1, alloc_heads);
746                         to_fetch[nr_heads++] = ref;
747                 }
748                 else
749                         die("http transport does not support %s", buf->buf);
750
751                 strbuf_reset(buf);
752                 if (strbuf_getline(buf, stdin, '\n') == EOF)
753                         return;
754                 if (!*buf->buf)
755                         break;
756         } while (1);
757
758         if (fetch(nr_heads, to_fetch))
759                 exit(128); /* error already reported */
760         free_refs(list_head);
761         free(to_fetch);
762
763         printf("\n");
764         fflush(stdout);
765         strbuf_reset(buf);
766 }
767
768 static int push_dav(int nr_spec, char **specs)
769 {
770         const char **argv = xmalloc((10 + nr_spec) * sizeof(char*));
771         int argc = 0, i;
772
773         argv[argc++] = "http-push";
774         argv[argc++] = "--helper-status";
775         if (options.dry_run)
776                 argv[argc++] = "--dry-run";
777         if (options.verbosity > 1)
778                 argv[argc++] = "--verbose";
779         argv[argc++] = url;
780         for (i = 0; i < nr_spec; i++)
781                 argv[argc++] = specs[i];
782         argv[argc++] = NULL;
783
784         if (run_command_v_opt(argv, RUN_GIT_CMD))
785                 die("git-%s failed", argv[0]);
786         free(argv);
787         return 0;
788 }
789
790 static int push_git(struct discovery *heads, int nr_spec, char **specs)
791 {
792         struct rpc_state rpc;
793         const char **argv;
794         int argc = 0, i, err;
795
796         argv = xmalloc((10 + nr_spec) * sizeof(char*));
797         argv[argc++] = "send-pack";
798         argv[argc++] = "--stateless-rpc";
799         argv[argc++] = "--helper-status";
800         if (options.thin)
801                 argv[argc++] = "--thin";
802         if (options.dry_run)
803                 argv[argc++] = "--dry-run";
804         if (options.verbosity == 0)
805                 argv[argc++] = "--quiet";
806         else if (options.verbosity > 1)
807                 argv[argc++] = "--verbose";
808         argv[argc++] = options.progress ? "--progress" : "--no-progress";
809         argv[argc++] = url;
810         for (i = 0; i < nr_spec; i++)
811                 argv[argc++] = specs[i];
812         argv[argc++] = NULL;
813
814         memset(&rpc, 0, sizeof(rpc));
815         rpc.service_name = "git-receive-pack",
816         rpc.argv = argv;
817
818         err = rpc_service(&rpc, heads);
819         if (rpc.result.len)
820                 write_or_die(1, rpc.result.buf, rpc.result.len);
821         strbuf_release(&rpc.result);
822         free(argv);
823         return err;
824 }
825
826 static int push(int nr_spec, char **specs)
827 {
828         struct discovery *heads = discover_refs("git-receive-pack", 1);
829         int ret;
830
831         if (heads->proto_git)
832                 ret = push_git(heads, nr_spec, specs);
833         else
834                 ret = push_dav(nr_spec, specs);
835         free_discovery(heads);
836         return ret;
837 }
838
839 static void parse_push(struct strbuf *buf)
840 {
841         char **specs = NULL;
842         int alloc_spec = 0, nr_spec = 0, i, ret;
843
844         do {
845                 if (!prefixcmp(buf->buf, "push ")) {
846                         ALLOC_GROW(specs, nr_spec + 1, alloc_spec);
847                         specs[nr_spec++] = xstrdup(buf->buf + 5);
848                 }
849                 else
850                         die("http transport does not support %s", buf->buf);
851
852                 strbuf_reset(buf);
853                 if (strbuf_getline(buf, stdin, '\n') == EOF)
854                         goto free_specs;
855                 if (!*buf->buf)
856                         break;
857         } while (1);
858
859         ret = push(nr_spec, specs);
860         printf("\n");
861         fflush(stdout);
862
863         if (ret)
864                 exit(128); /* error already reported */
865
866  free_specs:
867         for (i = 0; i < nr_spec; i++)
868                 free(specs[i]);
869         free(specs);
870 }
871
872 int main(int argc, const char **argv)
873 {
874         struct strbuf buf = STRBUF_INIT;
875         int nongit;
876
877         git_extract_argv0_path(argv[0]);
878         setup_git_directory_gently(&nongit);
879         if (argc < 2) {
880                 fprintf(stderr, "Remote needed\n");
881                 return 1;
882         }
883
884         options.verbosity = 1;
885         options.progress = !!isatty(2);
886         options.thin = 1;
887
888         remote = remote_get(argv[1]);
889
890         if (argc > 2) {
891                 end_url_with_slash(&buf, argv[2]);
892         } else {
893                 end_url_with_slash(&buf, remote->url[0]);
894         }
895
896         url = strbuf_detach(&buf, NULL);
897
898         http_init(remote, url, 0);
899
900         do {
901                 if (strbuf_getline(&buf, stdin, '\n') == EOF) {
902                         if (ferror(stdin))
903                                 fprintf(stderr, "Error reading command stream\n");
904                         else
905                                 fprintf(stderr, "Unexpected end of command stream\n");
906                         return 1;
907                 }
908                 if (buf.len == 0)
909                         break;
910                 if (!prefixcmp(buf.buf, "fetch ")) {
911                         if (nongit)
912                                 die("Fetch attempted without a local repo");
913                         parse_fetch(&buf);
914
915                 } else if (!strcmp(buf.buf, "list") || !prefixcmp(buf.buf, "list ")) {
916                         int for_push = !!strstr(buf.buf + 4, "for-push");
917                         output_refs(get_refs(for_push));
918
919                 } else if (!prefixcmp(buf.buf, "push ")) {
920                         parse_push(&buf);
921
922                 } else if (!prefixcmp(buf.buf, "option ")) {
923                         char *name = buf.buf + strlen("option ");
924                         char *value = strchr(name, ' ');
925                         int result;
926
927                         if (value)
928                                 *value++ = '\0';
929                         else
930                                 value = "true";
931
932                         result = set_option(name, value);
933                         if (!result)
934                                 printf("ok\n");
935                         else if (result < 0)
936                                 printf("error invalid value\n");
937                         else
938                                 printf("unsupported\n");
939                         fflush(stdout);
940
941                 } else if (!strcmp(buf.buf, "capabilities")) {
942                         printf("fetch\n");
943                         printf("option\n");
944                         printf("push\n");
945                         printf("\n");
946                         fflush(stdout);
947                 } else {
948                         fprintf(stderr, "Unknown command '%s'\n", buf.buf);
949                         return 1;
950                 }
951                 strbuf_reset(&buf);
952         } while (1);
953
954         http_cleanup();
955
956         return 0;
957 }