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