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