Merge branch 'ab/commit-m-with-fixup' into maint
[git/debian.git] / http-push.c
blob14435ab65d1bbe3fc73be6a6d774b6ab6ffc8360
1 #include "cache.h"
2 #include "commit.h"
3 #include "tag.h"
4 #include "blob.h"
5 #include "http.h"
6 #include "refs.h"
7 #include "diff.h"
8 #include "revision.h"
9 #include "exec_cmd.h"
10 #include "remote.h"
11 #include "list-objects.h"
12 #include "sigchain.h"
13 #include "argv-array.h"
14 #include "packfile.h"
16 #ifdef EXPAT_NEEDS_XMLPARSE_H
17 #include <xmlparse.h>
18 #else
19 #include <expat.h>
20 #endif
22 static const char http_push_usage[] =
23 "git http-push [--all] [--dry-run] [--force] [--verbose] <remote> [<head>...]\n";
25 #ifndef XML_STATUS_OK
26 enum XML_Status {
27 XML_STATUS_OK = 1,
28 XML_STATUS_ERROR = 0
30 #define XML_STATUS_OK 1
31 #define XML_STATUS_ERROR 0
32 #endif
34 #define PREV_BUF_SIZE 4096
36 /* DAV methods */
37 #define DAV_LOCK "LOCK"
38 #define DAV_MKCOL "MKCOL"
39 #define DAV_MOVE "MOVE"
40 #define DAV_PROPFIND "PROPFIND"
41 #define DAV_PUT "PUT"
42 #define DAV_UNLOCK "UNLOCK"
43 #define DAV_DELETE "DELETE"
45 /* DAV lock flags */
46 #define DAV_PROP_LOCKWR (1u << 0)
47 #define DAV_PROP_LOCKEX (1u << 1)
48 #define DAV_LOCK_OK (1u << 2)
50 /* DAV XML properties */
51 #define DAV_CTX_LOCKENTRY ".multistatus.response.propstat.prop.supportedlock.lockentry"
52 #define DAV_CTX_LOCKTYPE_WRITE ".multistatus.response.propstat.prop.supportedlock.lockentry.locktype.write"
53 #define DAV_CTX_LOCKTYPE_EXCLUSIVE ".multistatus.response.propstat.prop.supportedlock.lockentry.lockscope.exclusive"
54 #define DAV_ACTIVELOCK_OWNER ".prop.lockdiscovery.activelock.owner.href"
55 #define DAV_ACTIVELOCK_TIMEOUT ".prop.lockdiscovery.activelock.timeout"
56 #define DAV_ACTIVELOCK_TOKEN ".prop.lockdiscovery.activelock.locktoken.href"
57 #define DAV_PROPFIND_RESP ".multistatus.response"
58 #define DAV_PROPFIND_NAME ".multistatus.response.href"
59 #define DAV_PROPFIND_COLLECTION ".multistatus.response.propstat.prop.resourcetype.collection"
61 /* DAV request body templates */
62 #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>"
63 #define PROPFIND_ALL_REQUEST "<?xml version=\"1.0\" encoding=\"utf-8\" ?>\n<D:propfind xmlns:D=\"DAV:\">\n<D:allprop/>\n</D:propfind>"
64 #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>"
66 #define LOCK_TIME 600
67 #define LOCK_REFRESH 30
69 /* Remember to update object flag allocation in object.h */
70 #define LOCAL (1u<<16)
71 #define REMOTE (1u<<17)
72 #define FETCHING (1u<<18)
73 #define PUSHING (1u<<19)
75 /* We allow "recursive" symbolic refs. Only within reason, though */
76 #define MAXDEPTH 5
78 static int pushing;
79 static int aborted;
80 static signed char remote_dir_exists[256];
82 static int push_verbosely;
83 static int push_all = MATCH_REFS_NONE;
84 static int force_all;
85 static int dry_run;
86 static int helper_status;
88 static struct object_list *objects;
90 struct repo {
91 char *url;
92 char *path;
93 int path_len;
94 int has_info_refs;
95 int can_update_info_refs;
96 int has_info_packs;
97 struct packed_git *packs;
98 struct remote_lock *locks;
101 static struct repo *repo;
103 enum transfer_state {
104 NEED_FETCH,
105 RUN_FETCH_LOOSE,
106 RUN_FETCH_PACKED,
107 NEED_PUSH,
108 RUN_MKCOL,
109 RUN_PUT,
110 RUN_MOVE,
111 ABORTED,
112 COMPLETE
115 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 enum transfer_state state;
123 CURLcode curl_result;
124 char errorstr[CURL_ERROR_SIZE];
125 long http_code;
126 void *userData;
127 struct active_request_slot *slot;
128 struct transfer_request *next;
131 static struct transfer_request *request_queue_head;
133 struct xml_ctx {
134 char *name;
135 int len;
136 char *cdata;
137 void (*userFunc)(struct xml_ctx *ctx, int tag_closed);
138 void *userData;
141 struct remote_lock {
142 char *url;
143 char *owner;
144 char *token;
145 char tmpfile_suffix[41];
146 time_t start_time;
147 long timeout;
148 int refreshing;
149 struct remote_lock *next;
152 /* Flags that control remote_ls processing */
153 #define PROCESS_FILES (1u << 0)
154 #define PROCESS_DIRS (1u << 1)
155 #define RECURSIVE (1u << 2)
157 /* Flags that remote_ls passes to callback functions */
158 #define IS_DIR (1u << 0)
160 struct remote_ls_ctx {
161 char *path;
162 void (*userFunc)(struct remote_ls_ctx *ls);
163 void *userData;
164 int flags;
165 char *dentry_name;
166 int dentry_flags;
167 struct remote_ls_ctx *parent;
170 /* get_dav_token_headers options */
171 enum dav_header_flag {
172 DAV_HEADER_IF = (1u << 0),
173 DAV_HEADER_LOCK = (1u << 1),
174 DAV_HEADER_TIMEOUT = (1u << 2)
177 static char *xml_entities(const char *s)
179 struct strbuf buf = STRBUF_INIT;
180 strbuf_addstr_xml_quoted(&buf, s);
181 return strbuf_detach(&buf, NULL);
184 static void curl_setup_http_get(CURL *curl, const char *url,
185 const char *custom_req)
187 curl_easy_setopt(curl, CURLOPT_HTTPGET, 1);
188 curl_easy_setopt(curl, CURLOPT_URL, url);
189 curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, custom_req);
190 curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, fwrite_null);
193 static void curl_setup_http(CURL *curl, const char *url,
194 const char *custom_req, struct buffer *buffer,
195 curl_write_callback write_fn)
197 curl_easy_setopt(curl, CURLOPT_PUT, 1);
198 curl_easy_setopt(curl, CURLOPT_URL, url);
199 curl_easy_setopt(curl, CURLOPT_INFILE, buffer);
200 curl_easy_setopt(curl, CURLOPT_INFILESIZE, buffer->buf.len);
201 curl_easy_setopt(curl, CURLOPT_READFUNCTION, fread_buffer);
202 #ifndef NO_CURL_IOCTL
203 curl_easy_setopt(curl, CURLOPT_IOCTLFUNCTION, ioctl_buffer);
204 curl_easy_setopt(curl, CURLOPT_IOCTLDATA, buffer);
205 #endif
206 curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_fn);
207 curl_easy_setopt(curl, CURLOPT_NOBODY, 0);
208 curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, custom_req);
209 curl_easy_setopt(curl, CURLOPT_UPLOAD, 1);
212 static struct curl_slist *get_dav_token_headers(struct remote_lock *lock, enum dav_header_flag options)
214 struct strbuf buf = STRBUF_INIT;
215 struct curl_slist *dav_headers = http_copy_default_headers();
217 if (options & DAV_HEADER_IF) {
218 strbuf_addf(&buf, "If: (<%s>)", lock->token);
219 dav_headers = curl_slist_append(dav_headers, buf.buf);
220 strbuf_reset(&buf);
222 if (options & DAV_HEADER_LOCK) {
223 strbuf_addf(&buf, "Lock-Token: <%s>", lock->token);
224 dav_headers = curl_slist_append(dav_headers, buf.buf);
225 strbuf_reset(&buf);
227 if (options & DAV_HEADER_TIMEOUT) {
228 strbuf_addf(&buf, "Timeout: Second-%ld", lock->timeout);
229 dav_headers = curl_slist_append(dav_headers, buf.buf);
230 strbuf_reset(&buf);
232 strbuf_release(&buf);
234 return dav_headers;
237 static void finish_request(struct transfer_request *request);
238 static void release_request(struct transfer_request *request);
240 static void process_response(void *callback_data)
242 struct transfer_request *request =
243 (struct transfer_request *)callback_data;
245 finish_request(request);
248 #ifdef USE_CURL_MULTI
250 static void start_fetch_loose(struct transfer_request *request)
252 struct active_request_slot *slot;
253 struct http_object_request *obj_req;
255 obj_req = new_http_object_request(repo->url, request->obj->oid.hash);
256 if (obj_req == NULL) {
257 request->state = ABORTED;
258 return;
261 slot = obj_req->slot;
262 slot->callback_func = process_response;
263 slot->callback_data = request;
264 request->slot = slot;
265 request->userData = obj_req;
267 /* Try to get the request started, abort the request on error */
268 request->state = RUN_FETCH_LOOSE;
269 if (!start_active_slot(slot)) {
270 fprintf(stderr, "Unable to start GET request\n");
271 repo->can_update_info_refs = 0;
272 release_http_object_request(obj_req);
273 release_request(request);
277 static void start_mkcol(struct transfer_request *request)
279 char *hex = oid_to_hex(&request->obj->oid);
280 struct active_request_slot *slot;
282 request->url = get_remote_object_url(repo->url, hex, 1);
284 slot = get_active_slot();
285 slot->callback_func = process_response;
286 slot->callback_data = request;
287 curl_setup_http_get(slot->curl, request->url, DAV_MKCOL);
288 curl_easy_setopt(slot->curl, CURLOPT_ERRORBUFFER, request->errorstr);
290 if (start_active_slot(slot)) {
291 request->slot = slot;
292 request->state = RUN_MKCOL;
293 } else {
294 request->state = ABORTED;
295 FREE_AND_NULL(request->url);
298 #endif
300 static void start_fetch_packed(struct transfer_request *request)
302 struct packed_git *target;
304 struct transfer_request *check_request = request_queue_head;
305 struct http_pack_request *preq;
307 target = find_sha1_pack(request->obj->oid.hash, repo->packs);
308 if (!target) {
309 fprintf(stderr, "Unable to fetch %s, will not be able to update server info refs\n", oid_to_hex(&request->obj->oid));
310 repo->can_update_info_refs = 0;
311 release_request(request);
312 return;
315 fprintf(stderr, "Fetching pack %s\n", sha1_to_hex(target->sha1));
316 fprintf(stderr, " which contains %s\n", oid_to_hex(&request->obj->oid));
318 preq = new_http_pack_request(target, repo->url);
319 if (preq == NULL) {
320 repo->can_update_info_refs = 0;
321 return;
323 preq->lst = &repo->packs;
325 /* Make sure there isn't another open request for this pack */
326 while (check_request) {
327 if (check_request->state == RUN_FETCH_PACKED &&
328 !strcmp(check_request->url, preq->url)) {
329 release_http_pack_request(preq);
330 release_request(request);
331 return;
333 check_request = check_request->next;
336 preq->slot->callback_func = process_response;
337 preq->slot->callback_data = request;
338 request->slot = preq->slot;
339 request->userData = preq;
341 /* Try to get the request started, abort the request on error */
342 request->state = RUN_FETCH_PACKED;
343 if (!start_active_slot(preq->slot)) {
344 fprintf(stderr, "Unable to start GET request\n");
345 release_http_pack_request(preq);
346 repo->can_update_info_refs = 0;
347 release_request(request);
351 static void start_put(struct transfer_request *request)
353 char *hex = oid_to_hex(&request->obj->oid);
354 struct active_request_slot *slot;
355 struct strbuf buf = STRBUF_INIT;
356 enum object_type type;
357 char hdr[50];
358 void *unpacked;
359 unsigned long len;
360 int hdrlen;
361 ssize_t size;
362 git_zstream stream;
364 unpacked = read_sha1_file(request->obj->oid.hash, &type, &len);
365 hdrlen = xsnprintf(hdr, sizeof(hdr), "%s %lu", typename(type), len) + 1;
367 /* Set it up */
368 git_deflate_init(&stream, zlib_compression_level);
369 size = git_deflate_bound(&stream, len + hdrlen);
370 strbuf_init(&request->buffer.buf, size);
371 request->buffer.posn = 0;
373 /* Compress it */
374 stream.next_out = (unsigned char *)request->buffer.buf.buf;
375 stream.avail_out = size;
377 /* First header.. */
378 stream.next_in = (void *)hdr;
379 stream.avail_in = hdrlen;
380 while (git_deflate(&stream, 0) == Z_OK)
381 ; /* nothing */
383 /* Then the data itself.. */
384 stream.next_in = unpacked;
385 stream.avail_in = len;
386 while (git_deflate(&stream, Z_FINISH) == Z_OK)
387 ; /* nothing */
388 git_deflate_end(&stream);
389 free(unpacked);
391 request->buffer.buf.len = stream.total_out;
393 strbuf_addstr(&buf, "Destination: ");
394 append_remote_object_url(&buf, repo->url, hex, 0);
395 request->dest = strbuf_detach(&buf, NULL);
397 append_remote_object_url(&buf, repo->url, hex, 0);
398 strbuf_add(&buf, request->lock->tmpfile_suffix, 41);
399 request->url = strbuf_detach(&buf, NULL);
401 slot = get_active_slot();
402 slot->callback_func = process_response;
403 slot->callback_data = request;
404 curl_setup_http(slot->curl, request->url, DAV_PUT,
405 &request->buffer, fwrite_null);
407 if (start_active_slot(slot)) {
408 request->slot = slot;
409 request->state = RUN_PUT;
410 } else {
411 request->state = ABORTED;
412 FREE_AND_NULL(request->url);
416 static void start_move(struct transfer_request *request)
418 struct active_request_slot *slot;
419 struct curl_slist *dav_headers = http_copy_default_headers();
421 slot = get_active_slot();
422 slot->callback_func = process_response;
423 slot->callback_data = request;
424 curl_setup_http_get(slot->curl, request->url, DAV_MOVE);
425 dav_headers = curl_slist_append(dav_headers, request->dest);
426 dav_headers = curl_slist_append(dav_headers, "Overwrite: T");
427 curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, dav_headers);
429 if (start_active_slot(slot)) {
430 request->slot = slot;
431 request->state = RUN_MOVE;
432 } else {
433 request->state = ABORTED;
434 FREE_AND_NULL(request->url);
438 static int refresh_lock(struct remote_lock *lock)
440 struct active_request_slot *slot;
441 struct slot_results results;
442 struct curl_slist *dav_headers;
443 int rc = 0;
445 lock->refreshing = 1;
447 dav_headers = get_dav_token_headers(lock, DAV_HEADER_IF | DAV_HEADER_TIMEOUT);
449 slot = get_active_slot();
450 slot->results = &results;
451 curl_setup_http_get(slot->curl, lock->url, DAV_LOCK);
452 curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, dav_headers);
454 if (start_active_slot(slot)) {
455 run_active_slot(slot);
456 if (results.curl_result != CURLE_OK) {
457 fprintf(stderr, "LOCK HTTP error %ld\n",
458 results.http_code);
459 } else {
460 lock->start_time = time(NULL);
461 rc = 1;
465 lock->refreshing = 0;
466 curl_slist_free_all(dav_headers);
468 return rc;
471 static void check_locks(void)
473 struct remote_lock *lock = repo->locks;
474 time_t current_time = time(NULL);
475 int time_remaining;
477 while (lock) {
478 time_remaining = lock->start_time + lock->timeout -
479 current_time;
480 if (!lock->refreshing && time_remaining < LOCK_REFRESH) {
481 if (!refresh_lock(lock)) {
482 fprintf(stderr,
483 "Unable to refresh lock for %s\n",
484 lock->url);
485 aborted = 1;
486 return;
489 lock = lock->next;
493 static void release_request(struct transfer_request *request)
495 struct transfer_request *entry = request_queue_head;
497 if (request == request_queue_head) {
498 request_queue_head = request->next;
499 } else {
500 while (entry->next != NULL && entry->next != request)
501 entry = entry->next;
502 if (entry->next == request)
503 entry->next = entry->next->next;
506 free(request->url);
507 free(request);
510 static void finish_request(struct transfer_request *request)
512 struct http_pack_request *preq;
513 struct http_object_request *obj_req;
515 request->curl_result = request->slot->curl_result;
516 request->http_code = request->slot->http_code;
517 request->slot = NULL;
519 /* Keep locks active */
520 check_locks();
522 if (request->headers != NULL)
523 curl_slist_free_all(request->headers);
525 /* URL is reused for MOVE after PUT */
526 if (request->state != RUN_PUT) {
527 FREE_AND_NULL(request->url);
530 if (request->state == RUN_MKCOL) {
531 if (request->curl_result == CURLE_OK ||
532 request->http_code == 405) {
533 remote_dir_exists[request->obj->oid.hash[0]] = 1;
534 start_put(request);
535 } else {
536 fprintf(stderr, "MKCOL %s failed, aborting (%d/%ld)\n",
537 oid_to_hex(&request->obj->oid),
538 request->curl_result, request->http_code);
539 request->state = ABORTED;
540 aborted = 1;
542 } else if (request->state == RUN_PUT) {
543 if (request->curl_result == CURLE_OK) {
544 start_move(request);
545 } else {
546 fprintf(stderr, "PUT %s failed, aborting (%d/%ld)\n",
547 oid_to_hex(&request->obj->oid),
548 request->curl_result, request->http_code);
549 request->state = ABORTED;
550 aborted = 1;
552 } else if (request->state == RUN_MOVE) {
553 if (request->curl_result == CURLE_OK) {
554 if (push_verbosely)
555 fprintf(stderr, " sent %s\n",
556 oid_to_hex(&request->obj->oid));
557 request->obj->flags |= REMOTE;
558 release_request(request);
559 } else {
560 fprintf(stderr, "MOVE %s failed, aborting (%d/%ld)\n",
561 oid_to_hex(&request->obj->oid),
562 request->curl_result, request->http_code);
563 request->state = ABORTED;
564 aborted = 1;
566 } else if (request->state == RUN_FETCH_LOOSE) {
567 obj_req = (struct http_object_request *)request->userData;
569 if (finish_http_object_request(obj_req) == 0)
570 if (obj_req->rename == 0)
571 request->obj->flags |= (LOCAL | REMOTE);
573 /* Try fetching packed if necessary */
574 if (request->obj->flags & LOCAL) {
575 release_http_object_request(obj_req);
576 release_request(request);
577 } else
578 start_fetch_packed(request);
580 } else if (request->state == RUN_FETCH_PACKED) {
581 int fail = 1;
582 if (request->curl_result != CURLE_OK) {
583 fprintf(stderr, "Unable to get pack file %s\n%s",
584 request->url, curl_errorstr);
585 } else {
586 preq = (struct http_pack_request *)request->userData;
588 if (preq) {
589 if (finish_http_pack_request(preq) == 0)
590 fail = 0;
591 release_http_pack_request(preq);
594 if (fail)
595 repo->can_update_info_refs = 0;
596 release_request(request);
600 #ifdef USE_CURL_MULTI
601 static int is_running_queue;
602 static int fill_active_slot(void *unused)
604 struct transfer_request *request;
606 if (aborted || !is_running_queue)
607 return 0;
609 for (request = request_queue_head; request; request = request->next) {
610 if (request->state == NEED_FETCH) {
611 start_fetch_loose(request);
612 return 1;
613 } else if (pushing && request->state == NEED_PUSH) {
614 if (remote_dir_exists[request->obj->oid.hash[0]] == 1) {
615 start_put(request);
616 } else {
617 start_mkcol(request);
619 return 1;
622 return 0;
624 #endif
626 static void get_remote_object_list(unsigned char parent);
628 static void add_fetch_request(struct object *obj)
630 struct transfer_request *request;
632 check_locks();
635 * Don't fetch the object if it's known to exist locally
636 * or is already in the request queue
638 if (remote_dir_exists[obj->oid.hash[0]] == -1)
639 get_remote_object_list(obj->oid.hash[0]);
640 if (obj->flags & (LOCAL | FETCHING))
641 return;
643 obj->flags |= FETCHING;
644 request = xmalloc(sizeof(*request));
645 request->obj = obj;
646 request->url = NULL;
647 request->lock = NULL;
648 request->headers = NULL;
649 request->state = NEED_FETCH;
650 request->next = request_queue_head;
651 request_queue_head = request;
653 #ifdef USE_CURL_MULTI
654 fill_active_slots();
655 step_active_slots();
656 #endif
659 static int add_send_request(struct object *obj, struct remote_lock *lock)
661 struct transfer_request *request;
662 struct packed_git *target;
664 /* Keep locks active */
665 check_locks();
668 * Don't push the object if it's known to exist on the remote
669 * or is already in the request queue
671 if (remote_dir_exists[obj->oid.hash[0]] == -1)
672 get_remote_object_list(obj->oid.hash[0]);
673 if (obj->flags & (REMOTE | PUSHING))
674 return 0;
675 target = find_sha1_pack(obj->oid.hash, repo->packs);
676 if (target) {
677 obj->flags |= REMOTE;
678 return 0;
681 obj->flags |= PUSHING;
682 request = xmalloc(sizeof(*request));
683 request->obj = obj;
684 request->url = NULL;
685 request->lock = lock;
686 request->headers = NULL;
687 request->state = NEED_PUSH;
688 request->next = request_queue_head;
689 request_queue_head = request;
691 #ifdef USE_CURL_MULTI
692 fill_active_slots();
693 step_active_slots();
694 #endif
696 return 1;
699 static int fetch_indices(void)
701 int ret;
703 if (push_verbosely)
704 fprintf(stderr, "Getting pack list\n");
706 switch (http_get_info_packs(repo->url, &repo->packs)) {
707 case HTTP_OK:
708 case HTTP_MISSING_TARGET:
709 ret = 0;
710 break;
711 default:
712 ret = -1;
715 return ret;
718 static void one_remote_object(const struct object_id *oid)
720 struct object *obj;
722 obj = lookup_object(oid->hash);
723 if (!obj)
724 obj = parse_object(oid);
726 /* Ignore remote objects that don't exist locally */
727 if (!obj)
728 return;
730 obj->flags |= REMOTE;
731 if (!object_list_contains(objects, obj))
732 object_list_insert(obj, &objects);
735 static void handle_lockprop_ctx(struct xml_ctx *ctx, int tag_closed)
737 int *lock_flags = (int *)ctx->userData;
739 if (tag_closed) {
740 if (!strcmp(ctx->name, DAV_CTX_LOCKENTRY)) {
741 if ((*lock_flags & DAV_PROP_LOCKEX) &&
742 (*lock_flags & DAV_PROP_LOCKWR)) {
743 *lock_flags |= DAV_LOCK_OK;
745 *lock_flags &= DAV_LOCK_OK;
746 } else if (!strcmp(ctx->name, DAV_CTX_LOCKTYPE_WRITE)) {
747 *lock_flags |= DAV_PROP_LOCKWR;
748 } else if (!strcmp(ctx->name, DAV_CTX_LOCKTYPE_EXCLUSIVE)) {
749 *lock_flags |= DAV_PROP_LOCKEX;
754 static void handle_new_lock_ctx(struct xml_ctx *ctx, int tag_closed)
756 struct remote_lock *lock = (struct remote_lock *)ctx->userData;
757 git_SHA_CTX sha_ctx;
758 unsigned char lock_token_sha1[20];
760 if (tag_closed && ctx->cdata) {
761 if (!strcmp(ctx->name, DAV_ACTIVELOCK_OWNER)) {
762 lock->owner = xstrdup(ctx->cdata);
763 } else if (!strcmp(ctx->name, DAV_ACTIVELOCK_TIMEOUT)) {
764 const char *arg;
765 if (skip_prefix(ctx->cdata, "Second-", &arg))
766 lock->timeout = strtol(arg, NULL, 10);
767 } else if (!strcmp(ctx->name, DAV_ACTIVELOCK_TOKEN)) {
768 lock->token = xstrdup(ctx->cdata);
770 git_SHA1_Init(&sha_ctx);
771 git_SHA1_Update(&sha_ctx, lock->token, strlen(lock->token));
772 git_SHA1_Final(lock_token_sha1, &sha_ctx);
774 lock->tmpfile_suffix[0] = '_';
775 memcpy(lock->tmpfile_suffix + 1, sha1_to_hex(lock_token_sha1), 40);
780 static void one_remote_ref(const char *refname);
782 static void
783 xml_start_tag(void *userData, const char *name, const char **atts)
785 struct xml_ctx *ctx = (struct xml_ctx *)userData;
786 const char *c = strchr(name, ':');
787 int old_namelen, new_len;
789 if (c == NULL)
790 c = name;
791 else
792 c++;
794 old_namelen = strlen(ctx->name);
795 new_len = old_namelen + strlen(c) + 2;
797 if (new_len > ctx->len) {
798 ctx->name = xrealloc(ctx->name, new_len);
799 ctx->len = new_len;
801 xsnprintf(ctx->name + old_namelen, ctx->len - old_namelen, ".%s", c);
803 FREE_AND_NULL(ctx->cdata);
805 ctx->userFunc(ctx, 0);
808 static void
809 xml_end_tag(void *userData, const char *name)
811 struct xml_ctx *ctx = (struct xml_ctx *)userData;
812 const char *c = strchr(name, ':');
813 char *ep;
815 ctx->userFunc(ctx, 1);
817 if (c == NULL)
818 c = name;
819 else
820 c++;
822 ep = ctx->name + strlen(ctx->name) - strlen(c) - 1;
823 *ep = 0;
826 static void
827 xml_cdata(void *userData, const XML_Char *s, int len)
829 struct xml_ctx *ctx = (struct xml_ctx *)userData;
830 free(ctx->cdata);
831 ctx->cdata = xmemdupz(s, len);
834 static struct remote_lock *lock_remote(const char *path, long timeout)
836 struct active_request_slot *slot;
837 struct slot_results results;
838 struct buffer out_buffer = { STRBUF_INIT, 0 };
839 struct strbuf in_buffer = STRBUF_INIT;
840 char *url;
841 char *ep;
842 char timeout_header[25];
843 struct remote_lock *lock = NULL;
844 struct curl_slist *dav_headers = http_copy_default_headers();
845 struct xml_ctx ctx;
846 char *escaped;
848 url = xstrfmt("%s%s", repo->url, path);
850 /* Make sure leading directories exist for the remote ref */
851 ep = strchr(url + strlen(repo->url) + 1, '/');
852 while (ep) {
853 char saved_character = ep[1];
854 ep[1] = '\0';
855 slot = get_active_slot();
856 slot->results = &results;
857 curl_setup_http_get(slot->curl, url, DAV_MKCOL);
858 if (start_active_slot(slot)) {
859 run_active_slot(slot);
860 if (results.curl_result != CURLE_OK &&
861 results.http_code != 405) {
862 fprintf(stderr,
863 "Unable to create branch path %s\n",
864 url);
865 free(url);
866 return NULL;
868 } else {
869 fprintf(stderr, "Unable to start MKCOL request\n");
870 free(url);
871 return NULL;
873 ep[1] = saved_character;
874 ep = strchr(ep + 1, '/');
877 escaped = xml_entities(ident_default_email());
878 strbuf_addf(&out_buffer.buf, LOCK_REQUEST, escaped);
879 free(escaped);
881 xsnprintf(timeout_header, sizeof(timeout_header), "Timeout: Second-%ld", timeout);
882 dav_headers = curl_slist_append(dav_headers, timeout_header);
883 dav_headers = curl_slist_append(dav_headers, "Content-Type: text/xml");
885 slot = get_active_slot();
886 slot->results = &results;
887 curl_setup_http(slot->curl, url, DAV_LOCK, &out_buffer, fwrite_buffer);
888 curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, dav_headers);
889 curl_easy_setopt(slot->curl, CURLOPT_FILE, &in_buffer);
891 lock = xcalloc(1, sizeof(*lock));
892 lock->timeout = -1;
894 if (start_active_slot(slot)) {
895 run_active_slot(slot);
896 if (results.curl_result == CURLE_OK) {
897 XML_Parser parser = XML_ParserCreate(NULL);
898 enum XML_Status result;
899 ctx.name = xcalloc(10, 1);
900 ctx.len = 0;
901 ctx.cdata = NULL;
902 ctx.userFunc = handle_new_lock_ctx;
903 ctx.userData = lock;
904 XML_SetUserData(parser, &ctx);
905 XML_SetElementHandler(parser, xml_start_tag,
906 xml_end_tag);
907 XML_SetCharacterDataHandler(parser, xml_cdata);
908 result = XML_Parse(parser, in_buffer.buf,
909 in_buffer.len, 1);
910 free(ctx.name);
911 if (result != XML_STATUS_OK) {
912 fprintf(stderr, "XML error: %s\n",
913 XML_ErrorString(
914 XML_GetErrorCode(parser)));
915 lock->timeout = -1;
917 XML_ParserFree(parser);
919 } else {
920 fprintf(stderr, "Unable to start LOCK request\n");
923 curl_slist_free_all(dav_headers);
924 strbuf_release(&out_buffer.buf);
925 strbuf_release(&in_buffer);
927 if (lock->token == NULL || lock->timeout <= 0) {
928 free(lock->token);
929 free(lock->owner);
930 free(url);
931 FREE_AND_NULL(lock);
932 } else {
933 lock->url = url;
934 lock->start_time = time(NULL);
935 lock->next = repo->locks;
936 repo->locks = lock;
939 return lock;
942 static int unlock_remote(struct remote_lock *lock)
944 struct active_request_slot *slot;
945 struct slot_results results;
946 struct remote_lock *prev = repo->locks;
947 struct curl_slist *dav_headers;
948 int rc = 0;
950 dav_headers = get_dav_token_headers(lock, DAV_HEADER_LOCK);
952 slot = get_active_slot();
953 slot->results = &results;
954 curl_setup_http_get(slot->curl, lock->url, DAV_UNLOCK);
955 curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, dav_headers);
957 if (start_active_slot(slot)) {
958 run_active_slot(slot);
959 if (results.curl_result == CURLE_OK)
960 rc = 1;
961 else
962 fprintf(stderr, "UNLOCK HTTP error %ld\n",
963 results.http_code);
964 } else {
965 fprintf(stderr, "Unable to start UNLOCK request\n");
968 curl_slist_free_all(dav_headers);
970 if (repo->locks == lock) {
971 repo->locks = lock->next;
972 } else {
973 while (prev && prev->next != lock)
974 prev = prev->next;
975 if (prev)
976 prev->next = prev->next->next;
979 free(lock->owner);
980 free(lock->url);
981 free(lock->token);
982 free(lock);
984 return rc;
987 static void remove_locks(void)
989 struct remote_lock *lock = repo->locks;
991 fprintf(stderr, "Removing remote locks...\n");
992 while (lock) {
993 struct remote_lock *next = lock->next;
994 unlock_remote(lock);
995 lock = next;
999 static void remove_locks_on_signal(int signo)
1001 remove_locks();
1002 sigchain_pop(signo);
1003 raise(signo);
1006 static void remote_ls(const char *path, int flags,
1007 void (*userFunc)(struct remote_ls_ctx *ls),
1008 void *userData);
1010 /* extract hex from sharded "xx/x{38}" filename */
1011 static int get_oid_hex_from_objpath(const char *path, struct object_id *oid)
1013 if (strlen(path) != GIT_SHA1_HEXSZ + 1)
1014 return -1;
1016 if (hex_to_bytes(oid->hash, path, 1))
1017 return -1;
1018 path += 2;
1019 path++; /* skip '/' */
1021 return hex_to_bytes(oid->hash + 1, path, GIT_SHA1_RAWSZ - 1);
1024 static void process_ls_object(struct remote_ls_ctx *ls)
1026 unsigned int *parent = (unsigned int *)ls->userData;
1027 const char *path = ls->dentry_name;
1028 struct object_id oid;
1030 if (!strcmp(ls->path, ls->dentry_name) && (ls->flags & IS_DIR)) {
1031 remote_dir_exists[*parent] = 1;
1032 return;
1035 if (!skip_prefix(path, "objects/", &path) ||
1036 get_oid_hex_from_objpath(path, &oid))
1037 return;
1039 one_remote_object(&oid);
1042 static void process_ls_ref(struct remote_ls_ctx *ls)
1044 if (!strcmp(ls->path, ls->dentry_name) && (ls->dentry_flags & IS_DIR)) {
1045 fprintf(stderr, " %s\n", ls->dentry_name);
1046 return;
1049 if (!(ls->dentry_flags & IS_DIR))
1050 one_remote_ref(ls->dentry_name);
1053 static void handle_remote_ls_ctx(struct xml_ctx *ctx, int tag_closed)
1055 struct remote_ls_ctx *ls = (struct remote_ls_ctx *)ctx->userData;
1057 if (tag_closed) {
1058 if (!strcmp(ctx->name, DAV_PROPFIND_RESP) && ls->dentry_name) {
1059 if (ls->dentry_flags & IS_DIR) {
1061 /* ensure collection names end with slash */
1062 str_end_url_with_slash(ls->dentry_name, &ls->dentry_name);
1064 if (ls->flags & PROCESS_DIRS) {
1065 ls->userFunc(ls);
1067 if (strcmp(ls->dentry_name, ls->path) &&
1068 ls->flags & RECURSIVE) {
1069 remote_ls(ls->dentry_name,
1070 ls->flags,
1071 ls->userFunc,
1072 ls->userData);
1074 } else if (ls->flags & PROCESS_FILES) {
1075 ls->userFunc(ls);
1077 } else if (!strcmp(ctx->name, DAV_PROPFIND_NAME) && ctx->cdata) {
1078 char *path = ctx->cdata;
1079 if (*ctx->cdata == 'h') {
1080 path = strstr(path, "//");
1081 if (path) {
1082 path = strchr(path+2, '/');
1085 if (path) {
1086 const char *url = repo->url;
1087 if (repo->path)
1088 url = repo->path;
1089 if (strncmp(path, url, repo->path_len))
1090 error("Parsed path '%s' does not match url: '%s'",
1091 path, url);
1092 else {
1093 path += repo->path_len;
1094 ls->dentry_name = xstrdup(path);
1097 } else if (!strcmp(ctx->name, DAV_PROPFIND_COLLECTION)) {
1098 ls->dentry_flags |= IS_DIR;
1100 } else if (!strcmp(ctx->name, DAV_PROPFIND_RESP)) {
1101 FREE_AND_NULL(ls->dentry_name);
1102 ls->dentry_flags = 0;
1107 * NEEDSWORK: remote_ls() ignores info/refs on the remote side. But it
1108 * should _only_ heed the information from that file, instead of trying to
1109 * determine the refs from the remote file system (badly: it does not even
1110 * know about packed-refs).
1112 static void remote_ls(const char *path, int flags,
1113 void (*userFunc)(struct remote_ls_ctx *ls),
1114 void *userData)
1116 char *url = xstrfmt("%s%s", repo->url, path);
1117 struct active_request_slot *slot;
1118 struct slot_results results;
1119 struct strbuf in_buffer = STRBUF_INIT;
1120 struct buffer out_buffer = { STRBUF_INIT, 0 };
1121 struct curl_slist *dav_headers = http_copy_default_headers();
1122 struct xml_ctx ctx;
1123 struct remote_ls_ctx ls;
1125 ls.flags = flags;
1126 ls.path = xstrdup(path);
1127 ls.dentry_name = NULL;
1128 ls.dentry_flags = 0;
1129 ls.userData = userData;
1130 ls.userFunc = userFunc;
1132 strbuf_addstr(&out_buffer.buf, PROPFIND_ALL_REQUEST);
1134 dav_headers = curl_slist_append(dav_headers, "Depth: 1");
1135 dav_headers = curl_slist_append(dav_headers, "Content-Type: text/xml");
1137 slot = get_active_slot();
1138 slot->results = &results;
1139 curl_setup_http(slot->curl, url, DAV_PROPFIND,
1140 &out_buffer, fwrite_buffer);
1141 curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, dav_headers);
1142 curl_easy_setopt(slot->curl, CURLOPT_FILE, &in_buffer);
1144 if (start_active_slot(slot)) {
1145 run_active_slot(slot);
1146 if (results.curl_result == CURLE_OK) {
1147 XML_Parser parser = XML_ParserCreate(NULL);
1148 enum XML_Status result;
1149 ctx.name = xcalloc(10, 1);
1150 ctx.len = 0;
1151 ctx.cdata = NULL;
1152 ctx.userFunc = handle_remote_ls_ctx;
1153 ctx.userData = &ls;
1154 XML_SetUserData(parser, &ctx);
1155 XML_SetElementHandler(parser, xml_start_tag,
1156 xml_end_tag);
1157 XML_SetCharacterDataHandler(parser, xml_cdata);
1158 result = XML_Parse(parser, in_buffer.buf,
1159 in_buffer.len, 1);
1160 free(ctx.name);
1162 if (result != XML_STATUS_OK) {
1163 fprintf(stderr, "XML error: %s\n",
1164 XML_ErrorString(
1165 XML_GetErrorCode(parser)));
1167 XML_ParserFree(parser);
1169 } else {
1170 fprintf(stderr, "Unable to start PROPFIND request\n");
1173 free(ls.path);
1174 free(url);
1175 strbuf_release(&out_buffer.buf);
1176 strbuf_release(&in_buffer);
1177 curl_slist_free_all(dav_headers);
1180 static void get_remote_object_list(unsigned char parent)
1182 char path[] = "objects/XX/";
1183 static const char hex[] = "0123456789abcdef";
1184 unsigned int val = parent;
1186 path[8] = hex[val >> 4];
1187 path[9] = hex[val & 0xf];
1188 remote_dir_exists[val] = 0;
1189 remote_ls(path, (PROCESS_FILES | PROCESS_DIRS),
1190 process_ls_object, &val);
1193 static int locking_available(void)
1195 struct active_request_slot *slot;
1196 struct slot_results results;
1197 struct strbuf in_buffer = STRBUF_INIT;
1198 struct buffer out_buffer = { STRBUF_INIT, 0 };
1199 struct curl_slist *dav_headers = http_copy_default_headers();
1200 struct xml_ctx ctx;
1201 int lock_flags = 0;
1202 char *escaped;
1204 escaped = xml_entities(repo->url);
1205 strbuf_addf(&out_buffer.buf, PROPFIND_SUPPORTEDLOCK_REQUEST, escaped);
1206 free(escaped);
1208 dav_headers = curl_slist_append(dav_headers, "Depth: 0");
1209 dav_headers = curl_slist_append(dav_headers, "Content-Type: text/xml");
1211 slot = get_active_slot();
1212 slot->results = &results;
1213 curl_setup_http(slot->curl, repo->url, DAV_PROPFIND,
1214 &out_buffer, fwrite_buffer);
1215 curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, dav_headers);
1216 curl_easy_setopt(slot->curl, CURLOPT_FILE, &in_buffer);
1218 if (start_active_slot(slot)) {
1219 run_active_slot(slot);
1220 if (results.curl_result == CURLE_OK) {
1221 XML_Parser parser = XML_ParserCreate(NULL);
1222 enum XML_Status result;
1223 ctx.name = xcalloc(10, 1);
1224 ctx.len = 0;
1225 ctx.cdata = NULL;
1226 ctx.userFunc = handle_lockprop_ctx;
1227 ctx.userData = &lock_flags;
1228 XML_SetUserData(parser, &ctx);
1229 XML_SetElementHandler(parser, xml_start_tag,
1230 xml_end_tag);
1231 result = XML_Parse(parser, in_buffer.buf,
1232 in_buffer.len, 1);
1233 free(ctx.name);
1235 if (result != XML_STATUS_OK) {
1236 fprintf(stderr, "XML error: %s\n",
1237 XML_ErrorString(
1238 XML_GetErrorCode(parser)));
1239 lock_flags = 0;
1241 XML_ParserFree(parser);
1242 if (!lock_flags)
1243 error("no DAV locking support on %s",
1244 repo->url);
1246 } else {
1247 error("Cannot access URL %s, return code %d",
1248 repo->url, results.curl_result);
1249 lock_flags = 0;
1251 } else {
1252 error("Unable to start PROPFIND request on %s", repo->url);
1255 strbuf_release(&out_buffer.buf);
1256 strbuf_release(&in_buffer);
1257 curl_slist_free_all(dav_headers);
1259 return lock_flags;
1262 static struct object_list **add_one_object(struct object *obj, struct object_list **p)
1264 struct object_list *entry = xmalloc(sizeof(struct object_list));
1265 entry->item = obj;
1266 entry->next = *p;
1267 *p = entry;
1268 return &entry->next;
1271 static struct object_list **process_blob(struct blob *blob,
1272 struct object_list **p)
1274 struct object *obj = &blob->object;
1276 obj->flags |= LOCAL;
1278 if (obj->flags & (UNINTERESTING | SEEN))
1279 return p;
1281 obj->flags |= SEEN;
1282 return add_one_object(obj, p);
1285 static struct object_list **process_tree(struct tree *tree,
1286 struct object_list **p)
1288 struct object *obj = &tree->object;
1289 struct tree_desc desc;
1290 struct name_entry entry;
1292 obj->flags |= LOCAL;
1294 if (obj->flags & (UNINTERESTING | SEEN))
1295 return p;
1296 if (parse_tree(tree) < 0)
1297 die("bad tree object %s", oid_to_hex(&obj->oid));
1299 obj->flags |= SEEN;
1300 p = add_one_object(obj, p);
1302 init_tree_desc(&desc, tree->buffer, tree->size);
1304 while (tree_entry(&desc, &entry))
1305 switch (object_type(entry.mode)) {
1306 case OBJ_TREE:
1307 p = process_tree(lookup_tree(entry.oid), p);
1308 break;
1309 case OBJ_BLOB:
1310 p = process_blob(lookup_blob(entry.oid), p);
1311 break;
1312 default:
1313 /* Subproject commit - not in this repository */
1314 break;
1317 free_tree_buffer(tree);
1318 return p;
1321 static int get_delta(struct rev_info *revs, struct remote_lock *lock)
1323 int i;
1324 struct commit *commit;
1325 struct object_list **p = &objects;
1326 int count = 0;
1328 while ((commit = get_revision(revs)) != NULL) {
1329 p = process_tree(commit->tree, p);
1330 commit->object.flags |= LOCAL;
1331 if (!(commit->object.flags & UNINTERESTING))
1332 count += add_send_request(&commit->object, lock);
1335 for (i = 0; i < revs->pending.nr; i++) {
1336 struct object_array_entry *entry = revs->pending.objects + i;
1337 struct object *obj = entry->item;
1338 const char *name = entry->name;
1340 if (obj->flags & (UNINTERESTING | SEEN))
1341 continue;
1342 if (obj->type == OBJ_TAG) {
1343 obj->flags |= SEEN;
1344 p = add_one_object(obj, p);
1345 continue;
1347 if (obj->type == OBJ_TREE) {
1348 p = process_tree((struct tree *)obj, p);
1349 continue;
1351 if (obj->type == OBJ_BLOB) {
1352 p = process_blob((struct blob *)obj, p);
1353 continue;
1355 die("unknown pending object %s (%s)", oid_to_hex(&obj->oid), name);
1358 while (objects) {
1359 if (!(objects->item->flags & UNINTERESTING))
1360 count += add_send_request(objects->item, lock);
1361 objects = objects->next;
1364 return count;
1367 static int update_remote(unsigned char *sha1, struct remote_lock *lock)
1369 struct active_request_slot *slot;
1370 struct slot_results results;
1371 struct buffer out_buffer = { STRBUF_INIT, 0 };
1372 struct curl_slist *dav_headers;
1374 dav_headers = get_dav_token_headers(lock, DAV_HEADER_IF);
1376 strbuf_addf(&out_buffer.buf, "%s\n", sha1_to_hex(sha1));
1378 slot = get_active_slot();
1379 slot->results = &results;
1380 curl_setup_http(slot->curl, lock->url, DAV_PUT,
1381 &out_buffer, fwrite_null);
1382 curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, dav_headers);
1384 if (start_active_slot(slot)) {
1385 run_active_slot(slot);
1386 strbuf_release(&out_buffer.buf);
1387 if (results.curl_result != CURLE_OK) {
1388 fprintf(stderr,
1389 "PUT error: curl result=%d, HTTP code=%ld\n",
1390 results.curl_result, results.http_code);
1391 /* We should attempt recovery? */
1392 return 0;
1394 } else {
1395 strbuf_release(&out_buffer.buf);
1396 fprintf(stderr, "Unable to start PUT request\n");
1397 return 0;
1400 return 1;
1403 static struct ref *remote_refs;
1405 static void one_remote_ref(const char *refname)
1407 struct ref *ref;
1408 struct object *obj;
1410 ref = alloc_ref(refname);
1412 if (http_fetch_ref(repo->url, ref) != 0) {
1413 fprintf(stderr,
1414 "Unable to fetch ref %s from %s\n",
1415 refname, repo->url);
1416 free(ref);
1417 return;
1421 * Fetch a copy of the object if it doesn't exist locally - it
1422 * may be required for updating server info later.
1424 if (repo->can_update_info_refs && !has_object_file(&ref->old_oid)) {
1425 obj = lookup_unknown_object(ref->old_oid.hash);
1426 fprintf(stderr, " fetch %s for %s\n",
1427 oid_to_hex(&ref->old_oid), refname);
1428 add_fetch_request(obj);
1431 ref->next = remote_refs;
1432 remote_refs = ref;
1435 static void get_dav_remote_heads(void)
1437 remote_ls("refs/", (PROCESS_FILES | PROCESS_DIRS | RECURSIVE), process_ls_ref, NULL);
1440 static void add_remote_info_ref(struct remote_ls_ctx *ls)
1442 struct strbuf *buf = (struct strbuf *)ls->userData;
1443 struct object *o;
1444 struct ref *ref;
1446 ref = alloc_ref(ls->dentry_name);
1448 if (http_fetch_ref(repo->url, ref) != 0) {
1449 fprintf(stderr,
1450 "Unable to fetch ref %s from %s\n",
1451 ls->dentry_name, repo->url);
1452 aborted = 1;
1453 free(ref);
1454 return;
1457 o = parse_object(&ref->old_oid);
1458 if (!o) {
1459 fprintf(stderr,
1460 "Unable to parse object %s for remote ref %s\n",
1461 oid_to_hex(&ref->old_oid), ls->dentry_name);
1462 aborted = 1;
1463 free(ref);
1464 return;
1467 strbuf_addf(buf, "%s\t%s\n",
1468 oid_to_hex(&ref->old_oid), ls->dentry_name);
1470 if (o->type == OBJ_TAG) {
1471 o = deref_tag(o, ls->dentry_name, 0);
1472 if (o)
1473 strbuf_addf(buf, "%s\t%s^{}\n",
1474 oid_to_hex(&o->oid), ls->dentry_name);
1476 free(ref);
1479 static void update_remote_info_refs(struct remote_lock *lock)
1481 struct buffer buffer = { STRBUF_INIT, 0 };
1482 struct active_request_slot *slot;
1483 struct slot_results results;
1484 struct curl_slist *dav_headers;
1486 remote_ls("refs/", (PROCESS_FILES | RECURSIVE),
1487 add_remote_info_ref, &buffer.buf);
1488 if (!aborted) {
1489 dav_headers = get_dav_token_headers(lock, DAV_HEADER_IF);
1491 slot = get_active_slot();
1492 slot->results = &results;
1493 curl_setup_http(slot->curl, lock->url, DAV_PUT,
1494 &buffer, fwrite_null);
1495 curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, dav_headers);
1497 if (start_active_slot(slot)) {
1498 run_active_slot(slot);
1499 if (results.curl_result != CURLE_OK) {
1500 fprintf(stderr,
1501 "PUT error: curl result=%d, HTTP code=%ld\n",
1502 results.curl_result, results.http_code);
1506 strbuf_release(&buffer.buf);
1509 static int remote_exists(const char *path)
1511 char *url = xstrfmt("%s%s", repo->url, path);
1512 int ret;
1515 switch (http_get_strbuf(url, NULL, NULL)) {
1516 case HTTP_OK:
1517 ret = 1;
1518 break;
1519 case HTTP_MISSING_TARGET:
1520 ret = 0;
1521 break;
1522 case HTTP_ERROR:
1523 error("unable to access '%s': %s", url, curl_errorstr);
1524 /* fallthrough */
1525 default:
1526 ret = -1;
1528 free(url);
1529 return ret;
1532 static void fetch_symref(const char *path, char **symref, struct object_id *oid)
1534 char *url = xstrfmt("%s%s", repo->url, path);
1535 struct strbuf buffer = STRBUF_INIT;
1536 const char *name;
1538 if (http_get_strbuf(url, &buffer, NULL) != HTTP_OK)
1539 die("Couldn't get %s for remote symref\n%s", url,
1540 curl_errorstr);
1541 free(url);
1543 FREE_AND_NULL(*symref);
1544 oidclr(oid);
1546 if (buffer.len == 0)
1547 return;
1549 /* Cut off trailing newline. */
1550 strbuf_rtrim(&buffer);
1552 /* If it's a symref, set the refname; otherwise try for a sha1 */
1553 if (skip_prefix(buffer.buf, "ref: ", &name)) {
1554 *symref = xmemdupz(name, buffer.len - (name - buffer.buf));
1555 } else {
1556 get_oid_hex(buffer.buf, oid);
1559 strbuf_release(&buffer);
1562 static int verify_merge_base(struct object_id *head_oid, struct ref *remote)
1564 struct commit *head = lookup_commit_or_die(head_oid, "HEAD");
1565 struct commit *branch = lookup_commit_or_die(&remote->old_oid,
1566 remote->name);
1568 return in_merge_bases(branch, head);
1571 static int delete_remote_branch(const char *pattern, int force)
1573 struct ref *refs = remote_refs;
1574 struct ref *remote_ref = NULL;
1575 struct object_id head_oid;
1576 char *symref = NULL;
1577 int match;
1578 int patlen = strlen(pattern);
1579 int i;
1580 struct active_request_slot *slot;
1581 struct slot_results results;
1582 char *url;
1584 /* Find the remote branch(es) matching the specified branch name */
1585 for (match = 0; refs; refs = refs->next) {
1586 char *name = refs->name;
1587 int namelen = strlen(name);
1588 if (namelen < patlen ||
1589 memcmp(name + namelen - patlen, pattern, patlen))
1590 continue;
1591 if (namelen != patlen && name[namelen - patlen - 1] != '/')
1592 continue;
1593 match++;
1594 remote_ref = refs;
1596 if (match == 0)
1597 return error("No remote branch matches %s", pattern);
1598 if (match != 1)
1599 return error("More than one remote branch matches %s",
1600 pattern);
1603 * Remote HEAD must be a symref (not exactly foolproof; a remote
1604 * symlink to a symref will look like a symref)
1606 fetch_symref("HEAD", &symref, &head_oid);
1607 if (!symref)
1608 return error("Remote HEAD is not a symref");
1610 /* Remote branch must not be the remote HEAD */
1611 for (i = 0; symref && i < MAXDEPTH; i++) {
1612 if (!strcmp(remote_ref->name, symref))
1613 return error("Remote branch %s is the current HEAD",
1614 remote_ref->name);
1615 fetch_symref(symref, &symref, &head_oid);
1618 /* Run extra sanity checks if delete is not forced */
1619 if (!force) {
1620 /* Remote HEAD must resolve to a known object */
1621 if (symref)
1622 return error("Remote HEAD symrefs too deep");
1623 if (is_null_oid(&head_oid))
1624 return error("Unable to resolve remote HEAD");
1625 if (!has_object_file(&head_oid))
1626 return error("Remote HEAD resolves to object %s\nwhich does not exist locally, perhaps you need to fetch?", oid_to_hex(&head_oid));
1628 /* Remote branch must resolve to a known object */
1629 if (is_null_oid(&remote_ref->old_oid))
1630 return error("Unable to resolve remote branch %s",
1631 remote_ref->name);
1632 if (!has_object_file(&remote_ref->old_oid))
1633 return error("Remote branch %s resolves to object %s\nwhich does not exist locally, perhaps you need to fetch?", remote_ref->name, oid_to_hex(&remote_ref->old_oid));
1635 /* Remote branch must be an ancestor of remote HEAD */
1636 if (!verify_merge_base(&head_oid, remote_ref)) {
1637 return error("The branch '%s' is not an ancestor "
1638 "of your current HEAD.\n"
1639 "If you are sure you want to delete it,"
1640 " run:\n\t'git http-push -D %s %s'",
1641 remote_ref->name, repo->url, pattern);
1645 /* Send delete request */
1646 fprintf(stderr, "Removing remote branch '%s'\n", remote_ref->name);
1647 if (dry_run)
1648 return 0;
1649 url = xstrfmt("%s%s", repo->url, remote_ref->name);
1650 slot = get_active_slot();
1651 slot->results = &results;
1652 curl_setup_http_get(slot->curl, url, DAV_DELETE);
1653 if (start_active_slot(slot)) {
1654 run_active_slot(slot);
1655 free(url);
1656 if (results.curl_result != CURLE_OK)
1657 return error("DELETE request failed (%d/%ld)",
1658 results.curl_result, results.http_code);
1659 } else {
1660 free(url);
1661 return error("Unable to start DELETE request");
1664 return 0;
1667 static void run_request_queue(void)
1669 #ifdef USE_CURL_MULTI
1670 is_running_queue = 1;
1671 fill_active_slots();
1672 add_fill_function(NULL, fill_active_slot);
1673 #endif
1674 do {
1675 finish_all_active_slots();
1676 #ifdef USE_CURL_MULTI
1677 fill_active_slots();
1678 #endif
1679 } while (request_queue_head && !aborted);
1681 #ifdef USE_CURL_MULTI
1682 is_running_queue = 0;
1683 #endif
1686 int cmd_main(int argc, const char **argv)
1688 struct transfer_request *request;
1689 struct transfer_request *next_request;
1690 int nr_refspec = 0;
1691 const char **refspec = NULL;
1692 struct remote_lock *ref_lock = NULL;
1693 struct remote_lock *info_ref_lock = NULL;
1694 struct rev_info revs;
1695 int delete_branch = 0;
1696 int force_delete = 0;
1697 int objects_to_send;
1698 int rc = 0;
1699 int i;
1700 int new_refs;
1701 struct ref *ref, *local_refs;
1703 repo = xcalloc(1, sizeof(*repo));
1705 argv++;
1706 for (i = 1; i < argc; i++, argv++) {
1707 const char *arg = *argv;
1709 if (*arg == '-') {
1710 if (!strcmp(arg, "--all")) {
1711 push_all = MATCH_REFS_ALL;
1712 continue;
1714 if (!strcmp(arg, "--force")) {
1715 force_all = 1;
1716 continue;
1718 if (!strcmp(arg, "--dry-run")) {
1719 dry_run = 1;
1720 continue;
1722 if (!strcmp(arg, "--helper-status")) {
1723 helper_status = 1;
1724 continue;
1726 if (!strcmp(arg, "--verbose")) {
1727 push_verbosely = 1;
1728 http_is_verbose = 1;
1729 continue;
1731 if (!strcmp(arg, "-d")) {
1732 delete_branch = 1;
1733 continue;
1735 if (!strcmp(arg, "-D")) {
1736 delete_branch = 1;
1737 force_delete = 1;
1738 continue;
1740 if (!strcmp(arg, "-h"))
1741 usage(http_push_usage);
1743 if (!repo->url) {
1744 char *path = strstr(arg, "//");
1745 str_end_url_with_slash(arg, &repo->url);
1746 repo->path_len = strlen(repo->url);
1747 if (path) {
1748 repo->path = strchr(path+2, '/');
1749 if (repo->path)
1750 repo->path_len = strlen(repo->path);
1752 continue;
1754 refspec = argv;
1755 nr_refspec = argc - i;
1756 break;
1759 #ifndef USE_CURL_MULTI
1760 die("git-push is not available for http/https repository when not compiled with USE_CURL_MULTI");
1761 #endif
1763 if (!repo->url)
1764 usage(http_push_usage);
1766 if (delete_branch && nr_refspec != 1)
1767 die("You must specify only one branch name when deleting a remote branch");
1769 setup_git_directory();
1771 memset(remote_dir_exists, -1, 256);
1773 http_init(NULL, repo->url, 1);
1775 #ifdef USE_CURL_MULTI
1776 is_running_queue = 0;
1777 #endif
1779 /* Verify DAV compliance/lock support */
1780 if (!locking_available()) {
1781 rc = 1;
1782 goto cleanup;
1785 sigchain_push_common(remove_locks_on_signal);
1787 /* Check whether the remote has server info files */
1788 repo->can_update_info_refs = 0;
1789 repo->has_info_refs = remote_exists("info/refs");
1790 repo->has_info_packs = remote_exists("objects/info/packs");
1791 if (repo->has_info_refs) {
1792 info_ref_lock = lock_remote("info/refs", LOCK_TIME);
1793 if (info_ref_lock)
1794 repo->can_update_info_refs = 1;
1795 else {
1796 error("cannot lock existing info/refs");
1797 rc = 1;
1798 goto cleanup;
1801 if (repo->has_info_packs)
1802 fetch_indices();
1804 /* Get a list of all local and remote heads to validate refspecs */
1805 local_refs = get_local_heads();
1806 fprintf(stderr, "Fetching remote heads...\n");
1807 get_dav_remote_heads();
1808 run_request_queue();
1810 /* Remove a remote branch if -d or -D was specified */
1811 if (delete_branch) {
1812 if (delete_remote_branch(refspec[0], force_delete) == -1) {
1813 fprintf(stderr, "Unable to delete remote branch %s\n",
1814 refspec[0]);
1815 if (helper_status)
1816 printf("error %s cannot remove\n", refspec[0]);
1818 goto cleanup;
1821 /* match them up */
1822 if (match_push_refs(local_refs, &remote_refs,
1823 nr_refspec, (const char **) refspec, push_all)) {
1824 rc = -1;
1825 goto cleanup;
1827 if (!remote_refs) {
1828 fprintf(stderr, "No refs in common and none specified; doing nothing.\n");
1829 if (helper_status)
1830 printf("error null no match\n");
1831 rc = 0;
1832 goto cleanup;
1835 new_refs = 0;
1836 for (ref = remote_refs; ref; ref = ref->next) {
1837 struct argv_array commit_argv = ARGV_ARRAY_INIT;
1839 if (!ref->peer_ref)
1840 continue;
1842 if (is_null_oid(&ref->peer_ref->new_oid)) {
1843 if (delete_remote_branch(ref->name, 1) == -1) {
1844 error("Could not remove %s", ref->name);
1845 if (helper_status)
1846 printf("error %s cannot remove\n", ref->name);
1847 rc = -4;
1849 else if (helper_status)
1850 printf("ok %s\n", ref->name);
1851 new_refs++;
1852 continue;
1855 if (!oidcmp(&ref->old_oid, &ref->peer_ref->new_oid)) {
1856 if (push_verbosely)
1857 fprintf(stderr, "'%s': up-to-date\n", ref->name);
1858 if (helper_status)
1859 printf("ok %s up to date\n", ref->name);
1860 continue;
1863 if (!force_all &&
1864 !is_null_oid(&ref->old_oid) &&
1865 !ref->force) {
1866 if (!has_object_file(&ref->old_oid) ||
1867 !ref_newer(&ref->peer_ref->new_oid,
1868 &ref->old_oid)) {
1870 * We do not have the remote ref, or
1871 * we know that the remote ref is not
1872 * an ancestor of what we are trying to
1873 * push. Either way this can be losing
1874 * commits at the remote end and likely
1875 * we were not up to date to begin with.
1877 error("remote '%s' is not an ancestor of\n"
1878 "local '%s'.\n"
1879 "Maybe you are not up-to-date and "
1880 "need to pull first?",
1881 ref->name,
1882 ref->peer_ref->name);
1883 if (helper_status)
1884 printf("error %s non-fast forward\n", ref->name);
1885 rc = -2;
1886 continue;
1889 oidcpy(&ref->new_oid, &ref->peer_ref->new_oid);
1890 new_refs++;
1892 fprintf(stderr, "updating '%s'", ref->name);
1893 if (strcmp(ref->name, ref->peer_ref->name))
1894 fprintf(stderr, " using '%s'", ref->peer_ref->name);
1895 fprintf(stderr, "\n from %s\n to %s\n",
1896 oid_to_hex(&ref->old_oid), oid_to_hex(&ref->new_oid));
1897 if (dry_run) {
1898 if (helper_status)
1899 printf("ok %s\n", ref->name);
1900 continue;
1903 /* Lock remote branch ref */
1904 ref_lock = lock_remote(ref->name, LOCK_TIME);
1905 if (ref_lock == NULL) {
1906 fprintf(stderr, "Unable to lock remote branch %s\n",
1907 ref->name);
1908 if (helper_status)
1909 printf("error %s lock error\n", ref->name);
1910 rc = 1;
1911 continue;
1914 /* Set up revision info for this refspec */
1915 argv_array_push(&commit_argv, ""); /* ignored */
1916 argv_array_push(&commit_argv, "--objects");
1917 argv_array_push(&commit_argv, oid_to_hex(&ref->new_oid));
1918 if (!push_all && !is_null_oid(&ref->old_oid))
1919 argv_array_pushf(&commit_argv, "^%s",
1920 oid_to_hex(&ref->old_oid));
1921 init_revisions(&revs, setup_git_directory());
1922 setup_revisions(commit_argv.argc, commit_argv.argv, &revs, NULL);
1923 revs.edge_hint = 0; /* just in case */
1925 /* Generate a list of objects that need to be pushed */
1926 pushing = 0;
1927 if (prepare_revision_walk(&revs))
1928 die("revision walk setup failed");
1929 mark_edges_uninteresting(&revs, NULL);
1930 objects_to_send = get_delta(&revs, ref_lock);
1931 finish_all_active_slots();
1933 /* Push missing objects to remote, this would be a
1934 convenient time to pack them first if appropriate. */
1935 pushing = 1;
1936 if (objects_to_send)
1937 fprintf(stderr, " sending %d objects\n",
1938 objects_to_send);
1940 run_request_queue();
1942 /* Update the remote branch if all went well */
1943 if (aborted || !update_remote(ref->new_oid.hash, ref_lock))
1944 rc = 1;
1946 if (!rc)
1947 fprintf(stderr, " done\n");
1948 if (helper_status)
1949 printf("%s %s\n", !rc ? "ok" : "error", ref->name);
1950 unlock_remote(ref_lock);
1951 check_locks();
1952 argv_array_clear(&commit_argv);
1955 /* Update remote server info if appropriate */
1956 if (repo->has_info_refs && new_refs) {
1957 if (info_ref_lock && repo->can_update_info_refs) {
1958 fprintf(stderr, "Updating remote server info\n");
1959 if (!dry_run)
1960 update_remote_info_refs(info_ref_lock);
1961 } else {
1962 fprintf(stderr, "Unable to update server info\n");
1966 cleanup:
1967 if (info_ref_lock)
1968 unlock_remote(info_ref_lock);
1969 free(repo);
1971 http_cleanup();
1973 request = request_queue_head;
1974 while (request != NULL) {
1975 next_request = request->next;
1976 release_request(request);
1977 request = next_request;
1980 return rc;