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