Merge branch 'wp/add-patch-find'
[git/dscho.git] / http-push.c
blob18d81acd1b3743761b23ded035dc58e32b6aad80
1 #include "cache.h"
2 #include "commit.h"
3 #include "pack.h"
4 #include "tag.h"
5 #include "blob.h"
6 #include "http.h"
7 #include "refs.h"
8 #include "diff.h"
9 #include "revision.h"
10 #include "exec_cmd.h"
11 #include "remote.h"
12 #include "list-objects.h"
13 #include "sigchain.h"
15 #include <expat.h>
17 static const char http_push_usage[] =
18 "git http-push [--all] [--dry-run] [--force] [--verbose] <remote> [<head>...]\n";
20 #ifndef XML_STATUS_OK
21 enum XML_Status {
22 XML_STATUS_OK = 1,
23 XML_STATUS_ERROR = 0
25 #define XML_STATUS_OK 1
26 #define XML_STATUS_ERROR 0
27 #endif
29 #define PREV_BUF_SIZE 4096
30 #define RANGE_HEADER_SIZE 30
32 /* DAV methods */
33 #define DAV_LOCK "LOCK"
34 #define DAV_MKCOL "MKCOL"
35 #define DAV_MOVE "MOVE"
36 #define DAV_PROPFIND "PROPFIND"
37 #define DAV_PUT "PUT"
38 #define DAV_UNLOCK "UNLOCK"
39 #define DAV_DELETE "DELETE"
41 /* DAV lock flags */
42 #define DAV_PROP_LOCKWR (1u << 0)
43 #define DAV_PROP_LOCKEX (1u << 1)
44 #define DAV_LOCK_OK (1u << 2)
46 /* DAV XML properties */
47 #define DAV_CTX_LOCKENTRY ".multistatus.response.propstat.prop.supportedlock.lockentry"
48 #define DAV_CTX_LOCKTYPE_WRITE ".multistatus.response.propstat.prop.supportedlock.lockentry.locktype.write"
49 #define DAV_CTX_LOCKTYPE_EXCLUSIVE ".multistatus.response.propstat.prop.supportedlock.lockentry.lockscope.exclusive"
50 #define DAV_ACTIVELOCK_OWNER ".prop.lockdiscovery.activelock.owner.href"
51 #define DAV_ACTIVELOCK_TIMEOUT ".prop.lockdiscovery.activelock.timeout"
52 #define DAV_ACTIVELOCK_TOKEN ".prop.lockdiscovery.activelock.locktoken.href"
53 #define DAV_PROPFIND_RESP ".multistatus.response"
54 #define DAV_PROPFIND_NAME ".multistatus.response.href"
55 #define DAV_PROPFIND_COLLECTION ".multistatus.response.propstat.prop.resourcetype.collection"
57 /* DAV request body templates */
58 #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>"
59 #define PROPFIND_ALL_REQUEST "<?xml version=\"1.0\" encoding=\"utf-8\" ?>\n<D:propfind xmlns:D=\"DAV:\">\n<D:allprop/>\n</D:propfind>"
60 #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>"
62 #define LOCK_TIME 600
63 #define LOCK_REFRESH 30
65 /* bits #0-15 in revision.h */
67 #define LOCAL (1u<<16)
68 #define REMOTE (1u<<17)
69 #define FETCHING (1u<<18)
70 #define PUSHING (1u<<19)
72 /* We allow "recursive" symbolic refs. Only within reason, though */
73 #define MAXDEPTH 5
75 static int pushing;
76 static int aborted;
77 static signed char remote_dir_exists[256];
79 static struct curl_slist *no_pragma_header;
81 static int push_verbosely;
82 static int push_all = MATCH_REFS_NONE;
83 static int force_all;
84 static int dry_run;
86 static struct object_list *objects;
88 struct repo
90 char *url;
91 char *path;
92 int path_len;
93 int has_info_refs;
94 int can_update_info_refs;
95 int has_info_packs;
96 struct packed_git *packs;
97 struct remote_lock *locks;
100 static struct repo *remote;
102 enum transfer_state {
103 NEED_FETCH,
104 RUN_FETCH_LOOSE,
105 RUN_FETCH_PACKED,
106 NEED_PUSH,
107 RUN_MKCOL,
108 RUN_PUT,
109 RUN_MOVE,
110 ABORTED,
111 COMPLETE,
114 struct transfer_request
116 struct object *obj;
117 char *url;
118 char *dest;
119 struct remote_lock *lock;
120 struct curl_slist *headers;
121 struct buffer buffer;
122 char filename[PATH_MAX];
123 char tmpfile[PATH_MAX];
124 int local_fileno;
125 FILE *local_stream;
126 enum transfer_state state;
127 CURLcode curl_result;
128 char errorstr[CURL_ERROR_SIZE];
129 long http_code;
130 unsigned char real_sha1[20];
131 git_SHA_CTX c;
132 z_stream stream;
133 int zret;
134 int rename;
135 void *userData;
136 struct active_request_slot *slot;
137 struct transfer_request *next;
140 static struct transfer_request *request_queue_head;
142 struct xml_ctx
144 char *name;
145 int len;
146 char *cdata;
147 void (*userFunc)(struct xml_ctx *ctx, int tag_closed);
148 void *userData;
151 struct remote_lock
153 char *url;
154 char *owner;
155 char *token;
156 time_t start_time;
157 long timeout;
158 int refreshing;
159 struct remote_lock *next;
162 /* Flags that control remote_ls processing */
163 #define PROCESS_FILES (1u << 0)
164 #define PROCESS_DIRS (1u << 1)
165 #define RECURSIVE (1u << 2)
167 /* Flags that remote_ls passes to callback functions */
168 #define IS_DIR (1u << 0)
170 struct remote_ls_ctx
172 char *path;
173 void (*userFunc)(struct remote_ls_ctx *ls);
174 void *userData;
175 int flags;
176 char *dentry_name;
177 int dentry_flags;
178 struct remote_ls_ctx *parent;
181 /* get_dav_token_headers options */
182 enum dav_header_flag {
183 DAV_HEADER_IF = (1u << 0),
184 DAV_HEADER_LOCK = (1u << 1),
185 DAV_HEADER_TIMEOUT = (1u << 2)
188 static struct curl_slist *get_dav_token_headers(struct remote_lock *lock, enum dav_header_flag options)
190 struct strbuf buf = STRBUF_INIT;
191 struct curl_slist *dav_headers = NULL;
193 if (options & DAV_HEADER_IF) {
194 strbuf_addf(&buf, "If: (<%s>)", lock->token);
195 dav_headers = curl_slist_append(dav_headers, buf.buf);
196 strbuf_reset(&buf);
198 if (options & DAV_HEADER_LOCK) {
199 strbuf_addf(&buf, "Lock-Token: <%s>", lock->token);
200 dav_headers = curl_slist_append(dav_headers, buf.buf);
201 strbuf_reset(&buf);
203 if (options & DAV_HEADER_TIMEOUT) {
204 strbuf_addf(&buf, "Timeout: Second-%ld", lock->timeout);
205 dav_headers = curl_slist_append(dav_headers, buf.buf);
206 strbuf_reset(&buf);
208 strbuf_release(&buf);
210 return dav_headers;
213 static void finish_request(struct transfer_request *request);
214 static void release_request(struct transfer_request *request);
216 static void process_response(void *callback_data)
218 struct transfer_request *request =
219 (struct transfer_request *)callback_data;
221 finish_request(request);
224 #ifdef USE_CURL_MULTI
225 static size_t fwrite_sha1_file(void *ptr, size_t eltsize, size_t nmemb,
226 void *data)
228 unsigned char expn[4096];
229 size_t size = eltsize * nmemb;
230 int posn = 0;
231 struct transfer_request *request = (struct transfer_request *)data;
232 do {
233 ssize_t retval = xwrite(request->local_fileno,
234 (char *) ptr + posn, size - posn);
235 if (retval < 0)
236 return posn;
237 posn += retval;
238 } while (posn < size);
240 request->stream.avail_in = size;
241 request->stream.next_in = ptr;
242 do {
243 request->stream.next_out = expn;
244 request->stream.avail_out = sizeof(expn);
245 request->zret = git_inflate(&request->stream, Z_SYNC_FLUSH);
246 git_SHA1_Update(&request->c, expn,
247 sizeof(expn) - request->stream.avail_out);
248 } while (request->stream.avail_in && request->zret == Z_OK);
249 data_received++;
250 return size;
253 static void start_fetch_loose(struct transfer_request *request)
255 char *hex = sha1_to_hex(request->obj->sha1);
256 char *filename;
257 char prevfile[PATH_MAX];
258 char *url;
259 char *posn;
260 int prevlocal;
261 unsigned char prev_buf[PREV_BUF_SIZE];
262 ssize_t prev_read = 0;
263 long prev_posn = 0;
264 char range[RANGE_HEADER_SIZE];
265 struct curl_slist *range_header = NULL;
266 struct active_request_slot *slot;
268 filename = sha1_file_name(request->obj->sha1);
269 snprintf(request->filename, sizeof(request->filename), "%s", filename);
270 snprintf(request->tmpfile, sizeof(request->tmpfile),
271 "%s.temp", filename);
273 snprintf(prevfile, sizeof(prevfile), "%s.prev", request->filename);
274 unlink(prevfile);
275 rename(request->tmpfile, prevfile);
276 unlink(request->tmpfile);
278 if (request->local_fileno != -1)
279 error("fd leakage in start: %d", request->local_fileno);
280 request->local_fileno = open(request->tmpfile,
281 O_WRONLY | O_CREAT | O_EXCL, 0666);
282 /* This could have failed due to the "lazy directory creation";
283 * try to mkdir the last path component.
285 if (request->local_fileno < 0 && errno == ENOENT) {
286 char *dir = strrchr(request->tmpfile, '/');
287 if (dir) {
288 *dir = 0;
289 mkdir(request->tmpfile, 0777);
290 *dir = '/';
292 request->local_fileno = open(request->tmpfile,
293 O_WRONLY | O_CREAT | O_EXCL, 0666);
296 if (request->local_fileno < 0) {
297 request->state = ABORTED;
298 error("Couldn't create temporary file %s for %s: %s",
299 request->tmpfile, request->filename, strerror(errno));
300 return;
303 memset(&request->stream, 0, sizeof(request->stream));
305 git_inflate_init(&request->stream);
307 git_SHA1_Init(&request->c);
309 url = xmalloc(strlen(remote->url) + 50);
310 request->url = xmalloc(strlen(remote->url) + 50);
311 strcpy(url, remote->url);
312 posn = url + strlen(remote->url);
313 strcpy(posn, "objects/");
314 posn += 8;
315 memcpy(posn, hex, 2);
316 posn += 2;
317 *(posn++) = '/';
318 strcpy(posn, hex + 2);
319 strcpy(request->url, url);
321 /* If a previous temp file is present, process what was already
322 fetched. */
323 prevlocal = open(prevfile, O_RDONLY);
324 if (prevlocal != -1) {
325 do {
326 prev_read = xread(prevlocal, prev_buf, PREV_BUF_SIZE);
327 if (prev_read>0) {
328 if (fwrite_sha1_file(prev_buf,
330 prev_read,
331 request) == prev_read) {
332 prev_posn += prev_read;
333 } else {
334 prev_read = -1;
337 } while (prev_read > 0);
338 close(prevlocal);
340 unlink(prevfile);
342 /* Reset inflate/SHA1 if there was an error reading the previous temp
343 file; also rewind to the beginning of the local file. */
344 if (prev_read == -1) {
345 memset(&request->stream, 0, sizeof(request->stream));
346 git_inflate_init(&request->stream);
347 git_SHA1_Init(&request->c);
348 if (prev_posn>0) {
349 prev_posn = 0;
350 lseek(request->local_fileno, 0, SEEK_SET);
351 ftruncate(request->local_fileno, 0);
355 slot = get_active_slot();
356 slot->callback_func = process_response;
357 slot->callback_data = request;
358 request->slot = slot;
360 curl_easy_setopt(slot->curl, CURLOPT_FILE, request);
361 curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION, fwrite_sha1_file);
362 curl_easy_setopt(slot->curl, CURLOPT_ERRORBUFFER, request->errorstr);
363 curl_easy_setopt(slot->curl, CURLOPT_URL, url);
364 curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, no_pragma_header);
366 /* If we have successfully processed data from a previous fetch
367 attempt, only fetch the data we don't already have. */
368 if (prev_posn>0) {
369 if (push_verbosely)
370 fprintf(stderr,
371 "Resuming fetch of object %s at byte %ld\n",
372 hex, prev_posn);
373 sprintf(range, "Range: bytes=%ld-", prev_posn);
374 range_header = curl_slist_append(range_header, range);
375 curl_easy_setopt(slot->curl,
376 CURLOPT_HTTPHEADER, range_header);
379 /* Try to get the request started, abort the request on error */
380 request->state = RUN_FETCH_LOOSE;
381 if (!start_active_slot(slot)) {
382 fprintf(stderr, "Unable to start GET request\n");
383 remote->can_update_info_refs = 0;
384 release_request(request);
388 static void start_mkcol(struct transfer_request *request)
390 char *hex = sha1_to_hex(request->obj->sha1);
391 struct active_request_slot *slot;
392 char *posn;
394 request->url = xmalloc(strlen(remote->url) + 13);
395 strcpy(request->url, remote->url);
396 posn = request->url + strlen(remote->url);
397 strcpy(posn, "objects/");
398 posn += 8;
399 memcpy(posn, hex, 2);
400 posn += 2;
401 strcpy(posn, "/");
403 slot = get_active_slot();
404 slot->callback_func = process_response;
405 slot->callback_data = request;
406 curl_easy_setopt(slot->curl, CURLOPT_HTTPGET, 1); /* undo PUT setup */
407 curl_easy_setopt(slot->curl, CURLOPT_URL, request->url);
408 curl_easy_setopt(slot->curl, CURLOPT_ERRORBUFFER, request->errorstr);
409 curl_easy_setopt(slot->curl, CURLOPT_CUSTOMREQUEST, DAV_MKCOL);
410 curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION, fwrite_null);
412 if (start_active_slot(slot)) {
413 request->slot = slot;
414 request->state = RUN_MKCOL;
415 } else {
416 request->state = ABORTED;
417 free(request->url);
418 request->url = NULL;
421 #endif
423 static void start_fetch_packed(struct transfer_request *request)
425 char *url;
426 struct packed_git *target;
427 FILE *packfile;
428 char *filename;
429 long prev_posn = 0;
430 char range[RANGE_HEADER_SIZE];
431 struct curl_slist *range_header = NULL;
433 struct transfer_request *check_request = request_queue_head;
434 struct active_request_slot *slot;
436 target = find_sha1_pack(request->obj->sha1, remote->packs);
437 if (!target) {
438 fprintf(stderr, "Unable to fetch %s, will not be able to update server info refs\n", sha1_to_hex(request->obj->sha1));
439 remote->can_update_info_refs = 0;
440 release_request(request);
441 return;
444 fprintf(stderr, "Fetching pack %s\n", sha1_to_hex(target->sha1));
445 fprintf(stderr, " which contains %s\n", sha1_to_hex(request->obj->sha1));
447 filename = sha1_pack_name(target->sha1);
448 snprintf(request->filename, sizeof(request->filename), "%s", filename);
449 snprintf(request->tmpfile, sizeof(request->tmpfile),
450 "%s.temp", filename);
452 url = xmalloc(strlen(remote->url) + 64);
453 sprintf(url, "%sobjects/pack/pack-%s.pack",
454 remote->url, sha1_to_hex(target->sha1));
456 /* Make sure there isn't another open request for this pack */
457 while (check_request) {
458 if (check_request->state == RUN_FETCH_PACKED &&
459 !strcmp(check_request->url, url)) {
460 free(url);
461 release_request(request);
462 return;
464 check_request = check_request->next;
467 packfile = fopen(request->tmpfile, "a");
468 if (!packfile) {
469 fprintf(stderr, "Unable to open local file %s for pack",
470 request->tmpfile);
471 remote->can_update_info_refs = 0;
472 free(url);
473 return;
476 slot = get_active_slot();
477 slot->callback_func = process_response;
478 slot->callback_data = request;
479 request->slot = slot;
480 request->local_stream = packfile;
481 request->userData = target;
483 request->url = url;
484 curl_easy_setopt(slot->curl, CURLOPT_FILE, packfile);
485 curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION, fwrite);
486 curl_easy_setopt(slot->curl, CURLOPT_URL, url);
487 curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, no_pragma_header);
488 slot->local = packfile;
490 /* If there is data present from a previous transfer attempt,
491 resume where it left off */
492 prev_posn = ftell(packfile);
493 if (prev_posn>0) {
494 if (push_verbosely)
495 fprintf(stderr,
496 "Resuming fetch of pack %s at byte %ld\n",
497 sha1_to_hex(target->sha1), prev_posn);
498 sprintf(range, "Range: bytes=%ld-", prev_posn);
499 range_header = curl_slist_append(range_header, range);
500 curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, range_header);
503 /* Try to get the request started, abort the request on error */
504 request->state = RUN_FETCH_PACKED;
505 if (!start_active_slot(slot)) {
506 fprintf(stderr, "Unable to start GET request\n");
507 remote->can_update_info_refs = 0;
508 release_request(request);
512 static void start_put(struct transfer_request *request)
514 char *hex = sha1_to_hex(request->obj->sha1);
515 struct active_request_slot *slot;
516 char *posn;
517 enum object_type type;
518 char hdr[50];
519 void *unpacked;
520 unsigned long len;
521 int hdrlen;
522 ssize_t size;
523 z_stream stream;
525 unpacked = read_sha1_file(request->obj->sha1, &type, &len);
526 hdrlen = sprintf(hdr, "%s %lu", typename(type), len) + 1;
528 /* Set it up */
529 memset(&stream, 0, sizeof(stream));
530 deflateInit(&stream, zlib_compression_level);
531 size = deflateBound(&stream, len + hdrlen);
532 strbuf_init(&request->buffer.buf, size);
533 request->buffer.posn = 0;
535 /* Compress it */
536 stream.next_out = (unsigned char *)request->buffer.buf.buf;
537 stream.avail_out = size;
539 /* First header.. */
540 stream.next_in = (void *)hdr;
541 stream.avail_in = hdrlen;
542 while (deflate(&stream, 0) == Z_OK)
543 /* nothing */;
545 /* Then the data itself.. */
546 stream.next_in = unpacked;
547 stream.avail_in = len;
548 while (deflate(&stream, Z_FINISH) == Z_OK)
549 /* nothing */;
550 deflateEnd(&stream);
551 free(unpacked);
553 request->buffer.buf.len = stream.total_out;
555 request->url = xmalloc(strlen(remote->url) +
556 strlen(request->lock->token) + 51);
557 strcpy(request->url, remote->url);
558 posn = request->url + strlen(remote->url);
559 strcpy(posn, "objects/");
560 posn += 8;
561 memcpy(posn, hex, 2);
562 posn += 2;
563 *(posn++) = '/';
564 strcpy(posn, hex + 2);
565 request->dest = xmalloc(strlen(request->url) + 14);
566 sprintf(request->dest, "Destination: %s", request->url);
567 posn += 38;
568 *(posn++) = '_';
569 strcpy(posn, request->lock->token);
571 slot = get_active_slot();
572 slot->callback_func = process_response;
573 slot->callback_data = request;
574 curl_easy_setopt(slot->curl, CURLOPT_INFILE, &request->buffer);
575 curl_easy_setopt(slot->curl, CURLOPT_INFILESIZE, request->buffer.buf.len);
576 curl_easy_setopt(slot->curl, CURLOPT_READFUNCTION, fread_buffer);
577 curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION, fwrite_null);
578 curl_easy_setopt(slot->curl, CURLOPT_CUSTOMREQUEST, DAV_PUT);
579 curl_easy_setopt(slot->curl, CURLOPT_UPLOAD, 1);
580 curl_easy_setopt(slot->curl, CURLOPT_PUT, 1);
581 curl_easy_setopt(slot->curl, CURLOPT_NOBODY, 0);
582 curl_easy_setopt(slot->curl, CURLOPT_URL, request->url);
584 if (start_active_slot(slot)) {
585 request->slot = slot;
586 request->state = RUN_PUT;
587 } else {
588 request->state = ABORTED;
589 free(request->url);
590 request->url = NULL;
594 static void start_move(struct transfer_request *request)
596 struct active_request_slot *slot;
597 struct curl_slist *dav_headers = NULL;
599 slot = get_active_slot();
600 slot->callback_func = process_response;
601 slot->callback_data = request;
602 curl_easy_setopt(slot->curl, CURLOPT_HTTPGET, 1); /* undo PUT setup */
603 curl_easy_setopt(slot->curl, CURLOPT_CUSTOMREQUEST, DAV_MOVE);
604 dav_headers = curl_slist_append(dav_headers, request->dest);
605 dav_headers = curl_slist_append(dav_headers, "Overwrite: T");
606 curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, dav_headers);
607 curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION, fwrite_null);
608 curl_easy_setopt(slot->curl, CURLOPT_URL, request->url);
610 if (start_active_slot(slot)) {
611 request->slot = slot;
612 request->state = RUN_MOVE;
613 } else {
614 request->state = ABORTED;
615 free(request->url);
616 request->url = NULL;
620 static int refresh_lock(struct remote_lock *lock)
622 struct active_request_slot *slot;
623 struct slot_results results;
624 struct curl_slist *dav_headers;
625 int rc = 0;
627 lock->refreshing = 1;
629 dav_headers = get_dav_token_headers(lock, DAV_HEADER_IF | DAV_HEADER_TIMEOUT);
631 slot = get_active_slot();
632 slot->results = &results;
633 curl_easy_setopt(slot->curl, CURLOPT_HTTPGET, 1);
634 curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION, fwrite_null);
635 curl_easy_setopt(slot->curl, CURLOPT_URL, lock->url);
636 curl_easy_setopt(slot->curl, CURLOPT_CUSTOMREQUEST, DAV_LOCK);
637 curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, dav_headers);
639 if (start_active_slot(slot)) {
640 run_active_slot(slot);
641 if (results.curl_result != CURLE_OK) {
642 fprintf(stderr, "LOCK HTTP error %ld\n",
643 results.http_code);
644 } else {
645 lock->start_time = time(NULL);
646 rc = 1;
650 lock->refreshing = 0;
651 curl_slist_free_all(dav_headers);
653 return rc;
656 static void check_locks(void)
658 struct remote_lock *lock = remote->locks;
659 time_t current_time = time(NULL);
660 int time_remaining;
662 while (lock) {
663 time_remaining = lock->start_time + lock->timeout -
664 current_time;
665 if (!lock->refreshing && time_remaining < LOCK_REFRESH) {
666 if (!refresh_lock(lock)) {
667 fprintf(stderr,
668 "Unable to refresh lock for %s\n",
669 lock->url);
670 aborted = 1;
671 return;
674 lock = lock->next;
678 static void release_request(struct transfer_request *request)
680 struct transfer_request *entry = request_queue_head;
682 if (request == request_queue_head) {
683 request_queue_head = request->next;
684 } else {
685 while (entry->next != NULL && entry->next != request)
686 entry = entry->next;
687 if (entry->next == request)
688 entry->next = entry->next->next;
691 if (request->local_fileno != -1)
692 close(request->local_fileno);
693 if (request->local_stream)
694 fclose(request->local_stream);
695 free(request->url);
696 free(request);
699 static void finish_request(struct transfer_request *request)
701 struct stat st;
702 struct packed_git *target;
703 struct packed_git **lst;
705 request->curl_result = request->slot->curl_result;
706 request->http_code = request->slot->http_code;
707 request->slot = NULL;
709 /* Keep locks active */
710 check_locks();
712 if (request->headers != NULL)
713 curl_slist_free_all(request->headers);
715 /* URL is reused for MOVE after PUT */
716 if (request->state != RUN_PUT) {
717 free(request->url);
718 request->url = NULL;
721 if (request->state == RUN_MKCOL) {
722 if (request->curl_result == CURLE_OK ||
723 request->http_code == 405) {
724 remote_dir_exists[request->obj->sha1[0]] = 1;
725 start_put(request);
726 } else {
727 fprintf(stderr, "MKCOL %s failed, aborting (%d/%ld)\n",
728 sha1_to_hex(request->obj->sha1),
729 request->curl_result, request->http_code);
730 request->state = ABORTED;
731 aborted = 1;
733 } else if (request->state == RUN_PUT) {
734 if (request->curl_result == CURLE_OK) {
735 start_move(request);
736 } else {
737 fprintf(stderr, "PUT %s failed, aborting (%d/%ld)\n",
738 sha1_to_hex(request->obj->sha1),
739 request->curl_result, request->http_code);
740 request->state = ABORTED;
741 aborted = 1;
743 } else if (request->state == RUN_MOVE) {
744 if (request->curl_result == CURLE_OK) {
745 if (push_verbosely)
746 fprintf(stderr, " sent %s\n",
747 sha1_to_hex(request->obj->sha1));
748 request->obj->flags |= REMOTE;
749 release_request(request);
750 } else {
751 fprintf(stderr, "MOVE %s failed, aborting (%d/%ld)\n",
752 sha1_to_hex(request->obj->sha1),
753 request->curl_result, request->http_code);
754 request->state = ABORTED;
755 aborted = 1;
757 } else if (request->state == RUN_FETCH_LOOSE) {
758 fchmod(request->local_fileno, 0444);
759 close(request->local_fileno); request->local_fileno = -1;
761 if (request->curl_result != CURLE_OK &&
762 request->http_code != 416) {
763 if (stat(request->tmpfile, &st) == 0) {
764 if (st.st_size == 0)
765 unlink(request->tmpfile);
767 } else {
768 if (request->http_code == 416)
769 fprintf(stderr, "Warning: requested range invalid; we may already have all the data.\n");
771 git_inflate_end(&request->stream);
772 git_SHA1_Final(request->real_sha1, &request->c);
773 if (request->zret != Z_STREAM_END) {
774 unlink(request->tmpfile);
775 } else if (hashcmp(request->obj->sha1, request->real_sha1)) {
776 unlink(request->tmpfile);
777 } else {
778 request->rename =
779 move_temp_to_file(
780 request->tmpfile,
781 request->filename);
782 if (request->rename == 0) {
783 request->obj->flags |= (LOCAL | REMOTE);
788 /* Try fetching packed if necessary */
789 if (request->obj->flags & LOCAL)
790 release_request(request);
791 else
792 start_fetch_packed(request);
794 } else if (request->state == RUN_FETCH_PACKED) {
795 if (request->curl_result != CURLE_OK) {
796 fprintf(stderr, "Unable to get pack file %s\n%s",
797 request->url, curl_errorstr);
798 remote->can_update_info_refs = 0;
799 } else {
800 off_t pack_size = ftell(request->local_stream);
802 fclose(request->local_stream);
803 request->local_stream = NULL;
804 if (!move_temp_to_file(request->tmpfile,
805 request->filename)) {
806 target = (struct packed_git *)request->userData;
807 target->pack_size = pack_size;
808 lst = &remote->packs;
809 while (*lst != target)
810 lst = &((*lst)->next);
811 *lst = (*lst)->next;
813 if (!verify_pack(target))
814 install_packed_git(target);
815 else
816 remote->can_update_info_refs = 0;
819 release_request(request);
823 #ifdef USE_CURL_MULTI
824 static int fill_active_slot(void *unused)
826 struct transfer_request *request = request_queue_head;
828 if (aborted)
829 return 0;
831 for (request = request_queue_head; request; request = request->next) {
832 if (request->state == NEED_FETCH) {
833 start_fetch_loose(request);
834 return 1;
835 } else if (pushing && request->state == NEED_PUSH) {
836 if (remote_dir_exists[request->obj->sha1[0]] == 1) {
837 start_put(request);
838 } else {
839 start_mkcol(request);
841 return 1;
844 return 0;
846 #endif
848 static void get_remote_object_list(unsigned char parent);
850 static void add_fetch_request(struct object *obj)
852 struct transfer_request *request;
854 check_locks();
857 * Don't fetch the object if it's known to exist locally
858 * or is already in the request queue
860 if (remote_dir_exists[obj->sha1[0]] == -1)
861 get_remote_object_list(obj->sha1[0]);
862 if (obj->flags & (LOCAL | FETCHING))
863 return;
865 obj->flags |= FETCHING;
866 request = xmalloc(sizeof(*request));
867 request->obj = obj;
868 request->url = NULL;
869 request->lock = NULL;
870 request->headers = NULL;
871 request->local_fileno = -1;
872 request->local_stream = NULL;
873 request->state = NEED_FETCH;
874 request->next = request_queue_head;
875 request_queue_head = request;
877 #ifdef USE_CURL_MULTI
878 fill_active_slots();
879 step_active_slots();
880 #endif
883 static int add_send_request(struct object *obj, struct remote_lock *lock)
885 struct transfer_request *request = request_queue_head;
886 struct packed_git *target;
888 /* Keep locks active */
889 check_locks();
892 * Don't push the object if it's known to exist on the remote
893 * or is already in the request queue
895 if (remote_dir_exists[obj->sha1[0]] == -1)
896 get_remote_object_list(obj->sha1[0]);
897 if (obj->flags & (REMOTE | PUSHING))
898 return 0;
899 target = find_sha1_pack(obj->sha1, remote->packs);
900 if (target) {
901 obj->flags |= REMOTE;
902 return 0;
905 obj->flags |= PUSHING;
906 request = xmalloc(sizeof(*request));
907 request->obj = obj;
908 request->url = NULL;
909 request->lock = lock;
910 request->headers = NULL;
911 request->local_fileno = -1;
912 request->local_stream = NULL;
913 request->state = NEED_PUSH;
914 request->next = request_queue_head;
915 request_queue_head = request;
917 #ifdef USE_CURL_MULTI
918 fill_active_slots();
919 step_active_slots();
920 #endif
922 return 1;
925 static int fetch_index(unsigned char *sha1)
927 char *hex = sha1_to_hex(sha1);
928 char *filename;
929 char *url;
930 char tmpfile[PATH_MAX];
931 long prev_posn = 0;
932 char range[RANGE_HEADER_SIZE];
933 struct curl_slist *range_header = NULL;
935 FILE *indexfile;
936 struct active_request_slot *slot;
937 struct slot_results results;
939 /* Don't use the index if the pack isn't there */
940 url = xmalloc(strlen(remote->url) + 64);
941 sprintf(url, "%sobjects/pack/pack-%s.pack", remote->url, hex);
942 slot = get_active_slot();
943 slot->results = &results;
944 curl_easy_setopt(slot->curl, CURLOPT_URL, url);
945 curl_easy_setopt(slot->curl, CURLOPT_NOBODY, 1);
946 if (start_active_slot(slot)) {
947 run_active_slot(slot);
948 if (results.curl_result != CURLE_OK) {
949 free(url);
950 return error("Unable to verify pack %s is available",
951 hex);
953 } else {
954 free(url);
955 return error("Unable to start request");
958 if (has_pack_index(sha1)) {
959 free(url);
960 return 0;
963 if (push_verbosely)
964 fprintf(stderr, "Getting index for pack %s\n", hex);
966 sprintf(url, "%sobjects/pack/pack-%s.idx", remote->url, hex);
968 filename = sha1_pack_index_name(sha1);
969 snprintf(tmpfile, sizeof(tmpfile), "%s.temp", filename);
970 indexfile = fopen(tmpfile, "a");
971 if (!indexfile) {
972 free(url);
973 return error("Unable to open local file %s for pack index",
974 tmpfile);
977 slot = get_active_slot();
978 slot->results = &results;
979 curl_easy_setopt(slot->curl, CURLOPT_NOBODY, 0);
980 curl_easy_setopt(slot->curl, CURLOPT_HTTPGET, 1);
981 curl_easy_setopt(slot->curl, CURLOPT_FILE, indexfile);
982 curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION, fwrite);
983 curl_easy_setopt(slot->curl, CURLOPT_URL, url);
984 curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, no_pragma_header);
985 slot->local = indexfile;
987 /* If there is data present from a previous transfer attempt,
988 resume where it left off */
989 prev_posn = ftell(indexfile);
990 if (prev_posn>0) {
991 if (push_verbosely)
992 fprintf(stderr,
993 "Resuming fetch of index for pack %s at byte %ld\n",
994 hex, prev_posn);
995 sprintf(range, "Range: bytes=%ld-", prev_posn);
996 range_header = curl_slist_append(range_header, range);
997 curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, range_header);
1000 if (start_active_slot(slot)) {
1001 run_active_slot(slot);
1002 if (results.curl_result != CURLE_OK) {
1003 free(url);
1004 fclose(indexfile);
1005 return error("Unable to get pack index %s\n%s", url,
1006 curl_errorstr);
1008 } else {
1009 free(url);
1010 fclose(indexfile);
1011 return error("Unable to start request");
1014 free(url);
1015 fclose(indexfile);
1017 return move_temp_to_file(tmpfile, filename);
1020 static int setup_index(unsigned char *sha1)
1022 struct packed_git *new_pack;
1024 if (fetch_index(sha1))
1025 return -1;
1027 new_pack = parse_pack_index(sha1);
1028 new_pack->next = remote->packs;
1029 remote->packs = new_pack;
1030 return 0;
1033 static int fetch_indices(void)
1035 unsigned char sha1[20];
1036 char *url;
1037 struct strbuf buffer = STRBUF_INIT;
1038 char *data;
1039 int i = 0;
1041 struct active_request_slot *slot;
1042 struct slot_results results;
1044 if (push_verbosely)
1045 fprintf(stderr, "Getting pack list\n");
1047 url = xmalloc(strlen(remote->url) + 20);
1048 sprintf(url, "%sobjects/info/packs", remote->url);
1050 slot = get_active_slot();
1051 slot->results = &results;
1052 curl_easy_setopt(slot->curl, CURLOPT_FILE, &buffer);
1053 curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION, fwrite_buffer);
1054 curl_easy_setopt(slot->curl, CURLOPT_URL, url);
1055 curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, NULL);
1056 if (start_active_slot(slot)) {
1057 run_active_slot(slot);
1058 if (results.curl_result != CURLE_OK) {
1059 strbuf_release(&buffer);
1060 free(url);
1061 if (results.http_code == 404)
1062 return 0;
1063 else
1064 return error("%s", curl_errorstr);
1066 } else {
1067 strbuf_release(&buffer);
1068 free(url);
1069 return error("Unable to start request");
1071 free(url);
1073 data = buffer.buf;
1074 while (i < buffer.len) {
1075 switch (data[i]) {
1076 case 'P':
1077 i++;
1078 if (i + 52 < buffer.len &&
1079 !prefixcmp(data + i, " pack-") &&
1080 !prefixcmp(data + i + 46, ".pack\n")) {
1081 get_sha1_hex(data + i + 6, sha1);
1082 setup_index(sha1);
1083 i += 51;
1084 break;
1086 default:
1087 while (data[i] != '\n')
1088 i++;
1090 i++;
1093 strbuf_release(&buffer);
1094 return 0;
1097 static void one_remote_object(const char *hex)
1099 unsigned char sha1[20];
1100 struct object *obj;
1102 if (get_sha1_hex(hex, sha1) != 0)
1103 return;
1105 obj = lookup_object(sha1);
1106 if (!obj)
1107 obj = parse_object(sha1);
1109 /* Ignore remote objects that don't exist locally */
1110 if (!obj)
1111 return;
1113 obj->flags |= REMOTE;
1114 if (!object_list_contains(objects, obj))
1115 object_list_insert(obj, &objects);
1118 static void handle_lockprop_ctx(struct xml_ctx *ctx, int tag_closed)
1120 int *lock_flags = (int *)ctx->userData;
1122 if (tag_closed) {
1123 if (!strcmp(ctx->name, DAV_CTX_LOCKENTRY)) {
1124 if ((*lock_flags & DAV_PROP_LOCKEX) &&
1125 (*lock_flags & DAV_PROP_LOCKWR)) {
1126 *lock_flags |= DAV_LOCK_OK;
1128 *lock_flags &= DAV_LOCK_OK;
1129 } else if (!strcmp(ctx->name, DAV_CTX_LOCKTYPE_WRITE)) {
1130 *lock_flags |= DAV_PROP_LOCKWR;
1131 } else if (!strcmp(ctx->name, DAV_CTX_LOCKTYPE_EXCLUSIVE)) {
1132 *lock_flags |= DAV_PROP_LOCKEX;
1137 static void handle_new_lock_ctx(struct xml_ctx *ctx, int tag_closed)
1139 struct remote_lock *lock = (struct remote_lock *)ctx->userData;
1141 if (tag_closed && ctx->cdata) {
1142 if (!strcmp(ctx->name, DAV_ACTIVELOCK_OWNER)) {
1143 lock->owner = xmalloc(strlen(ctx->cdata) + 1);
1144 strcpy(lock->owner, ctx->cdata);
1145 } else if (!strcmp(ctx->name, DAV_ACTIVELOCK_TIMEOUT)) {
1146 if (!prefixcmp(ctx->cdata, "Second-"))
1147 lock->timeout =
1148 strtol(ctx->cdata + 7, NULL, 10);
1149 } else if (!strcmp(ctx->name, DAV_ACTIVELOCK_TOKEN)) {
1150 lock->token = xmalloc(strlen(ctx->cdata) + 1);
1151 strcpy(lock->token, ctx->cdata);
1156 static void one_remote_ref(char *refname);
1158 static void
1159 xml_start_tag(void *userData, const char *name, const char **atts)
1161 struct xml_ctx *ctx = (struct xml_ctx *)userData;
1162 const char *c = strchr(name, ':');
1163 int new_len;
1165 if (c == NULL)
1166 c = name;
1167 else
1168 c++;
1170 new_len = strlen(ctx->name) + strlen(c) + 2;
1172 if (new_len > ctx->len) {
1173 ctx->name = xrealloc(ctx->name, new_len);
1174 ctx->len = new_len;
1176 strcat(ctx->name, ".");
1177 strcat(ctx->name, c);
1179 free(ctx->cdata);
1180 ctx->cdata = NULL;
1182 ctx->userFunc(ctx, 0);
1185 static void
1186 xml_end_tag(void *userData, const char *name)
1188 struct xml_ctx *ctx = (struct xml_ctx *)userData;
1189 const char *c = strchr(name, ':');
1190 char *ep;
1192 ctx->userFunc(ctx, 1);
1194 if (c == NULL)
1195 c = name;
1196 else
1197 c++;
1199 ep = ctx->name + strlen(ctx->name) - strlen(c) - 1;
1200 *ep = 0;
1203 static void
1204 xml_cdata(void *userData, const XML_Char *s, int len)
1206 struct xml_ctx *ctx = (struct xml_ctx *)userData;
1207 free(ctx->cdata);
1208 ctx->cdata = xmemdupz(s, len);
1211 static struct remote_lock *lock_remote(const char *path, long timeout)
1213 struct active_request_slot *slot;
1214 struct slot_results results;
1215 struct buffer out_buffer = { STRBUF_INIT, 0 };
1216 struct strbuf in_buffer = STRBUF_INIT;
1217 char *url;
1218 char *ep;
1219 char timeout_header[25];
1220 struct remote_lock *lock = NULL;
1221 struct curl_slist *dav_headers = NULL;
1222 struct xml_ctx ctx;
1224 url = xmalloc(strlen(remote->url) + strlen(path) + 1);
1225 sprintf(url, "%s%s", remote->url, path);
1227 /* Make sure leading directories exist for the remote ref */
1228 ep = strchr(url + strlen(remote->url) + 1, '/');
1229 while (ep) {
1230 char saved_character = ep[1];
1231 ep[1] = '\0';
1232 slot = get_active_slot();
1233 slot->results = &results;
1234 curl_easy_setopt(slot->curl, CURLOPT_HTTPGET, 1);
1235 curl_easy_setopt(slot->curl, CURLOPT_URL, url);
1236 curl_easy_setopt(slot->curl, CURLOPT_CUSTOMREQUEST, DAV_MKCOL);
1237 curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION, fwrite_null);
1238 if (start_active_slot(slot)) {
1239 run_active_slot(slot);
1240 if (results.curl_result != CURLE_OK &&
1241 results.http_code != 405) {
1242 fprintf(stderr,
1243 "Unable to create branch path %s\n",
1244 url);
1245 free(url);
1246 return NULL;
1248 } else {
1249 fprintf(stderr, "Unable to start MKCOL request\n");
1250 free(url);
1251 return NULL;
1253 ep[1] = saved_character;
1254 ep = strchr(ep + 1, '/');
1257 strbuf_addf(&out_buffer.buf, LOCK_REQUEST, git_default_email);
1259 sprintf(timeout_header, "Timeout: Second-%ld", timeout);
1260 dav_headers = curl_slist_append(dav_headers, timeout_header);
1261 dav_headers = curl_slist_append(dav_headers, "Content-Type: text/xml");
1263 slot = get_active_slot();
1264 slot->results = &results;
1265 curl_easy_setopt(slot->curl, CURLOPT_INFILE, &out_buffer);
1266 curl_easy_setopt(slot->curl, CURLOPT_INFILESIZE, out_buffer.buf.len);
1267 curl_easy_setopt(slot->curl, CURLOPT_READFUNCTION, fread_buffer);
1268 curl_easy_setopt(slot->curl, CURLOPT_FILE, &in_buffer);
1269 curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION, fwrite_buffer);
1270 curl_easy_setopt(slot->curl, CURLOPT_URL, url);
1271 curl_easy_setopt(slot->curl, CURLOPT_UPLOAD, 1);
1272 curl_easy_setopt(slot->curl, CURLOPT_CUSTOMREQUEST, DAV_LOCK);
1273 curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, dav_headers);
1275 lock = xcalloc(1, sizeof(*lock));
1276 lock->timeout = -1;
1278 if (start_active_slot(slot)) {
1279 run_active_slot(slot);
1280 if (results.curl_result == CURLE_OK) {
1281 XML_Parser parser = XML_ParserCreate(NULL);
1282 enum XML_Status result;
1283 ctx.name = xcalloc(10, 1);
1284 ctx.len = 0;
1285 ctx.cdata = NULL;
1286 ctx.userFunc = handle_new_lock_ctx;
1287 ctx.userData = lock;
1288 XML_SetUserData(parser, &ctx);
1289 XML_SetElementHandler(parser, xml_start_tag,
1290 xml_end_tag);
1291 XML_SetCharacterDataHandler(parser, xml_cdata);
1292 result = XML_Parse(parser, in_buffer.buf,
1293 in_buffer.len, 1);
1294 free(ctx.name);
1295 if (result != XML_STATUS_OK) {
1296 fprintf(stderr, "XML error: %s\n",
1297 XML_ErrorString(
1298 XML_GetErrorCode(parser)));
1299 lock->timeout = -1;
1301 XML_ParserFree(parser);
1303 } else {
1304 fprintf(stderr, "Unable to start LOCK request\n");
1307 curl_slist_free_all(dav_headers);
1308 strbuf_release(&out_buffer.buf);
1309 strbuf_release(&in_buffer);
1311 if (lock->token == NULL || lock->timeout <= 0) {
1312 free(lock->token);
1313 free(lock->owner);
1314 free(url);
1315 free(lock);
1316 lock = NULL;
1317 } else {
1318 lock->url = url;
1319 lock->start_time = time(NULL);
1320 lock->next = remote->locks;
1321 remote->locks = lock;
1324 return lock;
1327 static int unlock_remote(struct remote_lock *lock)
1329 struct active_request_slot *slot;
1330 struct slot_results results;
1331 struct remote_lock *prev = remote->locks;
1332 struct curl_slist *dav_headers;
1333 int rc = 0;
1335 dav_headers = get_dav_token_headers(lock, DAV_HEADER_LOCK);
1337 slot = get_active_slot();
1338 slot->results = &results;
1339 curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION, fwrite_null);
1340 curl_easy_setopt(slot->curl, CURLOPT_URL, lock->url);
1341 curl_easy_setopt(slot->curl, CURLOPT_CUSTOMREQUEST, DAV_UNLOCK);
1342 curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, dav_headers);
1344 if (start_active_slot(slot)) {
1345 run_active_slot(slot);
1346 if (results.curl_result == CURLE_OK)
1347 rc = 1;
1348 else
1349 fprintf(stderr, "UNLOCK HTTP error %ld\n",
1350 results.http_code);
1351 } else {
1352 fprintf(stderr, "Unable to start UNLOCK request\n");
1355 curl_slist_free_all(dav_headers);
1357 if (remote->locks == lock) {
1358 remote->locks = lock->next;
1359 } else {
1360 while (prev && prev->next != lock)
1361 prev = prev->next;
1362 if (prev)
1363 prev->next = prev->next->next;
1366 free(lock->owner);
1367 free(lock->url);
1368 free(lock->token);
1369 free(lock);
1371 return rc;
1374 static void remove_locks(void)
1376 struct remote_lock *lock = remote->locks;
1378 fprintf(stderr, "Removing remote locks...\n");
1379 while (lock) {
1380 unlock_remote(lock);
1381 lock = lock->next;
1385 static void remove_locks_on_signal(int signo)
1387 remove_locks();
1388 sigchain_pop(signo);
1389 raise(signo);
1392 static void remote_ls(const char *path, int flags,
1393 void (*userFunc)(struct remote_ls_ctx *ls),
1394 void *userData);
1396 static void process_ls_object(struct remote_ls_ctx *ls)
1398 unsigned int *parent = (unsigned int *)ls->userData;
1399 char *path = ls->dentry_name;
1400 char *obj_hex;
1402 if (!strcmp(ls->path, ls->dentry_name) && (ls->flags & IS_DIR)) {
1403 remote_dir_exists[*parent] = 1;
1404 return;
1407 if (strlen(path) != 49)
1408 return;
1409 path += 8;
1410 obj_hex = xmalloc(strlen(path));
1411 /* NB: path is not null-terminated, can not use strlcpy here */
1412 memcpy(obj_hex, path, 2);
1413 strcpy(obj_hex + 2, path + 3);
1414 one_remote_object(obj_hex);
1415 free(obj_hex);
1418 static void process_ls_ref(struct remote_ls_ctx *ls)
1420 if (!strcmp(ls->path, ls->dentry_name) && (ls->dentry_flags & IS_DIR)) {
1421 fprintf(stderr, " %s\n", ls->dentry_name);
1422 return;
1425 if (!(ls->dentry_flags & IS_DIR))
1426 one_remote_ref(ls->dentry_name);
1429 static void handle_remote_ls_ctx(struct xml_ctx *ctx, int tag_closed)
1431 struct remote_ls_ctx *ls = (struct remote_ls_ctx *)ctx->userData;
1433 if (tag_closed) {
1434 if (!strcmp(ctx->name, DAV_PROPFIND_RESP) && ls->dentry_name) {
1435 if (ls->dentry_flags & IS_DIR) {
1436 if (ls->flags & PROCESS_DIRS) {
1437 ls->userFunc(ls);
1439 if (strcmp(ls->dentry_name, ls->path) &&
1440 ls->flags & RECURSIVE) {
1441 remote_ls(ls->dentry_name,
1442 ls->flags,
1443 ls->userFunc,
1444 ls->userData);
1446 } else if (ls->flags & PROCESS_FILES) {
1447 ls->userFunc(ls);
1449 } else if (!strcmp(ctx->name, DAV_PROPFIND_NAME) && ctx->cdata) {
1450 char *path = ctx->cdata;
1451 if (*ctx->cdata == 'h') {
1452 path = strstr(path, "//");
1453 if (path) {
1454 path = strchr(path+2, '/');
1457 if (path) {
1458 path += remote->path_len;
1459 ls->dentry_name = xstrdup(path);
1461 } else if (!strcmp(ctx->name, DAV_PROPFIND_COLLECTION)) {
1462 ls->dentry_flags |= IS_DIR;
1464 } else if (!strcmp(ctx->name, DAV_PROPFIND_RESP)) {
1465 free(ls->dentry_name);
1466 ls->dentry_name = NULL;
1467 ls->dentry_flags = 0;
1472 * NEEDSWORK: remote_ls() ignores info/refs on the remote side. But it
1473 * should _only_ heed the information from that file, instead of trying to
1474 * determine the refs from the remote file system (badly: it does not even
1475 * know about packed-refs).
1477 static void remote_ls(const char *path, int flags,
1478 void (*userFunc)(struct remote_ls_ctx *ls),
1479 void *userData)
1481 char *url = xmalloc(strlen(remote->url) + strlen(path) + 1);
1482 struct active_request_slot *slot;
1483 struct slot_results results;
1484 struct strbuf in_buffer = STRBUF_INIT;
1485 struct buffer out_buffer = { STRBUF_INIT, 0 };
1486 struct curl_slist *dav_headers = NULL;
1487 struct xml_ctx ctx;
1488 struct remote_ls_ctx ls;
1490 ls.flags = flags;
1491 ls.path = xstrdup(path);
1492 ls.dentry_name = NULL;
1493 ls.dentry_flags = 0;
1494 ls.userData = userData;
1495 ls.userFunc = userFunc;
1497 sprintf(url, "%s%s", remote->url, path);
1499 strbuf_addf(&out_buffer.buf, PROPFIND_ALL_REQUEST);
1501 dav_headers = curl_slist_append(dav_headers, "Depth: 1");
1502 dav_headers = curl_slist_append(dav_headers, "Content-Type: text/xml");
1504 slot = get_active_slot();
1505 slot->results = &results;
1506 curl_easy_setopt(slot->curl, CURLOPT_INFILE, &out_buffer);
1507 curl_easy_setopt(slot->curl, CURLOPT_INFILESIZE, out_buffer.buf.len);
1508 curl_easy_setopt(slot->curl, CURLOPT_READFUNCTION, fread_buffer);
1509 curl_easy_setopt(slot->curl, CURLOPT_FILE, &in_buffer);
1510 curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION, fwrite_buffer);
1511 curl_easy_setopt(slot->curl, CURLOPT_URL, url);
1512 curl_easy_setopt(slot->curl, CURLOPT_UPLOAD, 1);
1513 curl_easy_setopt(slot->curl, CURLOPT_CUSTOMREQUEST, DAV_PROPFIND);
1514 curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, dav_headers);
1516 if (start_active_slot(slot)) {
1517 run_active_slot(slot);
1518 if (results.curl_result == CURLE_OK) {
1519 XML_Parser parser = XML_ParserCreate(NULL);
1520 enum XML_Status result;
1521 ctx.name = xcalloc(10, 1);
1522 ctx.len = 0;
1523 ctx.cdata = NULL;
1524 ctx.userFunc = handle_remote_ls_ctx;
1525 ctx.userData = &ls;
1526 XML_SetUserData(parser, &ctx);
1527 XML_SetElementHandler(parser, xml_start_tag,
1528 xml_end_tag);
1529 XML_SetCharacterDataHandler(parser, xml_cdata);
1530 result = XML_Parse(parser, in_buffer.buf,
1531 in_buffer.len, 1);
1532 free(ctx.name);
1534 if (result != XML_STATUS_OK) {
1535 fprintf(stderr, "XML error: %s\n",
1536 XML_ErrorString(
1537 XML_GetErrorCode(parser)));
1539 XML_ParserFree(parser);
1541 } else {
1542 fprintf(stderr, "Unable to start PROPFIND request\n");
1545 free(ls.path);
1546 free(url);
1547 strbuf_release(&out_buffer.buf);
1548 strbuf_release(&in_buffer);
1549 curl_slist_free_all(dav_headers);
1552 static void get_remote_object_list(unsigned char parent)
1554 char path[] = "objects/XX/";
1555 static const char hex[] = "0123456789abcdef";
1556 unsigned int val = parent;
1558 path[8] = hex[val >> 4];
1559 path[9] = hex[val & 0xf];
1560 remote_dir_exists[val] = 0;
1561 remote_ls(path, (PROCESS_FILES | PROCESS_DIRS),
1562 process_ls_object, &val);
1565 static int locking_available(void)
1567 struct active_request_slot *slot;
1568 struct slot_results results;
1569 struct strbuf in_buffer = STRBUF_INIT;
1570 struct buffer out_buffer = { STRBUF_INIT, 0 };
1571 struct curl_slist *dav_headers = NULL;
1572 struct xml_ctx ctx;
1573 int lock_flags = 0;
1575 strbuf_addf(&out_buffer.buf, PROPFIND_SUPPORTEDLOCK_REQUEST, remote->url);
1577 dav_headers = curl_slist_append(dav_headers, "Depth: 0");
1578 dav_headers = curl_slist_append(dav_headers, "Content-Type: text/xml");
1580 slot = get_active_slot();
1581 slot->results = &results;
1582 curl_easy_setopt(slot->curl, CURLOPT_INFILE, &out_buffer);
1583 curl_easy_setopt(slot->curl, CURLOPT_INFILESIZE, out_buffer.buf.len);
1584 curl_easy_setopt(slot->curl, CURLOPT_READFUNCTION, fread_buffer);
1585 curl_easy_setopt(slot->curl, CURLOPT_FILE, &in_buffer);
1586 curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION, fwrite_buffer);
1587 curl_easy_setopt(slot->curl, CURLOPT_URL, remote->url);
1588 curl_easy_setopt(slot->curl, CURLOPT_UPLOAD, 1);
1589 curl_easy_setopt(slot->curl, CURLOPT_CUSTOMREQUEST, DAV_PROPFIND);
1590 curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, dav_headers);
1592 if (start_active_slot(slot)) {
1593 run_active_slot(slot);
1594 if (results.curl_result == CURLE_OK) {
1595 XML_Parser parser = XML_ParserCreate(NULL);
1596 enum XML_Status result;
1597 ctx.name = xcalloc(10, 1);
1598 ctx.len = 0;
1599 ctx.cdata = NULL;
1600 ctx.userFunc = handle_lockprop_ctx;
1601 ctx.userData = &lock_flags;
1602 XML_SetUserData(parser, &ctx);
1603 XML_SetElementHandler(parser, xml_start_tag,
1604 xml_end_tag);
1605 result = XML_Parse(parser, in_buffer.buf,
1606 in_buffer.len, 1);
1607 free(ctx.name);
1609 if (result != XML_STATUS_OK) {
1610 fprintf(stderr, "XML error: %s\n",
1611 XML_ErrorString(
1612 XML_GetErrorCode(parser)));
1613 lock_flags = 0;
1615 XML_ParserFree(parser);
1616 if (!lock_flags)
1617 error("Error: no DAV locking support on %s",
1618 remote->url);
1620 } else {
1621 error("Cannot access URL %s, return code %d",
1622 remote->url, results.curl_result);
1623 lock_flags = 0;
1625 } else {
1626 error("Unable to start PROPFIND request on %s", remote->url);
1629 strbuf_release(&out_buffer.buf);
1630 strbuf_release(&in_buffer);
1631 curl_slist_free_all(dav_headers);
1633 return lock_flags;
1636 static struct object_list **add_one_object(struct object *obj, struct object_list **p)
1638 struct object_list *entry = xmalloc(sizeof(struct object_list));
1639 entry->item = obj;
1640 entry->next = *p;
1641 *p = entry;
1642 return &entry->next;
1645 static struct object_list **process_blob(struct blob *blob,
1646 struct object_list **p,
1647 struct name_path *path,
1648 const char *name)
1650 struct object *obj = &blob->object;
1652 obj->flags |= LOCAL;
1654 if (obj->flags & (UNINTERESTING | SEEN))
1655 return p;
1657 obj->flags |= SEEN;
1658 return add_one_object(obj, p);
1661 static struct object_list **process_tree(struct tree *tree,
1662 struct object_list **p,
1663 struct name_path *path,
1664 const char *name)
1666 struct object *obj = &tree->object;
1667 struct tree_desc desc;
1668 struct name_entry entry;
1669 struct name_path me;
1671 obj->flags |= LOCAL;
1673 if (obj->flags & (UNINTERESTING | SEEN))
1674 return p;
1675 if (parse_tree(tree) < 0)
1676 die("bad tree object %s", sha1_to_hex(obj->sha1));
1678 obj->flags |= SEEN;
1679 name = xstrdup(name);
1680 p = add_one_object(obj, p);
1681 me.up = path;
1682 me.elem = name;
1683 me.elem_len = strlen(name);
1685 init_tree_desc(&desc, tree->buffer, tree->size);
1687 while (tree_entry(&desc, &entry))
1688 switch (object_type(entry.mode)) {
1689 case OBJ_TREE:
1690 p = process_tree(lookup_tree(entry.sha1), p, &me, name);
1691 break;
1692 case OBJ_BLOB:
1693 p = process_blob(lookup_blob(entry.sha1), p, &me, name);
1694 break;
1695 default:
1696 /* Subproject commit - not in this repository */
1697 break;
1700 free(tree->buffer);
1701 tree->buffer = NULL;
1702 return p;
1705 static int get_delta(struct rev_info *revs, struct remote_lock *lock)
1707 int i;
1708 struct commit *commit;
1709 struct object_list **p = &objects;
1710 int count = 0;
1712 while ((commit = get_revision(revs)) != NULL) {
1713 p = process_tree(commit->tree, p, NULL, "");
1714 commit->object.flags |= LOCAL;
1715 if (!(commit->object.flags & UNINTERESTING))
1716 count += add_send_request(&commit->object, lock);
1719 for (i = 0; i < revs->pending.nr; i++) {
1720 struct object_array_entry *entry = revs->pending.objects + i;
1721 struct object *obj = entry->item;
1722 const char *name = entry->name;
1724 if (obj->flags & (UNINTERESTING | SEEN))
1725 continue;
1726 if (obj->type == OBJ_TAG) {
1727 obj->flags |= SEEN;
1728 p = add_one_object(obj, p);
1729 continue;
1731 if (obj->type == OBJ_TREE) {
1732 p = process_tree((struct tree *)obj, p, NULL, name);
1733 continue;
1735 if (obj->type == OBJ_BLOB) {
1736 p = process_blob((struct blob *)obj, p, NULL, name);
1737 continue;
1739 die("unknown pending object %s (%s)", sha1_to_hex(obj->sha1), name);
1742 while (objects) {
1743 if (!(objects->item->flags & UNINTERESTING))
1744 count += add_send_request(objects->item, lock);
1745 objects = objects->next;
1748 return count;
1751 static int update_remote(unsigned char *sha1, struct remote_lock *lock)
1753 struct active_request_slot *slot;
1754 struct slot_results results;
1755 struct buffer out_buffer = { STRBUF_INIT, 0 };
1756 struct curl_slist *dav_headers;
1758 dav_headers = get_dav_token_headers(lock, DAV_HEADER_IF);
1760 strbuf_addf(&out_buffer.buf, "%s\n", sha1_to_hex(sha1));
1762 slot = get_active_slot();
1763 slot->results = &results;
1764 curl_easy_setopt(slot->curl, CURLOPT_INFILE, &out_buffer);
1765 curl_easy_setopt(slot->curl, CURLOPT_INFILESIZE, out_buffer.buf.len);
1766 curl_easy_setopt(slot->curl, CURLOPT_READFUNCTION, fread_buffer);
1767 curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION, fwrite_null);
1768 curl_easy_setopt(slot->curl, CURLOPT_CUSTOMREQUEST, DAV_PUT);
1769 curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, dav_headers);
1770 curl_easy_setopt(slot->curl, CURLOPT_UPLOAD, 1);
1771 curl_easy_setopt(slot->curl, CURLOPT_PUT, 1);
1772 curl_easy_setopt(slot->curl, CURLOPT_URL, lock->url);
1774 if (start_active_slot(slot)) {
1775 run_active_slot(slot);
1776 strbuf_release(&out_buffer.buf);
1777 if (results.curl_result != CURLE_OK) {
1778 fprintf(stderr,
1779 "PUT error: curl result=%d, HTTP code=%ld\n",
1780 results.curl_result, results.http_code);
1781 /* We should attempt recovery? */
1782 return 0;
1784 } else {
1785 strbuf_release(&out_buffer.buf);
1786 fprintf(stderr, "Unable to start PUT request\n");
1787 return 0;
1790 return 1;
1793 static struct ref *local_refs, **local_tail;
1794 static struct ref *remote_refs, **remote_tail;
1796 static int one_local_ref(const char *refname, const unsigned char *sha1, int flag, void *cb_data)
1798 struct ref *ref;
1799 int len = strlen(refname) + 1;
1800 ref = xcalloc(1, sizeof(*ref) + len);
1801 hashcpy(ref->new_sha1, sha1);
1802 memcpy(ref->name, refname, len);
1803 *local_tail = ref;
1804 local_tail = &ref->next;
1805 return 0;
1808 static void one_remote_ref(char *refname)
1810 struct ref *ref;
1811 struct object *obj;
1813 ref = alloc_ref(refname);
1815 if (http_fetch_ref(remote->url, ref) != 0) {
1816 fprintf(stderr,
1817 "Unable to fetch ref %s from %s\n",
1818 refname, remote->url);
1819 free(ref);
1820 return;
1824 * Fetch a copy of the object if it doesn't exist locally - it
1825 * may be required for updating server info later.
1827 if (remote->can_update_info_refs && !has_sha1_file(ref->old_sha1)) {
1828 obj = lookup_unknown_object(ref->old_sha1);
1829 if (obj) {
1830 fprintf(stderr, " fetch %s for %s\n",
1831 sha1_to_hex(ref->old_sha1), refname);
1832 add_fetch_request(obj);
1836 *remote_tail = ref;
1837 remote_tail = &ref->next;
1840 static void get_local_heads(void)
1842 local_tail = &local_refs;
1843 for_each_ref(one_local_ref, NULL);
1846 static void get_dav_remote_heads(void)
1848 remote_tail = &remote_refs;
1849 remote_ls("refs/", (PROCESS_FILES | PROCESS_DIRS | RECURSIVE), process_ls_ref, NULL);
1852 static int is_zero_sha1(const unsigned char *sha1)
1854 int i;
1856 for (i = 0; i < 20; i++) {
1857 if (*sha1++)
1858 return 0;
1860 return 1;
1863 static void unmark_and_free(struct commit_list *list, unsigned int mark)
1865 while (list) {
1866 struct commit_list *temp = list;
1867 temp->item->object.flags &= ~mark;
1868 list = temp->next;
1869 free(temp);
1873 static int ref_newer(const unsigned char *new_sha1,
1874 const unsigned char *old_sha1)
1876 struct object *o;
1877 struct commit *old, *new;
1878 struct commit_list *list, *used;
1879 int found = 0;
1881 /* Both new and old must be commit-ish and new is descendant of
1882 * old. Otherwise we require --force.
1884 o = deref_tag(parse_object(old_sha1), NULL, 0);
1885 if (!o || o->type != OBJ_COMMIT)
1886 return 0;
1887 old = (struct commit *) o;
1889 o = deref_tag(parse_object(new_sha1), NULL, 0);
1890 if (!o || o->type != OBJ_COMMIT)
1891 return 0;
1892 new = (struct commit *) o;
1894 if (parse_commit(new) < 0)
1895 return 0;
1897 used = list = NULL;
1898 commit_list_insert(new, &list);
1899 while (list) {
1900 new = pop_most_recent_commit(&list, TMP_MARK);
1901 commit_list_insert(new, &used);
1902 if (new == old) {
1903 found = 1;
1904 break;
1907 unmark_and_free(list, TMP_MARK);
1908 unmark_and_free(used, TMP_MARK);
1909 return found;
1912 static void add_remote_info_ref(struct remote_ls_ctx *ls)
1914 struct strbuf *buf = (struct strbuf *)ls->userData;
1915 struct object *o;
1916 int len;
1917 char *ref_info;
1918 struct ref *ref;
1920 ref = alloc_ref(ls->dentry_name);
1922 if (http_fetch_ref(remote->url, ref) != 0) {
1923 fprintf(stderr,
1924 "Unable to fetch ref %s from %s\n",
1925 ls->dentry_name, remote->url);
1926 aborted = 1;
1927 free(ref);
1928 return;
1931 o = parse_object(ref->old_sha1);
1932 if (!o) {
1933 fprintf(stderr,
1934 "Unable to parse object %s for remote ref %s\n",
1935 sha1_to_hex(ref->old_sha1), ls->dentry_name);
1936 aborted = 1;
1937 free(ref);
1938 return;
1941 len = strlen(ls->dentry_name) + 42;
1942 ref_info = xcalloc(len + 1, 1);
1943 sprintf(ref_info, "%s %s\n",
1944 sha1_to_hex(ref->old_sha1), ls->dentry_name);
1945 fwrite_buffer(ref_info, 1, len, buf);
1946 free(ref_info);
1948 if (o->type == OBJ_TAG) {
1949 o = deref_tag(o, ls->dentry_name, 0);
1950 if (o) {
1951 len = strlen(ls->dentry_name) + 45;
1952 ref_info = xcalloc(len + 1, 1);
1953 sprintf(ref_info, "%s %s^{}\n",
1954 sha1_to_hex(o->sha1), ls->dentry_name);
1955 fwrite_buffer(ref_info, 1, len, buf);
1956 free(ref_info);
1959 free(ref);
1962 static void update_remote_info_refs(struct remote_lock *lock)
1964 struct buffer buffer = { STRBUF_INIT, 0 };
1965 struct active_request_slot *slot;
1966 struct slot_results results;
1967 struct curl_slist *dav_headers;
1969 remote_ls("refs/", (PROCESS_FILES | RECURSIVE),
1970 add_remote_info_ref, &buffer.buf);
1971 if (!aborted) {
1972 dav_headers = get_dav_token_headers(lock, DAV_HEADER_IF);
1974 slot = get_active_slot();
1975 slot->results = &results;
1976 curl_easy_setopt(slot->curl, CURLOPT_INFILE, &buffer);
1977 curl_easy_setopt(slot->curl, CURLOPT_INFILESIZE, buffer.buf.len);
1978 curl_easy_setopt(slot->curl, CURLOPT_READFUNCTION, fread_buffer);
1979 curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION, fwrite_null);
1980 curl_easy_setopt(slot->curl, CURLOPT_CUSTOMREQUEST, DAV_PUT);
1981 curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, dav_headers);
1982 curl_easy_setopt(slot->curl, CURLOPT_UPLOAD, 1);
1983 curl_easy_setopt(slot->curl, CURLOPT_PUT, 1);
1984 curl_easy_setopt(slot->curl, CURLOPT_URL, lock->url);
1986 if (start_active_slot(slot)) {
1987 run_active_slot(slot);
1988 if (results.curl_result != CURLE_OK) {
1989 fprintf(stderr,
1990 "PUT error: curl result=%d, HTTP code=%ld\n",
1991 results.curl_result, results.http_code);
1995 strbuf_release(&buffer.buf);
1998 static int remote_exists(const char *path)
2000 char *url = xmalloc(strlen(remote->url) + strlen(path) + 1);
2001 struct active_request_slot *slot;
2002 struct slot_results results;
2003 int ret = -1;
2005 sprintf(url, "%s%s", remote->url, path);
2007 slot = get_active_slot();
2008 slot->results = &results;
2009 curl_easy_setopt(slot->curl, CURLOPT_URL, url);
2010 curl_easy_setopt(slot->curl, CURLOPT_NOBODY, 1);
2012 if (start_active_slot(slot)) {
2013 run_active_slot(slot);
2014 if (results.http_code == 404)
2015 ret = 0;
2016 else if (results.curl_result == CURLE_OK)
2017 ret = 1;
2018 else
2019 fprintf(stderr, "HEAD HTTP error %ld\n", results.http_code);
2020 } else {
2021 fprintf(stderr, "Unable to start HEAD request\n");
2024 free(url);
2025 return ret;
2028 static void fetch_symref(const char *path, char **symref, unsigned char *sha1)
2030 char *url;
2031 struct strbuf buffer = STRBUF_INIT;
2032 struct active_request_slot *slot;
2033 struct slot_results results;
2035 url = xmalloc(strlen(remote->url) + strlen(path) + 1);
2036 sprintf(url, "%s%s", remote->url, path);
2038 slot = get_active_slot();
2039 slot->results = &results;
2040 curl_easy_setopt(slot->curl, CURLOPT_FILE, &buffer);
2041 curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION, fwrite_buffer);
2042 curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, NULL);
2043 curl_easy_setopt(slot->curl, CURLOPT_URL, url);
2044 if (start_active_slot(slot)) {
2045 run_active_slot(slot);
2046 if (results.curl_result != CURLE_OK) {
2047 die("Couldn't get %s for remote symref\n%s",
2048 url, curl_errorstr);
2050 } else {
2051 die("Unable to start remote symref request");
2053 free(url);
2055 free(*symref);
2056 *symref = NULL;
2057 hashclr(sha1);
2059 if (buffer.len == 0)
2060 return;
2062 /* If it's a symref, set the refname; otherwise try for a sha1 */
2063 if (!prefixcmp((char *)buffer.buf, "ref: ")) {
2064 *symref = xmemdupz((char *)buffer.buf + 5, buffer.len - 6);
2065 } else {
2066 get_sha1_hex(buffer.buf, sha1);
2069 strbuf_release(&buffer);
2072 static int verify_merge_base(unsigned char *head_sha1, unsigned char *branch_sha1)
2074 struct commit *head = lookup_commit(head_sha1);
2075 struct commit *branch = lookup_commit(branch_sha1);
2076 struct commit_list *merge_bases = get_merge_bases(head, branch, 1);
2078 return (merge_bases && !merge_bases->next && merge_bases->item == branch);
2081 static int delete_remote_branch(char *pattern, int force)
2083 struct ref *refs = remote_refs;
2084 struct ref *remote_ref = NULL;
2085 unsigned char head_sha1[20];
2086 char *symref = NULL;
2087 int match;
2088 int patlen = strlen(pattern);
2089 int i;
2090 struct active_request_slot *slot;
2091 struct slot_results results;
2092 char *url;
2094 /* Find the remote branch(es) matching the specified branch name */
2095 for (match = 0; refs; refs = refs->next) {
2096 char *name = refs->name;
2097 int namelen = strlen(name);
2098 if (namelen < patlen ||
2099 memcmp(name + namelen - patlen, pattern, patlen))
2100 continue;
2101 if (namelen != patlen && name[namelen - patlen - 1] != '/')
2102 continue;
2103 match++;
2104 remote_ref = refs;
2106 if (match == 0)
2107 return error("No remote branch matches %s", pattern);
2108 if (match != 1)
2109 return error("More than one remote branch matches %s",
2110 pattern);
2113 * Remote HEAD must be a symref (not exactly foolproof; a remote
2114 * symlink to a symref will look like a symref)
2116 fetch_symref("HEAD", &symref, head_sha1);
2117 if (!symref)
2118 return error("Remote HEAD is not a symref");
2120 /* Remote branch must not be the remote HEAD */
2121 for (i=0; symref && i<MAXDEPTH; i++) {
2122 if (!strcmp(remote_ref->name, symref))
2123 return error("Remote branch %s is the current HEAD",
2124 remote_ref->name);
2125 fetch_symref(symref, &symref, head_sha1);
2128 /* Run extra sanity checks if delete is not forced */
2129 if (!force) {
2130 /* Remote HEAD must resolve to a known object */
2131 if (symref)
2132 return error("Remote HEAD symrefs too deep");
2133 if (is_zero_sha1(head_sha1))
2134 return error("Unable to resolve remote HEAD");
2135 if (!has_sha1_file(head_sha1))
2136 return error("Remote HEAD resolves to object %s\nwhich does not exist locally, perhaps you need to fetch?", sha1_to_hex(head_sha1));
2138 /* Remote branch must resolve to a known object */
2139 if (is_zero_sha1(remote_ref->old_sha1))
2140 return error("Unable to resolve remote branch %s",
2141 remote_ref->name);
2142 if (!has_sha1_file(remote_ref->old_sha1))
2143 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));
2145 /* Remote branch must be an ancestor of remote HEAD */
2146 if (!verify_merge_base(head_sha1, remote_ref->old_sha1)) {
2147 return error("The branch '%s' is not an ancestor "
2148 "of your current HEAD.\n"
2149 "If you are sure you want to delete it,"
2150 " run:\n\t'git http-push -D %s %s'",
2151 remote_ref->name, remote->url, pattern);
2155 /* Send delete request */
2156 fprintf(stderr, "Removing remote branch '%s'\n", remote_ref->name);
2157 if (dry_run)
2158 return 0;
2159 url = xmalloc(strlen(remote->url) + strlen(remote_ref->name) + 1);
2160 sprintf(url, "%s%s", remote->url, remote_ref->name);
2161 slot = get_active_slot();
2162 slot->results = &results;
2163 curl_easy_setopt(slot->curl, CURLOPT_HTTPGET, 1);
2164 curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION, fwrite_null);
2165 curl_easy_setopt(slot->curl, CURLOPT_URL, url);
2166 curl_easy_setopt(slot->curl, CURLOPT_CUSTOMREQUEST, DAV_DELETE);
2167 if (start_active_slot(slot)) {
2168 run_active_slot(slot);
2169 free(url);
2170 if (results.curl_result != CURLE_OK)
2171 return error("DELETE request failed (%d/%ld)\n",
2172 results.curl_result, results.http_code);
2173 } else {
2174 free(url);
2175 return error("Unable to start DELETE request");
2178 return 0;
2181 int main(int argc, char **argv)
2183 struct transfer_request *request;
2184 struct transfer_request *next_request;
2185 int nr_refspec = 0;
2186 char **refspec = NULL;
2187 struct remote_lock *ref_lock = NULL;
2188 struct remote_lock *info_ref_lock = NULL;
2189 struct rev_info revs;
2190 int delete_branch = 0;
2191 int force_delete = 0;
2192 int objects_to_send;
2193 int rc = 0;
2194 int i;
2195 int new_refs;
2196 struct ref *ref;
2197 char *rewritten_url = NULL;
2199 git_extract_argv0_path(argv[0]);
2201 setup_git_directory();
2203 remote = xcalloc(sizeof(*remote), 1);
2205 argv++;
2206 for (i = 1; i < argc; i++, argv++) {
2207 char *arg = *argv;
2209 if (*arg == '-') {
2210 if (!strcmp(arg, "--all")) {
2211 push_all = MATCH_REFS_ALL;
2212 continue;
2214 if (!strcmp(arg, "--force")) {
2215 force_all = 1;
2216 continue;
2218 if (!strcmp(arg, "--dry-run")) {
2219 dry_run = 1;
2220 continue;
2222 if (!strcmp(arg, "--verbose")) {
2223 push_verbosely = 1;
2224 continue;
2226 if (!strcmp(arg, "-d")) {
2227 delete_branch = 1;
2228 continue;
2230 if (!strcmp(arg, "-D")) {
2231 delete_branch = 1;
2232 force_delete = 1;
2233 continue;
2236 if (!remote->url) {
2237 char *path = strstr(arg, "//");
2238 remote->url = arg;
2239 remote->path_len = strlen(arg);
2240 if (path) {
2241 remote->path = strchr(path+2, '/');
2242 if (remote->path)
2243 remote->path_len = strlen(remote->path);
2245 continue;
2247 refspec = argv;
2248 nr_refspec = argc - i;
2249 break;
2252 #ifndef USE_CURL_MULTI
2253 die("git-push is not available for http/https repository when not compiled with USE_CURL_MULTI");
2254 #endif
2256 if (!remote->url)
2257 usage(http_push_usage);
2259 if (delete_branch && nr_refspec != 1)
2260 die("You must specify only one branch name when deleting a remote branch");
2262 memset(remote_dir_exists, -1, 256);
2264 http_init(NULL);
2266 no_pragma_header = curl_slist_append(no_pragma_header, "Pragma:");
2268 if (remote->url && remote->url[strlen(remote->url)-1] != '/') {
2269 rewritten_url = xmalloc(strlen(remote->url)+2);
2270 strcpy(rewritten_url, remote->url);
2271 strcat(rewritten_url, "/");
2272 remote->path = rewritten_url + (remote->path - remote->url);
2273 remote->path_len++;
2274 remote->url = rewritten_url;
2277 /* Verify DAV compliance/lock support */
2278 if (!locking_available()) {
2279 rc = 1;
2280 goto cleanup;
2283 sigchain_push_common(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;