Merge branch 'js/maint-all-implies-HEAD'
[alt-git.git] / http-push.c
blob59037df5025f0e71b882d53489fe5274aa9065f0
1 #include "cache.h"
2 #include "commit.h"
3 #include "pack.h"
4 #include "tag.h"
5 #include "blob.h"
6 #include "http.h"
7 #include "refs.h"
8 #include "diff.h"
9 #include "revision.h"
10 #include "exec_cmd.h"
11 #include "remote.h"
12 #include "list-objects.h"
14 #include <expat.h>
16 static const char http_push_usage[] =
17 "git http-push [--all] [--dry-run] [--force] [--verbose] <remote> [<head>...]\n";
19 #ifndef XML_STATUS_OK
20 enum XML_Status {
21 XML_STATUS_OK = 1,
22 XML_STATUS_ERROR = 0
24 #define XML_STATUS_OK 1
25 #define XML_STATUS_ERROR 0
26 #endif
28 #define PREV_BUF_SIZE 4096
29 #define RANGE_HEADER_SIZE 30
31 /* DAV methods */
32 #define DAV_LOCK "LOCK"
33 #define DAV_MKCOL "MKCOL"
34 #define DAV_MOVE "MOVE"
35 #define DAV_PROPFIND "PROPFIND"
36 #define DAV_PUT "PUT"
37 #define DAV_UNLOCK "UNLOCK"
38 #define DAV_DELETE "DELETE"
40 /* DAV lock flags */
41 #define DAV_PROP_LOCKWR (1u << 0)
42 #define DAV_PROP_LOCKEX (1u << 1)
43 #define DAV_LOCK_OK (1u << 2)
45 /* DAV XML properties */
46 #define DAV_CTX_LOCKENTRY ".multistatus.response.propstat.prop.supportedlock.lockentry"
47 #define DAV_CTX_LOCKTYPE_WRITE ".multistatus.response.propstat.prop.supportedlock.lockentry.locktype.write"
48 #define DAV_CTX_LOCKTYPE_EXCLUSIVE ".multistatus.response.propstat.prop.supportedlock.lockentry.lockscope.exclusive"
49 #define DAV_ACTIVELOCK_OWNER ".prop.lockdiscovery.activelock.owner.href"
50 #define DAV_ACTIVELOCK_TIMEOUT ".prop.lockdiscovery.activelock.timeout"
51 #define DAV_ACTIVELOCK_TOKEN ".prop.lockdiscovery.activelock.locktoken.href"
52 #define DAV_PROPFIND_RESP ".multistatus.response"
53 #define DAV_PROPFIND_NAME ".multistatus.response.href"
54 #define DAV_PROPFIND_COLLECTION ".multistatus.response.propstat.prop.resourcetype.collection"
56 /* DAV request body templates */
57 #define PROPFIND_SUPPORTEDLOCK_REQUEST "<?xml version=\"1.0\" encoding=\"utf-8\" ?>\n<D:propfind xmlns:D=\"DAV:\">\n<D:prop xmlns:R=\"%s\">\n<D:supportedlock/>\n</D:prop>\n</D:propfind>"
58 #define PROPFIND_ALL_REQUEST "<?xml version=\"1.0\" encoding=\"utf-8\" ?>\n<D:propfind xmlns:D=\"DAV:\">\n<D:allprop/>\n</D:propfind>"
59 #define LOCK_REQUEST "<?xml version=\"1.0\" encoding=\"utf-8\" ?>\n<D:lockinfo xmlns:D=\"DAV:\">\n<D:lockscope><D:exclusive/></D:lockscope>\n<D:locktype><D:write/></D:locktype>\n<D:owner>\n<D:href>mailto:%s</D:href>\n</D:owner>\n</D:lockinfo>"
61 #define LOCK_TIME 600
62 #define LOCK_REFRESH 30
64 /* bits #0-15 in revision.h */
66 #define LOCAL (1u<<16)
67 #define REMOTE (1u<<17)
68 #define FETCHING (1u<<18)
69 #define PUSHING (1u<<19)
71 /* We allow "recursive" symbolic refs. Only within reason, though */
72 #define MAXDEPTH 5
74 static int pushing;
75 static int aborted;
76 static signed char remote_dir_exists[256];
78 static struct curl_slist *no_pragma_header;
80 static int push_verbosely;
81 static int push_all = MATCH_REFS_NONE;
82 static int force_all;
83 static int dry_run;
85 static struct object_list *objects;
87 struct repo
89 char *url;
90 char *path;
91 int path_len;
92 int has_info_refs;
93 int can_update_info_refs;
94 int has_info_packs;
95 struct packed_git *packs;
96 struct remote_lock *locks;
99 static struct repo *remote;
101 enum transfer_state {
102 NEED_FETCH,
103 RUN_FETCH_LOOSE,
104 RUN_FETCH_PACKED,
105 NEED_PUSH,
106 RUN_MKCOL,
107 RUN_PUT,
108 RUN_MOVE,
109 ABORTED,
110 COMPLETE,
113 struct transfer_request
115 struct object *obj;
116 char *url;
117 char *dest;
118 struct remote_lock *lock;
119 struct curl_slist *headers;
120 struct buffer buffer;
121 char filename[PATH_MAX];
122 char tmpfile[PATH_MAX];
123 int local_fileno;
124 FILE *local_stream;
125 enum transfer_state state;
126 CURLcode curl_result;
127 char errorstr[CURL_ERROR_SIZE];
128 long http_code;
129 unsigned char real_sha1[20];
130 git_SHA_CTX c;
131 z_stream stream;
132 int zret;
133 int rename;
134 void *userData;
135 struct active_request_slot *slot;
136 struct transfer_request *next;
139 static struct transfer_request *request_queue_head;
141 struct xml_ctx
143 char *name;
144 int len;
145 char *cdata;
146 void (*userFunc)(struct xml_ctx *ctx, int tag_closed);
147 void *userData;
150 struct remote_lock
152 char *url;
153 char *owner;
154 char *token;
155 time_t start_time;
156 long timeout;
157 int refreshing;
158 struct remote_lock *next;
161 /* Flags that control remote_ls processing */
162 #define PROCESS_FILES (1u << 0)
163 #define PROCESS_DIRS (1u << 1)
164 #define RECURSIVE (1u << 2)
166 /* Flags that remote_ls passes to callback functions */
167 #define IS_DIR (1u << 0)
169 struct remote_ls_ctx
171 char *path;
172 void (*userFunc)(struct remote_ls_ctx *ls);
173 void *userData;
174 int flags;
175 char *dentry_name;
176 int dentry_flags;
177 struct remote_ls_ctx *parent;
180 /* get_dav_token_headers options */
181 enum dav_header_flag {
182 DAV_HEADER_IF = (1u << 0),
183 DAV_HEADER_LOCK = (1u << 1),
184 DAV_HEADER_TIMEOUT = (1u << 2)
187 static struct curl_slist *get_dav_token_headers(struct remote_lock *lock, enum dav_header_flag options)
189 struct strbuf buf = STRBUF_INIT;
190 struct curl_slist *dav_headers = NULL;
192 if (options & DAV_HEADER_IF) {
193 strbuf_addf(&buf, "If: (<%s>)", lock->token);
194 dav_headers = curl_slist_append(dav_headers, buf.buf);
195 strbuf_reset(&buf);
197 if (options & DAV_HEADER_LOCK) {
198 strbuf_addf(&buf, "Lock-Token: <%s>", lock->token);
199 dav_headers = curl_slist_append(dav_headers, buf.buf);
200 strbuf_reset(&buf);
202 if (options & DAV_HEADER_TIMEOUT) {
203 strbuf_addf(&buf, "Timeout: Second-%ld", lock->timeout);
204 dav_headers = curl_slist_append(dav_headers, buf.buf);
205 strbuf_reset(&buf);
207 strbuf_release(&buf);
209 return dav_headers;
212 static void finish_request(struct transfer_request *request);
213 static void release_request(struct transfer_request *request);
215 static void process_response(void *callback_data)
217 struct transfer_request *request =
218 (struct transfer_request *)callback_data;
220 finish_request(request);
223 #ifdef USE_CURL_MULTI
224 static size_t fwrite_sha1_file(void *ptr, size_t eltsize, size_t nmemb,
225 void *data)
227 unsigned char expn[4096];
228 size_t size = eltsize * nmemb;
229 int posn = 0;
230 struct transfer_request *request = (struct transfer_request *)data;
231 do {
232 ssize_t retval = xwrite(request->local_fileno,
233 (char *) ptr + posn, size - posn);
234 if (retval < 0)
235 return posn;
236 posn += retval;
237 } while (posn < size);
239 request->stream.avail_in = size;
240 request->stream.next_in = ptr;
241 do {
242 request->stream.next_out = expn;
243 request->stream.avail_out = sizeof(expn);
244 request->zret = git_inflate(&request->stream, Z_SYNC_FLUSH);
245 git_SHA1_Update(&request->c, expn,
246 sizeof(expn) - request->stream.avail_out);
247 } while (request->stream.avail_in && request->zret == Z_OK);
248 data_received++;
249 return size;
252 static void start_fetch_loose(struct transfer_request *request)
254 char *hex = sha1_to_hex(request->obj->sha1);
255 char *filename;
256 char prevfile[PATH_MAX];
257 char *url;
258 char *posn;
259 int prevlocal;
260 unsigned char prev_buf[PREV_BUF_SIZE];
261 ssize_t prev_read = 0;
262 long prev_posn = 0;
263 char range[RANGE_HEADER_SIZE];
264 struct curl_slist *range_header = NULL;
265 struct active_request_slot *slot;
267 filename = sha1_file_name(request->obj->sha1);
268 snprintf(request->filename, sizeof(request->filename), "%s", filename);
269 snprintf(request->tmpfile, sizeof(request->tmpfile),
270 "%s.temp", filename);
272 snprintf(prevfile, sizeof(prevfile), "%s.prev", request->filename);
273 unlink(prevfile);
274 rename(request->tmpfile, prevfile);
275 unlink(request->tmpfile);
277 if (request->local_fileno != -1)
278 error("fd leakage in start: %d", request->local_fileno);
279 request->local_fileno = open(request->tmpfile,
280 O_WRONLY | O_CREAT | O_EXCL, 0666);
281 /* This could have failed due to the "lazy directory creation";
282 * try to mkdir the last path component.
284 if (request->local_fileno < 0 && errno == ENOENT) {
285 char *dir = strrchr(request->tmpfile, '/');
286 if (dir) {
287 *dir = 0;
288 mkdir(request->tmpfile, 0777);
289 *dir = '/';
291 request->local_fileno = open(request->tmpfile,
292 O_WRONLY | O_CREAT | O_EXCL, 0666);
295 if (request->local_fileno < 0) {
296 request->state = ABORTED;
297 error("Couldn't create temporary file %s for %s: %s",
298 request->tmpfile, request->filename, strerror(errno));
299 return;
302 memset(&request->stream, 0, sizeof(request->stream));
304 git_inflate_init(&request->stream);
306 git_SHA1_Init(&request->c);
308 url = xmalloc(strlen(remote->url) + 50);
309 request->url = xmalloc(strlen(remote->url) + 50);
310 strcpy(url, remote->url);
311 posn = url + strlen(remote->url);
312 strcpy(posn, "objects/");
313 posn += 8;
314 memcpy(posn, hex, 2);
315 posn += 2;
316 *(posn++) = '/';
317 strcpy(posn, hex + 2);
318 strcpy(request->url, url);
320 /* If a previous temp file is present, process what was already
321 fetched. */
322 prevlocal = open(prevfile, O_RDONLY);
323 if (prevlocal != -1) {
324 do {
325 prev_read = xread(prevlocal, prev_buf, PREV_BUF_SIZE);
326 if (prev_read>0) {
327 if (fwrite_sha1_file(prev_buf,
329 prev_read,
330 request) == prev_read) {
331 prev_posn += prev_read;
332 } else {
333 prev_read = -1;
336 } while (prev_read > 0);
337 close(prevlocal);
339 unlink(prevfile);
341 /* Reset inflate/SHA1 if there was an error reading the previous temp
342 file; also rewind to the beginning of the local file. */
343 if (prev_read == -1) {
344 memset(&request->stream, 0, sizeof(request->stream));
345 git_inflate_init(&request->stream);
346 git_SHA1_Init(&request->c);
347 if (prev_posn>0) {
348 prev_posn = 0;
349 lseek(request->local_fileno, 0, SEEK_SET);
350 ftruncate(request->local_fileno, 0);
354 slot = get_active_slot();
355 slot->callback_func = process_response;
356 slot->callback_data = request;
357 request->slot = slot;
359 curl_easy_setopt(slot->curl, CURLOPT_FILE, request);
360 curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION, fwrite_sha1_file);
361 curl_easy_setopt(slot->curl, CURLOPT_ERRORBUFFER, request->errorstr);
362 curl_easy_setopt(slot->curl, CURLOPT_URL, url);
363 curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, no_pragma_header);
365 /* If we have successfully processed data from a previous fetch
366 attempt, only fetch the data we don't already have. */
367 if (prev_posn>0) {
368 if (push_verbosely)
369 fprintf(stderr,
370 "Resuming fetch of object %s at byte %ld\n",
371 hex, prev_posn);
372 sprintf(range, "Range: bytes=%ld-", prev_posn);
373 range_header = curl_slist_append(range_header, range);
374 curl_easy_setopt(slot->curl,
375 CURLOPT_HTTPHEADER, range_header);
378 /* Try to get the request started, abort the request on error */
379 request->state = RUN_FETCH_LOOSE;
380 if (!start_active_slot(slot)) {
381 fprintf(stderr, "Unable to start GET request\n");
382 remote->can_update_info_refs = 0;
383 release_request(request);
387 static void start_mkcol(struct transfer_request *request)
389 char *hex = sha1_to_hex(request->obj->sha1);
390 struct active_request_slot *slot;
391 char *posn;
393 request->url = xmalloc(strlen(remote->url) + 13);
394 strcpy(request->url, remote->url);
395 posn = request->url + strlen(remote->url);
396 strcpy(posn, "objects/");
397 posn += 8;
398 memcpy(posn, hex, 2);
399 posn += 2;
400 strcpy(posn, "/");
402 slot = get_active_slot();
403 slot->callback_func = process_response;
404 slot->callback_data = request;
405 curl_easy_setopt(slot->curl, CURLOPT_HTTPGET, 1); /* undo PUT setup */
406 curl_easy_setopt(slot->curl, CURLOPT_URL, request->url);
407 curl_easy_setopt(slot->curl, CURLOPT_ERRORBUFFER, request->errorstr);
408 curl_easy_setopt(slot->curl, CURLOPT_CUSTOMREQUEST, DAV_MKCOL);
409 curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION, fwrite_null);
411 if (start_active_slot(slot)) {
412 request->slot = slot;
413 request->state = RUN_MKCOL;
414 } else {
415 request->state = ABORTED;
416 free(request->url);
417 request->url = NULL;
420 #endif
422 static void start_fetch_packed(struct transfer_request *request)
424 char *url;
425 struct packed_git *target;
426 FILE *packfile;
427 char *filename;
428 long prev_posn = 0;
429 char range[RANGE_HEADER_SIZE];
430 struct curl_slist *range_header = NULL;
432 struct transfer_request *check_request = request_queue_head;
433 struct active_request_slot *slot;
435 target = find_sha1_pack(request->obj->sha1, remote->packs);
436 if (!target) {
437 fprintf(stderr, "Unable to fetch %s, will not be able to update server info refs\n", sha1_to_hex(request->obj->sha1));
438 remote->can_update_info_refs = 0;
439 release_request(request);
440 return;
443 fprintf(stderr, "Fetching pack %s\n", sha1_to_hex(target->sha1));
444 fprintf(stderr, " which contains %s\n", sha1_to_hex(request->obj->sha1));
446 filename = sha1_pack_name(target->sha1);
447 snprintf(request->filename, sizeof(request->filename), "%s", filename);
448 snprintf(request->tmpfile, sizeof(request->tmpfile),
449 "%s.temp", filename);
451 url = xmalloc(strlen(remote->url) + 64);
452 sprintf(url, "%sobjects/pack/pack-%s.pack",
453 remote->url, sha1_to_hex(target->sha1));
455 /* Make sure there isn't another open request for this pack */
456 while (check_request) {
457 if (check_request->state == RUN_FETCH_PACKED &&
458 !strcmp(check_request->url, url)) {
459 free(url);
460 release_request(request);
461 return;
463 check_request = check_request->next;
466 packfile = fopen(request->tmpfile, "a");
467 if (!packfile) {
468 fprintf(stderr, "Unable to open local file %s for pack",
469 request->tmpfile);
470 remote->can_update_info_refs = 0;
471 free(url);
472 return;
475 slot = get_active_slot();
476 slot->callback_func = process_response;
477 slot->callback_data = request;
478 request->slot = slot;
479 request->local_stream = packfile;
480 request->userData = target;
482 request->url = url;
483 curl_easy_setopt(slot->curl, CURLOPT_FILE, packfile);
484 curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION, fwrite);
485 curl_easy_setopt(slot->curl, CURLOPT_URL, url);
486 curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, no_pragma_header);
487 slot->local = packfile;
489 /* If there is data present from a previous transfer attempt,
490 resume where it left off */
491 prev_posn = ftell(packfile);
492 if (prev_posn>0) {
493 if (push_verbosely)
494 fprintf(stderr,
495 "Resuming fetch of pack %s at byte %ld\n",
496 sha1_to_hex(target->sha1), prev_posn);
497 sprintf(range, "Range: bytes=%ld-", prev_posn);
498 range_header = curl_slist_append(range_header, range);
499 curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, range_header);
502 /* Try to get the request started, abort the request on error */
503 request->state = RUN_FETCH_PACKED;
504 if (!start_active_slot(slot)) {
505 fprintf(stderr, "Unable to start GET request\n");
506 remote->can_update_info_refs = 0;
507 release_request(request);
511 static void start_put(struct transfer_request *request)
513 char *hex = sha1_to_hex(request->obj->sha1);
514 struct active_request_slot *slot;
515 char *posn;
516 enum object_type type;
517 char hdr[50];
518 void *unpacked;
519 unsigned long len;
520 int hdrlen;
521 ssize_t size;
522 z_stream stream;
524 unpacked = read_sha1_file(request->obj->sha1, &type, &len);
525 hdrlen = sprintf(hdr, "%s %lu", typename(type), len) + 1;
527 /* Set it up */
528 memset(&stream, 0, sizeof(stream));
529 deflateInit(&stream, zlib_compression_level);
530 size = deflateBound(&stream, len + hdrlen);
531 strbuf_init(&request->buffer.buf, size);
532 request->buffer.posn = 0;
534 /* Compress it */
535 stream.next_out = (unsigned char *)request->buffer.buf.buf;
536 stream.avail_out = size;
538 /* First header.. */
539 stream.next_in = (void *)hdr;
540 stream.avail_in = hdrlen;
541 while (deflate(&stream, 0) == Z_OK)
542 /* nothing */;
544 /* Then the data itself.. */
545 stream.next_in = unpacked;
546 stream.avail_in = len;
547 while (deflate(&stream, Z_FINISH) == Z_OK)
548 /* nothing */;
549 deflateEnd(&stream);
550 free(unpacked);
552 request->buffer.buf.len = stream.total_out;
554 request->url = xmalloc(strlen(remote->url) +
555 strlen(request->lock->token) + 51);
556 strcpy(request->url, remote->url);
557 posn = request->url + strlen(remote->url);
558 strcpy(posn, "objects/");
559 posn += 8;
560 memcpy(posn, hex, 2);
561 posn += 2;
562 *(posn++) = '/';
563 strcpy(posn, hex + 2);
564 request->dest = xmalloc(strlen(request->url) + 14);
565 sprintf(request->dest, "Destination: %s", request->url);
566 posn += 38;
567 *(posn++) = '_';
568 strcpy(posn, request->lock->token);
570 slot = get_active_slot();
571 slot->callback_func = process_response;
572 slot->callback_data = request;
573 curl_easy_setopt(slot->curl, CURLOPT_INFILE, &request->buffer);
574 curl_easy_setopt(slot->curl, CURLOPT_INFILESIZE, request->buffer.buf.len);
575 curl_easy_setopt(slot->curl, CURLOPT_READFUNCTION, fread_buffer);
576 curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION, fwrite_null);
577 curl_easy_setopt(slot->curl, CURLOPT_CUSTOMREQUEST, DAV_PUT);
578 curl_easy_setopt(slot->curl, CURLOPT_UPLOAD, 1);
579 curl_easy_setopt(slot->curl, CURLOPT_PUT, 1);
580 curl_easy_setopt(slot->curl, CURLOPT_NOBODY, 0);
581 curl_easy_setopt(slot->curl, CURLOPT_URL, request->url);
583 if (start_active_slot(slot)) {
584 request->slot = slot;
585 request->state = RUN_PUT;
586 } else {
587 request->state = ABORTED;
588 free(request->url);
589 request->url = NULL;
593 static void start_move(struct transfer_request *request)
595 struct active_request_slot *slot;
596 struct curl_slist *dav_headers = NULL;
598 slot = get_active_slot();
599 slot->callback_func = process_response;
600 slot->callback_data = request;
601 curl_easy_setopt(slot->curl, CURLOPT_HTTPGET, 1); /* undo PUT setup */
602 curl_easy_setopt(slot->curl, CURLOPT_CUSTOMREQUEST, DAV_MOVE);
603 dav_headers = curl_slist_append(dav_headers, request->dest);
604 dav_headers = curl_slist_append(dav_headers, "Overwrite: T");
605 curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, dav_headers);
606 curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION, fwrite_null);
607 curl_easy_setopt(slot->curl, CURLOPT_URL, request->url);
609 if (start_active_slot(slot)) {
610 request->slot = slot;
611 request->state = RUN_MOVE;
612 } else {
613 request->state = ABORTED;
614 free(request->url);
615 request->url = NULL;
619 static int refresh_lock(struct remote_lock *lock)
621 struct active_request_slot *slot;
622 struct slot_results results;
623 struct curl_slist *dav_headers;
624 int rc = 0;
626 lock->refreshing = 1;
628 dav_headers = get_dav_token_headers(lock, DAV_HEADER_IF | DAV_HEADER_TIMEOUT);
630 slot = get_active_slot();
631 slot->results = &results;
632 curl_easy_setopt(slot->curl, CURLOPT_HTTPGET, 1);
633 curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION, fwrite_null);
634 curl_easy_setopt(slot->curl, CURLOPT_URL, lock->url);
635 curl_easy_setopt(slot->curl, CURLOPT_CUSTOMREQUEST, DAV_LOCK);
636 curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, dav_headers);
638 if (start_active_slot(slot)) {
639 run_active_slot(slot);
640 if (results.curl_result != CURLE_OK) {
641 fprintf(stderr, "LOCK HTTP error %ld\n",
642 results.http_code);
643 } else {
644 lock->start_time = time(NULL);
645 rc = 1;
649 lock->refreshing = 0;
650 curl_slist_free_all(dav_headers);
652 return rc;
655 static void check_locks(void)
657 struct remote_lock *lock = remote->locks;
658 time_t current_time = time(NULL);
659 int time_remaining;
661 while (lock) {
662 time_remaining = lock->start_time + lock->timeout -
663 current_time;
664 if (!lock->refreshing && time_remaining < LOCK_REFRESH) {
665 if (!refresh_lock(lock)) {
666 fprintf(stderr,
667 "Unable to refresh lock for %s\n",
668 lock->url);
669 aborted = 1;
670 return;
673 lock = lock->next;
677 static void release_request(struct transfer_request *request)
679 struct transfer_request *entry = request_queue_head;
681 if (request == request_queue_head) {
682 request_queue_head = request->next;
683 } else {
684 while (entry->next != NULL && entry->next != request)
685 entry = entry->next;
686 if (entry->next == request)
687 entry->next = entry->next->next;
690 if (request->local_fileno != -1)
691 close(request->local_fileno);
692 if (request->local_stream)
693 fclose(request->local_stream);
694 free(request->url);
695 free(request);
698 static void finish_request(struct transfer_request *request)
700 struct stat st;
701 struct packed_git *target;
702 struct packed_git **lst;
704 request->curl_result = request->slot->curl_result;
705 request->http_code = request->slot->http_code;
706 request->slot = NULL;
708 /* Keep locks active */
709 check_locks();
711 if (request->headers != NULL)
712 curl_slist_free_all(request->headers);
714 /* URL is reused for MOVE after PUT */
715 if (request->state != RUN_PUT) {
716 free(request->url);
717 request->url = NULL;
720 if (request->state == RUN_MKCOL) {
721 if (request->curl_result == CURLE_OK ||
722 request->http_code == 405) {
723 remote_dir_exists[request->obj->sha1[0]] = 1;
724 start_put(request);
725 } else {
726 fprintf(stderr, "MKCOL %s failed, aborting (%d/%ld)\n",
727 sha1_to_hex(request->obj->sha1),
728 request->curl_result, request->http_code);
729 request->state = ABORTED;
730 aborted = 1;
732 } else if (request->state == RUN_PUT) {
733 if (request->curl_result == CURLE_OK) {
734 start_move(request);
735 } else {
736 fprintf(stderr, "PUT %s failed, aborting (%d/%ld)\n",
737 sha1_to_hex(request->obj->sha1),
738 request->curl_result, request->http_code);
739 request->state = ABORTED;
740 aborted = 1;
742 } else if (request->state == RUN_MOVE) {
743 if (request->curl_result == CURLE_OK) {
744 if (push_verbosely)
745 fprintf(stderr, " sent %s\n",
746 sha1_to_hex(request->obj->sha1));
747 request->obj->flags |= REMOTE;
748 release_request(request);
749 } else {
750 fprintf(stderr, "MOVE %s failed, aborting (%d/%ld)\n",
751 sha1_to_hex(request->obj->sha1),
752 request->curl_result, request->http_code);
753 request->state = ABORTED;
754 aborted = 1;
756 } else if (request->state == RUN_FETCH_LOOSE) {
757 fchmod(request->local_fileno, 0444);
758 close(request->local_fileno); request->local_fileno = -1;
760 if (request->curl_result != CURLE_OK &&
761 request->http_code != 416) {
762 if (stat(request->tmpfile, &st) == 0) {
763 if (st.st_size == 0)
764 unlink(request->tmpfile);
766 } else {
767 if (request->http_code == 416)
768 fprintf(stderr, "Warning: requested range invalid; we may already have all the data.\n");
770 git_inflate_end(&request->stream);
771 git_SHA1_Final(request->real_sha1, &request->c);
772 if (request->zret != Z_STREAM_END) {
773 unlink(request->tmpfile);
774 } else if (hashcmp(request->obj->sha1, request->real_sha1)) {
775 unlink(request->tmpfile);
776 } else {
777 request->rename =
778 move_temp_to_file(
779 request->tmpfile,
780 request->filename);
781 if (request->rename == 0) {
782 request->obj->flags |= (LOCAL | REMOTE);
787 /* Try fetching packed if necessary */
788 if (request->obj->flags & LOCAL)
789 release_request(request);
790 else
791 start_fetch_packed(request);
793 } else if (request->state == RUN_FETCH_PACKED) {
794 if (request->curl_result != CURLE_OK) {
795 fprintf(stderr, "Unable to get pack file %s\n%s",
796 request->url, curl_errorstr);
797 remote->can_update_info_refs = 0;
798 } else {
799 off_t pack_size = ftell(request->local_stream);
801 fclose(request->local_stream);
802 request->local_stream = NULL;
803 if (!move_temp_to_file(request->tmpfile,
804 request->filename)) {
805 target = (struct packed_git *)request->userData;
806 target->pack_size = pack_size;
807 lst = &remote->packs;
808 while (*lst != target)
809 lst = &((*lst)->next);
810 *lst = (*lst)->next;
812 if (!verify_pack(target))
813 install_packed_git(target);
814 else
815 remote->can_update_info_refs = 0;
818 release_request(request);
822 #ifdef USE_CURL_MULTI
823 static int fill_active_slot(void *unused)
825 struct transfer_request *request = request_queue_head;
827 if (aborted)
828 return 0;
830 for (request = request_queue_head; request; request = request->next) {
831 if (request->state == NEED_FETCH) {
832 start_fetch_loose(request);
833 return 1;
834 } else if (pushing && request->state == NEED_PUSH) {
835 if (remote_dir_exists[request->obj->sha1[0]] == 1) {
836 start_put(request);
837 } else {
838 start_mkcol(request);
840 return 1;
843 return 0;
845 #endif
847 static void get_remote_object_list(unsigned char parent);
849 static void add_fetch_request(struct object *obj)
851 struct transfer_request *request;
853 check_locks();
856 * Don't fetch the object if it's known to exist locally
857 * or is already in the request queue
859 if (remote_dir_exists[obj->sha1[0]] == -1)
860 get_remote_object_list(obj->sha1[0]);
861 if (obj->flags & (LOCAL | FETCHING))
862 return;
864 obj->flags |= FETCHING;
865 request = xmalloc(sizeof(*request));
866 request->obj = obj;
867 request->url = NULL;
868 request->lock = NULL;
869 request->headers = NULL;
870 request->local_fileno = -1;
871 request->local_stream = NULL;
872 request->state = NEED_FETCH;
873 request->next = request_queue_head;
874 request_queue_head = request;
876 #ifdef USE_CURL_MULTI
877 fill_active_slots();
878 step_active_slots();
879 #endif
882 static int add_send_request(struct object *obj, struct remote_lock *lock)
884 struct transfer_request *request = request_queue_head;
885 struct packed_git *target;
887 /* Keep locks active */
888 check_locks();
891 * Don't push the object if it's known to exist on the remote
892 * or is already in the request queue
894 if (remote_dir_exists[obj->sha1[0]] == -1)
895 get_remote_object_list(obj->sha1[0]);
896 if (obj->flags & (REMOTE | PUSHING))
897 return 0;
898 target = find_sha1_pack(obj->sha1, remote->packs);
899 if (target) {
900 obj->flags |= REMOTE;
901 return 0;
904 obj->flags |= PUSHING;
905 request = xmalloc(sizeof(*request));
906 request->obj = obj;
907 request->url = NULL;
908 request->lock = lock;
909 request->headers = NULL;
910 request->local_fileno = -1;
911 request->local_stream = NULL;
912 request->state = NEED_PUSH;
913 request->next = request_queue_head;
914 request_queue_head = request;
916 #ifdef USE_CURL_MULTI
917 fill_active_slots();
918 step_active_slots();
919 #endif
921 return 1;
924 static int fetch_index(unsigned char *sha1)
926 char *hex = sha1_to_hex(sha1);
927 char *filename;
928 char *url;
929 char tmpfile[PATH_MAX];
930 long prev_posn = 0;
931 char range[RANGE_HEADER_SIZE];
932 struct curl_slist *range_header = NULL;
934 FILE *indexfile;
935 struct active_request_slot *slot;
936 struct slot_results results;
938 /* Don't use the index if the pack isn't there */
939 url = xmalloc(strlen(remote->url) + 64);
940 sprintf(url, "%sobjects/pack/pack-%s.pack", remote->url, hex);
941 slot = get_active_slot();
942 slot->results = &results;
943 curl_easy_setopt(slot->curl, CURLOPT_URL, url);
944 curl_easy_setopt(slot->curl, CURLOPT_NOBODY, 1);
945 if (start_active_slot(slot)) {
946 run_active_slot(slot);
947 if (results.curl_result != CURLE_OK) {
948 free(url);
949 return error("Unable to verify pack %s is available",
950 hex);
952 } else {
953 free(url);
954 return error("Unable to start request");
957 if (has_pack_index(sha1)) {
958 free(url);
959 return 0;
962 if (push_verbosely)
963 fprintf(stderr, "Getting index for pack %s\n", hex);
965 sprintf(url, "%sobjects/pack/pack-%s.idx", remote->url, hex);
967 filename = sha1_pack_index_name(sha1);
968 snprintf(tmpfile, sizeof(tmpfile), "%s.temp", filename);
969 indexfile = fopen(tmpfile, "a");
970 if (!indexfile) {
971 free(url);
972 return error("Unable to open local file %s for pack index",
973 tmpfile);
976 slot = get_active_slot();
977 slot->results = &results;
978 curl_easy_setopt(slot->curl, CURLOPT_NOBODY, 0);
979 curl_easy_setopt(slot->curl, CURLOPT_HTTPGET, 1);
980 curl_easy_setopt(slot->curl, CURLOPT_FILE, indexfile);
981 curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION, fwrite);
982 curl_easy_setopt(slot->curl, CURLOPT_URL, url);
983 curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, no_pragma_header);
984 slot->local = indexfile;
986 /* If there is data present from a previous transfer attempt,
987 resume where it left off */
988 prev_posn = ftell(indexfile);
989 if (prev_posn>0) {
990 if (push_verbosely)
991 fprintf(stderr,
992 "Resuming fetch of index for pack %s at byte %ld\n",
993 hex, prev_posn);
994 sprintf(range, "Range: bytes=%ld-", prev_posn);
995 range_header = curl_slist_append(range_header, range);
996 curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, range_header);
999 if (start_active_slot(slot)) {
1000 run_active_slot(slot);
1001 if (results.curl_result != CURLE_OK) {
1002 free(url);
1003 fclose(indexfile);
1004 return error("Unable to get pack index %s\n%s", url,
1005 curl_errorstr);
1007 } else {
1008 free(url);
1009 fclose(indexfile);
1010 return error("Unable to start request");
1013 free(url);
1014 fclose(indexfile);
1016 return move_temp_to_file(tmpfile, filename);
1019 static int setup_index(unsigned char *sha1)
1021 struct packed_git *new_pack;
1023 if (fetch_index(sha1))
1024 return -1;
1026 new_pack = parse_pack_index(sha1);
1027 new_pack->next = remote->packs;
1028 remote->packs = new_pack;
1029 return 0;
1032 static int fetch_indices(void)
1034 unsigned char sha1[20];
1035 char *url;
1036 struct strbuf buffer = STRBUF_INIT;
1037 char *data;
1038 int i = 0;
1040 struct active_request_slot *slot;
1041 struct slot_results results;
1043 if (push_verbosely)
1044 fprintf(stderr, "Getting pack list\n");
1046 url = xmalloc(strlen(remote->url) + 20);
1047 sprintf(url, "%sobjects/info/packs", remote->url);
1049 slot = get_active_slot();
1050 slot->results = &results;
1051 curl_easy_setopt(slot->curl, CURLOPT_FILE, &buffer);
1052 curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION, fwrite_buffer);
1053 curl_easy_setopt(slot->curl, CURLOPT_URL, url);
1054 curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, NULL);
1055 if (start_active_slot(slot)) {
1056 run_active_slot(slot);
1057 if (results.curl_result != CURLE_OK) {
1058 strbuf_release(&buffer);
1059 free(url);
1060 if (results.http_code == 404)
1061 return 0;
1062 else
1063 return error("%s", curl_errorstr);
1065 } else {
1066 strbuf_release(&buffer);
1067 free(url);
1068 return error("Unable to start request");
1070 free(url);
1072 data = buffer.buf;
1073 while (i < buffer.len) {
1074 switch (data[i]) {
1075 case 'P':
1076 i++;
1077 if (i + 52 < buffer.len &&
1078 !prefixcmp(data + i, " pack-") &&
1079 !prefixcmp(data + i + 46, ".pack\n")) {
1080 get_sha1_hex(data + i + 6, sha1);
1081 setup_index(sha1);
1082 i += 51;
1083 break;
1085 default:
1086 while (data[i] != '\n')
1087 i++;
1089 i++;
1092 strbuf_release(&buffer);
1093 return 0;
1096 static void one_remote_object(const char *hex)
1098 unsigned char sha1[20];
1099 struct object *obj;
1101 if (get_sha1_hex(hex, sha1) != 0)
1102 return;
1104 obj = lookup_object(sha1);
1105 if (!obj)
1106 obj = parse_object(sha1);
1108 /* Ignore remote objects that don't exist locally */
1109 if (!obj)
1110 return;
1112 obj->flags |= REMOTE;
1113 if (!object_list_contains(objects, obj))
1114 object_list_insert(obj, &objects);
1117 static void handle_lockprop_ctx(struct xml_ctx *ctx, int tag_closed)
1119 int *lock_flags = (int *)ctx->userData;
1121 if (tag_closed) {
1122 if (!strcmp(ctx->name, DAV_CTX_LOCKENTRY)) {
1123 if ((*lock_flags & DAV_PROP_LOCKEX) &&
1124 (*lock_flags & DAV_PROP_LOCKWR)) {
1125 *lock_flags |= DAV_LOCK_OK;
1127 *lock_flags &= DAV_LOCK_OK;
1128 } else if (!strcmp(ctx->name, DAV_CTX_LOCKTYPE_WRITE)) {
1129 *lock_flags |= DAV_PROP_LOCKWR;
1130 } else if (!strcmp(ctx->name, DAV_CTX_LOCKTYPE_EXCLUSIVE)) {
1131 *lock_flags |= DAV_PROP_LOCKEX;
1136 static void handle_new_lock_ctx(struct xml_ctx *ctx, int tag_closed)
1138 struct remote_lock *lock = (struct remote_lock *)ctx->userData;
1140 if (tag_closed && ctx->cdata) {
1141 if (!strcmp(ctx->name, DAV_ACTIVELOCK_OWNER)) {
1142 lock->owner = xmalloc(strlen(ctx->cdata) + 1);
1143 strcpy(lock->owner, ctx->cdata);
1144 } else if (!strcmp(ctx->name, DAV_ACTIVELOCK_TIMEOUT)) {
1145 if (!prefixcmp(ctx->cdata, "Second-"))
1146 lock->timeout =
1147 strtol(ctx->cdata + 7, NULL, 10);
1148 } else if (!strcmp(ctx->name, DAV_ACTIVELOCK_TOKEN)) {
1149 lock->token = xmalloc(strlen(ctx->cdata) + 1);
1150 strcpy(lock->token, ctx->cdata);
1155 static void one_remote_ref(char *refname);
1157 static void
1158 xml_start_tag(void *userData, const char *name, const char **atts)
1160 struct xml_ctx *ctx = (struct xml_ctx *)userData;
1161 const char *c = strchr(name, ':');
1162 int new_len;
1164 if (c == NULL)
1165 c = name;
1166 else
1167 c++;
1169 new_len = strlen(ctx->name) + strlen(c) + 2;
1171 if (new_len > ctx->len) {
1172 ctx->name = xrealloc(ctx->name, new_len);
1173 ctx->len = new_len;
1175 strcat(ctx->name, ".");
1176 strcat(ctx->name, c);
1178 free(ctx->cdata);
1179 ctx->cdata = NULL;
1181 ctx->userFunc(ctx, 0);
1184 static void
1185 xml_end_tag(void *userData, const char *name)
1187 struct xml_ctx *ctx = (struct xml_ctx *)userData;
1188 const char *c = strchr(name, ':');
1189 char *ep;
1191 ctx->userFunc(ctx, 1);
1193 if (c == NULL)
1194 c = name;
1195 else
1196 c++;
1198 ep = ctx->name + strlen(ctx->name) - strlen(c) - 1;
1199 *ep = 0;
1202 static void
1203 xml_cdata(void *userData, const XML_Char *s, int len)
1205 struct xml_ctx *ctx = (struct xml_ctx *)userData;
1206 free(ctx->cdata);
1207 ctx->cdata = xmemdupz(s, len);
1210 static struct remote_lock *lock_remote(const char *path, long timeout)
1212 struct active_request_slot *slot;
1213 struct slot_results results;
1214 struct buffer out_buffer = { STRBUF_INIT, 0 };
1215 struct strbuf in_buffer = STRBUF_INIT;
1216 char *url;
1217 char *ep;
1218 char timeout_header[25];
1219 struct remote_lock *lock = NULL;
1220 struct curl_slist *dav_headers = NULL;
1221 struct xml_ctx ctx;
1223 url = xmalloc(strlen(remote->url) + strlen(path) + 1);
1224 sprintf(url, "%s%s", remote->url, path);
1226 /* Make sure leading directories exist for the remote ref */
1227 ep = strchr(url + strlen(remote->url) + 1, '/');
1228 while (ep) {
1229 char saved_character = ep[1];
1230 ep[1] = '\0';
1231 slot = get_active_slot();
1232 slot->results = &results;
1233 curl_easy_setopt(slot->curl, CURLOPT_HTTPGET, 1);
1234 curl_easy_setopt(slot->curl, CURLOPT_URL, url);
1235 curl_easy_setopt(slot->curl, CURLOPT_CUSTOMREQUEST, DAV_MKCOL);
1236 curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION, fwrite_null);
1237 if (start_active_slot(slot)) {
1238 run_active_slot(slot);
1239 if (results.curl_result != CURLE_OK &&
1240 results.http_code != 405) {
1241 fprintf(stderr,
1242 "Unable to create branch path %s\n",
1243 url);
1244 free(url);
1245 return NULL;
1247 } else {
1248 fprintf(stderr, "Unable to start MKCOL request\n");
1249 free(url);
1250 return NULL;
1252 ep[1] = saved_character;
1253 ep = strchr(ep + 1, '/');
1256 strbuf_addf(&out_buffer.buf, LOCK_REQUEST, git_default_email);
1258 sprintf(timeout_header, "Timeout: Second-%ld", timeout);
1259 dav_headers = curl_slist_append(dav_headers, timeout_header);
1260 dav_headers = curl_slist_append(dav_headers, "Content-Type: text/xml");
1262 slot = get_active_slot();
1263 slot->results = &results;
1264 curl_easy_setopt(slot->curl, CURLOPT_INFILE, &out_buffer);
1265 curl_easy_setopt(slot->curl, CURLOPT_INFILESIZE, out_buffer.buf.len);
1266 curl_easy_setopt(slot->curl, CURLOPT_READFUNCTION, fread_buffer);
1267 curl_easy_setopt(slot->curl, CURLOPT_FILE, &in_buffer);
1268 curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION, fwrite_buffer);
1269 curl_easy_setopt(slot->curl, CURLOPT_URL, url);
1270 curl_easy_setopt(slot->curl, CURLOPT_UPLOAD, 1);
1271 curl_easy_setopt(slot->curl, CURLOPT_CUSTOMREQUEST, DAV_LOCK);
1272 curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, dav_headers);
1274 lock = xcalloc(1, sizeof(*lock));
1275 lock->timeout = -1;
1277 if (start_active_slot(slot)) {
1278 run_active_slot(slot);
1279 if (results.curl_result == CURLE_OK) {
1280 XML_Parser parser = XML_ParserCreate(NULL);
1281 enum XML_Status result;
1282 ctx.name = xcalloc(10, 1);
1283 ctx.len = 0;
1284 ctx.cdata = NULL;
1285 ctx.userFunc = handle_new_lock_ctx;
1286 ctx.userData = lock;
1287 XML_SetUserData(parser, &ctx);
1288 XML_SetElementHandler(parser, xml_start_tag,
1289 xml_end_tag);
1290 XML_SetCharacterDataHandler(parser, xml_cdata);
1291 result = XML_Parse(parser, in_buffer.buf,
1292 in_buffer.len, 1);
1293 free(ctx.name);
1294 if (result != XML_STATUS_OK) {
1295 fprintf(stderr, "XML error: %s\n",
1296 XML_ErrorString(
1297 XML_GetErrorCode(parser)));
1298 lock->timeout = -1;
1300 XML_ParserFree(parser);
1302 } else {
1303 fprintf(stderr, "Unable to start LOCK request\n");
1306 curl_slist_free_all(dav_headers);
1307 strbuf_release(&out_buffer.buf);
1308 strbuf_release(&in_buffer);
1310 if (lock->token == NULL || lock->timeout <= 0) {
1311 free(lock->token);
1312 free(lock->owner);
1313 free(url);
1314 free(lock);
1315 lock = NULL;
1316 } else {
1317 lock->url = url;
1318 lock->start_time = time(NULL);
1319 lock->next = remote->locks;
1320 remote->locks = lock;
1323 return lock;
1326 static int unlock_remote(struct remote_lock *lock)
1328 struct active_request_slot *slot;
1329 struct slot_results results;
1330 struct remote_lock *prev = remote->locks;
1331 struct curl_slist *dav_headers;
1332 int rc = 0;
1334 dav_headers = get_dav_token_headers(lock, DAV_HEADER_LOCK);
1336 slot = get_active_slot();
1337 slot->results = &results;
1338 curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION, fwrite_null);
1339 curl_easy_setopt(slot->curl, CURLOPT_URL, lock->url);
1340 curl_easy_setopt(slot->curl, CURLOPT_CUSTOMREQUEST, DAV_UNLOCK);
1341 curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, dav_headers);
1343 if (start_active_slot(slot)) {
1344 run_active_slot(slot);
1345 if (results.curl_result == CURLE_OK)
1346 rc = 1;
1347 else
1348 fprintf(stderr, "UNLOCK HTTP error %ld\n",
1349 results.http_code);
1350 } else {
1351 fprintf(stderr, "Unable to start UNLOCK request\n");
1354 curl_slist_free_all(dav_headers);
1356 if (remote->locks == lock) {
1357 remote->locks = lock->next;
1358 } else {
1359 while (prev && prev->next != lock)
1360 prev = prev->next;
1361 if (prev)
1362 prev->next = prev->next->next;
1365 free(lock->owner);
1366 free(lock->url);
1367 free(lock->token);
1368 free(lock);
1370 return rc;
1373 static void remove_locks(void)
1375 struct remote_lock *lock = remote->locks;
1377 fprintf(stderr, "Removing remote locks...\n");
1378 while (lock) {
1379 unlock_remote(lock);
1380 lock = lock->next;
1384 static void remove_locks_on_signal(int signo)
1386 remove_locks();
1387 signal(signo, SIG_DFL);
1388 raise(signo);
1391 static void remote_ls(const char *path, int flags,
1392 void (*userFunc)(struct remote_ls_ctx *ls),
1393 void *userData);
1395 static void process_ls_object(struct remote_ls_ctx *ls)
1397 unsigned int *parent = (unsigned int *)ls->userData;
1398 char *path = ls->dentry_name;
1399 char *obj_hex;
1401 if (!strcmp(ls->path, ls->dentry_name) && (ls->flags & IS_DIR)) {
1402 remote_dir_exists[*parent] = 1;
1403 return;
1406 if (strlen(path) != 49)
1407 return;
1408 path += 8;
1409 obj_hex = xmalloc(strlen(path));
1410 /* NB: path is not null-terminated, can not use strlcpy here */
1411 memcpy(obj_hex, path, 2);
1412 strcpy(obj_hex + 2, path + 3);
1413 one_remote_object(obj_hex);
1414 free(obj_hex);
1417 static void process_ls_ref(struct remote_ls_ctx *ls)
1419 if (!strcmp(ls->path, ls->dentry_name) && (ls->dentry_flags & IS_DIR)) {
1420 fprintf(stderr, " %s\n", ls->dentry_name);
1421 return;
1424 if (!(ls->dentry_flags & IS_DIR))
1425 one_remote_ref(ls->dentry_name);
1428 static void handle_remote_ls_ctx(struct xml_ctx *ctx, int tag_closed)
1430 struct remote_ls_ctx *ls = (struct remote_ls_ctx *)ctx->userData;
1432 if (tag_closed) {
1433 if (!strcmp(ctx->name, DAV_PROPFIND_RESP) && ls->dentry_name) {
1434 if (ls->dentry_flags & IS_DIR) {
1435 if (ls->flags & PROCESS_DIRS) {
1436 ls->userFunc(ls);
1438 if (strcmp(ls->dentry_name, ls->path) &&
1439 ls->flags & RECURSIVE) {
1440 remote_ls(ls->dentry_name,
1441 ls->flags,
1442 ls->userFunc,
1443 ls->userData);
1445 } else if (ls->flags & PROCESS_FILES) {
1446 ls->userFunc(ls);
1448 } else if (!strcmp(ctx->name, DAV_PROPFIND_NAME) && ctx->cdata) {
1449 char *path = ctx->cdata;
1450 if (*ctx->cdata == 'h') {
1451 path = strstr(path, "//");
1452 if (path) {
1453 path = strchr(path+2, '/');
1456 if (path) {
1457 path += remote->path_len;
1458 ls->dentry_name = xstrdup(path);
1460 } else if (!strcmp(ctx->name, DAV_PROPFIND_COLLECTION)) {
1461 ls->dentry_flags |= IS_DIR;
1463 } else if (!strcmp(ctx->name, DAV_PROPFIND_RESP)) {
1464 free(ls->dentry_name);
1465 ls->dentry_name = NULL;
1466 ls->dentry_flags = 0;
1471 * NEEDSWORK: remote_ls() ignores info/refs on the remote side. But it
1472 * should _only_ heed the information from that file, instead of trying to
1473 * determine the refs from the remote file system (badly: it does not even
1474 * know about packed-refs).
1476 static void remote_ls(const char *path, int flags,
1477 void (*userFunc)(struct remote_ls_ctx *ls),
1478 void *userData)
1480 char *url = xmalloc(strlen(remote->url) + strlen(path) + 1);
1481 struct active_request_slot *slot;
1482 struct slot_results results;
1483 struct strbuf in_buffer = STRBUF_INIT;
1484 struct buffer out_buffer = { STRBUF_INIT, 0 };
1485 struct curl_slist *dav_headers = NULL;
1486 struct xml_ctx ctx;
1487 struct remote_ls_ctx ls;
1489 ls.flags = flags;
1490 ls.path = xstrdup(path);
1491 ls.dentry_name = NULL;
1492 ls.dentry_flags = 0;
1493 ls.userData = userData;
1494 ls.userFunc = userFunc;
1496 sprintf(url, "%s%s", remote->url, path);
1498 strbuf_addf(&out_buffer.buf, PROPFIND_ALL_REQUEST);
1500 dav_headers = curl_slist_append(dav_headers, "Depth: 1");
1501 dav_headers = curl_slist_append(dav_headers, "Content-Type: text/xml");
1503 slot = get_active_slot();
1504 slot->results = &results;
1505 curl_easy_setopt(slot->curl, CURLOPT_INFILE, &out_buffer);
1506 curl_easy_setopt(slot->curl, CURLOPT_INFILESIZE, out_buffer.buf.len);
1507 curl_easy_setopt(slot->curl, CURLOPT_READFUNCTION, fread_buffer);
1508 curl_easy_setopt(slot->curl, CURLOPT_FILE, &in_buffer);
1509 curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION, fwrite_buffer);
1510 curl_easy_setopt(slot->curl, CURLOPT_URL, url);
1511 curl_easy_setopt(slot->curl, CURLOPT_UPLOAD, 1);
1512 curl_easy_setopt(slot->curl, CURLOPT_CUSTOMREQUEST, DAV_PROPFIND);
1513 curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, dav_headers);
1515 if (start_active_slot(slot)) {
1516 run_active_slot(slot);
1517 if (results.curl_result == CURLE_OK) {
1518 XML_Parser parser = XML_ParserCreate(NULL);
1519 enum XML_Status result;
1520 ctx.name = xcalloc(10, 1);
1521 ctx.len = 0;
1522 ctx.cdata = NULL;
1523 ctx.userFunc = handle_remote_ls_ctx;
1524 ctx.userData = &ls;
1525 XML_SetUserData(parser, &ctx);
1526 XML_SetElementHandler(parser, xml_start_tag,
1527 xml_end_tag);
1528 XML_SetCharacterDataHandler(parser, xml_cdata);
1529 result = XML_Parse(parser, in_buffer.buf,
1530 in_buffer.len, 1);
1531 free(ctx.name);
1533 if (result != XML_STATUS_OK) {
1534 fprintf(stderr, "XML error: %s\n",
1535 XML_ErrorString(
1536 XML_GetErrorCode(parser)));
1538 XML_ParserFree(parser);
1540 } else {
1541 fprintf(stderr, "Unable to start PROPFIND request\n");
1544 free(ls.path);
1545 free(url);
1546 strbuf_release(&out_buffer.buf);
1547 strbuf_release(&in_buffer);
1548 curl_slist_free_all(dav_headers);
1551 static void get_remote_object_list(unsigned char parent)
1553 char path[] = "objects/XX/";
1554 static const char hex[] = "0123456789abcdef";
1555 unsigned int val = parent;
1557 path[8] = hex[val >> 4];
1558 path[9] = hex[val & 0xf];
1559 remote_dir_exists[val] = 0;
1560 remote_ls(path, (PROCESS_FILES | PROCESS_DIRS),
1561 process_ls_object, &val);
1564 static int locking_available(void)
1566 struct active_request_slot *slot;
1567 struct slot_results results;
1568 struct strbuf in_buffer = STRBUF_INIT;
1569 struct buffer out_buffer = { STRBUF_INIT, 0 };
1570 struct curl_slist *dav_headers = NULL;
1571 struct xml_ctx ctx;
1572 int lock_flags = 0;
1574 strbuf_addf(&out_buffer.buf, PROPFIND_SUPPORTEDLOCK_REQUEST, remote->url);
1576 dav_headers = curl_slist_append(dav_headers, "Depth: 0");
1577 dav_headers = curl_slist_append(dav_headers, "Content-Type: text/xml");
1579 slot = get_active_slot();
1580 slot->results = &results;
1581 curl_easy_setopt(slot->curl, CURLOPT_INFILE, &out_buffer);
1582 curl_easy_setopt(slot->curl, CURLOPT_INFILESIZE, out_buffer.buf.len);
1583 curl_easy_setopt(slot->curl, CURLOPT_READFUNCTION, fread_buffer);
1584 curl_easy_setopt(slot->curl, CURLOPT_FILE, &in_buffer);
1585 curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION, fwrite_buffer);
1586 curl_easy_setopt(slot->curl, CURLOPT_URL, remote->url);
1587 curl_easy_setopt(slot->curl, CURLOPT_UPLOAD, 1);
1588 curl_easy_setopt(slot->curl, CURLOPT_CUSTOMREQUEST, DAV_PROPFIND);
1589 curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, dav_headers);
1591 if (start_active_slot(slot)) {
1592 run_active_slot(slot);
1593 if (results.curl_result == CURLE_OK) {
1594 XML_Parser parser = XML_ParserCreate(NULL);
1595 enum XML_Status result;
1596 ctx.name = xcalloc(10, 1);
1597 ctx.len = 0;
1598 ctx.cdata = NULL;
1599 ctx.userFunc = handle_lockprop_ctx;
1600 ctx.userData = &lock_flags;
1601 XML_SetUserData(parser, &ctx);
1602 XML_SetElementHandler(parser, xml_start_tag,
1603 xml_end_tag);
1604 result = XML_Parse(parser, in_buffer.buf,
1605 in_buffer.len, 1);
1606 free(ctx.name);
1608 if (result != XML_STATUS_OK) {
1609 fprintf(stderr, "XML error: %s\n",
1610 XML_ErrorString(
1611 XML_GetErrorCode(parser)));
1612 lock_flags = 0;
1614 XML_ParserFree(parser);
1615 if (!lock_flags)
1616 error("Error: no DAV locking support on %s",
1617 remote->url);
1619 } else {
1620 error("Cannot access URL %s, return code %d",
1621 remote->url, results.curl_result);
1622 lock_flags = 0;
1624 } else {
1625 error("Unable to start PROPFIND request on %s", remote->url);
1628 strbuf_release(&out_buffer.buf);
1629 strbuf_release(&in_buffer);
1630 curl_slist_free_all(dav_headers);
1632 return lock_flags;
1635 static struct object_list **add_one_object(struct object *obj, struct object_list **p)
1637 struct object_list *entry = xmalloc(sizeof(struct object_list));
1638 entry->item = obj;
1639 entry->next = *p;
1640 *p = entry;
1641 return &entry->next;
1644 static struct object_list **process_blob(struct blob *blob,
1645 struct object_list **p,
1646 struct name_path *path,
1647 const char *name)
1649 struct object *obj = &blob->object;
1651 obj->flags |= LOCAL;
1653 if (obj->flags & (UNINTERESTING | SEEN))
1654 return p;
1656 obj->flags |= SEEN;
1657 return add_one_object(obj, p);
1660 static struct object_list **process_tree(struct tree *tree,
1661 struct object_list **p,
1662 struct name_path *path,
1663 const char *name)
1665 struct object *obj = &tree->object;
1666 struct tree_desc desc;
1667 struct name_entry entry;
1668 struct name_path me;
1670 obj->flags |= LOCAL;
1672 if (obj->flags & (UNINTERESTING | SEEN))
1673 return p;
1674 if (parse_tree(tree) < 0)
1675 die("bad tree object %s", sha1_to_hex(obj->sha1));
1677 obj->flags |= SEEN;
1678 name = xstrdup(name);
1679 p = add_one_object(obj, p);
1680 me.up = path;
1681 me.elem = name;
1682 me.elem_len = strlen(name);
1684 init_tree_desc(&desc, tree->buffer, tree->size);
1686 while (tree_entry(&desc, &entry))
1687 switch (object_type(entry.mode)) {
1688 case OBJ_TREE:
1689 p = process_tree(lookup_tree(entry.sha1), p, &me, name);
1690 break;
1691 case OBJ_BLOB:
1692 p = process_blob(lookup_blob(entry.sha1), p, &me, name);
1693 break;
1694 default:
1695 /* Subproject commit - not in this repository */
1696 break;
1699 free(tree->buffer);
1700 tree->buffer = NULL;
1701 return p;
1704 static int get_delta(struct rev_info *revs, struct remote_lock *lock)
1706 int i;
1707 struct commit *commit;
1708 struct object_list **p = &objects;
1709 int count = 0;
1711 while ((commit = get_revision(revs)) != NULL) {
1712 p = process_tree(commit->tree, p, NULL, "");
1713 commit->object.flags |= LOCAL;
1714 if (!(commit->object.flags & UNINTERESTING))
1715 count += add_send_request(&commit->object, lock);
1718 for (i = 0; i < revs->pending.nr; i++) {
1719 struct object_array_entry *entry = revs->pending.objects + i;
1720 struct object *obj = entry->item;
1721 const char *name = entry->name;
1723 if (obj->flags & (UNINTERESTING | SEEN))
1724 continue;
1725 if (obj->type == OBJ_TAG) {
1726 obj->flags |= SEEN;
1727 p = add_one_object(obj, p);
1728 continue;
1730 if (obj->type == OBJ_TREE) {
1731 p = process_tree((struct tree *)obj, p, NULL, name);
1732 continue;
1734 if (obj->type == OBJ_BLOB) {
1735 p = process_blob((struct blob *)obj, p, NULL, name);
1736 continue;
1738 die("unknown pending object %s (%s)", sha1_to_hex(obj->sha1), name);
1741 while (objects) {
1742 if (!(objects->item->flags & UNINTERESTING))
1743 count += add_send_request(objects->item, lock);
1744 objects = objects->next;
1747 return count;
1750 static int update_remote(unsigned char *sha1, struct remote_lock *lock)
1752 struct active_request_slot *slot;
1753 struct slot_results results;
1754 struct buffer out_buffer = { STRBUF_INIT, 0 };
1755 struct curl_slist *dav_headers;
1757 dav_headers = get_dav_token_headers(lock, DAV_HEADER_IF);
1759 strbuf_addf(&out_buffer.buf, "%s\n", sha1_to_hex(sha1));
1761 slot = get_active_slot();
1762 slot->results = &results;
1763 curl_easy_setopt(slot->curl, CURLOPT_INFILE, &out_buffer);
1764 curl_easy_setopt(slot->curl, CURLOPT_INFILESIZE, out_buffer.buf.len);
1765 curl_easy_setopt(slot->curl, CURLOPT_READFUNCTION, fread_buffer);
1766 curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION, fwrite_null);
1767 curl_easy_setopt(slot->curl, CURLOPT_CUSTOMREQUEST, DAV_PUT);
1768 curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, dav_headers);
1769 curl_easy_setopt(slot->curl, CURLOPT_UPLOAD, 1);
1770 curl_easy_setopt(slot->curl, CURLOPT_PUT, 1);
1771 curl_easy_setopt(slot->curl, CURLOPT_URL, lock->url);
1773 if (start_active_slot(slot)) {
1774 run_active_slot(slot);
1775 strbuf_release(&out_buffer.buf);
1776 if (results.curl_result != CURLE_OK) {
1777 fprintf(stderr,
1778 "PUT error: curl result=%d, HTTP code=%ld\n",
1779 results.curl_result, results.http_code);
1780 /* We should attempt recovery? */
1781 return 0;
1783 } else {
1784 strbuf_release(&out_buffer.buf);
1785 fprintf(stderr, "Unable to start PUT request\n");
1786 return 0;
1789 return 1;
1792 static struct ref *local_refs, **local_tail;
1793 static struct ref *remote_refs, **remote_tail;
1795 static int one_local_ref(const char *refname, const unsigned char *sha1, int flag, void *cb_data)
1797 struct ref *ref;
1798 int len = strlen(refname) + 1;
1799 ref = xcalloc(1, sizeof(*ref) + len);
1800 hashcpy(ref->new_sha1, sha1);
1801 memcpy(ref->name, refname, len);
1802 *local_tail = ref;
1803 local_tail = &ref->next;
1804 return 0;
1807 static void one_remote_ref(char *refname)
1809 struct ref *ref;
1810 struct object *obj;
1812 ref = alloc_ref(refname);
1814 if (http_fetch_ref(remote->url, ref) != 0) {
1815 fprintf(stderr,
1816 "Unable to fetch ref %s from %s\n",
1817 refname, remote->url);
1818 free(ref);
1819 return;
1823 * Fetch a copy of the object if it doesn't exist locally - it
1824 * may be required for updating server info later.
1826 if (remote->can_update_info_refs && !has_sha1_file(ref->old_sha1)) {
1827 obj = lookup_unknown_object(ref->old_sha1);
1828 if (obj) {
1829 fprintf(stderr, " fetch %s for %s\n",
1830 sha1_to_hex(ref->old_sha1), refname);
1831 add_fetch_request(obj);
1835 *remote_tail = ref;
1836 remote_tail = &ref->next;
1839 static void get_local_heads(void)
1841 local_tail = &local_refs;
1842 for_each_ref(one_local_ref, NULL);
1845 static void get_dav_remote_heads(void)
1847 remote_tail = &remote_refs;
1848 remote_ls("refs/", (PROCESS_FILES | PROCESS_DIRS | RECURSIVE), process_ls_ref, NULL);
1851 static int is_zero_sha1(const unsigned char *sha1)
1853 int i;
1855 for (i = 0; i < 20; i++) {
1856 if (*sha1++)
1857 return 0;
1859 return 1;
1862 static void unmark_and_free(struct commit_list *list, unsigned int mark)
1864 while (list) {
1865 struct commit_list *temp = list;
1866 temp->item->object.flags &= ~mark;
1867 list = temp->next;
1868 free(temp);
1872 static int ref_newer(const unsigned char *new_sha1,
1873 const unsigned char *old_sha1)
1875 struct object *o;
1876 struct commit *old, *new;
1877 struct commit_list *list, *used;
1878 int found = 0;
1880 /* Both new and old must be commit-ish and new is descendant of
1881 * old. Otherwise we require --force.
1883 o = deref_tag(parse_object(old_sha1), NULL, 0);
1884 if (!o || o->type != OBJ_COMMIT)
1885 return 0;
1886 old = (struct commit *) o;
1888 o = deref_tag(parse_object(new_sha1), NULL, 0);
1889 if (!o || o->type != OBJ_COMMIT)
1890 return 0;
1891 new = (struct commit *) o;
1893 if (parse_commit(new) < 0)
1894 return 0;
1896 used = list = NULL;
1897 commit_list_insert(new, &list);
1898 while (list) {
1899 new = pop_most_recent_commit(&list, TMP_MARK);
1900 commit_list_insert(new, &used);
1901 if (new == old) {
1902 found = 1;
1903 break;
1906 unmark_and_free(list, TMP_MARK);
1907 unmark_and_free(used, TMP_MARK);
1908 return found;
1911 static void add_remote_info_ref(struct remote_ls_ctx *ls)
1913 struct strbuf *buf = (struct strbuf *)ls->userData;
1914 struct object *o;
1915 int len;
1916 char *ref_info;
1917 struct ref *ref;
1919 ref = alloc_ref(ls->dentry_name);
1921 if (http_fetch_ref(remote->url, ref) != 0) {
1922 fprintf(stderr,
1923 "Unable to fetch ref %s from %s\n",
1924 ls->dentry_name, remote->url);
1925 aborted = 1;
1926 free(ref);
1927 return;
1930 o = parse_object(ref->old_sha1);
1931 if (!o) {
1932 fprintf(stderr,
1933 "Unable to parse object %s for remote ref %s\n",
1934 sha1_to_hex(ref->old_sha1), ls->dentry_name);
1935 aborted = 1;
1936 free(ref);
1937 return;
1940 len = strlen(ls->dentry_name) + 42;
1941 ref_info = xcalloc(len + 1, 1);
1942 sprintf(ref_info, "%s %s\n",
1943 sha1_to_hex(ref->old_sha1), ls->dentry_name);
1944 fwrite_buffer(ref_info, 1, len, buf);
1945 free(ref_info);
1947 if (o->type == OBJ_TAG) {
1948 o = deref_tag(o, ls->dentry_name, 0);
1949 if (o) {
1950 len = strlen(ls->dentry_name) + 45;
1951 ref_info = xcalloc(len + 1, 1);
1952 sprintf(ref_info, "%s %s^{}\n",
1953 sha1_to_hex(o->sha1), ls->dentry_name);
1954 fwrite_buffer(ref_info, 1, len, buf);
1955 free(ref_info);
1958 free(ref);
1961 static void update_remote_info_refs(struct remote_lock *lock)
1963 struct buffer buffer = { STRBUF_INIT, 0 };
1964 struct active_request_slot *slot;
1965 struct slot_results results;
1966 struct curl_slist *dav_headers;
1968 remote_ls("refs/", (PROCESS_FILES | RECURSIVE),
1969 add_remote_info_ref, &buffer.buf);
1970 if (!aborted) {
1971 dav_headers = get_dav_token_headers(lock, DAV_HEADER_IF);
1973 slot = get_active_slot();
1974 slot->results = &results;
1975 curl_easy_setopt(slot->curl, CURLOPT_INFILE, &buffer);
1976 curl_easy_setopt(slot->curl, CURLOPT_INFILESIZE, buffer.buf.len);
1977 curl_easy_setopt(slot->curl, CURLOPT_READFUNCTION, fread_buffer);
1978 curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION, fwrite_null);
1979 curl_easy_setopt(slot->curl, CURLOPT_CUSTOMREQUEST, DAV_PUT);
1980 curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, dav_headers);
1981 curl_easy_setopt(slot->curl, CURLOPT_UPLOAD, 1);
1982 curl_easy_setopt(slot->curl, CURLOPT_PUT, 1);
1983 curl_easy_setopt(slot->curl, CURLOPT_URL, lock->url);
1985 if (start_active_slot(slot)) {
1986 run_active_slot(slot);
1987 if (results.curl_result != CURLE_OK) {
1988 fprintf(stderr,
1989 "PUT error: curl result=%d, HTTP code=%ld\n",
1990 results.curl_result, results.http_code);
1994 strbuf_release(&buffer.buf);
1997 static int remote_exists(const char *path)
1999 char *url = xmalloc(strlen(remote->url) + strlen(path) + 1);
2000 struct active_request_slot *slot;
2001 struct slot_results results;
2002 int ret = -1;
2004 sprintf(url, "%s%s", remote->url, path);
2006 slot = get_active_slot();
2007 slot->results = &results;
2008 curl_easy_setopt(slot->curl, CURLOPT_URL, url);
2009 curl_easy_setopt(slot->curl, CURLOPT_NOBODY, 1);
2011 if (start_active_slot(slot)) {
2012 run_active_slot(slot);
2013 if (results.http_code == 404)
2014 ret = 0;
2015 else if (results.curl_result == CURLE_OK)
2016 ret = 1;
2017 else
2018 fprintf(stderr, "HEAD HTTP error %ld\n", results.http_code);
2019 } else {
2020 fprintf(stderr, "Unable to start HEAD request\n");
2023 free(url);
2024 return ret;
2027 static void fetch_symref(const char *path, char **symref, unsigned char *sha1)
2029 char *url;
2030 struct strbuf buffer = STRBUF_INIT;
2031 struct active_request_slot *slot;
2032 struct slot_results results;
2034 url = xmalloc(strlen(remote->url) + strlen(path) + 1);
2035 sprintf(url, "%s%s", remote->url, path);
2037 slot = get_active_slot();
2038 slot->results = &results;
2039 curl_easy_setopt(slot->curl, CURLOPT_FILE, &buffer);
2040 curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION, fwrite_buffer);
2041 curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, NULL);
2042 curl_easy_setopt(slot->curl, CURLOPT_URL, url);
2043 if (start_active_slot(slot)) {
2044 run_active_slot(slot);
2045 if (results.curl_result != CURLE_OK) {
2046 die("Couldn't get %s for remote symref\n%s",
2047 url, curl_errorstr);
2049 } else {
2050 die("Unable to start remote symref request");
2052 free(url);
2054 free(*symref);
2055 *symref = NULL;
2056 hashclr(sha1);
2058 if (buffer.len == 0)
2059 return;
2061 /* If it's a symref, set the refname; otherwise try for a sha1 */
2062 if (!prefixcmp((char *)buffer.buf, "ref: ")) {
2063 *symref = xmemdupz((char *)buffer.buf + 5, buffer.len - 6);
2064 } else {
2065 get_sha1_hex(buffer.buf, sha1);
2068 strbuf_release(&buffer);
2071 static int verify_merge_base(unsigned char *head_sha1, unsigned char *branch_sha1)
2073 struct commit *head = lookup_commit(head_sha1);
2074 struct commit *branch = lookup_commit(branch_sha1);
2075 struct commit_list *merge_bases = get_merge_bases(head, branch, 1);
2077 return (merge_bases && !merge_bases->next && merge_bases->item == branch);
2080 static int delete_remote_branch(char *pattern, int force)
2082 struct ref *refs = remote_refs;
2083 struct ref *remote_ref = NULL;
2084 unsigned char head_sha1[20];
2085 char *symref = NULL;
2086 int match;
2087 int patlen = strlen(pattern);
2088 int i;
2089 struct active_request_slot *slot;
2090 struct slot_results results;
2091 char *url;
2093 /* Find the remote branch(es) matching the specified branch name */
2094 for (match = 0; refs; refs = refs->next) {
2095 char *name = refs->name;
2096 int namelen = strlen(name);
2097 if (namelen < patlen ||
2098 memcmp(name + namelen - patlen, pattern, patlen))
2099 continue;
2100 if (namelen != patlen && name[namelen - patlen - 1] != '/')
2101 continue;
2102 match++;
2103 remote_ref = refs;
2105 if (match == 0)
2106 return error("No remote branch matches %s", pattern);
2107 if (match != 1)
2108 return error("More than one remote branch matches %s",
2109 pattern);
2112 * Remote HEAD must be a symref (not exactly foolproof; a remote
2113 * symlink to a symref will look like a symref)
2115 fetch_symref("HEAD", &symref, head_sha1);
2116 if (!symref)
2117 return error("Remote HEAD is not a symref");
2119 /* Remote branch must not be the remote HEAD */
2120 for (i=0; symref && i<MAXDEPTH; i++) {
2121 if (!strcmp(remote_ref->name, symref))
2122 return error("Remote branch %s is the current HEAD",
2123 remote_ref->name);
2124 fetch_symref(symref, &symref, head_sha1);
2127 /* Run extra sanity checks if delete is not forced */
2128 if (!force) {
2129 /* Remote HEAD must resolve to a known object */
2130 if (symref)
2131 return error("Remote HEAD symrefs too deep");
2132 if (is_zero_sha1(head_sha1))
2133 return error("Unable to resolve remote HEAD");
2134 if (!has_sha1_file(head_sha1))
2135 return error("Remote HEAD resolves to object %s\nwhich does not exist locally, perhaps you need to fetch?", sha1_to_hex(head_sha1));
2137 /* Remote branch must resolve to a known object */
2138 if (is_zero_sha1(remote_ref->old_sha1))
2139 return error("Unable to resolve remote branch %s",
2140 remote_ref->name);
2141 if (!has_sha1_file(remote_ref->old_sha1))
2142 return error("Remote branch %s resolves to object %s\nwhich does not exist locally, perhaps you need to fetch?", remote_ref->name, sha1_to_hex(remote_ref->old_sha1));
2144 /* Remote branch must be an ancestor of remote HEAD */
2145 if (!verify_merge_base(head_sha1, remote_ref->old_sha1)) {
2146 return error("The branch '%s' is not an ancestor "
2147 "of your current HEAD.\n"
2148 "If you are sure you want to delete it,"
2149 " run:\n\t'git http-push -D %s %s'",
2150 remote_ref->name, remote->url, pattern);
2154 /* Send delete request */
2155 fprintf(stderr, "Removing remote branch '%s'\n", remote_ref->name);
2156 if (dry_run)
2157 return 0;
2158 url = xmalloc(strlen(remote->url) + strlen(remote_ref->name) + 1);
2159 sprintf(url, "%s%s", remote->url, remote_ref->name);
2160 slot = get_active_slot();
2161 slot->results = &results;
2162 curl_easy_setopt(slot->curl, CURLOPT_HTTPGET, 1);
2163 curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION, fwrite_null);
2164 curl_easy_setopt(slot->curl, CURLOPT_URL, url);
2165 curl_easy_setopt(slot->curl, CURLOPT_CUSTOMREQUEST, DAV_DELETE);
2166 if (start_active_slot(slot)) {
2167 run_active_slot(slot);
2168 free(url);
2169 if (results.curl_result != CURLE_OK)
2170 return error("DELETE request failed (%d/%ld)\n",
2171 results.curl_result, results.http_code);
2172 } else {
2173 free(url);
2174 return error("Unable to start DELETE request");
2177 return 0;
2180 int main(int argc, char **argv)
2182 struct transfer_request *request;
2183 struct transfer_request *next_request;
2184 int nr_refspec = 0;
2185 char **refspec = NULL;
2186 struct remote_lock *ref_lock = NULL;
2187 struct remote_lock *info_ref_lock = NULL;
2188 struct rev_info revs;
2189 int delete_branch = 0;
2190 int force_delete = 0;
2191 int objects_to_send;
2192 int rc = 0;
2193 int i;
2194 int new_refs;
2195 struct ref *ref;
2196 char *rewritten_url = NULL;
2198 setup_git_directory();
2200 remote = xcalloc(sizeof(*remote), 1);
2202 argv++;
2203 for (i = 1; i < argc; i++, argv++) {
2204 char *arg = *argv;
2206 if (*arg == '-') {
2207 if (!strcmp(arg, "--all")) {
2208 push_all = MATCH_REFS_ALL;
2209 continue;
2211 if (!strcmp(arg, "--force")) {
2212 force_all = 1;
2213 continue;
2215 if (!strcmp(arg, "--dry-run")) {
2216 dry_run = 1;
2217 continue;
2219 if (!strcmp(arg, "--verbose")) {
2220 push_verbosely = 1;
2221 continue;
2223 if (!strcmp(arg, "-d")) {
2224 delete_branch = 1;
2225 continue;
2227 if (!strcmp(arg, "-D")) {
2228 delete_branch = 1;
2229 force_delete = 1;
2230 continue;
2233 if (!remote->url) {
2234 char *path = strstr(arg, "//");
2235 remote->url = arg;
2236 remote->path_len = strlen(arg);
2237 if (path) {
2238 remote->path = strchr(path+2, '/');
2239 if (remote->path)
2240 remote->path_len = strlen(remote->path);
2242 continue;
2244 refspec = argv;
2245 nr_refspec = argc - i;
2246 break;
2249 #ifndef USE_CURL_MULTI
2250 die("git-push is not available for http/https repository when not compiled with USE_CURL_MULTI");
2251 #endif
2253 if (!remote->url)
2254 usage(http_push_usage);
2256 if (delete_branch && nr_refspec != 1)
2257 die("You must specify only one branch name when deleting a remote branch");
2259 memset(remote_dir_exists, -1, 256);
2261 http_init(NULL);
2263 no_pragma_header = curl_slist_append(no_pragma_header, "Pragma:");
2265 if (remote->url && remote->url[strlen(remote->url)-1] != '/') {
2266 rewritten_url = xmalloc(strlen(remote->url)+2);
2267 strcpy(rewritten_url, remote->url);
2268 strcat(rewritten_url, "/");
2269 remote->path = rewritten_url + (remote->path - remote->url);
2270 remote->path_len++;
2271 remote->url = rewritten_url;
2274 /* Verify DAV compliance/lock support */
2275 if (!locking_available()) {
2276 rc = 1;
2277 goto cleanup;
2280 signal(SIGINT, remove_locks_on_signal);
2281 signal(SIGHUP, remove_locks_on_signal);
2282 signal(SIGQUIT, remove_locks_on_signal);
2283 signal(SIGTERM, remove_locks_on_signal);
2285 /* Check whether the remote has server info files */
2286 remote->can_update_info_refs = 0;
2287 remote->has_info_refs = remote_exists("info/refs");
2288 remote->has_info_packs = remote_exists("objects/info/packs");
2289 if (remote->has_info_refs) {
2290 info_ref_lock = lock_remote("info/refs", LOCK_TIME);
2291 if (info_ref_lock)
2292 remote->can_update_info_refs = 1;
2293 else {
2294 fprintf(stderr, "Error: cannot lock existing info/refs\n");
2295 rc = 1;
2296 goto cleanup;
2299 if (remote->has_info_packs)
2300 fetch_indices();
2302 /* Get a list of all local and remote heads to validate refspecs */
2303 get_local_heads();
2304 fprintf(stderr, "Fetching remote heads...\n");
2305 get_dav_remote_heads();
2307 /* Remove a remote branch if -d or -D was specified */
2308 if (delete_branch) {
2309 if (delete_remote_branch(refspec[0], force_delete) == -1)
2310 fprintf(stderr, "Unable to delete remote branch %s\n",
2311 refspec[0]);
2312 goto cleanup;
2315 /* match them up */
2316 if (!remote_tail)
2317 remote_tail = &remote_refs;
2318 if (match_refs(local_refs, remote_refs, &remote_tail,
2319 nr_refspec, (const char **) refspec, push_all)) {
2320 rc = -1;
2321 goto cleanup;
2323 if (!remote_refs) {
2324 fprintf(stderr, "No refs in common and none specified; doing nothing.\n");
2325 rc = 0;
2326 goto cleanup;
2329 new_refs = 0;
2330 for (ref = remote_refs; ref; ref = ref->next) {
2331 char old_hex[60], *new_hex;
2332 const char *commit_argv[4];
2333 int commit_argc;
2334 char *new_sha1_hex, *old_sha1_hex;
2336 if (!ref->peer_ref)
2337 continue;
2339 if (is_zero_sha1(ref->peer_ref->new_sha1)) {
2340 if (delete_remote_branch(ref->name, 1) == -1) {
2341 error("Could not remove %s", ref->name);
2342 rc = -4;
2344 new_refs++;
2345 continue;
2348 if (!hashcmp(ref->old_sha1, ref->peer_ref->new_sha1)) {
2349 if (push_verbosely || 1)
2350 fprintf(stderr, "'%s': up-to-date\n", ref->name);
2351 continue;
2354 if (!force_all &&
2355 !is_zero_sha1(ref->old_sha1) &&
2356 !ref->force) {
2357 if (!has_sha1_file(ref->old_sha1) ||
2358 !ref_newer(ref->peer_ref->new_sha1,
2359 ref->old_sha1)) {
2361 * We do not have the remote ref, or
2362 * we know that the remote ref is not
2363 * an ancestor of what we are trying to
2364 * push. Either way this can be losing
2365 * commits at the remote end and likely
2366 * we were not up to date to begin with.
2368 error("remote '%s' is not an ancestor of\n"
2369 "local '%s'.\n"
2370 "Maybe you are not up-to-date and "
2371 "need to pull first?",
2372 ref->name,
2373 ref->peer_ref->name);
2374 rc = -2;
2375 continue;
2378 hashcpy(ref->new_sha1, ref->peer_ref->new_sha1);
2379 new_refs++;
2380 strcpy(old_hex, sha1_to_hex(ref->old_sha1));
2381 new_hex = sha1_to_hex(ref->new_sha1);
2383 fprintf(stderr, "updating '%s'", ref->name);
2384 if (strcmp(ref->name, ref->peer_ref->name))
2385 fprintf(stderr, " using '%s'", ref->peer_ref->name);
2386 fprintf(stderr, "\n from %s\n to %s\n", old_hex, new_hex);
2387 if (dry_run)
2388 continue;
2390 /* Lock remote branch ref */
2391 ref_lock = lock_remote(ref->name, LOCK_TIME);
2392 if (ref_lock == NULL) {
2393 fprintf(stderr, "Unable to lock remote branch %s\n",
2394 ref->name);
2395 rc = 1;
2396 continue;
2399 /* Set up revision info for this refspec */
2400 commit_argc = 3;
2401 new_sha1_hex = xstrdup(sha1_to_hex(ref->new_sha1));
2402 old_sha1_hex = NULL;
2403 commit_argv[1] = "--objects";
2404 commit_argv[2] = new_sha1_hex;
2405 if (!push_all && !is_zero_sha1(ref->old_sha1)) {
2406 old_sha1_hex = xmalloc(42);
2407 sprintf(old_sha1_hex, "^%s",
2408 sha1_to_hex(ref->old_sha1));
2409 commit_argv[3] = old_sha1_hex;
2410 commit_argc++;
2412 init_revisions(&revs, setup_git_directory());
2413 setup_revisions(commit_argc, commit_argv, &revs, NULL);
2414 revs.edge_hint = 0; /* just in case */
2415 free(new_sha1_hex);
2416 if (old_sha1_hex) {
2417 free(old_sha1_hex);
2418 commit_argv[1] = NULL;
2421 /* Generate a list of objects that need to be pushed */
2422 pushing = 0;
2423 if (prepare_revision_walk(&revs))
2424 die("revision walk setup failed");
2425 mark_edges_uninteresting(revs.commits, &revs, NULL);
2426 objects_to_send = get_delta(&revs, ref_lock);
2427 finish_all_active_slots();
2429 /* Push missing objects to remote, this would be a
2430 convenient time to pack them first if appropriate. */
2431 pushing = 1;
2432 if (objects_to_send)
2433 fprintf(stderr, " sending %d objects\n",
2434 objects_to_send);
2435 #ifdef USE_CURL_MULTI
2436 fill_active_slots();
2437 add_fill_function(NULL, fill_active_slot);
2438 #endif
2439 do {
2440 finish_all_active_slots();
2441 #ifdef USE_CURL_MULTI
2442 fill_active_slots();
2443 #endif
2444 } while (request_queue_head && !aborted);
2446 /* Update the remote branch if all went well */
2447 if (aborted || !update_remote(ref->new_sha1, ref_lock))
2448 rc = 1;
2450 if (!rc)
2451 fprintf(stderr, " done\n");
2452 unlock_remote(ref_lock);
2453 check_locks();
2456 /* Update remote server info if appropriate */
2457 if (remote->has_info_refs && new_refs) {
2458 if (info_ref_lock && remote->can_update_info_refs) {
2459 fprintf(stderr, "Updating remote server info\n");
2460 if (!dry_run)
2461 update_remote_info_refs(info_ref_lock);
2462 } else {
2463 fprintf(stderr, "Unable to update server info\n");
2467 cleanup:
2468 free(rewritten_url);
2469 if (info_ref_lock)
2470 unlock_remote(info_ref_lock);
2471 free(remote);
2473 curl_slist_free_all(no_pragma_header);
2475 http_cleanup();
2477 request = request_queue_head;
2478 while (request != NULL) {
2479 next_request = request->next;
2480 release_request(request);
2481 request = next_request;
2484 return rc;