fetch.c: do not call process_tree() from process_tree().
[git/jrn.git] / http-push.c
blobb1c018a08993dfd7278f3db35b9a140ab0e166d6
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"
13 #include <expat.h>
15 static const char http_push_usage[] =
16 "git-http-push [--all] [--force] [--verbose] <remote> [<head>...]\n";
18 #ifndef XML_STATUS_OK
19 enum XML_Status {
20 XML_STATUS_OK = 1,
21 XML_STATUS_ERROR = 0
23 #define XML_STATUS_OK 1
24 #define XML_STATUS_ERROR 0
25 #endif
27 #define PREV_BUF_SIZE 4096
28 #define RANGE_HEADER_SIZE 30
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"
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)
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"
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>"
60 #define LOCK_TIME 600
61 #define LOCK_REFRESH 30
63 /* bits #0-15 in revision.h */
65 #define LOCAL (1u<<16)
66 #define REMOTE (1u<<17)
67 #define FETCHING (1u<<18)
68 #define PUSHING (1u<<19)
70 /* We allow "recursive" symbolic refs. Only within reason, though */
71 #define MAXDEPTH 5
73 static int pushing = 0;
74 static int aborted = 0;
75 static signed char remote_dir_exists[256];
77 static struct curl_slist *no_pragma_header;
78 static struct curl_slist *default_headers;
80 static int push_verbosely = 0;
81 static int push_all = 0;
82 static int force_all = 0;
84 static struct object_list *objects = NULL;
86 struct repo
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;
97 static struct repo *remote = NULL;
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,
111 struct transfer_request
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;
137 static struct transfer_request *request_queue_head = NULL;
139 struct xml_ctx
141 char *name;
142 int len;
143 char *cdata;
144 void (*userFunc)(struct xml_ctx *ctx, int tag_closed);
145 void *userData;
148 struct remote_lock
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;
159 /* Flags that control remote_ls processing */
160 #define PROCESS_FILES (1u << 0)
161 #define PROCESS_DIRS (1u << 1)
162 #define RECURSIVE (1u << 2)
164 /* Flags that remote_ls passes to callback functions */
165 #define IS_DIR (1u << 0)
167 struct remote_ls_ctx
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;
178 static void finish_request(struct transfer_request *request);
179 static void release_request(struct transfer_request *request);
181 static void process_response(void *callback_data)
183 struct transfer_request *request =
184 (struct transfer_request *)callback_data;
186 finish_request(request);
189 static size_t fwrite_sha1_file(void *ptr, size_t eltsize, size_t nmemb,
190 void *data)
192 unsigned char expn[4096];
193 size_t size = eltsize * nmemb;
194 int posn = 0;
195 struct transfer_request *request = (struct transfer_request *)data;
196 do {
197 ssize_t retval = write(request->local_fileno,
198 ptr + posn, size - posn);
199 if (retval < 0)
200 return posn;
201 posn += retval;
202 } while (posn < size);
204 request->stream.avail_in = size;
205 request->stream.next_in = ptr;
206 do {
207 request->stream.next_out = expn;
208 request->stream.avail_out = sizeof(expn);
209 request->zret = inflate(&request->stream, Z_SYNC_FLUSH);
210 SHA1_Update(&request->c, expn,
211 sizeof(expn) - request->stream.avail_out);
212 } while (request->stream.avail_in && request->zret == Z_OK);
213 data_received++;
214 return size;
217 static void start_fetch_loose(struct transfer_request *request)
219 char *hex = sha1_to_hex(request->obj->sha1);
220 char *filename;
221 char prevfile[PATH_MAX];
222 char *url;
223 char *posn;
224 int prevlocal;
225 unsigned char prev_buf[PREV_BUF_SIZE];
226 ssize_t prev_read = 0;
227 long prev_posn = 0;
228 char range[RANGE_HEADER_SIZE];
229 struct curl_slist *range_header = NULL;
230 struct active_request_slot *slot;
232 filename = sha1_file_name(request->obj->sha1);
233 snprintf(request->filename, sizeof(request->filename), "%s", filename);
234 snprintf(request->tmpfile, sizeof(request->tmpfile),
235 "%s.temp", filename);
237 snprintf(prevfile, sizeof(prevfile), "%s.prev", request->filename);
238 unlink(prevfile);
239 rename(request->tmpfile, prevfile);
240 unlink(request->tmpfile);
242 if (request->local_fileno != -1)
243 error("fd leakage in start: %d", request->local_fileno);
244 request->local_fileno = open(request->tmpfile,
245 O_WRONLY | O_CREAT | O_EXCL, 0666);
246 /* This could have failed due to the "lazy directory creation";
247 * try to mkdir the last path component.
249 if (request->local_fileno < 0 && errno == ENOENT) {
250 char *dir = strrchr(request->tmpfile, '/');
251 if (dir) {
252 *dir = 0;
253 mkdir(request->tmpfile, 0777);
254 *dir = '/';
256 request->local_fileno = open(request->tmpfile,
257 O_WRONLY | O_CREAT | O_EXCL, 0666);
260 if (request->local_fileno < 0) {
261 request->state = ABORTED;
262 error("Couldn't create temporary file %s for %s: %s",
263 request->tmpfile, request->filename, strerror(errno));
264 return;
267 memset(&request->stream, 0, sizeof(request->stream));
269 inflateInit(&request->stream);
271 SHA1_Init(&request->c);
273 url = xmalloc(strlen(remote->url) + 50);
274 request->url = xmalloc(strlen(remote->url) + 50);
275 strcpy(url, remote->url);
276 posn = url + strlen(remote->url);
277 strcpy(posn, "objects/");
278 posn += 8;
279 memcpy(posn, hex, 2);
280 posn += 2;
281 *(posn++) = '/';
282 strcpy(posn, hex + 2);
283 strcpy(request->url, url);
285 /* If a previous temp file is present, process what was already
286 fetched. */
287 prevlocal = open(prevfile, O_RDONLY);
288 if (prevlocal != -1) {
289 do {
290 prev_read = read(prevlocal, prev_buf, PREV_BUF_SIZE);
291 if (prev_read>0) {
292 if (fwrite_sha1_file(prev_buf,
294 prev_read,
295 request) == prev_read) {
296 prev_posn += prev_read;
297 } else {
298 prev_read = -1;
301 } while (prev_read > 0);
302 close(prevlocal);
304 unlink(prevfile);
306 /* Reset inflate/SHA1 if there was an error reading the previous temp
307 file; also rewind to the beginning of the local file. */
308 if (prev_read == -1) {
309 memset(&request->stream, 0, sizeof(request->stream));
310 inflateInit(&request->stream);
311 SHA1_Init(&request->c);
312 if (prev_posn>0) {
313 prev_posn = 0;
314 lseek(request->local_fileno, SEEK_SET, 0);
315 ftruncate(request->local_fileno, 0);
319 slot = get_active_slot();
320 slot->callback_func = process_response;
321 slot->callback_data = request;
322 request->slot = slot;
324 curl_easy_setopt(slot->curl, CURLOPT_FILE, request);
325 curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION, fwrite_sha1_file);
326 curl_easy_setopt(slot->curl, CURLOPT_ERRORBUFFER, request->errorstr);
327 curl_easy_setopt(slot->curl, CURLOPT_URL, url);
328 curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, no_pragma_header);
330 /* If we have successfully processed data from a previous fetch
331 attempt, only fetch the data we don't already have. */
332 if (prev_posn>0) {
333 if (push_verbosely)
334 fprintf(stderr,
335 "Resuming fetch of object %s at byte %ld\n",
336 hex, prev_posn);
337 sprintf(range, "Range: bytes=%ld-", prev_posn);
338 range_header = curl_slist_append(range_header, range);
339 curl_easy_setopt(slot->curl,
340 CURLOPT_HTTPHEADER, range_header);
343 /* Try to get the request started, abort the request on error */
344 request->state = RUN_FETCH_LOOSE;
345 if (!start_active_slot(slot)) {
346 fprintf(stderr, "Unable to start GET request\n");
347 remote->can_update_info_refs = 0;
348 release_request(request);
352 static void start_fetch_packed(struct transfer_request *request)
354 char *url;
355 struct packed_git *target;
356 FILE *packfile;
357 char *filename;
358 long prev_posn = 0;
359 char range[RANGE_HEADER_SIZE];
360 struct curl_slist *range_header = NULL;
362 struct transfer_request *check_request = request_queue_head;
363 struct active_request_slot *slot;
365 target = find_sha1_pack(request->obj->sha1, remote->packs);
366 if (!target) {
367 fprintf(stderr, "Unable to fetch %s, will not be able to update server info refs\n", sha1_to_hex(request->obj->sha1));
368 remote->can_update_info_refs = 0;
369 release_request(request);
370 return;
373 fprintf(stderr, "Fetching pack %s\n", sha1_to_hex(target->sha1));
374 fprintf(stderr, " which contains %s\n", sha1_to_hex(request->obj->sha1));
376 filename = sha1_pack_name(target->sha1);
377 snprintf(request->filename, sizeof(request->filename), "%s", filename);
378 snprintf(request->tmpfile, sizeof(request->tmpfile),
379 "%s.temp", filename);
381 url = xmalloc(strlen(remote->url) + 64);
382 sprintf(url, "%sobjects/pack/pack-%s.pack",
383 remote->url, sha1_to_hex(target->sha1));
385 /* Make sure there isn't another open request for this pack */
386 while (check_request) {
387 if (check_request->state == RUN_FETCH_PACKED &&
388 !strcmp(check_request->url, url)) {
389 free(url);
390 release_request(request);
391 return;
393 check_request = check_request->next;
396 packfile = fopen(request->tmpfile, "a");
397 if (!packfile) {
398 fprintf(stderr, "Unable to open local file %s for pack",
399 filename);
400 remote->can_update_info_refs = 0;
401 free(url);
402 return;
405 slot = get_active_slot();
406 slot->callback_func = process_response;
407 slot->callback_data = request;
408 request->slot = slot;
409 request->local_stream = packfile;
410 request->userData = target;
412 request->url = url;
413 curl_easy_setopt(slot->curl, CURLOPT_FILE, packfile);
414 curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION, fwrite);
415 curl_easy_setopt(slot->curl, CURLOPT_URL, url);
416 curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, no_pragma_header);
417 slot->local = packfile;
419 /* If there is data present from a previous transfer attempt,
420 resume where it left off */
421 prev_posn = ftell(packfile);
422 if (prev_posn>0) {
423 if (push_verbosely)
424 fprintf(stderr,
425 "Resuming fetch of pack %s at byte %ld\n",
426 sha1_to_hex(target->sha1), prev_posn);
427 sprintf(range, "Range: bytes=%ld-", prev_posn);
428 range_header = curl_slist_append(range_header, range);
429 curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, range_header);
432 /* Try to get the request started, abort the request on error */
433 request->state = RUN_FETCH_PACKED;
434 if (!start_active_slot(slot)) {
435 fprintf(stderr, "Unable to start GET request\n");
436 remote->can_update_info_refs = 0;
437 release_request(request);
441 static void start_mkcol(struct transfer_request *request)
443 char *hex = sha1_to_hex(request->obj->sha1);
444 struct active_request_slot *slot;
445 char *posn;
447 request->url = xmalloc(strlen(remote->url) + 13);
448 strcpy(request->url, remote->url);
449 posn = request->url + strlen(remote->url);
450 strcpy(posn, "objects/");
451 posn += 8;
452 memcpy(posn, hex, 2);
453 posn += 2;
454 strcpy(posn, "/");
456 slot = get_active_slot();
457 slot->callback_func = process_response;
458 slot->callback_data = request;
459 curl_easy_setopt(slot->curl, CURLOPT_HTTPGET, 1); /* undo PUT setup */
460 curl_easy_setopt(slot->curl, CURLOPT_URL, request->url);
461 curl_easy_setopt(slot->curl, CURLOPT_ERRORBUFFER, request->errorstr);
462 curl_easy_setopt(slot->curl, CURLOPT_CUSTOMREQUEST, DAV_MKCOL);
463 curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION, fwrite_null);
465 if (start_active_slot(slot)) {
466 request->slot = slot;
467 request->state = RUN_MKCOL;
468 } else {
469 request->state = ABORTED;
470 free(request->url);
471 request->url = NULL;
475 static void start_put(struct transfer_request *request)
477 char *hex = sha1_to_hex(request->obj->sha1);
478 struct active_request_slot *slot;
479 char *posn;
480 char type[20];
481 char hdr[50];
482 void *unpacked;
483 unsigned long len;
484 int hdrlen;
485 ssize_t size;
486 z_stream stream;
488 unpacked = read_sha1_file(request->obj->sha1, type, &len);
489 hdrlen = sprintf(hdr, "%s %lu", type, len) + 1;
491 /* Set it up */
492 memset(&stream, 0, sizeof(stream));
493 deflateInit(&stream, Z_BEST_COMPRESSION);
494 size = deflateBound(&stream, len + hdrlen);
495 request->buffer.buffer = xmalloc(size);
497 /* Compress it */
498 stream.next_out = request->buffer.buffer;
499 stream.avail_out = size;
501 /* First header.. */
502 stream.next_in = (void *)hdr;
503 stream.avail_in = hdrlen;
504 while (deflate(&stream, 0) == Z_OK)
505 /* nothing */;
507 /* Then the data itself.. */
508 stream.next_in = unpacked;
509 stream.avail_in = len;
510 while (deflate(&stream, Z_FINISH) == Z_OK)
511 /* nothing */;
512 deflateEnd(&stream);
513 free(unpacked);
515 request->buffer.size = stream.total_out;
516 request->buffer.posn = 0;
518 request->url = xmalloc(strlen(remote->url) +
519 strlen(request->lock->token) + 51);
520 strcpy(request->url, remote->url);
521 posn = request->url + strlen(remote->url);
522 strcpy(posn, "objects/");
523 posn += 8;
524 memcpy(posn, hex, 2);
525 posn += 2;
526 *(posn++) = '/';
527 strcpy(posn, hex + 2);
528 request->dest = xmalloc(strlen(request->url) + 14);
529 sprintf(request->dest, "Destination: %s", request->url);
530 posn += 38;
531 *(posn++) = '.';
532 strcpy(posn, request->lock->token);
534 slot = get_active_slot();
535 slot->callback_func = process_response;
536 slot->callback_data = request;
537 curl_easy_setopt(slot->curl, CURLOPT_INFILE, &request->buffer);
538 curl_easy_setopt(slot->curl, CURLOPT_INFILESIZE, request->buffer.size);
539 curl_easy_setopt(slot->curl, CURLOPT_READFUNCTION, fread_buffer);
540 curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION, fwrite_null);
541 curl_easy_setopt(slot->curl, CURLOPT_CUSTOMREQUEST, DAV_PUT);
542 curl_easy_setopt(slot->curl, CURLOPT_UPLOAD, 1);
543 curl_easy_setopt(slot->curl, CURLOPT_PUT, 1);
544 curl_easy_setopt(slot->curl, CURLOPT_NOBODY, 0);
545 curl_easy_setopt(slot->curl, CURLOPT_URL, request->url);
547 if (start_active_slot(slot)) {
548 request->slot = slot;
549 request->state = RUN_PUT;
550 } else {
551 request->state = ABORTED;
552 free(request->url);
553 request->url = NULL;
557 static void start_move(struct transfer_request *request)
559 struct active_request_slot *slot;
560 struct curl_slist *dav_headers = NULL;
562 slot = get_active_slot();
563 slot->callback_func = process_response;
564 slot->callback_data = request;
565 curl_easy_setopt(slot->curl, CURLOPT_HTTPGET, 1); /* undo PUT setup */
566 curl_easy_setopt(slot->curl, CURLOPT_CUSTOMREQUEST, DAV_MOVE);
567 dav_headers = curl_slist_append(dav_headers, request->dest);
568 dav_headers = curl_slist_append(dav_headers, "Overwrite: T");
569 curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, dav_headers);
570 curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION, fwrite_null);
571 curl_easy_setopt(slot->curl, CURLOPT_URL, request->url);
573 if (start_active_slot(slot)) {
574 request->slot = slot;
575 request->state = RUN_MOVE;
576 } else {
577 request->state = ABORTED;
578 free(request->url);
579 request->url = NULL;
583 static int refresh_lock(struct remote_lock *lock)
585 struct active_request_slot *slot;
586 struct slot_results results;
587 char *if_header;
588 char timeout_header[25];
589 struct curl_slist *dav_headers = NULL;
590 int rc = 0;
592 lock->refreshing = 1;
594 if_header = xmalloc(strlen(lock->token) + 25);
595 sprintf(if_header, "If: (<opaquelocktoken:%s>)", lock->token);
596 sprintf(timeout_header, "Timeout: Second-%ld", lock->timeout);
597 dav_headers = curl_slist_append(dav_headers, if_header);
598 dav_headers = curl_slist_append(dav_headers, timeout_header);
600 slot = get_active_slot();
601 slot->results = &results;
602 curl_easy_setopt(slot->curl, CURLOPT_HTTPGET, 1);
603 curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION, fwrite_null);
604 curl_easy_setopt(slot->curl, CURLOPT_URL, lock->url);
605 curl_easy_setopt(slot->curl, CURLOPT_CUSTOMREQUEST, DAV_LOCK);
606 curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, dav_headers);
608 if (start_active_slot(slot)) {
609 run_active_slot(slot);
610 if (results.curl_result != CURLE_OK) {
611 fprintf(stderr, "LOCK HTTP error %ld\n",
612 results.http_code);
613 } else {
614 lock->start_time = time(NULL);
615 rc = 1;
619 lock->refreshing = 0;
620 curl_slist_free_all(dav_headers);
621 free(if_header);
623 return rc;
626 static void check_locks(void)
628 struct remote_lock *lock = remote->locks;
629 time_t current_time = time(NULL);
630 int time_remaining;
632 while (lock) {
633 time_remaining = lock->start_time + lock->timeout -
634 current_time;
635 if (!lock->refreshing && time_remaining < LOCK_REFRESH) {
636 if (!refresh_lock(lock)) {
637 fprintf(stderr,
638 "Unable to refresh lock for %s\n",
639 lock->url);
640 aborted = 1;
641 return;
644 lock = lock->next;
648 static void release_request(struct transfer_request *request)
650 struct transfer_request *entry = request_queue_head;
652 if (request == request_queue_head) {
653 request_queue_head = request->next;
654 } else {
655 while (entry->next != NULL && entry->next != request)
656 entry = entry->next;
657 if (entry->next == request)
658 entry->next = entry->next->next;
661 if (request->local_fileno != -1)
662 close(request->local_fileno);
663 if (request->local_stream)
664 fclose(request->local_stream);
665 if (request->url != NULL)
666 free(request->url);
667 free(request);
670 static void finish_request(struct transfer_request *request)
672 struct stat st;
673 struct packed_git *target;
674 struct packed_git **lst;
676 request->curl_result = request->slot->curl_result;
677 request->http_code = request->slot->http_code;
678 request->slot = NULL;
680 /* Keep locks active */
681 check_locks();
683 if (request->headers != NULL)
684 curl_slist_free_all(request->headers);
686 /* URL is reused for MOVE after PUT */
687 if (request->state != RUN_PUT) {
688 free(request->url);
689 request->url = NULL;
692 if (request->state == RUN_MKCOL) {
693 if (request->curl_result == CURLE_OK ||
694 request->http_code == 405) {
695 remote_dir_exists[request->obj->sha1[0]] = 1;
696 start_put(request);
697 } else {
698 fprintf(stderr, "MKCOL %s failed, aborting (%d/%ld)\n",
699 sha1_to_hex(request->obj->sha1),
700 request->curl_result, request->http_code);
701 request->state = ABORTED;
702 aborted = 1;
704 } else if (request->state == RUN_PUT) {
705 if (request->curl_result == CURLE_OK) {
706 start_move(request);
707 } else {
708 fprintf(stderr, "PUT %s failed, aborting (%d/%ld)\n",
709 sha1_to_hex(request->obj->sha1),
710 request->curl_result, request->http_code);
711 request->state = ABORTED;
712 aborted = 1;
714 } else if (request->state == RUN_MOVE) {
715 if (request->curl_result == CURLE_OK) {
716 if (push_verbosely)
717 fprintf(stderr, " sent %s\n",
718 sha1_to_hex(request->obj->sha1));
719 request->obj->flags |= REMOTE;
720 release_request(request);
721 } else {
722 fprintf(stderr, "MOVE %s failed, aborting (%d/%ld)\n",
723 sha1_to_hex(request->obj->sha1),
724 request->curl_result, request->http_code);
725 request->state = ABORTED;
726 aborted = 1;
728 } else if (request->state == RUN_FETCH_LOOSE) {
729 fchmod(request->local_fileno, 0444);
730 close(request->local_fileno); request->local_fileno = -1;
732 if (request->curl_result != CURLE_OK &&
733 request->http_code != 416) {
734 if (stat(request->tmpfile, &st) == 0) {
735 if (st.st_size == 0)
736 unlink(request->tmpfile);
738 } else {
739 if (request->http_code == 416)
740 fprintf(stderr, "Warning: requested range invalid; we may already have all the data.\n");
742 inflateEnd(&request->stream);
743 SHA1_Final(request->real_sha1, &request->c);
744 if (request->zret != Z_STREAM_END) {
745 unlink(request->tmpfile);
746 } else if (memcmp(request->obj->sha1, request->real_sha1, 20)) {
747 unlink(request->tmpfile);
748 } else {
749 request->rename =
750 move_temp_to_file(
751 request->tmpfile,
752 request->filename);
753 if (request->rename == 0) {
754 request->obj->flags |= (LOCAL | REMOTE);
759 /* Try fetching packed if necessary */
760 if (request->obj->flags & LOCAL)
761 release_request(request);
762 else
763 start_fetch_packed(request);
765 } else if (request->state == RUN_FETCH_PACKED) {
766 if (request->curl_result != CURLE_OK) {
767 fprintf(stderr, "Unable to get pack file %s\n%s",
768 request->url, curl_errorstr);
769 remote->can_update_info_refs = 0;
770 } else {
771 fclose(request->local_stream);
772 request->local_stream = NULL;
773 if (!move_temp_to_file(request->tmpfile,
774 request->filename)) {
775 target = (struct packed_git *)request->userData;
776 lst = &remote->packs;
777 while (*lst != target)
778 lst = &((*lst)->next);
779 *lst = (*lst)->next;
781 if (!verify_pack(target, 0))
782 install_packed_git(target);
783 else
784 remote->can_update_info_refs = 0;
787 release_request(request);
791 void fill_active_slots(void)
793 struct transfer_request *request = request_queue_head;
794 struct transfer_request *next;
795 struct active_request_slot *slot = active_queue_head;
796 int num_transfers;
798 if (aborted)
799 return;
801 while (active_requests < max_requests && request != NULL) {
802 next = request->next;
803 if (request->state == NEED_FETCH) {
804 start_fetch_loose(request);
805 } else if (pushing && request->state == NEED_PUSH) {
806 if (remote_dir_exists[request->obj->sha1[0]] == 1) {
807 start_put(request);
808 } else {
809 start_mkcol(request);
811 curl_multi_perform(curlm, &num_transfers);
813 request = next;
816 while (slot != NULL) {
817 if (!slot->in_use && slot->curl != NULL) {
818 curl_easy_cleanup(slot->curl);
819 slot->curl = NULL;
821 slot = slot->next;
825 static void get_remote_object_list(unsigned char parent);
827 static void add_fetch_request(struct object *obj)
829 struct transfer_request *request;
831 check_locks();
834 * Don't fetch the object if it's known to exist locally
835 * or is already in the request queue
837 if (remote_dir_exists[obj->sha1[0]] == -1)
838 get_remote_object_list(obj->sha1[0]);
839 if (obj->flags & (LOCAL | FETCHING))
840 return;
842 obj->flags |= FETCHING;
843 request = xmalloc(sizeof(*request));
844 request->obj = obj;
845 request->url = NULL;
846 request->lock = NULL;
847 request->headers = NULL;
848 request->local_fileno = -1;
849 request->local_stream = NULL;
850 request->state = NEED_FETCH;
851 request->next = request_queue_head;
852 request_queue_head = request;
854 fill_active_slots();
855 step_active_slots();
858 static int add_send_request(struct object *obj, struct remote_lock *lock)
860 struct transfer_request *request = request_queue_head;
861 struct packed_git *target;
863 /* Keep locks active */
864 check_locks();
867 * Don't push the object if it's known to exist on the remote
868 * or is already in the request queue
870 if (remote_dir_exists[obj->sha1[0]] == -1)
871 get_remote_object_list(obj->sha1[0]);
872 if (obj->flags & (REMOTE | PUSHING))
873 return 0;
874 target = find_sha1_pack(obj->sha1, remote->packs);
875 if (target) {
876 obj->flags |= REMOTE;
877 return 0;
880 obj->flags |= PUSHING;
881 request = xmalloc(sizeof(*request));
882 request->obj = obj;
883 request->url = NULL;
884 request->lock = lock;
885 request->headers = NULL;
886 request->local_fileno = -1;
887 request->local_stream = NULL;
888 request->state = NEED_PUSH;
889 request->next = request_queue_head;
890 request_queue_head = request;
892 fill_active_slots();
893 step_active_slots();
895 return 1;
898 static int fetch_index(unsigned char *sha1)
900 char *hex = sha1_to_hex(sha1);
901 char *filename;
902 char *url;
903 char tmpfile[PATH_MAX];
904 long prev_posn = 0;
905 char range[RANGE_HEADER_SIZE];
906 struct curl_slist *range_header = NULL;
908 FILE *indexfile;
909 struct active_request_slot *slot;
910 struct slot_results results;
912 /* Don't use the index if the pack isn't there */
913 url = xmalloc(strlen(remote->url) + 64);
914 sprintf(url, "%sobjects/pack/pack-%s.pack", remote->url, hex);
915 slot = get_active_slot();
916 slot->results = &results;
917 curl_easy_setopt(slot->curl, CURLOPT_URL, url);
918 curl_easy_setopt(slot->curl, CURLOPT_NOBODY, 1);
919 if (start_active_slot(slot)) {
920 run_active_slot(slot);
921 if (results.curl_result != CURLE_OK) {
922 free(url);
923 return error("Unable to verify pack %s is available",
924 hex);
926 } else {
927 return error("Unable to start request");
930 if (has_pack_index(sha1))
931 return 0;
933 if (push_verbosely)
934 fprintf(stderr, "Getting index for pack %s\n", hex);
936 sprintf(url, "%sobjects/pack/pack-%s.idx", remote->url, hex);
938 filename = sha1_pack_index_name(sha1);
939 snprintf(tmpfile, sizeof(tmpfile), "%s.temp", filename);
940 indexfile = fopen(tmpfile, "a");
941 if (!indexfile)
942 return error("Unable to open local file %s for pack index",
943 filename);
945 slot = get_active_slot();
946 slot->results = &results;
947 curl_easy_setopt(slot->curl, CURLOPT_NOBODY, 0);
948 curl_easy_setopt(slot->curl, CURLOPT_HTTPGET, 1);
949 curl_easy_setopt(slot->curl, CURLOPT_FILE, indexfile);
950 curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION, fwrite);
951 curl_easy_setopt(slot->curl, CURLOPT_URL, url);
952 curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, no_pragma_header);
953 slot->local = indexfile;
955 /* If there is data present from a previous transfer attempt,
956 resume where it left off */
957 prev_posn = ftell(indexfile);
958 if (prev_posn>0) {
959 if (push_verbosely)
960 fprintf(stderr,
961 "Resuming fetch of index for pack %s at byte %ld\n",
962 hex, prev_posn);
963 sprintf(range, "Range: bytes=%ld-", prev_posn);
964 range_header = curl_slist_append(range_header, range);
965 curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, range_header);
968 if (start_active_slot(slot)) {
969 run_active_slot(slot);
970 if (results.curl_result != CURLE_OK) {
971 free(url);
972 fclose(indexfile);
973 return error("Unable to get pack index %s\n%s", url,
974 curl_errorstr);
976 } else {
977 free(url);
978 fclose(indexfile);
979 return error("Unable to start request");
982 free(url);
983 fclose(indexfile);
985 return move_temp_to_file(tmpfile, filename);
988 static int setup_index(unsigned char *sha1)
990 struct packed_git *new_pack;
992 if (fetch_index(sha1))
993 return -1;
995 new_pack = parse_pack_index(sha1);
996 new_pack->next = remote->packs;
997 remote->packs = new_pack;
998 return 0;
1001 static int fetch_indices(void)
1003 unsigned char sha1[20];
1004 char *url;
1005 struct buffer buffer;
1006 char *data;
1007 int i = 0;
1009 struct active_request_slot *slot;
1010 struct slot_results results;
1012 data = xcalloc(1, 4096);
1013 buffer.size = 4096;
1014 buffer.posn = 0;
1015 buffer.buffer = data;
1017 if (push_verbosely)
1018 fprintf(stderr, "Getting pack list\n");
1020 url = xmalloc(strlen(remote->url) + 20);
1021 sprintf(url, "%sobjects/info/packs", remote->url);
1023 slot = get_active_slot();
1024 slot->results = &results;
1025 curl_easy_setopt(slot->curl, CURLOPT_FILE, &buffer);
1026 curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION, fwrite_buffer);
1027 curl_easy_setopt(slot->curl, CURLOPT_URL, url);
1028 curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, NULL);
1029 if (start_active_slot(slot)) {
1030 run_active_slot(slot);
1031 if (results.curl_result != CURLE_OK) {
1032 free(buffer.buffer);
1033 free(url);
1034 if (results.http_code == 404)
1035 return 0;
1036 else
1037 return error("%s", curl_errorstr);
1039 } else {
1040 free(buffer.buffer);
1041 free(url);
1042 return error("Unable to start request");
1044 free(url);
1046 data = buffer.buffer;
1047 while (i < buffer.posn) {
1048 switch (data[i]) {
1049 case 'P':
1050 i++;
1051 if (i + 52 < buffer.posn &&
1052 !strncmp(data + i, " pack-", 6) &&
1053 !strncmp(data + i + 46, ".pack\n", 6)) {
1054 get_sha1_hex(data + i + 6, sha1);
1055 setup_index(sha1);
1056 i += 51;
1057 break;
1059 default:
1060 while (data[i] != '\n')
1061 i++;
1063 i++;
1066 free(buffer.buffer);
1067 return 0;
1070 static inline int needs_quote(int ch)
1072 switch (ch) {
1073 case '/': case '-': case '.':
1074 case 'A'...'Z': case 'a'...'z': case '0'...'9':
1075 return 0;
1076 default:
1077 return 1;
1081 static inline int hex(int v)
1083 if (v < 10) return '0' + v;
1084 else return 'A' + v - 10;
1087 static char *quote_ref_url(const char *base, const char *ref)
1089 const char *cp;
1090 char *dp, *qref;
1091 int len, baselen, ch;
1093 baselen = strlen(base);
1094 len = baselen + 1;
1095 for (cp = ref; (ch = *cp) != 0; cp++, len++)
1096 if (needs_quote(ch))
1097 len += 2; /* extra two hex plus replacement % */
1098 qref = xmalloc(len);
1099 memcpy(qref, base, baselen);
1100 for (cp = ref, dp = qref + baselen; (ch = *cp) != 0; cp++) {
1101 if (needs_quote(ch)) {
1102 *dp++ = '%';
1103 *dp++ = hex((ch >> 4) & 0xF);
1104 *dp++ = hex(ch & 0xF);
1106 else
1107 *dp++ = ch;
1109 *dp = 0;
1111 return qref;
1114 int fetch_ref(char *ref, unsigned char *sha1)
1116 char *url;
1117 char hex[42];
1118 struct buffer buffer;
1119 char *base = remote->url;
1120 struct active_request_slot *slot;
1121 struct slot_results results;
1122 buffer.size = 41;
1123 buffer.posn = 0;
1124 buffer.buffer = hex;
1125 hex[41] = '\0';
1127 url = quote_ref_url(base, ref);
1128 slot = get_active_slot();
1129 slot->results = &results;
1130 curl_easy_setopt(slot->curl, CURLOPT_FILE, &buffer);
1131 curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION, fwrite_buffer);
1132 curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, NULL);
1133 curl_easy_setopt(slot->curl, CURLOPT_URL, url);
1134 if (start_active_slot(slot)) {
1135 run_active_slot(slot);
1136 if (results.curl_result != CURLE_OK)
1137 return error("Couldn't get %s for %s\n%s",
1138 url, ref, curl_errorstr);
1139 } else {
1140 return error("Unable to start request");
1143 hex[40] = '\0';
1144 get_sha1_hex(hex, sha1);
1145 return 0;
1148 static void one_remote_object(const char *hex)
1150 unsigned char sha1[20];
1151 struct object *obj;
1153 if (get_sha1_hex(hex, sha1) != 0)
1154 return;
1156 obj = lookup_object(sha1);
1157 if (!obj)
1158 obj = parse_object(sha1);
1160 /* Ignore remote objects that don't exist locally */
1161 if (!obj)
1162 return;
1164 obj->flags |= REMOTE;
1165 if (!object_list_contains(objects, obj))
1166 add_object(obj, &objects, NULL, "");
1169 static void handle_lockprop_ctx(struct xml_ctx *ctx, int tag_closed)
1171 int *lock_flags = (int *)ctx->userData;
1173 if (tag_closed) {
1174 if (!strcmp(ctx->name, DAV_CTX_LOCKENTRY)) {
1175 if ((*lock_flags & DAV_PROP_LOCKEX) &&
1176 (*lock_flags & DAV_PROP_LOCKWR)) {
1177 *lock_flags |= DAV_LOCK_OK;
1179 *lock_flags &= DAV_LOCK_OK;
1180 } else if (!strcmp(ctx->name, DAV_CTX_LOCKTYPE_WRITE)) {
1181 *lock_flags |= DAV_PROP_LOCKWR;
1182 } else if (!strcmp(ctx->name, DAV_CTX_LOCKTYPE_EXCLUSIVE)) {
1183 *lock_flags |= DAV_PROP_LOCKEX;
1188 static void handle_new_lock_ctx(struct xml_ctx *ctx, int tag_closed)
1190 struct remote_lock *lock = (struct remote_lock *)ctx->userData;
1192 if (tag_closed && ctx->cdata) {
1193 if (!strcmp(ctx->name, DAV_ACTIVELOCK_OWNER)) {
1194 lock->owner = xmalloc(strlen(ctx->cdata) + 1);
1195 strcpy(lock->owner, ctx->cdata);
1196 } else if (!strcmp(ctx->name, DAV_ACTIVELOCK_TIMEOUT)) {
1197 if (!strncmp(ctx->cdata, "Second-", 7))
1198 lock->timeout =
1199 strtol(ctx->cdata + 7, NULL, 10);
1200 } else if (!strcmp(ctx->name, DAV_ACTIVELOCK_TOKEN)) {
1201 if (!strncmp(ctx->cdata, "opaquelocktoken:", 16)) {
1202 lock->token = xmalloc(strlen(ctx->cdata) - 15);
1203 strcpy(lock->token, ctx->cdata + 16);
1209 static void one_remote_ref(char *refname);
1211 static void
1212 xml_start_tag(void *userData, const char *name, const char **atts)
1214 struct xml_ctx *ctx = (struct xml_ctx *)userData;
1215 const char *c = strchr(name, ':');
1216 int new_len;
1218 if (c == NULL)
1219 c = name;
1220 else
1221 c++;
1223 new_len = strlen(ctx->name) + strlen(c) + 2;
1225 if (new_len > ctx->len) {
1226 ctx->name = xrealloc(ctx->name, new_len);
1227 ctx->len = new_len;
1229 strcat(ctx->name, ".");
1230 strcat(ctx->name, c);
1232 if (ctx->cdata) {
1233 free(ctx->cdata);
1234 ctx->cdata = NULL;
1237 ctx->userFunc(ctx, 0);
1240 static void
1241 xml_end_tag(void *userData, const char *name)
1243 struct xml_ctx *ctx = (struct xml_ctx *)userData;
1244 const char *c = strchr(name, ':');
1245 char *ep;
1247 ctx->userFunc(ctx, 1);
1249 if (c == NULL)
1250 c = name;
1251 else
1252 c++;
1254 ep = ctx->name + strlen(ctx->name) - strlen(c) - 1;
1255 *ep = 0;
1258 static void
1259 xml_cdata(void *userData, const XML_Char *s, int len)
1261 struct xml_ctx *ctx = (struct xml_ctx *)userData;
1262 if (ctx->cdata)
1263 free(ctx->cdata);
1264 ctx->cdata = xcalloc(len+1, 1);
1265 strncpy(ctx->cdata, s, len);
1268 static struct remote_lock *lock_remote(char *path, long timeout)
1270 struct active_request_slot *slot;
1271 struct slot_results results;
1272 struct buffer out_buffer;
1273 struct buffer in_buffer;
1274 char *out_data;
1275 char *in_data;
1276 char *url;
1277 char *ep;
1278 char timeout_header[25];
1279 struct remote_lock *lock = NULL;
1280 XML_Parser parser = XML_ParserCreate(NULL);
1281 enum XML_Status result;
1282 struct curl_slist *dav_headers = NULL;
1283 struct xml_ctx ctx;
1285 url = xmalloc(strlen(remote->url) + strlen(path) + 1);
1286 sprintf(url, "%s%s", remote->url, path);
1288 /* Make sure leading directories exist for the remote ref */
1289 ep = strchr(url + strlen(remote->url) + 11, '/');
1290 while (ep) {
1291 *ep = 0;
1292 slot = get_active_slot();
1293 slot->results = &results;
1294 curl_easy_setopt(slot->curl, CURLOPT_HTTPGET, 1);
1295 curl_easy_setopt(slot->curl, CURLOPT_URL, url);
1296 curl_easy_setopt(slot->curl, CURLOPT_CUSTOMREQUEST, DAV_MKCOL);
1297 curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION, fwrite_null);
1298 if (start_active_slot(slot)) {
1299 run_active_slot(slot);
1300 if (results.curl_result != CURLE_OK &&
1301 results.http_code != 405) {
1302 fprintf(stderr,
1303 "Unable to create branch path %s\n",
1304 url);
1305 free(url);
1306 return NULL;
1308 } else {
1309 fprintf(stderr, "Unable to start MKCOL request\n");
1310 free(url);
1311 return NULL;
1313 *ep = '/';
1314 ep = strchr(ep + 1, '/');
1317 out_buffer.size = strlen(LOCK_REQUEST) + strlen(git_default_email) - 2;
1318 out_data = xmalloc(out_buffer.size + 1);
1319 snprintf(out_data, out_buffer.size + 1, LOCK_REQUEST, git_default_email);
1320 out_buffer.posn = 0;
1321 out_buffer.buffer = out_data;
1323 in_buffer.size = 4096;
1324 in_data = xmalloc(in_buffer.size);
1325 in_buffer.posn = 0;
1326 in_buffer.buffer = in_data;
1328 sprintf(timeout_header, "Timeout: Second-%ld", timeout);
1329 dav_headers = curl_slist_append(dav_headers, timeout_header);
1330 dav_headers = curl_slist_append(dav_headers, "Content-Type: text/xml");
1332 slot = get_active_slot();
1333 slot->results = &results;
1334 curl_easy_setopt(slot->curl, CURLOPT_INFILE, &out_buffer);
1335 curl_easy_setopt(slot->curl, CURLOPT_INFILESIZE, out_buffer.size);
1336 curl_easy_setopt(slot->curl, CURLOPT_READFUNCTION, fread_buffer);
1337 curl_easy_setopt(slot->curl, CURLOPT_FILE, &in_buffer);
1338 curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION, fwrite_buffer);
1339 curl_easy_setopt(slot->curl, CURLOPT_URL, url);
1340 curl_easy_setopt(slot->curl, CURLOPT_UPLOAD, 1);
1341 curl_easy_setopt(slot->curl, CURLOPT_CUSTOMREQUEST, DAV_LOCK);
1342 curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, dav_headers);
1344 lock = xcalloc(1, sizeof(*lock));
1345 lock->timeout = -1;
1347 if (start_active_slot(slot)) {
1348 run_active_slot(slot);
1349 if (results.curl_result == CURLE_OK) {
1350 ctx.name = xcalloc(10, 1);
1351 ctx.len = 0;
1352 ctx.cdata = NULL;
1353 ctx.userFunc = handle_new_lock_ctx;
1354 ctx.userData = lock;
1355 XML_SetUserData(parser, &ctx);
1356 XML_SetElementHandler(parser, xml_start_tag,
1357 xml_end_tag);
1358 XML_SetCharacterDataHandler(parser, xml_cdata);
1359 result = XML_Parse(parser, in_buffer.buffer,
1360 in_buffer.posn, 1);
1361 free(ctx.name);
1362 if (result != XML_STATUS_OK) {
1363 fprintf(stderr, "XML error: %s\n",
1364 XML_ErrorString(
1365 XML_GetErrorCode(parser)));
1366 lock->timeout = -1;
1369 } else {
1370 fprintf(stderr, "Unable to start LOCK request\n");
1373 curl_slist_free_all(dav_headers);
1374 free(out_data);
1375 free(in_data);
1377 if (lock->token == NULL || lock->timeout <= 0) {
1378 if (lock->token != NULL)
1379 free(lock->token);
1380 if (lock->owner != NULL)
1381 free(lock->owner);
1382 free(url);
1383 free(lock);
1384 lock = NULL;
1385 } else {
1386 lock->url = url;
1387 lock->start_time = time(NULL);
1388 lock->next = remote->locks;
1389 remote->locks = lock;
1392 return lock;
1395 static int unlock_remote(struct remote_lock *lock)
1397 struct active_request_slot *slot;
1398 struct slot_results results;
1399 struct remote_lock *prev = remote->locks;
1400 char *lock_token_header;
1401 struct curl_slist *dav_headers = NULL;
1402 int rc = 0;
1404 lock_token_header = xmalloc(strlen(lock->token) + 31);
1405 sprintf(lock_token_header, "Lock-Token: <opaquelocktoken:%s>",
1406 lock->token);
1407 dav_headers = curl_slist_append(dav_headers, lock_token_header);
1409 slot = get_active_slot();
1410 slot->results = &results;
1411 curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION, fwrite_null);
1412 curl_easy_setopt(slot->curl, CURLOPT_URL, lock->url);
1413 curl_easy_setopt(slot->curl, CURLOPT_CUSTOMREQUEST, DAV_UNLOCK);
1414 curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, dav_headers);
1416 if (start_active_slot(slot)) {
1417 run_active_slot(slot);
1418 if (results.curl_result == CURLE_OK)
1419 rc = 1;
1420 else
1421 fprintf(stderr, "UNLOCK HTTP error %ld\n",
1422 results.http_code);
1423 } else {
1424 fprintf(stderr, "Unable to start UNLOCK request\n");
1427 curl_slist_free_all(dav_headers);
1428 free(lock_token_header);
1430 if (remote->locks == lock) {
1431 remote->locks = lock->next;
1432 } else {
1433 while (prev && prev->next != lock)
1434 prev = prev->next;
1435 if (prev)
1436 prev->next = prev->next->next;
1439 if (lock->owner != NULL)
1440 free(lock->owner);
1441 free(lock->url);
1442 free(lock->token);
1443 free(lock);
1445 return rc;
1448 static void remote_ls(const char *path, int flags,
1449 void (*userFunc)(struct remote_ls_ctx *ls),
1450 void *userData);
1452 static void process_ls_object(struct remote_ls_ctx *ls)
1454 unsigned int *parent = (unsigned int *)ls->userData;
1455 char *path = ls->dentry_name;
1456 char *obj_hex;
1458 if (!strcmp(ls->path, ls->dentry_name) && (ls->flags & IS_DIR)) {
1459 remote_dir_exists[*parent] = 1;
1460 return;
1463 if (strlen(path) != 49)
1464 return;
1465 path += 8;
1466 obj_hex = xmalloc(strlen(path));
1467 strncpy(obj_hex, path, 2);
1468 strcpy(obj_hex + 2, path + 3);
1469 one_remote_object(obj_hex);
1470 free(obj_hex);
1473 static void process_ls_ref(struct remote_ls_ctx *ls)
1475 if (!strcmp(ls->path, ls->dentry_name) && (ls->dentry_flags & IS_DIR)) {
1476 fprintf(stderr, " %s\n", ls->dentry_name);
1477 return;
1480 if (!(ls->dentry_flags & IS_DIR))
1481 one_remote_ref(ls->dentry_name);
1484 static void handle_remote_ls_ctx(struct xml_ctx *ctx, int tag_closed)
1486 struct remote_ls_ctx *ls = (struct remote_ls_ctx *)ctx->userData;
1488 if (tag_closed) {
1489 if (!strcmp(ctx->name, DAV_PROPFIND_RESP) && ls->dentry_name) {
1490 if (ls->dentry_flags & IS_DIR) {
1491 if (ls->flags & PROCESS_DIRS) {
1492 ls->userFunc(ls);
1494 if (strcmp(ls->dentry_name, ls->path) &&
1495 ls->flags & RECURSIVE) {
1496 remote_ls(ls->dentry_name,
1497 ls->flags,
1498 ls->userFunc,
1499 ls->userData);
1501 } else if (ls->flags & PROCESS_FILES) {
1502 ls->userFunc(ls);
1504 } else if (!strcmp(ctx->name, DAV_PROPFIND_NAME) && ctx->cdata) {
1505 ls->dentry_name = xmalloc(strlen(ctx->cdata) -
1506 remote->path_len + 1);
1507 strcpy(ls->dentry_name, ctx->cdata + remote->path_len);
1508 } else if (!strcmp(ctx->name, DAV_PROPFIND_COLLECTION)) {
1509 ls->dentry_flags |= IS_DIR;
1511 } else if (!strcmp(ctx->name, DAV_PROPFIND_RESP)) {
1512 if (ls->dentry_name) {
1513 free(ls->dentry_name);
1515 ls->dentry_name = NULL;
1516 ls->dentry_flags = 0;
1520 static void remote_ls(const char *path, int flags,
1521 void (*userFunc)(struct remote_ls_ctx *ls),
1522 void *userData)
1524 char *url = xmalloc(strlen(remote->url) + strlen(path) + 1);
1525 struct active_request_slot *slot;
1526 struct slot_results results;
1527 struct buffer in_buffer;
1528 struct buffer out_buffer;
1529 char *in_data;
1530 char *out_data;
1531 XML_Parser parser = XML_ParserCreate(NULL);
1532 enum XML_Status result;
1533 struct curl_slist *dav_headers = NULL;
1534 struct xml_ctx ctx;
1535 struct remote_ls_ctx ls;
1537 ls.flags = flags;
1538 ls.path = strdup(path);
1539 ls.dentry_name = NULL;
1540 ls.dentry_flags = 0;
1541 ls.userData = userData;
1542 ls.userFunc = userFunc;
1544 sprintf(url, "%s%s", remote->url, path);
1546 out_buffer.size = strlen(PROPFIND_ALL_REQUEST);
1547 out_data = xmalloc(out_buffer.size + 1);
1548 snprintf(out_data, out_buffer.size + 1, PROPFIND_ALL_REQUEST);
1549 out_buffer.posn = 0;
1550 out_buffer.buffer = out_data;
1552 in_buffer.size = 4096;
1553 in_data = xmalloc(in_buffer.size);
1554 in_buffer.posn = 0;
1555 in_buffer.buffer = in_data;
1557 dav_headers = curl_slist_append(dav_headers, "Depth: 1");
1558 dav_headers = curl_slist_append(dav_headers, "Content-Type: text/xml");
1560 slot = get_active_slot();
1561 slot->results = &results;
1562 curl_easy_setopt(slot->curl, CURLOPT_INFILE, &out_buffer);
1563 curl_easy_setopt(slot->curl, CURLOPT_INFILESIZE, out_buffer.size);
1564 curl_easy_setopt(slot->curl, CURLOPT_READFUNCTION, fread_buffer);
1565 curl_easy_setopt(slot->curl, CURLOPT_FILE, &in_buffer);
1566 curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION, fwrite_buffer);
1567 curl_easy_setopt(slot->curl, CURLOPT_URL, url);
1568 curl_easy_setopt(slot->curl, CURLOPT_UPLOAD, 1);
1569 curl_easy_setopt(slot->curl, CURLOPT_CUSTOMREQUEST, DAV_PROPFIND);
1570 curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, dav_headers);
1572 if (start_active_slot(slot)) {
1573 run_active_slot(slot);
1574 if (results.curl_result == CURLE_OK) {
1575 ctx.name = xcalloc(10, 1);
1576 ctx.len = 0;
1577 ctx.cdata = NULL;
1578 ctx.userFunc = handle_remote_ls_ctx;
1579 ctx.userData = &ls;
1580 XML_SetUserData(parser, &ctx);
1581 XML_SetElementHandler(parser, xml_start_tag,
1582 xml_end_tag);
1583 XML_SetCharacterDataHandler(parser, xml_cdata);
1584 result = XML_Parse(parser, in_buffer.buffer,
1585 in_buffer.posn, 1);
1586 free(ctx.name);
1588 if (result != XML_STATUS_OK) {
1589 fprintf(stderr, "XML error: %s\n",
1590 XML_ErrorString(
1591 XML_GetErrorCode(parser)));
1594 } else {
1595 fprintf(stderr, "Unable to start PROPFIND request\n");
1598 free(ls.path);
1599 free(url);
1600 free(out_data);
1601 free(in_buffer.buffer);
1602 curl_slist_free_all(dav_headers);
1605 static void get_remote_object_list(unsigned char parent)
1607 char path[] = "objects/XX/";
1608 static const char hex[] = "0123456789abcdef";
1609 unsigned int val = parent;
1611 path[8] = hex[val >> 4];
1612 path[9] = hex[val & 0xf];
1613 remote_dir_exists[val] = 0;
1614 remote_ls(path, (PROCESS_FILES | PROCESS_DIRS),
1615 process_ls_object, &val);
1618 static int locking_available(void)
1620 struct active_request_slot *slot;
1621 struct slot_results results;
1622 struct buffer in_buffer;
1623 struct buffer out_buffer;
1624 char *in_data;
1625 char *out_data;
1626 XML_Parser parser = XML_ParserCreate(NULL);
1627 enum XML_Status result;
1628 struct curl_slist *dav_headers = NULL;
1629 struct xml_ctx ctx;
1630 int lock_flags = 0;
1632 out_buffer.size =
1633 strlen(PROPFIND_SUPPORTEDLOCK_REQUEST) +
1634 strlen(remote->url) - 2;
1635 out_data = xmalloc(out_buffer.size + 1);
1636 snprintf(out_data, out_buffer.size + 1,
1637 PROPFIND_SUPPORTEDLOCK_REQUEST, remote->url);
1638 out_buffer.posn = 0;
1639 out_buffer.buffer = out_data;
1641 in_buffer.size = 4096;
1642 in_data = xmalloc(in_buffer.size);
1643 in_buffer.posn = 0;
1644 in_buffer.buffer = in_data;
1646 dav_headers = curl_slist_append(dav_headers, "Depth: 0");
1647 dav_headers = curl_slist_append(dav_headers, "Content-Type: text/xml");
1649 slot = get_active_slot();
1650 slot->results = &results;
1651 curl_easy_setopt(slot->curl, CURLOPT_INFILE, &out_buffer);
1652 curl_easy_setopt(slot->curl, CURLOPT_INFILESIZE, out_buffer.size);
1653 curl_easy_setopt(slot->curl, CURLOPT_READFUNCTION, fread_buffer);
1654 curl_easy_setopt(slot->curl, CURLOPT_FILE, &in_buffer);
1655 curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION, fwrite_buffer);
1656 curl_easy_setopt(slot->curl, CURLOPT_URL, remote->url);
1657 curl_easy_setopt(slot->curl, CURLOPT_UPLOAD, 1);
1658 curl_easy_setopt(slot->curl, CURLOPT_CUSTOMREQUEST, DAV_PROPFIND);
1659 curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, dav_headers);
1661 if (start_active_slot(slot)) {
1662 run_active_slot(slot);
1663 if (results.curl_result == CURLE_OK) {
1664 ctx.name = xcalloc(10, 1);
1665 ctx.len = 0;
1666 ctx.cdata = NULL;
1667 ctx.userFunc = handle_lockprop_ctx;
1668 ctx.userData = &lock_flags;
1669 XML_SetUserData(parser, &ctx);
1670 XML_SetElementHandler(parser, xml_start_tag,
1671 xml_end_tag);
1672 result = XML_Parse(parser, in_buffer.buffer,
1673 in_buffer.posn, 1);
1674 free(ctx.name);
1676 if (result != XML_STATUS_OK) {
1677 fprintf(stderr, "XML error: %s\n",
1678 XML_ErrorString(
1679 XML_GetErrorCode(parser)));
1680 lock_flags = 0;
1683 } else {
1684 fprintf(stderr, "Unable to start PROPFIND request\n");
1687 free(out_data);
1688 free(in_buffer.buffer);
1689 curl_slist_free_all(dav_headers);
1691 return lock_flags;
1694 static struct object_list **process_blob(struct blob *blob,
1695 struct object_list **p,
1696 struct name_path *path,
1697 const char *name)
1699 struct object *obj = &blob->object;
1701 obj->flags |= LOCAL;
1703 if (obj->flags & (UNINTERESTING | SEEN))
1704 return p;
1706 obj->flags |= SEEN;
1707 name = strdup(name);
1708 return add_object(obj, p, path, name);
1711 static struct object_list **process_tree(struct tree *tree,
1712 struct object_list **p,
1713 struct name_path *path,
1714 const char *name)
1716 struct object *obj = &tree->object;
1717 struct tree_desc desc;
1718 struct name_entry entry;
1719 struct name_path me;
1721 obj->flags |= LOCAL;
1723 if (obj->flags & (UNINTERESTING | SEEN))
1724 return p;
1725 if (parse_tree(tree) < 0)
1726 die("bad tree object %s", sha1_to_hex(obj->sha1));
1728 obj->flags |= SEEN;
1729 name = strdup(name);
1730 p = add_object(obj, p, NULL, name);
1731 me.up = path;
1732 me.elem = name;
1733 me.elem_len = strlen(name);
1735 desc.buf = tree->buffer;
1736 desc.size = tree->size;
1738 while (tree_entry(&desc, &entry)) {
1739 if (S_ISDIR(entry.mode))
1740 p = process_tree(lookup_tree(entry.sha1), p, &me, name);
1741 else
1742 p = process_blob(lookup_blob(entry.sha1), p, &me, name);
1744 free(tree->buffer);
1745 tree->buffer = NULL;
1746 return p;
1749 static int get_delta(struct rev_info *revs, struct remote_lock *lock)
1751 struct commit *commit;
1752 struct object_list **p = &objects, *pending;
1753 int count = 0;
1755 while ((commit = get_revision(revs)) != NULL) {
1756 p = process_tree(commit->tree, p, NULL, "");
1757 commit->object.flags |= LOCAL;
1758 if (!(commit->object.flags & UNINTERESTING))
1759 count += add_send_request(&commit->object, lock);
1762 for (pending = revs->pending_objects; pending; pending = pending->next) {
1763 struct object *obj = pending->item;
1764 const char *name = pending->name;
1766 if (obj->flags & (UNINTERESTING | SEEN))
1767 continue;
1768 if (obj->type == tag_type) {
1769 obj->flags |= SEEN;
1770 p = add_object(obj, p, NULL, name);
1771 continue;
1773 if (obj->type == tree_type) {
1774 p = process_tree((struct tree *)obj, p, NULL, name);
1775 continue;
1777 if (obj->type == blob_type) {
1778 p = process_blob((struct blob *)obj, p, NULL, name);
1779 continue;
1781 die("unknown pending object %s (%s)", sha1_to_hex(obj->sha1), name);
1784 while (objects) {
1785 if (!(objects->item->flags & UNINTERESTING))
1786 count += add_send_request(objects->item, lock);
1787 objects = objects->next;
1790 return count;
1793 static int update_remote(unsigned char *sha1, struct remote_lock *lock)
1795 struct active_request_slot *slot;
1796 struct slot_results results;
1797 char *out_data;
1798 char *if_header;
1799 struct buffer out_buffer;
1800 struct curl_slist *dav_headers = NULL;
1801 int i;
1803 if_header = xmalloc(strlen(lock->token) + 25);
1804 sprintf(if_header, "If: (<opaquelocktoken:%s>)", lock->token);
1805 dav_headers = curl_slist_append(dav_headers, if_header);
1807 out_buffer.size = 41;
1808 out_data = xmalloc(out_buffer.size + 1);
1809 i = snprintf(out_data, out_buffer.size + 1, "%s\n", sha1_to_hex(sha1));
1810 if (i != out_buffer.size) {
1811 fprintf(stderr, "Unable to initialize PUT request body\n");
1812 return 0;
1814 out_buffer.posn = 0;
1815 out_buffer.buffer = out_data;
1817 slot = get_active_slot();
1818 slot->results = &results;
1819 curl_easy_setopt(slot->curl, CURLOPT_INFILE, &out_buffer);
1820 curl_easy_setopt(slot->curl, CURLOPT_INFILESIZE, out_buffer.size);
1821 curl_easy_setopt(slot->curl, CURLOPT_READFUNCTION, fread_buffer);
1822 curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION, fwrite_null);
1823 curl_easy_setopt(slot->curl, CURLOPT_CUSTOMREQUEST, DAV_PUT);
1824 curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, dav_headers);
1825 curl_easy_setopt(slot->curl, CURLOPT_UPLOAD, 1);
1826 curl_easy_setopt(slot->curl, CURLOPT_PUT, 1);
1827 curl_easy_setopt(slot->curl, CURLOPT_URL, lock->url);
1829 if (start_active_slot(slot)) {
1830 run_active_slot(slot);
1831 free(out_data);
1832 free(if_header);
1833 if (results.curl_result != CURLE_OK) {
1834 fprintf(stderr,
1835 "PUT error: curl result=%d, HTTP code=%ld\n",
1836 results.curl_result, results.http_code);
1837 /* We should attempt recovery? */
1838 return 0;
1840 } else {
1841 free(out_data);
1842 free(if_header);
1843 fprintf(stderr, "Unable to start PUT request\n");
1844 return 0;
1847 return 1;
1850 static struct ref *local_refs, **local_tail;
1851 static struct ref *remote_refs, **remote_tail;
1853 static int one_local_ref(const char *refname, const unsigned char *sha1)
1855 struct ref *ref;
1856 int len = strlen(refname) + 1;
1857 ref = xcalloc(1, sizeof(*ref) + len);
1858 memcpy(ref->new_sha1, sha1, 20);
1859 memcpy(ref->name, refname, len);
1860 *local_tail = ref;
1861 local_tail = &ref->next;
1862 return 0;
1865 static void one_remote_ref(char *refname)
1867 struct ref *ref;
1868 unsigned char remote_sha1[20];
1869 struct object *obj;
1870 int len = strlen(refname) + 1;
1872 if (fetch_ref(refname, remote_sha1) != 0) {
1873 fprintf(stderr,
1874 "Unable to fetch ref %s from %s\n",
1875 refname, remote->url);
1876 return;
1880 * Fetch a copy of the object if it doesn't exist locally - it
1881 * may be required for updating server info later.
1883 if (remote->can_update_info_refs && !has_sha1_file(remote_sha1)) {
1884 obj = lookup_unknown_object(remote_sha1);
1885 if (obj) {
1886 fprintf(stderr, " fetch %s for %s\n",
1887 sha1_to_hex(remote_sha1), refname);
1888 add_fetch_request(obj);
1892 ref = xcalloc(1, sizeof(*ref) + len);
1893 memcpy(ref->old_sha1, remote_sha1, 20);
1894 memcpy(ref->name, refname, len);
1895 *remote_tail = ref;
1896 remote_tail = &ref->next;
1899 static void get_local_heads(void)
1901 local_tail = &local_refs;
1902 for_each_ref(one_local_ref);
1905 static void get_dav_remote_heads(void)
1907 remote_tail = &remote_refs;
1908 remote_ls("refs/", (PROCESS_FILES | PROCESS_DIRS | RECURSIVE), process_ls_ref, NULL);
1911 static int is_zero_sha1(const unsigned char *sha1)
1913 int i;
1915 for (i = 0; i < 20; i++) {
1916 if (*sha1++)
1917 return 0;
1919 return 1;
1922 static void unmark_and_free(struct commit_list *list, unsigned int mark)
1924 while (list) {
1925 struct commit_list *temp = list;
1926 temp->item->object.flags &= ~mark;
1927 list = temp->next;
1928 free(temp);
1932 static int ref_newer(const unsigned char *new_sha1,
1933 const unsigned char *old_sha1)
1935 struct object *o;
1936 struct commit *old, *new;
1937 struct commit_list *list, *used;
1938 int found = 0;
1940 /* Both new and old must be commit-ish and new is descendant of
1941 * old. Otherwise we require --force.
1943 o = deref_tag(parse_object(old_sha1), NULL, 0);
1944 if (!o || o->type != commit_type)
1945 return 0;
1946 old = (struct commit *) o;
1948 o = deref_tag(parse_object(new_sha1), NULL, 0);
1949 if (!o || o->type != commit_type)
1950 return 0;
1951 new = (struct commit *) o;
1953 if (parse_commit(new) < 0)
1954 return 0;
1956 used = list = NULL;
1957 commit_list_insert(new, &list);
1958 while (list) {
1959 new = pop_most_recent_commit(&list, TMP_MARK);
1960 commit_list_insert(new, &used);
1961 if (new == old) {
1962 found = 1;
1963 break;
1966 unmark_and_free(list, TMP_MARK);
1967 unmark_and_free(used, TMP_MARK);
1968 return found;
1971 static void mark_edge_parents_uninteresting(struct commit *commit)
1973 struct commit_list *parents;
1975 for (parents = commit->parents; parents; parents = parents->next) {
1976 struct commit *parent = parents->item;
1977 if (!(parent->object.flags & UNINTERESTING))
1978 continue;
1979 mark_tree_uninteresting(parent->tree);
1983 static void mark_edges_uninteresting(struct commit_list *list)
1985 for ( ; list; list = list->next) {
1986 struct commit *commit = list->item;
1988 if (commit->object.flags & UNINTERESTING) {
1989 mark_tree_uninteresting(commit->tree);
1990 continue;
1992 mark_edge_parents_uninteresting(commit);
1996 static void add_remote_info_ref(struct remote_ls_ctx *ls)
1998 struct buffer *buf = (struct buffer *)ls->userData;
1999 unsigned char remote_sha1[20];
2000 struct object *o;
2001 int len;
2002 char *ref_info;
2004 if (fetch_ref(ls->dentry_name, remote_sha1) != 0) {
2005 fprintf(stderr,
2006 "Unable to fetch ref %s from %s\n",
2007 ls->dentry_name, remote->url);
2008 aborted = 1;
2009 return;
2012 o = parse_object(remote_sha1);
2013 if (!o) {
2014 fprintf(stderr,
2015 "Unable to parse object %s for remote ref %s\n",
2016 sha1_to_hex(remote_sha1), ls->dentry_name);
2017 aborted = 1;
2018 return;
2021 len = strlen(ls->dentry_name) + 42;
2022 ref_info = xcalloc(len + 1, 1);
2023 sprintf(ref_info, "%s %s\n",
2024 sha1_to_hex(remote_sha1), ls->dentry_name);
2025 fwrite_buffer(ref_info, 1, len, buf);
2026 free(ref_info);
2028 if (o->type == tag_type) {
2029 o = deref_tag(o, ls->dentry_name, 0);
2030 if (o) {
2031 len = strlen(ls->dentry_name) + 45;
2032 ref_info = xcalloc(len + 1, 1);
2033 sprintf(ref_info, "%s %s^{}\n",
2034 sha1_to_hex(o->sha1), ls->dentry_name);
2035 fwrite_buffer(ref_info, 1, len, buf);
2036 free(ref_info);
2041 static void update_remote_info_refs(struct remote_lock *lock)
2043 struct buffer buffer;
2044 struct active_request_slot *slot;
2045 struct slot_results results;
2046 char *if_header;
2047 struct curl_slist *dav_headers = NULL;
2049 buffer.buffer = xcalloc(1, 4096);
2050 buffer.size = 4096;
2051 buffer.posn = 0;
2052 remote_ls("refs/", (PROCESS_FILES | RECURSIVE),
2053 add_remote_info_ref, &buffer);
2054 if (!aborted) {
2055 if_header = xmalloc(strlen(lock->token) + 25);
2056 sprintf(if_header, "If: (<opaquelocktoken:%s>)", lock->token);
2057 dav_headers = curl_slist_append(dav_headers, if_header);
2059 slot = get_active_slot();
2060 slot->results = &results;
2061 curl_easy_setopt(slot->curl, CURLOPT_INFILE, &buffer);
2062 curl_easy_setopt(slot->curl, CURLOPT_INFILESIZE, buffer.posn);
2063 curl_easy_setopt(slot->curl, CURLOPT_READFUNCTION, fread_buffer);
2064 curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION, fwrite_null);
2065 curl_easy_setopt(slot->curl, CURLOPT_CUSTOMREQUEST, DAV_PUT);
2066 curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, dav_headers);
2067 curl_easy_setopt(slot->curl, CURLOPT_UPLOAD, 1);
2068 curl_easy_setopt(slot->curl, CURLOPT_PUT, 1);
2069 curl_easy_setopt(slot->curl, CURLOPT_URL, lock->url);
2071 buffer.posn = 0;
2073 if (start_active_slot(slot)) {
2074 run_active_slot(slot);
2075 if (results.curl_result != CURLE_OK) {
2076 fprintf(stderr,
2077 "PUT error: curl result=%d, HTTP code=%ld\n",
2078 results.curl_result, results.http_code);
2081 free(if_header);
2083 free(buffer.buffer);
2086 static int remote_exists(const char *path)
2088 char *url = xmalloc(strlen(remote->url) + strlen(path) + 1);
2089 struct active_request_slot *slot;
2090 struct slot_results results;
2092 sprintf(url, "%s%s", remote->url, path);
2094 slot = get_active_slot();
2095 slot->results = &results;
2096 curl_easy_setopt(slot->curl, CURLOPT_URL, url);
2097 curl_easy_setopt(slot->curl, CURLOPT_NOBODY, 1);
2099 if (start_active_slot(slot)) {
2100 run_active_slot(slot);
2101 if (results.http_code == 404)
2102 return 0;
2103 else if (results.curl_result == CURLE_OK)
2104 return 1;
2105 else
2106 fprintf(stderr, "HEAD HTTP error %ld\n", results.http_code);
2107 } else {
2108 fprintf(stderr, "Unable to start HEAD request\n");
2111 return -1;
2114 static void fetch_symref(char *path, char **symref, unsigned char *sha1)
2116 char *url;
2117 struct buffer buffer;
2118 struct active_request_slot *slot;
2119 struct slot_results results;
2121 url = xmalloc(strlen(remote->url) + strlen(path) + 1);
2122 sprintf(url, "%s%s", remote->url, path);
2124 buffer.size = 4096;
2125 buffer.posn = 0;
2126 buffer.buffer = xmalloc(buffer.size);
2128 slot = get_active_slot();
2129 slot->results = &results;
2130 curl_easy_setopt(slot->curl, CURLOPT_FILE, &buffer);
2131 curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION, fwrite_buffer);
2132 curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, NULL);
2133 curl_easy_setopt(slot->curl, CURLOPT_URL, url);
2134 if (start_active_slot(slot)) {
2135 run_active_slot(slot);
2136 if (results.curl_result != CURLE_OK) {
2137 die("Couldn't get %s for remote symref\n%s",
2138 url, curl_errorstr);
2140 } else {
2141 die("Unable to start remote symref request");
2143 free(url);
2145 if (*symref != NULL)
2146 free(*symref);
2147 *symref = NULL;
2148 memset(sha1, 0, 20);
2150 if (buffer.posn == 0)
2151 return;
2153 /* If it's a symref, set the refname; otherwise try for a sha1 */
2154 if (!strncmp((char *)buffer.buffer, "ref: ", 5)) {
2155 *symref = xcalloc(buffer.posn - 5, 1);
2156 strncpy(*symref, (char *)buffer.buffer + 5, buffer.posn - 6);
2157 } else {
2158 get_sha1_hex(buffer.buffer, sha1);
2161 free(buffer.buffer);
2164 static int verify_merge_base(unsigned char *head_sha1, unsigned char *branch_sha1)
2166 int pipe_fd[2];
2167 pid_t merge_base_pid;
2168 char line[PATH_MAX + 20];
2169 unsigned char merge_sha1[20];
2170 int verified = 0;
2172 if (pipe(pipe_fd) < 0)
2173 die("Verify merge base: pipe failed");
2175 merge_base_pid = fork();
2176 if (!merge_base_pid) {
2177 static const char *args[] = {
2178 "merge-base",
2179 "-a",
2180 NULL,
2181 NULL,
2182 NULL
2184 args[2] = strdup(sha1_to_hex(head_sha1));
2185 args[3] = sha1_to_hex(branch_sha1);
2187 dup2(pipe_fd[1], 1);
2188 close(pipe_fd[0]);
2189 close(pipe_fd[1]);
2190 execv_git_cmd(args);
2191 die("merge-base setup failed");
2193 if (merge_base_pid < 0)
2194 die("merge-base fork failed");
2196 dup2(pipe_fd[0], 0);
2197 close(pipe_fd[0]);
2198 close(pipe_fd[1]);
2199 while (fgets(line, sizeof(line), stdin) != NULL) {
2200 if (get_sha1_hex(line, merge_sha1))
2201 die("expected sha1, got garbage:\n %s", line);
2202 if (!memcmp(branch_sha1, merge_sha1, 20)) {
2203 verified = 1;
2204 break;
2208 return verified;
2211 static int delete_remote_branch(char *pattern, int force)
2213 struct ref *refs = remote_refs;
2214 struct ref *remote_ref = NULL;
2215 unsigned char head_sha1[20];
2216 char *symref = NULL;
2217 int match;
2218 int patlen = strlen(pattern);
2219 int i;
2220 struct active_request_slot *slot;
2221 struct slot_results results;
2222 char *url;
2224 /* Find the remote branch(es) matching the specified branch name */
2225 for (match = 0; refs; refs = refs->next) {
2226 char *name = refs->name;
2227 int namelen = strlen(name);
2228 if (namelen < patlen ||
2229 memcmp(name + namelen - patlen, pattern, patlen))
2230 continue;
2231 if (namelen != patlen && name[namelen - patlen - 1] != '/')
2232 continue;
2233 match++;
2234 remote_ref = refs;
2236 if (match == 0)
2237 return error("No remote branch matches %s", pattern);
2238 if (match != 1)
2239 return error("More than one remote branch matches %s",
2240 pattern);
2243 * Remote HEAD must be a symref (not exactly foolproof; a remote
2244 * symlink to a symref will look like a symref)
2246 fetch_symref("HEAD", &symref, head_sha1);
2247 if (!symref)
2248 return error("Remote HEAD is not a symref");
2250 /* Remote branch must not be the remote HEAD */
2251 for (i=0; symref && i<MAXDEPTH; i++) {
2252 if (!strcmp(remote_ref->name, symref))
2253 return error("Remote branch %s is the current HEAD",
2254 remote_ref->name);
2255 fetch_symref(symref, &symref, head_sha1);
2258 /* Run extra sanity checks if delete is not forced */
2259 if (!force) {
2260 /* Remote HEAD must resolve to a known object */
2261 if (symref)
2262 return error("Remote HEAD symrefs too deep");
2263 if (is_zero_sha1(head_sha1))
2264 return error("Unable to resolve remote HEAD");
2265 if (!has_sha1_file(head_sha1))
2266 return error("Remote HEAD resolves to object %s\nwhich does not exist locally, perhaps you need to fetch?", sha1_to_hex(head_sha1));
2268 /* Remote branch must resolve to a known object */
2269 if (is_zero_sha1(remote_ref->old_sha1))
2270 return error("Unable to resolve remote branch %s",
2271 remote_ref->name);
2272 if (!has_sha1_file(remote_ref->old_sha1))
2273 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));
2275 /* Remote branch must be an ancestor of remote HEAD */
2276 if (!verify_merge_base(head_sha1, remote_ref->old_sha1)) {
2277 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);
2281 /* Send delete request */
2282 fprintf(stderr, "Removing remote branch '%s'\n", remote_ref->name);
2283 url = xmalloc(strlen(remote->url) + strlen(remote_ref->name) + 1);
2284 sprintf(url, "%s%s", remote->url, remote_ref->name);
2285 slot = get_active_slot();
2286 slot->results = &results;
2287 curl_easy_setopt(slot->curl, CURLOPT_HTTPGET, 1);
2288 curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION, fwrite_null);
2289 curl_easy_setopt(slot->curl, CURLOPT_URL, url);
2290 curl_easy_setopt(slot->curl, CURLOPT_CUSTOMREQUEST, DAV_DELETE);
2291 if (start_active_slot(slot)) {
2292 run_active_slot(slot);
2293 free(url);
2294 if (results.curl_result != CURLE_OK)
2295 return error("DELETE request failed (%d/%ld)\n",
2296 results.curl_result, results.http_code);
2297 } else {
2298 free(url);
2299 return error("Unable to start DELETE request");
2302 return 0;
2305 int main(int argc, char **argv)
2307 struct transfer_request *request;
2308 struct transfer_request *next_request;
2309 int nr_refspec = 0;
2310 char **refspec = NULL;
2311 struct remote_lock *ref_lock = NULL;
2312 struct remote_lock *info_ref_lock = NULL;
2313 struct rev_info revs;
2314 int delete_branch = 0;
2315 int force_delete = 0;
2316 int objects_to_send;
2317 int rc = 0;
2318 int i;
2319 int new_refs;
2320 struct ref *ref;
2322 setup_git_directory();
2323 setup_ident();
2325 remote = xcalloc(sizeof(*remote), 1);
2327 argv++;
2328 for (i = 1; i < argc; i++, argv++) {
2329 char *arg = *argv;
2331 if (*arg == '-') {
2332 if (!strcmp(arg, "--all")) {
2333 push_all = 1;
2334 continue;
2336 if (!strcmp(arg, "--force")) {
2337 force_all = 1;
2338 continue;
2340 if (!strcmp(arg, "--verbose")) {
2341 push_verbosely = 1;
2342 continue;
2344 if (!strcmp(arg, "-d")) {
2345 delete_branch = 1;
2346 continue;
2348 if (!strcmp(arg, "-D")) {
2349 delete_branch = 1;
2350 force_delete = 1;
2351 continue;
2354 if (!remote->url) {
2355 char *path = strstr(arg, "//");
2356 remote->url = arg;
2357 if (path) {
2358 path = strchr(path+2, '/');
2359 if (path)
2360 remote->path_len = strlen(path);
2362 continue;
2364 refspec = argv;
2365 nr_refspec = argc - i;
2366 break;
2369 if (!remote->url)
2370 usage(http_push_usage);
2372 if (delete_branch && nr_refspec != 1)
2373 die("You must specify only one branch name when deleting a remote branch");
2375 memset(remote_dir_exists, -1, 256);
2377 http_init();
2379 no_pragma_header = curl_slist_append(no_pragma_header, "Pragma:");
2380 default_headers = curl_slist_append(default_headers, "Range:");
2381 default_headers = curl_slist_append(default_headers, "Destination:");
2382 default_headers = curl_slist_append(default_headers, "If:");
2383 default_headers = curl_slist_append(default_headers,
2384 "Pragma: no-cache");
2386 /* Verify DAV compliance/lock support */
2387 if (!locking_available()) {
2388 fprintf(stderr, "Error: no DAV locking support on remote repo %s\n", remote->url);
2389 rc = 1;
2390 goto cleanup;
2393 /* Check whether the remote has server info files */
2394 remote->can_update_info_refs = 0;
2395 remote->has_info_refs = remote_exists("info/refs");
2396 remote->has_info_packs = remote_exists("objects/info/packs");
2397 if (remote->has_info_refs) {
2398 info_ref_lock = lock_remote("info/refs", LOCK_TIME);
2399 if (info_ref_lock)
2400 remote->can_update_info_refs = 1;
2402 if (remote->has_info_packs)
2403 fetch_indices();
2405 /* Get a list of all local and remote heads to validate refspecs */
2406 get_local_heads();
2407 fprintf(stderr, "Fetching remote heads...\n");
2408 get_dav_remote_heads();
2410 /* Remove a remote branch if -d or -D was specified */
2411 if (delete_branch) {
2412 if (delete_remote_branch(refspec[0], force_delete) == -1)
2413 fprintf(stderr, "Unable to delete remote branch %s\n",
2414 refspec[0]);
2415 goto cleanup;
2418 /* match them up */
2419 if (!remote_tail)
2420 remote_tail = &remote_refs;
2421 if (match_refs(local_refs, remote_refs, &remote_tail,
2422 nr_refspec, refspec, push_all))
2423 return -1;
2424 if (!remote_refs) {
2425 fprintf(stderr, "No refs in common and none specified; doing nothing.\n");
2426 return 0;
2429 new_refs = 0;
2430 for (ref = remote_refs; ref; ref = ref->next) {
2431 char old_hex[60], *new_hex;
2432 const char *commit_argv[4];
2433 int commit_argc;
2434 char *new_sha1_hex, *old_sha1_hex;
2436 if (!ref->peer_ref)
2437 continue;
2438 if (!memcmp(ref->old_sha1, ref->peer_ref->new_sha1, 20)) {
2439 if (push_verbosely || 1)
2440 fprintf(stderr, "'%s': up-to-date\n", ref->name);
2441 continue;
2444 if (!force_all &&
2445 !is_zero_sha1(ref->old_sha1) &&
2446 !ref->force) {
2447 if (!has_sha1_file(ref->old_sha1) ||
2448 !ref_newer(ref->peer_ref->new_sha1,
2449 ref->old_sha1)) {
2450 /* We do not have the remote ref, or
2451 * we know that the remote ref is not
2452 * an ancestor of what we are trying to
2453 * push. Either way this can be losing
2454 * commits at the remote end and likely
2455 * we were not up to date to begin with.
2457 error("remote '%s' is not a strict "
2458 "subset of local ref '%s'. "
2459 "maybe you are not up-to-date and "
2460 "need to pull first?",
2461 ref->name,
2462 ref->peer_ref->name);
2463 rc = -2;
2464 continue;
2467 memcpy(ref->new_sha1, ref->peer_ref->new_sha1, 20);
2468 if (is_zero_sha1(ref->new_sha1)) {
2469 error("cannot happen anymore");
2470 rc = -3;
2471 continue;
2473 new_refs++;
2474 strcpy(old_hex, sha1_to_hex(ref->old_sha1));
2475 new_hex = sha1_to_hex(ref->new_sha1);
2477 fprintf(stderr, "updating '%s'", ref->name);
2478 if (strcmp(ref->name, ref->peer_ref->name))
2479 fprintf(stderr, " using '%s'", ref->peer_ref->name);
2480 fprintf(stderr, "\n from %s\n to %s\n", old_hex, new_hex);
2483 /* Lock remote branch ref */
2484 ref_lock = lock_remote(ref->name, LOCK_TIME);
2485 if (ref_lock == NULL) {
2486 fprintf(stderr, "Unable to lock remote branch %s\n",
2487 ref->name);
2488 rc = 1;
2489 continue;
2492 /* Set up revision info for this refspec */
2493 commit_argc = 3;
2494 new_sha1_hex = strdup(sha1_to_hex(ref->new_sha1));
2495 old_sha1_hex = NULL;
2496 commit_argv[1] = "--objects";
2497 commit_argv[2] = new_sha1_hex;
2498 if (!push_all && !is_zero_sha1(ref->old_sha1)) {
2499 old_sha1_hex = xmalloc(42);
2500 sprintf(old_sha1_hex, "^%s",
2501 sha1_to_hex(ref->old_sha1));
2502 commit_argv[3] = old_sha1_hex;
2503 commit_argc++;
2505 init_revisions(&revs);
2506 setup_revisions(commit_argc, commit_argv, &revs, NULL);
2507 free(new_sha1_hex);
2508 if (old_sha1_hex) {
2509 free(old_sha1_hex);
2510 commit_argv[1] = NULL;
2513 /* Generate a list of objects that need to be pushed */
2514 pushing = 0;
2515 prepare_revision_walk(&revs);
2516 mark_edges_uninteresting(revs.commits);
2517 objects_to_send = get_delta(&revs, ref_lock);
2518 finish_all_active_slots();
2520 /* Push missing objects to remote, this would be a
2521 convenient time to pack them first if appropriate. */
2522 pushing = 1;
2523 if (objects_to_send)
2524 fprintf(stderr, " sending %d objects\n",
2525 objects_to_send);
2526 fill_active_slots();
2527 finish_all_active_slots();
2529 /* Update the remote branch if all went well */
2530 if (aborted || !update_remote(ref->new_sha1, ref_lock)) {
2531 rc = 1;
2532 goto unlock;
2535 unlock:
2536 if (!rc)
2537 fprintf(stderr, " done\n");
2538 unlock_remote(ref_lock);
2539 check_locks();
2542 /* Update remote server info if appropriate */
2543 if (remote->has_info_refs && new_refs) {
2544 if (info_ref_lock && remote->can_update_info_refs) {
2545 fprintf(stderr, "Updating remote server info\n");
2546 update_remote_info_refs(info_ref_lock);
2547 } else {
2548 fprintf(stderr, "Unable to update server info\n");
2551 if (info_ref_lock)
2552 unlock_remote(info_ref_lock);
2554 cleanup:
2555 free(remote);
2557 curl_slist_free_all(no_pragma_header);
2558 curl_slist_free_all(default_headers);
2560 http_cleanup();
2562 request = request_queue_head;
2563 while (request != NULL) {
2564 next_request = request->next;
2565 release_request(request);
2566 request = next_request;
2569 return rc;