http-push.c::remote_exists(): use the new http API
[git] / http-push.c
1 #include "cache.h"
2 #include "commit.h"
3 #include "pack.h"
4 #include "tag.h"
5 #include "blob.h"
6 #include "http.h"
7 #include "refs.h"
8 #include "diff.h"
9 #include "revision.h"
10 #include "exec_cmd.h"
11 #include "remote.h"
12 #include "list-objects.h"
13 #include "sigchain.h"
14
15 #include <expat.h>
16
17 static const char http_push_usage[] =
18 "git http-push [--all] [--dry-run] [--force] [--verbose] <remote> [<head>...]\n";
19
20 #ifndef XML_STATUS_OK
21 enum XML_Status {
22   XML_STATUS_OK = 1,
23   XML_STATUS_ERROR = 0
24 };
25 #define XML_STATUS_OK    1
26 #define XML_STATUS_ERROR 0
27 #endif
28
29 #define PREV_BUF_SIZE 4096
30
31 /* DAV methods */
32 #define DAV_LOCK "LOCK"
33 #define DAV_MKCOL "MKCOL"
34 #define DAV_MOVE "MOVE"
35 #define DAV_PROPFIND "PROPFIND"
36 #define DAV_PUT "PUT"
37 #define DAV_UNLOCK "UNLOCK"
38 #define DAV_DELETE "DELETE"
39
40 /* DAV lock flags */
41 #define DAV_PROP_LOCKWR (1u << 0)
42 #define DAV_PROP_LOCKEX (1u << 1)
43 #define DAV_LOCK_OK (1u << 2)
44
45 /* DAV XML properties */
46 #define DAV_CTX_LOCKENTRY ".multistatus.response.propstat.prop.supportedlock.lockentry"
47 #define DAV_CTX_LOCKTYPE_WRITE ".multistatus.response.propstat.prop.supportedlock.lockentry.locktype.write"
48 #define DAV_CTX_LOCKTYPE_EXCLUSIVE ".multistatus.response.propstat.prop.supportedlock.lockentry.lockscope.exclusive"
49 #define DAV_ACTIVELOCK_OWNER ".prop.lockdiscovery.activelock.owner.href"
50 #define DAV_ACTIVELOCK_TIMEOUT ".prop.lockdiscovery.activelock.timeout"
51 #define DAV_ACTIVELOCK_TOKEN ".prop.lockdiscovery.activelock.locktoken.href"
52 #define DAV_PROPFIND_RESP ".multistatus.response"
53 #define DAV_PROPFIND_NAME ".multistatus.response.href"
54 #define DAV_PROPFIND_COLLECTION ".multistatus.response.propstat.prop.resourcetype.collection"
55
56 /* DAV request body templates */
57 #define PROPFIND_SUPPORTEDLOCK_REQUEST "<?xml version=\"1.0\" encoding=\"utf-8\" ?>\n<D:propfind xmlns:D=\"DAV:\">\n<D:prop xmlns:R=\"%s\">\n<D:supportedlock/>\n</D:prop>\n</D:propfind>"
58 #define PROPFIND_ALL_REQUEST "<?xml version=\"1.0\" encoding=\"utf-8\" ?>\n<D:propfind xmlns:D=\"DAV:\">\n<D:allprop/>\n</D:propfind>"
59 #define LOCK_REQUEST "<?xml version=\"1.0\" encoding=\"utf-8\" ?>\n<D:lockinfo xmlns:D=\"DAV:\">\n<D:lockscope><D:exclusive/></D:lockscope>\n<D:locktype><D:write/></D:locktype>\n<D:owner>\n<D:href>mailto:%s</D:href>\n</D:owner>\n</D:lockinfo>"
60
61 #define LOCK_TIME 600
62 #define LOCK_REFRESH 30
63
64 /* bits #0-15 in revision.h */
65
66 #define LOCAL    (1u<<16)
67 #define REMOTE   (1u<<17)
68 #define FETCHING (1u<<18)
69 #define PUSHING  (1u<<19)
70
71 /* We allow "recursive" symbolic refs. Only within reason, though */
72 #define MAXDEPTH 5
73
74 static int pushing;
75 static int aborted;
76 static signed char remote_dir_exists[256];
77
78 static int push_verbosely;
79 static int push_all = MATCH_REFS_NONE;
80 static int force_all;
81 static int dry_run;
82
83 static struct object_list *objects;
84
85 struct repo
86 {
87         char *url;
88         char *path;
89         int path_len;
90         int has_info_refs;
91         int can_update_info_refs;
92         int has_info_packs;
93         struct packed_git *packs;
94         struct remote_lock *locks;
95 };
96
97 static struct repo *repo;
98
99 enum transfer_state {
100         NEED_FETCH,
101         RUN_FETCH_LOOSE,
102         RUN_FETCH_PACKED,
103         NEED_PUSH,
104         RUN_MKCOL,
105         RUN_PUT,
106         RUN_MOVE,
107         ABORTED,
108         COMPLETE,
109 };
110
111 struct transfer_request
112 {
113         struct object *obj;
114         char *url;
115         char *dest;
116         struct remote_lock *lock;
117         struct curl_slist *headers;
118         struct buffer buffer;
119         char filename[PATH_MAX];
120         char tmpfile[PATH_MAX];
121         int local_fileno;
122         FILE *local_stream;
123         enum transfer_state state;
124         CURLcode curl_result;
125         char errorstr[CURL_ERROR_SIZE];
126         long http_code;
127         unsigned char real_sha1[20];
128         git_SHA_CTX c;
129         z_stream stream;
130         int zret;
131         int rename;
132         void *userData;
133         struct active_request_slot *slot;
134         struct transfer_request *next;
135 };
136
137 static struct transfer_request *request_queue_head;
138
139 struct xml_ctx
140 {
141         char *name;
142         int len;
143         char *cdata;
144         void (*userFunc)(struct xml_ctx *ctx, int tag_closed);
145         void *userData;
146 };
147
148 struct remote_lock
149 {
150         char *url;
151         char *owner;
152         char *token;
153         char tmpfile_suffix[41];
154         time_t start_time;
155         long timeout;
156         int refreshing;
157         struct remote_lock *next;
158 };
159
160 /* Flags that control remote_ls processing */
161 #define PROCESS_FILES (1u << 0)
162 #define PROCESS_DIRS  (1u << 1)
163 #define RECURSIVE     (1u << 2)
164
165 /* Flags that remote_ls passes to callback functions */
166 #define IS_DIR (1u << 0)
167
168 struct remote_ls_ctx
169 {
170         char *path;
171         void (*userFunc)(struct remote_ls_ctx *ls);
172         void *userData;
173         int flags;
174         char *dentry_name;
175         int dentry_flags;
176         struct remote_ls_ctx *parent;
177 };
178
179 /* get_dav_token_headers options */
180 enum dav_header_flag {
181         DAV_HEADER_IF = (1u << 0),
182         DAV_HEADER_LOCK = (1u << 1),
183         DAV_HEADER_TIMEOUT = (1u << 2)
184 };
185
186 static char *xml_entities(char *s)
187 {
188         struct strbuf buf = STRBUF_INIT;
189         while (*s) {
190                 size_t len = strcspn(s, "\"<>&");
191                 strbuf_add(&buf, s, len);
192                 s += len;
193                 switch (*s) {
194                 case '"':
195                         strbuf_addstr(&buf, "&quot;");
196                         break;
197                 case '<':
198                         strbuf_addstr(&buf, "&lt;");
199                         break;
200                 case '>':
201                         strbuf_addstr(&buf, "&gt;");
202                         break;
203                 case '&':
204                         strbuf_addstr(&buf, "&amp;");
205                         break;
206                 }
207                 s++;
208         }
209         return strbuf_detach(&buf, NULL);
210 }
211
212 static struct curl_slist *get_dav_token_headers(struct remote_lock *lock, enum dav_header_flag options)
213 {
214         struct strbuf buf = STRBUF_INIT;
215         struct curl_slist *dav_headers = NULL;
216
217         if (options & DAV_HEADER_IF) {
218                 strbuf_addf(&buf, "If: (<%s>)", lock->token);
219                 dav_headers = curl_slist_append(dav_headers, buf.buf);
220                 strbuf_reset(&buf);
221         }
222         if (options & DAV_HEADER_LOCK) {
223                 strbuf_addf(&buf, "Lock-Token: <%s>", lock->token);
224                 dav_headers = curl_slist_append(dav_headers, buf.buf);
225                 strbuf_reset(&buf);
226         }
227         if (options & DAV_HEADER_TIMEOUT) {
228                 strbuf_addf(&buf, "Timeout: Second-%ld", lock->timeout);
229                 dav_headers = curl_slist_append(dav_headers, buf.buf);
230                 strbuf_reset(&buf);
231         }
232         strbuf_release(&buf);
233
234         return dav_headers;
235 }
236
237 static void append_remote_object_url(struct strbuf *buf, const char *url,
238                                      const char *hex,
239                                      int only_two_digit_prefix)
240 {
241         strbuf_addf(buf, "%sobjects/%.*s/", url, 2, hex);
242         if (!only_two_digit_prefix)
243                 strbuf_addf(buf, "%s", hex+2);
244 }
245
246 static void finish_request(struct transfer_request *request);
247 static void release_request(struct transfer_request *request);
248
249 static void process_response(void *callback_data)
250 {
251         struct transfer_request *request =
252                 (struct transfer_request *)callback_data;
253
254         finish_request(request);
255 }
256
257 #ifdef USE_CURL_MULTI
258
259 static char *get_remote_object_url(const char *url, const char *hex,
260                                    int only_two_digit_prefix)
261 {
262         struct strbuf buf = STRBUF_INIT;
263         append_remote_object_url(&buf, url, hex, only_two_digit_prefix);
264         return strbuf_detach(&buf, NULL);
265 }
266
267 static size_t fwrite_sha1_file(void *ptr, size_t eltsize, size_t nmemb,
268                                void *data)
269 {
270         unsigned char expn[4096];
271         size_t size = eltsize * nmemb;
272         int posn = 0;
273         struct transfer_request *request = (struct transfer_request *)data;
274         do {
275                 ssize_t retval = xwrite(request->local_fileno,
276                                         (char *) ptr + posn, size - posn);
277                 if (retval < 0)
278                         return posn;
279                 posn += retval;
280         } while (posn < size);
281
282         request->stream.avail_in = size;
283         request->stream.next_in = ptr;
284         do {
285                 request->stream.next_out = expn;
286                 request->stream.avail_out = sizeof(expn);
287                 request->zret = git_inflate(&request->stream, Z_SYNC_FLUSH);
288                 git_SHA1_Update(&request->c, expn,
289                                 sizeof(expn) - request->stream.avail_out);
290         } while (request->stream.avail_in && request->zret == Z_OK);
291         data_received++;
292         return size;
293 }
294
295 static void start_fetch_loose(struct transfer_request *request)
296 {
297         char *hex = sha1_to_hex(request->obj->sha1);
298         char *filename;
299         char prevfile[PATH_MAX];
300         char *url;
301         int prevlocal;
302         unsigned char prev_buf[PREV_BUF_SIZE];
303         ssize_t prev_read = 0;
304         long prev_posn = 0;
305         char range[RANGE_HEADER_SIZE];
306         struct curl_slist *range_header = NULL;
307         struct active_request_slot *slot;
308
309         filename = sha1_file_name(request->obj->sha1);
310         snprintf(request->filename, sizeof(request->filename), "%s", filename);
311         snprintf(request->tmpfile, sizeof(request->tmpfile),
312                  "%s.temp", filename);
313
314         snprintf(prevfile, sizeof(prevfile), "%s.prev", request->filename);
315         unlink_or_warn(prevfile);
316         rename(request->tmpfile, prevfile);
317         unlink_or_warn(request->tmpfile);
318
319         if (request->local_fileno != -1)
320                 error("fd leakage in start: %d", request->local_fileno);
321         request->local_fileno = open(request->tmpfile,
322                                      O_WRONLY | O_CREAT | O_EXCL, 0666);
323         /*
324          * This could have failed due to the "lazy directory creation";
325          * try to mkdir the last path component.
326          */
327         if (request->local_fileno < 0 && errno == ENOENT) {
328                 char *dir = strrchr(request->tmpfile, '/');
329                 if (dir) {
330                         *dir = 0;
331                         mkdir(request->tmpfile, 0777);
332                         *dir = '/';
333                 }
334                 request->local_fileno = open(request->tmpfile,
335                                              O_WRONLY | O_CREAT | O_EXCL, 0666);
336         }
337
338         if (request->local_fileno < 0) {
339                 request->state = ABORTED;
340                 error("Couldn't create temporary file %s for %s: %s",
341                       request->tmpfile, request->filename, strerror(errno));
342                 return;
343         }
344
345         memset(&request->stream, 0, sizeof(request->stream));
346
347         git_inflate_init(&request->stream);
348
349         git_SHA1_Init(&request->c);
350
351         url = get_remote_object_url(repo->url, hex, 0);
352         request->url = xstrdup(url);
353
354         /*
355          * If a previous temp file is present, process what was already
356          * fetched.
357          */
358         prevlocal = open(prevfile, O_RDONLY);
359         if (prevlocal != -1) {
360                 do {
361                         prev_read = xread(prevlocal, prev_buf, PREV_BUF_SIZE);
362                         if (prev_read>0) {
363                                 if (fwrite_sha1_file(prev_buf,
364                                                      1,
365                                                      prev_read,
366                                                      request) == prev_read)
367                                         prev_posn += prev_read;
368                                 else
369                                         prev_read = -1;
370                         }
371                 } while (prev_read > 0);
372                 close(prevlocal);
373         }
374         unlink_or_warn(prevfile);
375
376         /*
377          * Reset inflate/SHA1 if there was an error reading the previous temp
378          * file; also rewind to the beginning of the local file.
379          */
380         if (prev_read == -1) {
381                 memset(&request->stream, 0, sizeof(request->stream));
382                 git_inflate_init(&request->stream);
383                 git_SHA1_Init(&request->c);
384                 if (prev_posn>0) {
385                         prev_posn = 0;
386                         lseek(request->local_fileno, 0, SEEK_SET);
387                         ftruncate(request->local_fileno, 0);
388                 }
389         }
390
391         slot = get_active_slot();
392         slot->callback_func = process_response;
393         slot->callback_data = request;
394         request->slot = slot;
395
396         curl_easy_setopt(slot->curl, CURLOPT_FILE, request);
397         curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION, fwrite_sha1_file);
398         curl_easy_setopt(slot->curl, CURLOPT_ERRORBUFFER, request->errorstr);
399         curl_easy_setopt(slot->curl, CURLOPT_URL, url);
400         curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, no_pragma_header);
401
402         /*
403          * If we have successfully processed data from a previous fetch
404          * attempt, only fetch the data we don't already have.
405          */
406         if (prev_posn>0) {
407                 if (push_verbosely)
408                         fprintf(stderr,
409                                 "Resuming fetch of object %s at byte %ld\n",
410                                 hex, prev_posn);
411                 sprintf(range, "Range: bytes=%ld-", prev_posn);
412                 range_header = curl_slist_append(range_header, range);
413                 curl_easy_setopt(slot->curl,
414                                  CURLOPT_HTTPHEADER, range_header);
415         }
416
417         /* Try to get the request started, abort the request on error */
418         request->state = RUN_FETCH_LOOSE;
419         if (!start_active_slot(slot)) {
420                 fprintf(stderr, "Unable to start GET request\n");
421                 repo->can_update_info_refs = 0;
422                 release_request(request);
423         }
424 }
425
426 static void start_mkcol(struct transfer_request *request)
427 {
428         char *hex = sha1_to_hex(request->obj->sha1);
429         struct active_request_slot *slot;
430
431         request->url = get_remote_object_url(repo->url, hex, 1);
432
433         slot = get_active_slot();
434         slot->callback_func = process_response;
435         slot->callback_data = request;
436         curl_easy_setopt(slot->curl, CURLOPT_HTTPGET, 1); /* undo PUT setup */
437         curl_easy_setopt(slot->curl, CURLOPT_URL, request->url);
438         curl_easy_setopt(slot->curl, CURLOPT_ERRORBUFFER, request->errorstr);
439         curl_easy_setopt(slot->curl, CURLOPT_CUSTOMREQUEST, DAV_MKCOL);
440         curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION, fwrite_null);
441
442         if (start_active_slot(slot)) {
443                 request->slot = slot;
444                 request->state = RUN_MKCOL;
445         } else {
446                 request->state = ABORTED;
447                 free(request->url);
448                 request->url = NULL;
449         }
450 }
451 #endif
452
453 static void start_fetch_packed(struct transfer_request *request)
454 {
455         char *url;
456         struct packed_git *target;
457         FILE *packfile;
458         char *filename;
459         long prev_posn = 0;
460         char range[RANGE_HEADER_SIZE];
461         struct curl_slist *range_header = NULL;
462
463         struct transfer_request *check_request = request_queue_head;
464         struct active_request_slot *slot;
465
466         target = find_sha1_pack(request->obj->sha1, repo->packs);
467         if (!target) {
468                 fprintf(stderr, "Unable to fetch %s, will not be able to update server info refs\n", sha1_to_hex(request->obj->sha1));
469                 repo->can_update_info_refs = 0;
470                 release_request(request);
471                 return;
472         }
473
474         fprintf(stderr, "Fetching pack %s\n", sha1_to_hex(target->sha1));
475         fprintf(stderr, " which contains %s\n", sha1_to_hex(request->obj->sha1));
476
477         filename = sha1_pack_name(target->sha1);
478         snprintf(request->filename, sizeof(request->filename), "%s", filename);
479         snprintf(request->tmpfile, sizeof(request->tmpfile),
480                  "%s.temp", filename);
481
482         url = xmalloc(strlen(repo->url) + 64);
483         sprintf(url, "%sobjects/pack/pack-%s.pack",
484                 repo->url, sha1_to_hex(target->sha1));
485
486         /* Make sure there isn't another open request for this pack */
487         while (check_request) {
488                 if (check_request->state == RUN_FETCH_PACKED &&
489                     !strcmp(check_request->url, url)) {
490                         free(url);
491                         release_request(request);
492                         return;
493                 }
494                 check_request = check_request->next;
495         }
496
497         packfile = fopen(request->tmpfile, "a");
498         if (!packfile) {
499                 fprintf(stderr, "Unable to open local file %s for pack",
500                         request->tmpfile);
501                 repo->can_update_info_refs = 0;
502                 free(url);
503                 return;
504         }
505
506         slot = get_active_slot();
507         slot->callback_func = process_response;
508         slot->callback_data = request;
509         request->slot = slot;
510         request->local_stream = packfile;
511         request->userData = target;
512
513         request->url = url;
514         curl_easy_setopt(slot->curl, CURLOPT_FILE, packfile);
515         curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION, fwrite);
516         curl_easy_setopt(slot->curl, CURLOPT_URL, url);
517         curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, no_pragma_header);
518         slot->local = packfile;
519
520         /*
521          * If there is data present from a previous transfer attempt,
522          * resume where it left off
523          */
524         prev_posn = ftell(packfile);
525         if (prev_posn>0) {
526                 if (push_verbosely)
527                         fprintf(stderr,
528                                 "Resuming fetch of pack %s at byte %ld\n",
529                                 sha1_to_hex(target->sha1), prev_posn);
530                 sprintf(range, "Range: bytes=%ld-", prev_posn);
531                 range_header = curl_slist_append(range_header, range);
532                 curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, range_header);
533         }
534
535         /* Try to get the request started, abort the request on error */
536         request->state = RUN_FETCH_PACKED;
537         if (!start_active_slot(slot)) {
538                 fprintf(stderr, "Unable to start GET request\n");
539                 repo->can_update_info_refs = 0;
540                 release_request(request);
541         }
542 }
543
544 static void start_put(struct transfer_request *request)
545 {
546         char *hex = sha1_to_hex(request->obj->sha1);
547         struct active_request_slot *slot;
548         struct strbuf buf = STRBUF_INIT;
549         enum object_type type;
550         char hdr[50];
551         void *unpacked;
552         unsigned long len;
553         int hdrlen;
554         ssize_t size;
555         z_stream stream;
556
557         unpacked = read_sha1_file(request->obj->sha1, &type, &len);
558         hdrlen = sprintf(hdr, "%s %lu", typename(type), len) + 1;
559
560         /* Set it up */
561         memset(&stream, 0, sizeof(stream));
562         deflateInit(&stream, zlib_compression_level);
563         size = deflateBound(&stream, len + hdrlen);
564         strbuf_init(&request->buffer.buf, size);
565         request->buffer.posn = 0;
566
567         /* Compress it */
568         stream.next_out = (unsigned char *)request->buffer.buf.buf;
569         stream.avail_out = size;
570
571         /* First header.. */
572         stream.next_in = (void *)hdr;
573         stream.avail_in = hdrlen;
574         while (deflate(&stream, 0) == Z_OK)
575                 /* nothing */;
576
577         /* Then the data itself.. */
578         stream.next_in = unpacked;
579         stream.avail_in = len;
580         while (deflate(&stream, Z_FINISH) == Z_OK)
581                 /* nothing */;
582         deflateEnd(&stream);
583         free(unpacked);
584
585         request->buffer.buf.len = stream.total_out;
586
587         strbuf_addstr(&buf, "Destination: ");
588         append_remote_object_url(&buf, repo->url, hex, 0);
589         request->dest = strbuf_detach(&buf, NULL);
590
591         append_remote_object_url(&buf, repo->url, hex, 0);
592         strbuf_add(&buf, request->lock->tmpfile_suffix, 41);
593         request->url = strbuf_detach(&buf, NULL);
594
595         slot = get_active_slot();
596         slot->callback_func = process_response;
597         slot->callback_data = request;
598         curl_easy_setopt(slot->curl, CURLOPT_INFILE, &request->buffer);
599         curl_easy_setopt(slot->curl, CURLOPT_INFILESIZE, request->buffer.buf.len);
600         curl_easy_setopt(slot->curl, CURLOPT_READFUNCTION, fread_buffer);
601 #ifndef NO_CURL_IOCTL
602         curl_easy_setopt(slot->curl, CURLOPT_IOCTLFUNCTION, ioctl_buffer);
603         curl_easy_setopt(slot->curl, CURLOPT_IOCTLDATA, &request->buffer);
604 #endif
605         curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION, fwrite_null);
606         curl_easy_setopt(slot->curl, CURLOPT_CUSTOMREQUEST, DAV_PUT);
607         curl_easy_setopt(slot->curl, CURLOPT_UPLOAD, 1);
608         curl_easy_setopt(slot->curl, CURLOPT_PUT, 1);
609         curl_easy_setopt(slot->curl, CURLOPT_NOBODY, 0);
610         curl_easy_setopt(slot->curl, CURLOPT_URL, request->url);
611
612         if (start_active_slot(slot)) {
613                 request->slot = slot;
614                 request->state = RUN_PUT;
615         } else {
616                 request->state = ABORTED;
617                 free(request->url);
618                 request->url = NULL;
619         }
620 }
621
622 static void start_move(struct transfer_request *request)
623 {
624         struct active_request_slot *slot;
625         struct curl_slist *dav_headers = NULL;
626
627         slot = get_active_slot();
628         slot->callback_func = process_response;
629         slot->callback_data = request;
630         curl_easy_setopt(slot->curl, CURLOPT_HTTPGET, 1); /* undo PUT setup */
631         curl_easy_setopt(slot->curl, CURLOPT_CUSTOMREQUEST, DAV_MOVE);
632         dav_headers = curl_slist_append(dav_headers, request->dest);
633         dav_headers = curl_slist_append(dav_headers, "Overwrite: T");
634         curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, dav_headers);
635         curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION, fwrite_null);
636         curl_easy_setopt(slot->curl, CURLOPT_URL, request->url);
637
638         if (start_active_slot(slot)) {
639                 request->slot = slot;
640                 request->state = RUN_MOVE;
641         } else {
642                 request->state = ABORTED;
643                 free(request->url);
644                 request->url = NULL;
645         }
646 }
647
648 static int refresh_lock(struct remote_lock *lock)
649 {
650         struct active_request_slot *slot;
651         struct slot_results results;
652         struct curl_slist *dav_headers;
653         int rc = 0;
654
655         lock->refreshing = 1;
656
657         dav_headers = get_dav_token_headers(lock, DAV_HEADER_IF | DAV_HEADER_TIMEOUT);
658
659         slot = get_active_slot();
660         slot->results = &results;
661         curl_easy_setopt(slot->curl, CURLOPT_HTTPGET, 1);
662         curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION, fwrite_null);
663         curl_easy_setopt(slot->curl, CURLOPT_URL, lock->url);
664         curl_easy_setopt(slot->curl, CURLOPT_CUSTOMREQUEST, DAV_LOCK);
665         curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, dav_headers);
666
667         if (start_active_slot(slot)) {
668                 run_active_slot(slot);
669                 if (results.curl_result != CURLE_OK) {
670                         fprintf(stderr, "LOCK HTTP error %ld\n",
671                                 results.http_code);
672                 } else {
673                         lock->start_time = time(NULL);
674                         rc = 1;
675                 }
676         }
677
678         lock->refreshing = 0;
679         curl_slist_free_all(dav_headers);
680
681         return rc;
682 }
683
684 static void check_locks(void)
685 {
686         struct remote_lock *lock = repo->locks;
687         time_t current_time = time(NULL);
688         int time_remaining;
689
690         while (lock) {
691                 time_remaining = lock->start_time + lock->timeout -
692                         current_time;
693                 if (!lock->refreshing && time_remaining < LOCK_REFRESH) {
694                         if (!refresh_lock(lock)) {
695                                 fprintf(stderr,
696                                         "Unable to refresh lock for %s\n",
697                                         lock->url);
698                                 aborted = 1;
699                                 return;
700                         }
701                 }
702                 lock = lock->next;
703         }
704 }
705
706 static void release_request(struct transfer_request *request)
707 {
708         struct transfer_request *entry = request_queue_head;
709
710         if (request == request_queue_head) {
711                 request_queue_head = request->next;
712         } else {
713                 while (entry->next != NULL && entry->next != request)
714                         entry = entry->next;
715                 if (entry->next == request)
716                         entry->next = entry->next->next;
717         }
718
719         if (request->local_fileno != -1)
720                 close(request->local_fileno);
721         if (request->local_stream)
722                 fclose(request->local_stream);
723         free(request->url);
724         free(request);
725 }
726
727 static void finish_request(struct transfer_request *request)
728 {
729         struct stat st;
730         struct packed_git *target;
731         struct packed_git **lst;
732         struct active_request_slot *slot;
733
734         request->curl_result = request->slot->curl_result;
735         request->http_code = request->slot->http_code;
736         slot = request->slot;
737         request->slot = NULL;
738
739         /* Keep locks active */
740         check_locks();
741
742         if (request->headers != NULL)
743                 curl_slist_free_all(request->headers);
744
745         /* URL is reused for MOVE after PUT */
746         if (request->state != RUN_PUT) {
747                 free(request->url);
748                 request->url = NULL;
749         }
750
751         if (request->state == RUN_MKCOL) {
752                 if (request->curl_result == CURLE_OK ||
753                     request->http_code == 405) {
754                         remote_dir_exists[request->obj->sha1[0]] = 1;
755                         start_put(request);
756                 } else {
757                         fprintf(stderr, "MKCOL %s failed, aborting (%d/%ld)\n",
758                                 sha1_to_hex(request->obj->sha1),
759                                 request->curl_result, request->http_code);
760                         request->state = ABORTED;
761                         aborted = 1;
762                 }
763         } else if (request->state == RUN_PUT) {
764                 if (request->curl_result == CURLE_OK) {
765                         start_move(request);
766                 } else {
767                         fprintf(stderr, "PUT %s failed, aborting (%d/%ld)\n",
768                                 sha1_to_hex(request->obj->sha1),
769                                 request->curl_result, request->http_code);
770                         request->state = ABORTED;
771                         aborted = 1;
772                 }
773         } else if (request->state == RUN_MOVE) {
774                 if (request->curl_result == CURLE_OK) {
775                         if (push_verbosely)
776                                 fprintf(stderr, "    sent %s\n",
777                                         sha1_to_hex(request->obj->sha1));
778                         request->obj->flags |= REMOTE;
779                         release_request(request);
780                 } else {
781                         fprintf(stderr, "MOVE %s failed, aborting (%d/%ld)\n",
782                                 sha1_to_hex(request->obj->sha1),
783                                 request->curl_result, request->http_code);
784                         request->state = ABORTED;
785                         aborted = 1;
786                 }
787         } else if (request->state == RUN_FETCH_LOOSE) {
788                 close(request->local_fileno);
789                 request->local_fileno = -1;
790
791                 if (request->curl_result != CURLE_OK &&
792                     request->http_code != 416) {
793                         if (stat(request->tmpfile, &st) == 0) {
794                                 if (st.st_size == 0)
795                                         unlink_or_warn(request->tmpfile);
796                         }
797                 } else {
798                         if (request->http_code == 416)
799                                 warning("requested range invalid; we may already have all the data.");
800
801                         git_inflate_end(&request->stream);
802                         git_SHA1_Final(request->real_sha1, &request->c);
803                         if (request->zret != Z_STREAM_END) {
804                                 unlink_or_warn(request->tmpfile);
805                         } else if (hashcmp(request->obj->sha1, request->real_sha1)) {
806                                 unlink_or_warn(request->tmpfile);
807                         } else {
808                                 request->rename =
809                                         move_temp_to_file(
810                                                 request->tmpfile,
811                                                 request->filename);
812                                 if (request->rename == 0)
813                                         request->obj->flags |= (LOCAL | REMOTE);
814                         }
815                 }
816
817                 /* Try fetching packed if necessary */
818                 if (request->obj->flags & LOCAL)
819                         release_request(request);
820                 else
821                         start_fetch_packed(request);
822
823         } else if (request->state == RUN_FETCH_PACKED) {
824                 if (request->curl_result != CURLE_OK) {
825                         fprintf(stderr, "Unable to get pack file %s\n%s",
826                                 request->url, curl_errorstr);
827                         repo->can_update_info_refs = 0;
828                 } else {
829                         off_t pack_size = ftell(request->local_stream);
830
831                         fclose(request->local_stream);
832                         request->local_stream = NULL;
833                         slot->local = NULL;
834                         if (!move_temp_to_file(request->tmpfile,
835                                                request->filename)) {
836                                 target = (struct packed_git *)request->userData;
837                                 target->pack_size = pack_size;
838                                 lst = &repo->packs;
839                                 while (*lst != target)
840                                         lst = &((*lst)->next);
841                                 *lst = (*lst)->next;
842
843                                 if (!verify_pack(target))
844                                         install_packed_git(target);
845                                 else
846                                         repo->can_update_info_refs = 0;
847                         }
848                 }
849                 release_request(request);
850         }
851 }
852
853 #ifdef USE_CURL_MULTI
854 static int is_running_queue;
855 static int fill_active_slot(void *unused)
856 {
857         struct transfer_request *request;
858
859         if (aborted || !is_running_queue)
860                 return 0;
861
862         for (request = request_queue_head; request; request = request->next) {
863                 if (request->state == NEED_FETCH) {
864                         start_fetch_loose(request);
865                         return 1;
866                 } else if (pushing && request->state == NEED_PUSH) {
867                         if (remote_dir_exists[request->obj->sha1[0]] == 1) {
868                                 start_put(request);
869                         } else {
870                                 start_mkcol(request);
871                         }
872                         return 1;
873                 }
874         }
875         return 0;
876 }
877 #endif
878
879 static void get_remote_object_list(unsigned char parent);
880
881 static void add_fetch_request(struct object *obj)
882 {
883         struct transfer_request *request;
884
885         check_locks();
886
887         /*
888          * Don't fetch the object if it's known to exist locally
889          * or is already in the request queue
890          */
891         if (remote_dir_exists[obj->sha1[0]] == -1)
892                 get_remote_object_list(obj->sha1[0]);
893         if (obj->flags & (LOCAL | FETCHING))
894                 return;
895
896         obj->flags |= FETCHING;
897         request = xmalloc(sizeof(*request));
898         request->obj = obj;
899         request->url = NULL;
900         request->lock = NULL;
901         request->headers = NULL;
902         request->local_fileno = -1;
903         request->local_stream = NULL;
904         request->state = NEED_FETCH;
905         request->next = request_queue_head;
906         request_queue_head = request;
907
908 #ifdef USE_CURL_MULTI
909         fill_active_slots();
910         step_active_slots();
911 #endif
912 }
913
914 static int add_send_request(struct object *obj, struct remote_lock *lock)
915 {
916         struct transfer_request *request = request_queue_head;
917         struct packed_git *target;
918
919         /* Keep locks active */
920         check_locks();
921
922         /*
923          * Don't push the object if it's known to exist on the remote
924          * or is already in the request queue
925          */
926         if (remote_dir_exists[obj->sha1[0]] == -1)
927                 get_remote_object_list(obj->sha1[0]);
928         if (obj->flags & (REMOTE | PUSHING))
929                 return 0;
930         target = find_sha1_pack(obj->sha1, repo->packs);
931         if (target) {
932                 obj->flags |= REMOTE;
933                 return 0;
934         }
935
936         obj->flags |= PUSHING;
937         request = xmalloc(sizeof(*request));
938         request->obj = obj;
939         request->url = NULL;
940         request->lock = lock;
941         request->headers = NULL;
942         request->local_fileno = -1;
943         request->local_stream = NULL;
944         request->state = NEED_PUSH;
945         request->next = request_queue_head;
946         request_queue_head = request;
947
948 #ifdef USE_CURL_MULTI
949         fill_active_slots();
950         step_active_slots();
951 #endif
952
953         return 1;
954 }
955
956 static int fetch_index(unsigned char *sha1)
957 {
958         int ret = 0;
959         char *hex = xstrdup(sha1_to_hex(sha1));
960         char *filename;
961         char *url;
962         char tmpfile[PATH_MAX];
963         long prev_posn = 0;
964         char range[RANGE_HEADER_SIZE];
965         struct curl_slist *range_header = NULL;
966
967         FILE *indexfile;
968         struct active_request_slot *slot;
969         struct slot_results results;
970
971         /* Don't use the index if the pack isn't there */
972         url = xmalloc(strlen(repo->url) + 64);
973         sprintf(url, "%sobjects/pack/pack-%s.pack", repo->url, hex);
974         slot = get_active_slot();
975         slot->results = &results;
976         curl_easy_setopt(slot->curl, CURLOPT_URL, url);
977         curl_easy_setopt(slot->curl, CURLOPT_NOBODY, 1);
978         if (start_active_slot(slot)) {
979                 run_active_slot(slot);
980                 if (results.curl_result != CURLE_OK) {
981                         ret = error("Unable to verify pack %s is available",
982                                     hex);
983                         goto cleanup_pack;
984                 }
985         } else {
986                 ret = error("Unable to start request");
987                 goto cleanup_pack;
988         }
989
990         if (has_pack_index(sha1)) {
991                 ret = 0;
992                 goto cleanup_pack;
993         }
994
995         if (push_verbosely)
996                 fprintf(stderr, "Getting index for pack %s\n", hex);
997
998         sprintf(url, "%sobjects/pack/pack-%s.idx", repo->url, hex);
999
1000         filename = sha1_pack_index_name(sha1);
1001         snprintf(tmpfile, sizeof(tmpfile), "%s.temp", filename);
1002         indexfile = fopen(tmpfile, "a");
1003         if (!indexfile) {
1004                 ret = error("Unable to open local file %s for pack index",
1005                             tmpfile);
1006                 goto cleanup_pack;
1007         }
1008
1009         slot = get_active_slot();
1010         slot->results = &results;
1011         curl_easy_setopt(slot->curl, CURLOPT_NOBODY, 0);
1012         curl_easy_setopt(slot->curl, CURLOPT_HTTPGET, 1);
1013         curl_easy_setopt(slot->curl, CURLOPT_FILE, indexfile);
1014         curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION, fwrite);
1015         curl_easy_setopt(slot->curl, CURLOPT_URL, url);
1016         curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, no_pragma_header);
1017         slot->local = indexfile;
1018
1019         /*
1020          * If there is data present from a previous transfer attempt,
1021          * resume where it left off
1022          */
1023         prev_posn = ftell(indexfile);
1024         if (prev_posn>0) {
1025                 if (push_verbosely)
1026                         fprintf(stderr,
1027                                 "Resuming fetch of index for pack %s at byte %ld\n",
1028                                 hex, prev_posn);
1029                 sprintf(range, "Range: bytes=%ld-", prev_posn);
1030                 range_header = curl_slist_append(range_header, range);
1031                 curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, range_header);
1032         }
1033
1034         if (start_active_slot(slot)) {
1035                 run_active_slot(slot);
1036                 if (results.curl_result != CURLE_OK) {
1037                         ret = error("Unable to get pack index %s\n%s", url,
1038                                     curl_errorstr);
1039                         goto cleanup_index;
1040                 }
1041         } else {
1042                 ret = error("Unable to start request");
1043                 goto cleanup_index;
1044         }
1045
1046         ret = move_temp_to_file(tmpfile, filename);
1047
1048 cleanup_index:
1049         fclose(indexfile);
1050         slot->local = NULL;
1051 cleanup_pack:
1052         free(url);
1053         free(hex);
1054         return ret;
1055 }
1056
1057 static int setup_index(unsigned char *sha1)
1058 {
1059         struct packed_git *new_pack;
1060
1061         if (fetch_index(sha1))
1062                 return -1;
1063
1064         new_pack = parse_pack_index(sha1);
1065         if (!new_pack)
1066                 return -1; /* parse_pack_index() already issued error message */
1067         new_pack->next = repo->packs;
1068         repo->packs = new_pack;
1069         return 0;
1070 }
1071
1072 static int fetch_indices(void)
1073 {
1074         unsigned char sha1[20];
1075         char *url;
1076         struct strbuf buffer = STRBUF_INIT;
1077         char *data;
1078         int i = 0;
1079
1080         struct active_request_slot *slot;
1081         struct slot_results results;
1082
1083         if (push_verbosely)
1084                 fprintf(stderr, "Getting pack list\n");
1085
1086         url = xmalloc(strlen(repo->url) + 20);
1087         sprintf(url, "%sobjects/info/packs", repo->url);
1088
1089         slot = get_active_slot();
1090         slot->results = &results;
1091         curl_easy_setopt(slot->curl, CURLOPT_FILE, &buffer);
1092         curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION, fwrite_buffer);
1093         curl_easy_setopt(slot->curl, CURLOPT_URL, url);
1094         curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, NULL);
1095         if (start_active_slot(slot)) {
1096                 run_active_slot(slot);
1097                 if (results.curl_result != CURLE_OK) {
1098                         strbuf_release(&buffer);
1099                         free(url);
1100                         if (results.http_code == 404)
1101                                 return 0;
1102                         else
1103                                 return error("%s", curl_errorstr);
1104                 }
1105         } else {
1106                 strbuf_release(&buffer);
1107                 free(url);
1108                 return error("Unable to start request");
1109         }
1110         free(url);
1111
1112         data = buffer.buf;
1113         while (i < buffer.len) {
1114                 switch (data[i]) {
1115                 case 'P':
1116                         i++;
1117                         if (i + 52 < buffer.len &&
1118                             !prefixcmp(data + i, " pack-") &&
1119                             !prefixcmp(data + i + 46, ".pack\n")) {
1120                                 get_sha1_hex(data + i + 6, sha1);
1121                                 setup_index(sha1);
1122                                 i += 51;
1123                                 break;
1124                         }
1125                 default:
1126                         while (data[i] != '\n')
1127                                 i++;
1128                 }
1129                 i++;
1130         }
1131
1132         strbuf_release(&buffer);
1133         return 0;
1134 }
1135
1136 static void one_remote_object(const char *hex)
1137 {
1138         unsigned char sha1[20];
1139         struct object *obj;
1140
1141         if (get_sha1_hex(hex, sha1) != 0)
1142                 return;
1143
1144         obj = lookup_object(sha1);
1145         if (!obj)
1146                 obj = parse_object(sha1);
1147
1148         /* Ignore remote objects that don't exist locally */
1149         if (!obj)
1150                 return;
1151
1152         obj->flags |= REMOTE;
1153         if (!object_list_contains(objects, obj))
1154                 object_list_insert(obj, &objects);
1155 }
1156
1157 static void handle_lockprop_ctx(struct xml_ctx *ctx, int tag_closed)
1158 {
1159         int *lock_flags = (int *)ctx->userData;
1160
1161         if (tag_closed) {
1162                 if (!strcmp(ctx->name, DAV_CTX_LOCKENTRY)) {
1163                         if ((*lock_flags & DAV_PROP_LOCKEX) &&
1164                             (*lock_flags & DAV_PROP_LOCKWR)) {
1165                                 *lock_flags |= DAV_LOCK_OK;
1166                         }
1167                         *lock_flags &= DAV_LOCK_OK;
1168                 } else if (!strcmp(ctx->name, DAV_CTX_LOCKTYPE_WRITE)) {
1169                         *lock_flags |= DAV_PROP_LOCKWR;
1170                 } else if (!strcmp(ctx->name, DAV_CTX_LOCKTYPE_EXCLUSIVE)) {
1171                         *lock_flags |= DAV_PROP_LOCKEX;
1172                 }
1173         }
1174 }
1175
1176 static void handle_new_lock_ctx(struct xml_ctx *ctx, int tag_closed)
1177 {
1178         struct remote_lock *lock = (struct remote_lock *)ctx->userData;
1179         git_SHA_CTX sha_ctx;
1180         unsigned char lock_token_sha1[20];
1181
1182         if (tag_closed && ctx->cdata) {
1183                 if (!strcmp(ctx->name, DAV_ACTIVELOCK_OWNER)) {
1184                         lock->owner = xmalloc(strlen(ctx->cdata) + 1);
1185                         strcpy(lock->owner, ctx->cdata);
1186                 } else if (!strcmp(ctx->name, DAV_ACTIVELOCK_TIMEOUT)) {
1187                         if (!prefixcmp(ctx->cdata, "Second-"))
1188                                 lock->timeout =
1189                                         strtol(ctx->cdata + 7, NULL, 10);
1190                 } else if (!strcmp(ctx->name, DAV_ACTIVELOCK_TOKEN)) {
1191                         lock->token = xmalloc(strlen(ctx->cdata) + 1);
1192                         strcpy(lock->token, ctx->cdata);
1193
1194                         git_SHA1_Init(&sha_ctx);
1195                         git_SHA1_Update(&sha_ctx, lock->token, strlen(lock->token));
1196                         git_SHA1_Final(lock_token_sha1, &sha_ctx);
1197
1198                         lock->tmpfile_suffix[0] = '_';
1199                         memcpy(lock->tmpfile_suffix + 1, sha1_to_hex(lock_token_sha1), 40);
1200                 }
1201         }
1202 }
1203
1204 static void one_remote_ref(char *refname);
1205
1206 static void
1207 xml_start_tag(void *userData, const char *name, const char **atts)
1208 {
1209         struct xml_ctx *ctx = (struct xml_ctx *)userData;
1210         const char *c = strchr(name, ':');
1211         int new_len;
1212
1213         if (c == NULL)
1214                 c = name;
1215         else
1216                 c++;
1217
1218         new_len = strlen(ctx->name) + strlen(c) + 2;
1219
1220         if (new_len > ctx->len) {
1221                 ctx->name = xrealloc(ctx->name, new_len);
1222                 ctx->len = new_len;
1223         }
1224         strcat(ctx->name, ".");
1225         strcat(ctx->name, c);
1226
1227         free(ctx->cdata);
1228         ctx->cdata = NULL;
1229
1230         ctx->userFunc(ctx, 0);
1231 }
1232
1233 static void
1234 xml_end_tag(void *userData, const char *name)
1235 {
1236         struct xml_ctx *ctx = (struct xml_ctx *)userData;
1237         const char *c = strchr(name, ':');
1238         char *ep;
1239
1240         ctx->userFunc(ctx, 1);
1241
1242         if (c == NULL)
1243                 c = name;
1244         else
1245                 c++;
1246
1247         ep = ctx->name + strlen(ctx->name) - strlen(c) - 1;
1248         *ep = 0;
1249 }
1250
1251 static void
1252 xml_cdata(void *userData, const XML_Char *s, int len)
1253 {
1254         struct xml_ctx *ctx = (struct xml_ctx *)userData;
1255         free(ctx->cdata);
1256         ctx->cdata = xmemdupz(s, len);
1257 }
1258
1259 static struct remote_lock *lock_remote(const char *path, long timeout)
1260 {
1261         struct active_request_slot *slot;
1262         struct slot_results results;
1263         struct buffer out_buffer = { STRBUF_INIT, 0 };
1264         struct strbuf in_buffer = STRBUF_INIT;
1265         char *url;
1266         char *ep;
1267         char timeout_header[25];
1268         struct remote_lock *lock = NULL;
1269         struct curl_slist *dav_headers = NULL;
1270         struct xml_ctx ctx;
1271         char *escaped;
1272
1273         url = xmalloc(strlen(repo->url) + strlen(path) + 1);
1274         sprintf(url, "%s%s", repo->url, path);
1275
1276         /* Make sure leading directories exist for the remote ref */
1277         ep = strchr(url + strlen(repo->url) + 1, '/');
1278         while (ep) {
1279                 char saved_character = ep[1];
1280                 ep[1] = '\0';
1281                 slot = get_active_slot();
1282                 slot->results = &results;
1283                 curl_easy_setopt(slot->curl, CURLOPT_HTTPGET, 1);
1284                 curl_easy_setopt(slot->curl, CURLOPT_URL, url);
1285                 curl_easy_setopt(slot->curl, CURLOPT_CUSTOMREQUEST, DAV_MKCOL);
1286                 curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION, fwrite_null);
1287                 if (start_active_slot(slot)) {
1288                         run_active_slot(slot);
1289                         if (results.curl_result != CURLE_OK &&
1290                             results.http_code != 405) {
1291                                 fprintf(stderr,
1292                                         "Unable to create branch path %s\n",
1293                                         url);
1294                                 free(url);
1295                                 return NULL;
1296                         }
1297                 } else {
1298                         fprintf(stderr, "Unable to start MKCOL request\n");
1299                         free(url);
1300                         return NULL;
1301                 }
1302                 ep[1] = saved_character;
1303                 ep = strchr(ep + 1, '/');
1304         }
1305
1306         escaped = xml_entities(git_default_email);
1307         strbuf_addf(&out_buffer.buf, LOCK_REQUEST, escaped);
1308         free(escaped);
1309
1310         sprintf(timeout_header, "Timeout: Second-%ld", timeout);
1311         dav_headers = curl_slist_append(dav_headers, timeout_header);
1312         dav_headers = curl_slist_append(dav_headers, "Content-Type: text/xml");
1313
1314         slot = get_active_slot();
1315         slot->results = &results;
1316         curl_easy_setopt(slot->curl, CURLOPT_INFILE, &out_buffer);
1317         curl_easy_setopt(slot->curl, CURLOPT_INFILESIZE, out_buffer.buf.len);
1318         curl_easy_setopt(slot->curl, CURLOPT_READFUNCTION, fread_buffer);
1319 #ifndef NO_CURL_IOCTL
1320         curl_easy_setopt(slot->curl, CURLOPT_IOCTLFUNCTION, ioctl_buffer);
1321         curl_easy_setopt(slot->curl, CURLOPT_IOCTLDATA, &out_buffer);
1322 #endif
1323         curl_easy_setopt(slot->curl, CURLOPT_FILE, &in_buffer);
1324         curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION, fwrite_buffer);
1325         curl_easy_setopt(slot->curl, CURLOPT_URL, url);
1326         curl_easy_setopt(slot->curl, CURLOPT_UPLOAD, 1);
1327         curl_easy_setopt(slot->curl, CURLOPT_CUSTOMREQUEST, DAV_LOCK);
1328         curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, dav_headers);
1329
1330         lock = xcalloc(1, sizeof(*lock));
1331         lock->timeout = -1;
1332
1333         if (start_active_slot(slot)) {
1334                 run_active_slot(slot);
1335                 if (results.curl_result == CURLE_OK) {
1336                         XML_Parser parser = XML_ParserCreate(NULL);
1337                         enum XML_Status result;
1338                         ctx.name = xcalloc(10, 1);
1339                         ctx.len = 0;
1340                         ctx.cdata = NULL;
1341                         ctx.userFunc = handle_new_lock_ctx;
1342                         ctx.userData = lock;
1343                         XML_SetUserData(parser, &ctx);
1344                         XML_SetElementHandler(parser, xml_start_tag,
1345                                               xml_end_tag);
1346                         XML_SetCharacterDataHandler(parser, xml_cdata);
1347                         result = XML_Parse(parser, in_buffer.buf,
1348                                            in_buffer.len, 1);
1349                         free(ctx.name);
1350                         if (result != XML_STATUS_OK) {
1351                                 fprintf(stderr, "XML error: %s\n",
1352                                         XML_ErrorString(
1353                                                 XML_GetErrorCode(parser)));
1354                                 lock->timeout = -1;
1355                         }
1356                         XML_ParserFree(parser);
1357                 }
1358         } else {
1359                 fprintf(stderr, "Unable to start LOCK request\n");
1360         }
1361
1362         curl_slist_free_all(dav_headers);
1363         strbuf_release(&out_buffer.buf);
1364         strbuf_release(&in_buffer);
1365
1366         if (lock->token == NULL || lock->timeout <= 0) {
1367                 free(lock->token);
1368                 free(lock->owner);
1369                 free(url);
1370                 free(lock);
1371                 lock = NULL;
1372         } else {
1373                 lock->url = url;
1374                 lock->start_time = time(NULL);
1375                 lock->next = repo->locks;
1376                 repo->locks = lock;
1377         }
1378
1379         return lock;
1380 }
1381
1382 static int unlock_remote(struct remote_lock *lock)
1383 {
1384         struct active_request_slot *slot;
1385         struct slot_results results;
1386         struct remote_lock *prev = repo->locks;
1387         struct curl_slist *dav_headers;
1388         int rc = 0;
1389
1390         dav_headers = get_dav_token_headers(lock, DAV_HEADER_LOCK);
1391
1392         slot = get_active_slot();
1393         slot->results = &results;
1394         curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION, fwrite_null);
1395         curl_easy_setopt(slot->curl, CURLOPT_URL, lock->url);
1396         curl_easy_setopt(slot->curl, CURLOPT_CUSTOMREQUEST, DAV_UNLOCK);
1397         curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, dav_headers);
1398
1399         if (start_active_slot(slot)) {
1400                 run_active_slot(slot);
1401                 if (results.curl_result == CURLE_OK)
1402                         rc = 1;
1403                 else
1404                         fprintf(stderr, "UNLOCK HTTP error %ld\n",
1405                                 results.http_code);
1406         } else {
1407                 fprintf(stderr, "Unable to start UNLOCK request\n");
1408         }
1409
1410         curl_slist_free_all(dav_headers);
1411
1412         if (repo->locks == lock) {
1413                 repo->locks = lock->next;
1414         } else {
1415                 while (prev && prev->next != lock)
1416                         prev = prev->next;
1417                 if (prev)
1418                         prev->next = prev->next->next;
1419         }
1420
1421         free(lock->owner);
1422         free(lock->url);
1423         free(lock->token);
1424         free(lock);
1425
1426         return rc;
1427 }
1428
1429 static void remove_locks(void)
1430 {
1431         struct remote_lock *lock = repo->locks;
1432
1433         fprintf(stderr, "Removing remote locks...\n");
1434         while (lock) {
1435                 unlock_remote(lock);
1436                 lock = lock->next;
1437         }
1438 }
1439
1440 static void remove_locks_on_signal(int signo)
1441 {
1442         remove_locks();
1443         sigchain_pop(signo);
1444         raise(signo);
1445 }
1446
1447 static void remote_ls(const char *path, int flags,
1448                       void (*userFunc)(struct remote_ls_ctx *ls),
1449                       void *userData);
1450
1451 static void process_ls_object(struct remote_ls_ctx *ls)
1452 {
1453         unsigned int *parent = (unsigned int *)ls->userData;
1454         char *path = ls->dentry_name;
1455         char *obj_hex;
1456
1457         if (!strcmp(ls->path, ls->dentry_name) && (ls->flags & IS_DIR)) {
1458                 remote_dir_exists[*parent] = 1;
1459                 return;
1460         }
1461
1462         if (strlen(path) != 49)
1463                 return;
1464         path += 8;
1465         obj_hex = xmalloc(strlen(path));
1466         /* NB: path is not null-terminated, can not use strlcpy here */
1467         memcpy(obj_hex, path, 2);
1468         strcpy(obj_hex + 2, path + 3);
1469         one_remote_object(obj_hex);
1470         free(obj_hex);
1471 }
1472
1473 static void process_ls_ref(struct remote_ls_ctx *ls)
1474 {
1475         if (!strcmp(ls->path, ls->dentry_name) && (ls->dentry_flags & IS_DIR)) {
1476                 fprintf(stderr, "  %s\n", ls->dentry_name);
1477                 return;
1478         }
1479
1480         if (!(ls->dentry_flags & IS_DIR))
1481                 one_remote_ref(ls->dentry_name);
1482 }
1483
1484 static void handle_remote_ls_ctx(struct xml_ctx *ctx, int tag_closed)
1485 {
1486         struct remote_ls_ctx *ls = (struct remote_ls_ctx *)ctx->userData;
1487
1488         if (tag_closed) {
1489                 if (!strcmp(ctx->name, DAV_PROPFIND_RESP) && ls->dentry_name) {
1490                         if (ls->dentry_flags & IS_DIR) {
1491                                 if (ls->flags & PROCESS_DIRS) {
1492                                         ls->userFunc(ls);
1493                                 }
1494                                 if (strcmp(ls->dentry_name, ls->path) &&
1495                                     ls->flags & RECURSIVE) {
1496                                         remote_ls(ls->dentry_name,
1497                                                   ls->flags,
1498                                                   ls->userFunc,
1499                                                   ls->userData);
1500                                 }
1501                         } else if (ls->flags & PROCESS_FILES) {
1502                                 ls->userFunc(ls);
1503                         }
1504                 } else if (!strcmp(ctx->name, DAV_PROPFIND_NAME) && ctx->cdata) {
1505                         char *path = ctx->cdata;
1506                         if (*ctx->cdata == 'h') {
1507                                 path = strstr(path, "//");
1508                                 if (path) {
1509                                         path = strchr(path+2, '/');
1510                                 }
1511                         }
1512                         if (path) {
1513                                 path += repo->path_len;
1514                                 ls->dentry_name = xstrdup(path);
1515                         }
1516                 } else if (!strcmp(ctx->name, DAV_PROPFIND_COLLECTION)) {
1517                         ls->dentry_flags |= IS_DIR;
1518                 }
1519         } else if (!strcmp(ctx->name, DAV_PROPFIND_RESP)) {
1520                 free(ls->dentry_name);
1521                 ls->dentry_name = NULL;
1522                 ls->dentry_flags = 0;
1523         }
1524 }
1525
1526 /*
1527  * NEEDSWORK: remote_ls() ignores info/refs on the remote side.  But it
1528  * should _only_ heed the information from that file, instead of trying to
1529  * determine the refs from the remote file system (badly: it does not even
1530  * know about packed-refs).
1531  */
1532 static void remote_ls(const char *path, int flags,
1533                       void (*userFunc)(struct remote_ls_ctx *ls),
1534                       void *userData)
1535 {
1536         char *url = xmalloc(strlen(repo->url) + strlen(path) + 1);
1537         struct active_request_slot *slot;
1538         struct slot_results results;
1539         struct strbuf in_buffer = STRBUF_INIT;
1540         struct buffer out_buffer = { STRBUF_INIT, 0 };
1541         struct curl_slist *dav_headers = NULL;
1542         struct xml_ctx ctx;
1543         struct remote_ls_ctx ls;
1544
1545         ls.flags = flags;
1546         ls.path = xstrdup(path);
1547         ls.dentry_name = NULL;
1548         ls.dentry_flags = 0;
1549         ls.userData = userData;
1550         ls.userFunc = userFunc;
1551
1552         sprintf(url, "%s%s", repo->url, path);
1553
1554         strbuf_addf(&out_buffer.buf, PROPFIND_ALL_REQUEST);
1555
1556         dav_headers = curl_slist_append(dav_headers, "Depth: 1");
1557         dav_headers = curl_slist_append(dav_headers, "Content-Type: text/xml");
1558
1559         slot = get_active_slot();
1560         slot->results = &results;
1561         curl_easy_setopt(slot->curl, CURLOPT_INFILE, &out_buffer);
1562         curl_easy_setopt(slot->curl, CURLOPT_INFILESIZE, out_buffer.buf.len);
1563         curl_easy_setopt(slot->curl, CURLOPT_READFUNCTION, fread_buffer);
1564 #ifndef NO_CURL_IOCTL
1565         curl_easy_setopt(slot->curl, CURLOPT_IOCTLFUNCTION, ioctl_buffer);
1566         curl_easy_setopt(slot->curl, CURLOPT_IOCTLDATA, &out_buffer);
1567 #endif
1568         curl_easy_setopt(slot->curl, CURLOPT_FILE, &in_buffer);
1569         curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION, fwrite_buffer);
1570         curl_easy_setopt(slot->curl, CURLOPT_URL, url);
1571         curl_easy_setopt(slot->curl, CURLOPT_UPLOAD, 1);
1572         curl_easy_setopt(slot->curl, CURLOPT_CUSTOMREQUEST, DAV_PROPFIND);
1573         curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, dav_headers);
1574
1575         if (start_active_slot(slot)) {
1576                 run_active_slot(slot);
1577                 if (results.curl_result == CURLE_OK) {
1578                         XML_Parser parser = XML_ParserCreate(NULL);
1579                         enum XML_Status result;
1580                         ctx.name = xcalloc(10, 1);
1581                         ctx.len = 0;
1582                         ctx.cdata = NULL;
1583                         ctx.userFunc = handle_remote_ls_ctx;
1584                         ctx.userData = &ls;
1585                         XML_SetUserData(parser, &ctx);
1586                         XML_SetElementHandler(parser, xml_start_tag,
1587                                               xml_end_tag);
1588                         XML_SetCharacterDataHandler(parser, xml_cdata);
1589                         result = XML_Parse(parser, in_buffer.buf,
1590                                            in_buffer.len, 1);
1591                         free(ctx.name);
1592
1593                         if (result != XML_STATUS_OK) {
1594                                 fprintf(stderr, "XML error: %s\n",
1595                                         XML_ErrorString(
1596                                                 XML_GetErrorCode(parser)));
1597                         }
1598                         XML_ParserFree(parser);
1599                 }
1600         } else {
1601                 fprintf(stderr, "Unable to start PROPFIND request\n");
1602         }
1603
1604         free(ls.path);
1605         free(url);
1606         strbuf_release(&out_buffer.buf);
1607         strbuf_release(&in_buffer);
1608         curl_slist_free_all(dav_headers);
1609 }
1610
1611 static void get_remote_object_list(unsigned char parent)
1612 {
1613         char path[] = "objects/XX/";
1614         static const char hex[] = "0123456789abcdef";
1615         unsigned int val = parent;
1616
1617         path[8] = hex[val >> 4];
1618         path[9] = hex[val & 0xf];
1619         remote_dir_exists[val] = 0;
1620         remote_ls(path, (PROCESS_FILES | PROCESS_DIRS),
1621                   process_ls_object, &val);
1622 }
1623
1624 static int locking_available(void)
1625 {
1626         struct active_request_slot *slot;
1627         struct slot_results results;
1628         struct strbuf in_buffer = STRBUF_INIT;
1629         struct buffer out_buffer = { STRBUF_INIT, 0 };
1630         struct curl_slist *dav_headers = NULL;
1631         struct xml_ctx ctx;
1632         int lock_flags = 0;
1633         char *escaped;
1634
1635         escaped = xml_entities(repo->url);
1636         strbuf_addf(&out_buffer.buf, PROPFIND_SUPPORTEDLOCK_REQUEST, escaped);
1637         free(escaped);
1638
1639         dav_headers = curl_slist_append(dav_headers, "Depth: 0");
1640         dav_headers = curl_slist_append(dav_headers, "Content-Type: text/xml");
1641
1642         slot = get_active_slot();
1643         slot->results = &results;
1644         curl_easy_setopt(slot->curl, CURLOPT_INFILE, &out_buffer);
1645         curl_easy_setopt(slot->curl, CURLOPT_INFILESIZE, out_buffer.buf.len);
1646         curl_easy_setopt(slot->curl, CURLOPT_READFUNCTION, fread_buffer);
1647 #ifndef NO_CURL_IOCTL
1648         curl_easy_setopt(slot->curl, CURLOPT_IOCTLFUNCTION, ioctl_buffer);
1649         curl_easy_setopt(slot->curl, CURLOPT_IOCTLDATA, &out_buffer);
1650 #endif
1651         curl_easy_setopt(slot->curl, CURLOPT_FILE, &in_buffer);
1652         curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION, fwrite_buffer);
1653         curl_easy_setopt(slot->curl, CURLOPT_URL, repo->url);
1654         curl_easy_setopt(slot->curl, CURLOPT_UPLOAD, 1);
1655         curl_easy_setopt(slot->curl, CURLOPT_CUSTOMREQUEST, DAV_PROPFIND);
1656         curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, dav_headers);
1657
1658         if (start_active_slot(slot)) {
1659                 run_active_slot(slot);
1660                 if (results.curl_result == CURLE_OK) {
1661                         XML_Parser parser = XML_ParserCreate(NULL);
1662                         enum XML_Status result;
1663                         ctx.name = xcalloc(10, 1);
1664                         ctx.len = 0;
1665                         ctx.cdata = NULL;
1666                         ctx.userFunc = handle_lockprop_ctx;
1667                         ctx.userData = &lock_flags;
1668                         XML_SetUserData(parser, &ctx);
1669                         XML_SetElementHandler(parser, xml_start_tag,
1670                                               xml_end_tag);
1671                         result = XML_Parse(parser, in_buffer.buf,
1672                                            in_buffer.len, 1);
1673                         free(ctx.name);
1674
1675                         if (result != XML_STATUS_OK) {
1676                                 fprintf(stderr, "XML error: %s\n",
1677                                         XML_ErrorString(
1678                                                 XML_GetErrorCode(parser)));
1679                                 lock_flags = 0;
1680                         }
1681                         XML_ParserFree(parser);
1682                         if (!lock_flags)
1683                                 error("no DAV locking support on %s",
1684                                       repo->url);
1685
1686                 } else {
1687                         error("Cannot access URL %s, return code %d",
1688                               repo->url, results.curl_result);
1689                         lock_flags = 0;
1690                 }
1691         } else {
1692                 error("Unable to start PROPFIND request on %s", repo->url);
1693         }
1694
1695         strbuf_release(&out_buffer.buf);
1696         strbuf_release(&in_buffer);
1697         curl_slist_free_all(dav_headers);
1698
1699         return lock_flags;
1700 }
1701
1702 static struct object_list **add_one_object(struct object *obj, struct object_list **p)
1703 {
1704         struct object_list *entry = xmalloc(sizeof(struct object_list));
1705         entry->item = obj;
1706         entry->next = *p;
1707         *p = entry;
1708         return &entry->next;
1709 }
1710
1711 static struct object_list **process_blob(struct blob *blob,
1712                                          struct object_list **p,
1713                                          struct name_path *path,
1714                                          const char *name)
1715 {
1716         struct object *obj = &blob->object;
1717
1718         obj->flags |= LOCAL;
1719
1720         if (obj->flags & (UNINTERESTING | SEEN))
1721                 return p;
1722
1723         obj->flags |= SEEN;
1724         return add_one_object(obj, p);
1725 }
1726
1727 static struct object_list **process_tree(struct tree *tree,
1728                                          struct object_list **p,
1729                                          struct name_path *path,
1730                                          const char *name)
1731 {
1732         struct object *obj = &tree->object;
1733         struct tree_desc desc;
1734         struct name_entry entry;
1735         struct name_path me;
1736
1737         obj->flags |= LOCAL;
1738
1739         if (obj->flags & (UNINTERESTING | SEEN))
1740                 return p;
1741         if (parse_tree(tree) < 0)
1742                 die("bad tree object %s", sha1_to_hex(obj->sha1));
1743
1744         obj->flags |= SEEN;
1745         name = xstrdup(name);
1746         p = add_one_object(obj, p);
1747         me.up = path;
1748         me.elem = name;
1749         me.elem_len = strlen(name);
1750
1751         init_tree_desc(&desc, tree->buffer, tree->size);
1752
1753         while (tree_entry(&desc, &entry))
1754                 switch (object_type(entry.mode)) {
1755                 case OBJ_TREE:
1756                         p = process_tree(lookup_tree(entry.sha1), p, &me, name);
1757                         break;
1758                 case OBJ_BLOB:
1759                         p = process_blob(lookup_blob(entry.sha1), p, &me, name);
1760                         break;
1761                 default:
1762                         /* Subproject commit - not in this repository */
1763                         break;
1764                 }
1765
1766         free(tree->buffer);
1767         tree->buffer = NULL;
1768         return p;
1769 }
1770
1771 static int get_delta(struct rev_info *revs, struct remote_lock *lock)
1772 {
1773         int i;
1774         struct commit *commit;
1775         struct object_list **p = &objects;
1776         int count = 0;
1777
1778         while ((commit = get_revision(revs)) != NULL) {
1779                 p = process_tree(commit->tree, p, NULL, "");
1780                 commit->object.flags |= LOCAL;
1781                 if (!(commit->object.flags & UNINTERESTING))
1782                         count += add_send_request(&commit->object, lock);
1783         }
1784
1785         for (i = 0; i < revs->pending.nr; i++) {
1786                 struct object_array_entry *entry = revs->pending.objects + i;
1787                 struct object *obj = entry->item;
1788                 const char *name = entry->name;
1789
1790                 if (obj->flags & (UNINTERESTING | SEEN))
1791                         continue;
1792                 if (obj->type == OBJ_TAG) {
1793                         obj->flags |= SEEN;
1794                         p = add_one_object(obj, p);
1795                         continue;
1796                 }
1797                 if (obj->type == OBJ_TREE) {
1798                         p = process_tree((struct tree *)obj, p, NULL, name);
1799                         continue;
1800                 }
1801                 if (obj->type == OBJ_BLOB) {
1802                         p = process_blob((struct blob *)obj, p, NULL, name);
1803                         continue;
1804                 }
1805                 die("unknown pending object %s (%s)", sha1_to_hex(obj->sha1), name);
1806         }
1807
1808         while (objects) {
1809                 if (!(objects->item->flags & UNINTERESTING))
1810                         count += add_send_request(objects->item, lock);
1811                 objects = objects->next;
1812         }
1813
1814         return count;
1815 }
1816
1817 static int update_remote(unsigned char *sha1, struct remote_lock *lock)
1818 {
1819         struct active_request_slot *slot;
1820         struct slot_results results;
1821         struct buffer out_buffer = { STRBUF_INIT, 0 };
1822         struct curl_slist *dav_headers;
1823
1824         dav_headers = get_dav_token_headers(lock, DAV_HEADER_IF);
1825
1826         strbuf_addf(&out_buffer.buf, "%s\n", sha1_to_hex(sha1));
1827
1828         slot = get_active_slot();
1829         slot->results = &results;
1830         curl_easy_setopt(slot->curl, CURLOPT_INFILE, &out_buffer);
1831         curl_easy_setopt(slot->curl, CURLOPT_INFILESIZE, out_buffer.buf.len);
1832         curl_easy_setopt(slot->curl, CURLOPT_READFUNCTION, fread_buffer);
1833 #ifndef NO_CURL_IOCTL
1834         curl_easy_setopt(slot->curl, CURLOPT_IOCTLFUNCTION, ioctl_buffer);
1835         curl_easy_setopt(slot->curl, CURLOPT_IOCTLDATA, &out_buffer);
1836 #endif
1837         curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION, fwrite_null);
1838         curl_easy_setopt(slot->curl, CURLOPT_CUSTOMREQUEST, DAV_PUT);
1839         curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, dav_headers);
1840         curl_easy_setopt(slot->curl, CURLOPT_UPLOAD, 1);
1841         curl_easy_setopt(slot->curl, CURLOPT_PUT, 1);
1842         curl_easy_setopt(slot->curl, CURLOPT_URL, lock->url);
1843
1844         if (start_active_slot(slot)) {
1845                 run_active_slot(slot);
1846                 strbuf_release(&out_buffer.buf);
1847                 if (results.curl_result != CURLE_OK) {
1848                         fprintf(stderr,
1849                                 "PUT error: curl result=%d, HTTP code=%ld\n",
1850                                 results.curl_result, results.http_code);
1851                         /* We should attempt recovery? */
1852                         return 0;
1853                 }
1854         } else {
1855                 strbuf_release(&out_buffer.buf);
1856                 fprintf(stderr, "Unable to start PUT request\n");
1857                 return 0;
1858         }
1859
1860         return 1;
1861 }
1862
1863 static struct ref *remote_refs, **remote_tail;
1864
1865 static void one_remote_ref(char *refname)
1866 {
1867         struct ref *ref;
1868         struct object *obj;
1869
1870         ref = alloc_ref(refname);
1871
1872         if (http_fetch_ref(repo->url, ref) != 0) {
1873                 fprintf(stderr,
1874                         "Unable to fetch ref %s from %s\n",
1875                         refname, repo->url);
1876                 free(ref);
1877                 return;
1878         }
1879
1880         /*
1881          * Fetch a copy of the object if it doesn't exist locally - it
1882          * may be required for updating server info later.
1883          */
1884         if (repo->can_update_info_refs && !has_sha1_file(ref->old_sha1)) {
1885                 obj = lookup_unknown_object(ref->old_sha1);
1886                 if (obj) {
1887                         fprintf(stderr, "  fetch %s for %s\n",
1888                                 sha1_to_hex(ref->old_sha1), refname);
1889                         add_fetch_request(obj);
1890                 }
1891         }
1892
1893         *remote_tail = ref;
1894         remote_tail = &ref->next;
1895 }
1896
1897 static void get_dav_remote_heads(void)
1898 {
1899         remote_tail = &remote_refs;
1900         remote_ls("refs/", (PROCESS_FILES | PROCESS_DIRS | RECURSIVE), process_ls_ref, NULL);
1901 }
1902
1903 static int is_zero_sha1(const unsigned char *sha1)
1904 {
1905         int i;
1906
1907         for (i = 0; i < 20; i++) {
1908                 if (*sha1++)
1909                         return 0;
1910         }
1911         return 1;
1912 }
1913
1914 static void add_remote_info_ref(struct remote_ls_ctx *ls)
1915 {
1916         struct strbuf *buf = (struct strbuf *)ls->userData;
1917         struct object *o;
1918         int len;
1919         char *ref_info;
1920         struct ref *ref;
1921
1922         ref = alloc_ref(ls->dentry_name);
1923
1924         if (http_fetch_ref(repo->url, ref) != 0) {
1925                 fprintf(stderr,
1926                         "Unable to fetch ref %s from %s\n",
1927                         ls->dentry_name, repo->url);
1928                 aborted = 1;
1929                 free(ref);
1930                 return;
1931         }
1932
1933         o = parse_object(ref->old_sha1);
1934         if (!o) {
1935                 fprintf(stderr,
1936                         "Unable to parse object %s for remote ref %s\n",
1937                         sha1_to_hex(ref->old_sha1), ls->dentry_name);
1938                 aborted = 1;
1939                 free(ref);
1940                 return;
1941         }
1942
1943         len = strlen(ls->dentry_name) + 42;
1944         ref_info = xcalloc(len + 1, 1);
1945         sprintf(ref_info, "%s   %s\n",
1946                 sha1_to_hex(ref->old_sha1), ls->dentry_name);
1947         fwrite_buffer(ref_info, 1, len, buf);
1948         free(ref_info);
1949
1950         if (o->type == OBJ_TAG) {
1951                 o = deref_tag(o, ls->dentry_name, 0);
1952                 if (o) {
1953                         len = strlen(ls->dentry_name) + 45;
1954                         ref_info = xcalloc(len + 1, 1);
1955                         sprintf(ref_info, "%s   %s^{}\n",
1956                                 sha1_to_hex(o->sha1), ls->dentry_name);
1957                         fwrite_buffer(ref_info, 1, len, buf);
1958                         free(ref_info);
1959                 }
1960         }
1961         free(ref);
1962 }
1963
1964 static void update_remote_info_refs(struct remote_lock *lock)
1965 {
1966         struct buffer buffer = { STRBUF_INIT, 0 };
1967         struct active_request_slot *slot;
1968         struct slot_results results;
1969         struct curl_slist *dav_headers;
1970
1971         remote_ls("refs/", (PROCESS_FILES | RECURSIVE),
1972                   add_remote_info_ref, &buffer.buf);
1973         if (!aborted) {
1974                 dav_headers = get_dav_token_headers(lock, DAV_HEADER_IF);
1975
1976                 slot = get_active_slot();
1977                 slot->results = &results;
1978                 curl_easy_setopt(slot->curl, CURLOPT_INFILE, &buffer);
1979                 curl_easy_setopt(slot->curl, CURLOPT_INFILESIZE, buffer.buf.len);
1980                 curl_easy_setopt(slot->curl, CURLOPT_READFUNCTION, fread_buffer);
1981 #ifndef NO_CURL_IOCTL
1982                 curl_easy_setopt(slot->curl, CURLOPT_IOCTLFUNCTION, ioctl_buffer);
1983                 curl_easy_setopt(slot->curl, CURLOPT_IOCTLDATA, &buffer);
1984 #endif
1985                 curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION, fwrite_null);
1986                 curl_easy_setopt(slot->curl, CURLOPT_CUSTOMREQUEST, DAV_PUT);
1987                 curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, dav_headers);
1988                 curl_easy_setopt(slot->curl, CURLOPT_UPLOAD, 1);
1989                 curl_easy_setopt(slot->curl, CURLOPT_PUT, 1);
1990                 curl_easy_setopt(slot->curl, CURLOPT_URL, lock->url);
1991
1992                 if (start_active_slot(slot)) {
1993                         run_active_slot(slot);
1994                         if (results.curl_result != CURLE_OK) {
1995                                 fprintf(stderr,
1996                                         "PUT error: curl result=%d, HTTP code=%ld\n",
1997                                         results.curl_result, results.http_code);
1998                         }
1999                 }
2000         }
2001         strbuf_release(&buffer.buf);
2002 }
2003
2004 static int remote_exists(const char *path)
2005 {
2006         char *url = xmalloc(strlen(repo->url) + strlen(path) + 1);
2007         int ret;
2008
2009         sprintf(url, "%s%s", repo->url, path);
2010
2011         switch (http_get_strbuf(url, NULL, 0)) {
2012         case HTTP_OK:
2013                 ret = 1;
2014                 break;
2015         case HTTP_MISSING_TARGET:
2016                 ret = 0;
2017                 break;
2018         case HTTP_ERROR:
2019                 http_error(url, HTTP_ERROR);
2020         default:
2021                 ret = -1;
2022         }
2023         free(url);
2024         return ret;
2025 }
2026
2027 static void fetch_symref(const char *path, char **symref, unsigned char *sha1)
2028 {
2029         char *url;
2030         struct strbuf buffer = STRBUF_INIT;
2031         struct active_request_slot *slot;
2032         struct slot_results results;
2033
2034         url = xmalloc(strlen(repo->url) + strlen(path) + 1);
2035         sprintf(url, "%s%s", repo->url, path);
2036
2037         slot = get_active_slot();
2038         slot->results = &results;
2039         curl_easy_setopt(slot->curl, CURLOPT_FILE, &buffer);
2040         curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION, fwrite_buffer);
2041         curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, NULL);
2042         curl_easy_setopt(slot->curl, CURLOPT_URL, url);
2043         if (start_active_slot(slot)) {
2044                 run_active_slot(slot);
2045                 if (results.curl_result != CURLE_OK) {
2046                         die("Couldn't get %s for remote symref\n%s",
2047                             url, curl_errorstr);
2048                 }
2049         } else {
2050                 die("Unable to start remote symref request");
2051         }
2052         free(url);
2053
2054         free(*symref);
2055         *symref = NULL;
2056         hashclr(sha1);
2057
2058         if (buffer.len == 0)
2059                 return;
2060
2061         /* If it's a symref, set the refname; otherwise try for a sha1 */
2062         if (!prefixcmp((char *)buffer.buf, "ref: ")) {
2063                 *symref = xmemdupz((char *)buffer.buf + 5, buffer.len - 6);
2064         } else {
2065                 get_sha1_hex(buffer.buf, sha1);
2066         }
2067
2068         strbuf_release(&buffer);
2069 }
2070
2071 static int verify_merge_base(unsigned char *head_sha1, unsigned char *branch_sha1)
2072 {
2073         struct commit *head = lookup_commit(head_sha1);
2074         struct commit *branch = lookup_commit(branch_sha1);
2075         struct commit_list *merge_bases = get_merge_bases(head, branch, 1);
2076
2077         return (merge_bases && !merge_bases->next && merge_bases->item == branch);
2078 }
2079
2080 static int delete_remote_branch(char *pattern, int force)
2081 {
2082         struct ref *refs = remote_refs;
2083         struct ref *remote_ref = NULL;
2084         unsigned char head_sha1[20];
2085         char *symref = NULL;
2086         int match;
2087         int patlen = strlen(pattern);
2088         int i;
2089         struct active_request_slot *slot;
2090         struct slot_results results;
2091         char *url;
2092
2093         /* Find the remote branch(es) matching the specified branch name */
2094         for (match = 0; refs; refs = refs->next) {
2095                 char *name = refs->name;
2096                 int namelen = strlen(name);
2097                 if (namelen < patlen ||
2098                     memcmp(name + namelen - patlen, pattern, patlen))
2099                         continue;
2100                 if (namelen != patlen && name[namelen - patlen - 1] != '/')
2101                         continue;
2102                 match++;
2103                 remote_ref = refs;
2104         }
2105         if (match == 0)
2106                 return error("No remote branch matches %s", pattern);
2107         if (match != 1)
2108                 return error("More than one remote branch matches %s",
2109                              pattern);
2110
2111         /*
2112          * Remote HEAD must be a symref (not exactly foolproof; a remote
2113          * symlink to a symref will look like a symref)
2114          */
2115         fetch_symref("HEAD", &symref, head_sha1);
2116         if (!symref)
2117                 return error("Remote HEAD is not a symref");
2118
2119         /* Remote branch must not be the remote HEAD */
2120         for (i=0; symref && i<MAXDEPTH; i++) {
2121                 if (!strcmp(remote_ref->name, symref))
2122                         return error("Remote branch %s is the current HEAD",
2123                                      remote_ref->name);
2124                 fetch_symref(symref, &symref, head_sha1);
2125         }
2126
2127         /* Run extra sanity checks if delete is not forced */
2128         if (!force) {
2129                 /* Remote HEAD must resolve to a known object */
2130                 if (symref)
2131                         return error("Remote HEAD symrefs too deep");
2132                 if (is_zero_sha1(head_sha1))
2133                         return error("Unable to resolve remote HEAD");
2134                 if (!has_sha1_file(head_sha1))
2135                         return error("Remote HEAD resolves to object %s\nwhich does not exist locally, perhaps you need to fetch?", sha1_to_hex(head_sha1));
2136
2137                 /* Remote branch must resolve to a known object */
2138                 if (is_zero_sha1(remote_ref->old_sha1))
2139                         return error("Unable to resolve remote branch %s",
2140                                      remote_ref->name);
2141                 if (!has_sha1_file(remote_ref->old_sha1))
2142                         return error("Remote branch %s resolves to object %s\nwhich does not exist locally, perhaps you need to fetch?", remote_ref->name, sha1_to_hex(remote_ref->old_sha1));
2143
2144                 /* Remote branch must be an ancestor of remote HEAD */
2145                 if (!verify_merge_base(head_sha1, remote_ref->old_sha1)) {
2146                         return error("The branch '%s' is not an ancestor "
2147                                      "of your current HEAD.\n"
2148                                      "If you are sure you want to delete it,"
2149                                      " run:\n\t'git http-push -D %s %s'",
2150                                      remote_ref->name, repo->url, pattern);
2151                 }
2152         }
2153
2154         /* Send delete request */
2155         fprintf(stderr, "Removing remote branch '%s'\n", remote_ref->name);
2156         if (dry_run)
2157                 return 0;
2158         url = xmalloc(strlen(repo->url) + strlen(remote_ref->name) + 1);
2159         sprintf(url, "%s%s", repo->url, remote_ref->name);
2160         slot = get_active_slot();
2161         slot->results = &results;
2162         curl_easy_setopt(slot->curl, CURLOPT_HTTPGET, 1);
2163         curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION, fwrite_null);
2164         curl_easy_setopt(slot->curl, CURLOPT_URL, url);
2165         curl_easy_setopt(slot->curl, CURLOPT_CUSTOMREQUEST, DAV_DELETE);
2166         if (start_active_slot(slot)) {
2167                 run_active_slot(slot);
2168                 free(url);
2169                 if (results.curl_result != CURLE_OK)
2170                         return error("DELETE request failed (%d/%ld)\n",
2171                                      results.curl_result, results.http_code);
2172         } else {
2173                 free(url);
2174                 return error("Unable to start DELETE request");
2175         }
2176
2177         return 0;
2178 }
2179
2180 void run_request_queue(void)
2181 {
2182 #ifdef USE_CURL_MULTI
2183         is_running_queue = 1;
2184         fill_active_slots();
2185         add_fill_function(NULL, fill_active_slot);
2186 #endif
2187         do {
2188                 finish_all_active_slots();
2189 #ifdef USE_CURL_MULTI
2190                 fill_active_slots();
2191 #endif
2192         } while (request_queue_head && !aborted);
2193
2194 #ifdef USE_CURL_MULTI
2195         is_running_queue = 0;
2196 #endif
2197 }
2198
2199 int main(int argc, char **argv)
2200 {
2201         struct transfer_request *request;
2202         struct transfer_request *next_request;
2203         int nr_refspec = 0;
2204         char **refspec = NULL;
2205         struct remote_lock *ref_lock = NULL;
2206         struct remote_lock *info_ref_lock = NULL;
2207         struct rev_info revs;
2208         int delete_branch = 0;
2209         int force_delete = 0;
2210         int objects_to_send;
2211         int rc = 0;
2212         int i;
2213         int new_refs;
2214         struct ref *ref, *local_refs;
2215         struct remote *remote;
2216         char *rewritten_url = NULL;
2217
2218         git_extract_argv0_path(argv[0]);
2219
2220         setup_git_directory();
2221
2222         repo = xcalloc(sizeof(*repo), 1);
2223
2224         argv++;
2225         for (i = 1; i < argc; i++, argv++) {
2226                 char *arg = *argv;
2227
2228                 if (*arg == '-') {
2229                         if (!strcmp(arg, "--all")) {
2230                                 push_all = MATCH_REFS_ALL;
2231                                 continue;
2232                         }
2233                         if (!strcmp(arg, "--force")) {
2234                                 force_all = 1;
2235                                 continue;
2236                         }
2237                         if (!strcmp(arg, "--dry-run")) {
2238                                 dry_run = 1;
2239                                 continue;
2240                         }
2241                         if (!strcmp(arg, "--verbose")) {
2242                                 push_verbosely = 1;
2243                                 http_is_verbose = 1;
2244                                 continue;
2245                         }
2246                         if (!strcmp(arg, "-d")) {
2247                                 delete_branch = 1;
2248                                 continue;
2249                         }
2250                         if (!strcmp(arg, "-D")) {
2251                                 delete_branch = 1;
2252                                 force_delete = 1;
2253                                 continue;
2254                         }
2255                 }
2256                 if (!repo->url) {
2257                         char *path = strstr(arg, "//");
2258                         repo->url = arg;
2259                         repo->path_len = strlen(arg);
2260                         if (path) {
2261                                 repo->path = strchr(path+2, '/');
2262                                 if (repo->path)
2263                                         repo->path_len = strlen(repo->path);
2264                         }
2265                         continue;
2266                 }
2267                 refspec = argv;
2268                 nr_refspec = argc - i;
2269                 break;
2270         }
2271
2272 #ifndef USE_CURL_MULTI
2273         die("git-push is not available for http/https repository when not compiled with USE_CURL_MULTI");
2274 #endif
2275
2276         if (!repo->url)
2277                 usage(http_push_usage);
2278
2279         if (delete_branch && nr_refspec != 1)
2280                 die("You must specify only one branch name when deleting a remote branch");
2281
2282         memset(remote_dir_exists, -1, 256);
2283
2284         /*
2285          * Create a minimum remote by hand to give to http_init(),
2286          * primarily to allow it to look at the URL.
2287          */
2288         remote = xcalloc(sizeof(*remote), 1);
2289         ALLOC_GROW(remote->url, remote->url_nr + 1, remote->url_alloc);
2290         remote->url[remote->url_nr++] = repo->url;
2291         http_init(remote);
2292
2293         if (repo->url && repo->url[strlen(repo->url)-1] != '/') {
2294                 rewritten_url = xmalloc(strlen(repo->url)+2);
2295                 strcpy(rewritten_url, repo->url);
2296                 strcat(rewritten_url, "/");
2297                 repo->path = rewritten_url + (repo->path - repo->url);
2298                 repo->path_len++;
2299                 repo->url = rewritten_url;
2300         }
2301
2302 #ifdef USE_CURL_MULTI
2303         is_running_queue = 0;
2304 #endif
2305
2306         /* Verify DAV compliance/lock support */
2307         if (!locking_available()) {
2308                 rc = 1;
2309                 goto cleanup;
2310         }
2311
2312         sigchain_push_common(remove_locks_on_signal);
2313
2314         /* Check whether the remote has server info files */
2315         repo->can_update_info_refs = 0;
2316         repo->has_info_refs = remote_exists("info/refs");
2317         repo->has_info_packs = remote_exists("objects/info/packs");
2318         if (repo->has_info_refs) {
2319                 info_ref_lock = lock_remote("info/refs", LOCK_TIME);
2320                 if (info_ref_lock)
2321                         repo->can_update_info_refs = 1;
2322                 else {
2323                         error("cannot lock existing info/refs");
2324                         rc = 1;
2325                         goto cleanup;
2326                 }
2327         }
2328         if (repo->has_info_packs)
2329                 fetch_indices();
2330
2331         /* Get a list of all local and remote heads to validate refspecs */
2332         local_refs = get_local_heads();
2333         fprintf(stderr, "Fetching remote heads...\n");
2334         get_dav_remote_heads();
2335         run_request_queue();
2336
2337         /* Remove a remote branch if -d or -D was specified */
2338         if (delete_branch) {
2339                 if (delete_remote_branch(refspec[0], force_delete) == -1)
2340                         fprintf(stderr, "Unable to delete remote branch %s\n",
2341                                 refspec[0]);
2342                 goto cleanup;
2343         }
2344
2345         /* match them up */
2346         if (!remote_tail)
2347                 remote_tail = &remote_refs;
2348         if (match_refs(local_refs, remote_refs, &remote_tail,
2349                        nr_refspec, (const char **) refspec, push_all)) {
2350                 rc = -1;
2351                 goto cleanup;
2352         }
2353         if (!remote_refs) {
2354                 fprintf(stderr, "No refs in common and none specified; doing nothing.\n");
2355                 rc = 0;
2356                 goto cleanup;
2357         }
2358
2359         new_refs = 0;
2360         for (ref = remote_refs; ref; ref = ref->next) {
2361                 char old_hex[60], *new_hex;
2362                 const char *commit_argv[4];
2363                 int commit_argc;
2364                 char *new_sha1_hex, *old_sha1_hex;
2365
2366                 if (!ref->peer_ref)
2367                         continue;
2368
2369                 if (is_zero_sha1(ref->peer_ref->new_sha1)) {
2370                         if (delete_remote_branch(ref->name, 1) == -1) {
2371                                 error("Could not remove %s", ref->name);
2372                                 rc = -4;
2373                         }
2374                         new_refs++;
2375                         continue;
2376                 }
2377
2378                 if (!hashcmp(ref->old_sha1, ref->peer_ref->new_sha1)) {
2379                         if (push_verbosely || 1)
2380                                 fprintf(stderr, "'%s': up-to-date\n", ref->name);
2381                         continue;
2382                 }
2383
2384                 if (!force_all &&
2385                     !is_zero_sha1(ref->old_sha1) &&
2386                     !ref->force) {
2387                         if (!has_sha1_file(ref->old_sha1) ||
2388                             !ref_newer(ref->peer_ref->new_sha1,
2389                                        ref->old_sha1)) {
2390                                 /*
2391                                  * We do not have the remote ref, or
2392                                  * we know that the remote ref is not
2393                                  * an ancestor of what we are trying to
2394                                  * push.  Either way this can be losing
2395                                  * commits at the remote end and likely
2396                                  * we were not up to date to begin with.
2397                                  */
2398                                 error("remote '%s' is not an ancestor of\n"
2399                                       "local '%s'.\n"
2400                                       "Maybe you are not up-to-date and "
2401                                       "need to pull first?",
2402                                       ref->name,
2403                                       ref->peer_ref->name);
2404                                 rc = -2;
2405                                 continue;
2406                         }
2407                 }
2408                 hashcpy(ref->new_sha1, ref->peer_ref->new_sha1);
2409                 new_refs++;
2410                 strcpy(old_hex, sha1_to_hex(ref->old_sha1));
2411                 new_hex = sha1_to_hex(ref->new_sha1);
2412
2413                 fprintf(stderr, "updating '%s'", ref->name);
2414                 if (strcmp(ref->name, ref->peer_ref->name))
2415                         fprintf(stderr, " using '%s'", ref->peer_ref->name);
2416                 fprintf(stderr, "\n  from %s\n  to   %s\n", old_hex, new_hex);
2417                 if (dry_run)
2418                         continue;
2419
2420                 /* Lock remote branch ref */
2421                 ref_lock = lock_remote(ref->name, LOCK_TIME);
2422                 if (ref_lock == NULL) {
2423                         fprintf(stderr, "Unable to lock remote branch %s\n",
2424                                 ref->name);
2425                         rc = 1;
2426                         continue;
2427                 }
2428
2429                 /* Set up revision info for this refspec */
2430                 commit_argc = 3;
2431                 new_sha1_hex = xstrdup(sha1_to_hex(ref->new_sha1));
2432                 old_sha1_hex = NULL;
2433                 commit_argv[1] = "--objects";
2434                 commit_argv[2] = new_sha1_hex;
2435                 if (!push_all && !is_zero_sha1(ref->old_sha1)) {
2436                         old_sha1_hex = xmalloc(42);
2437                         sprintf(old_sha1_hex, "^%s",
2438                                 sha1_to_hex(ref->old_sha1));
2439                         commit_argv[3] = old_sha1_hex;
2440                         commit_argc++;
2441                 }
2442                 init_revisions(&revs, setup_git_directory());
2443                 setup_revisions(commit_argc, commit_argv, &revs, NULL);
2444                 revs.edge_hint = 0; /* just in case */
2445                 free(new_sha1_hex);
2446                 if (old_sha1_hex) {
2447                         free(old_sha1_hex);
2448                         commit_argv[1] = NULL;
2449                 }
2450
2451                 /* Generate a list of objects that need to be pushed */
2452                 pushing = 0;
2453                 if (prepare_revision_walk(&revs))
2454                         die("revision walk setup failed");
2455                 mark_edges_uninteresting(revs.commits, &revs, NULL);
2456                 objects_to_send = get_delta(&revs, ref_lock);
2457                 finish_all_active_slots();
2458
2459                 /* Push missing objects to remote, this would be a
2460                    convenient time to pack them first if appropriate. */
2461                 pushing = 1;
2462                 if (objects_to_send)
2463                         fprintf(stderr, "    sending %d objects\n",
2464                                 objects_to_send);
2465
2466                 run_request_queue();
2467
2468                 /* Update the remote branch if all went well */
2469                 if (aborted || !update_remote(ref->new_sha1, ref_lock))
2470                         rc = 1;
2471
2472                 if (!rc)
2473                         fprintf(stderr, "    done\n");
2474                 unlock_remote(ref_lock);
2475                 check_locks();
2476         }
2477
2478         /* Update remote server info if appropriate */
2479         if (repo->has_info_refs && new_refs) {
2480                 if (info_ref_lock && repo->can_update_info_refs) {
2481                         fprintf(stderr, "Updating remote server info\n");
2482                         if (!dry_run)
2483                                 update_remote_info_refs(info_ref_lock);
2484                 } else {
2485                         fprintf(stderr, "Unable to update server info\n");
2486                 }
2487         }
2488
2489  cleanup:
2490         free(rewritten_url);
2491         if (info_ref_lock)
2492                 unlock_remote(info_ref_lock);
2493         free(repo);
2494
2495         http_cleanup();
2496
2497         request = request_queue_head;
2498         while (request != NULL) {
2499                 next_request = request->next;
2500                 release_request(request);
2501                 request = next_request;
2502         }
2503
2504         return rc;
2505 }