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