Merge branch 'en/merge-recursive-tests'
[git.git] / http-push.c
blob7e38522098bf91c144adaee7f9f5476f8bc72cd2
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"
15 #include "object-store.h"
17 #ifdef EXPAT_NEEDS_XMLPARSE_H
18 #include <xmlparse.h>
19 #else
20 #include <expat.h>
21 #endif
23 static const char http_push_usage[] =
24 "git http-push [--all] [--dry-run] [--force] [--verbose] <remote> [<head>...]\n";
26 #ifndef XML_STATUS_OK
27 enum XML_Status {
28 XML_STATUS_OK = 1,
29 XML_STATUS_ERROR = 0
31 #define XML_STATUS_OK 1
32 #define XML_STATUS_ERROR 0
33 #endif
35 #define PREV_BUF_SIZE 4096
37 /* DAV methods */
38 #define DAV_LOCK "LOCK"
39 #define DAV_MKCOL "MKCOL"
40 #define DAV_MOVE "MOVE"
41 #define DAV_PROPFIND "PROPFIND"
42 #define DAV_PUT "PUT"
43 #define DAV_UNLOCK "UNLOCK"
44 #define DAV_DELETE "DELETE"
46 /* DAV lock flags */
47 #define DAV_PROP_LOCKWR (1u << 0)
48 #define DAV_PROP_LOCKEX (1u << 1)
49 #define DAV_LOCK_OK (1u << 2)
51 /* DAV XML properties */
52 #define DAV_CTX_LOCKENTRY ".multistatus.response.propstat.prop.supportedlock.lockentry"
53 #define DAV_CTX_LOCKTYPE_WRITE ".multistatus.response.propstat.prop.supportedlock.lockentry.locktype.write"
54 #define DAV_CTX_LOCKTYPE_EXCLUSIVE ".multistatus.response.propstat.prop.supportedlock.lockentry.lockscope.exclusive"
55 #define DAV_ACTIVELOCK_OWNER ".prop.lockdiscovery.activelock.owner.href"
56 #define DAV_ACTIVELOCK_TIMEOUT ".prop.lockdiscovery.activelock.timeout"
57 #define DAV_ACTIVELOCK_TOKEN ".prop.lockdiscovery.activelock.locktoken.href"
58 #define DAV_PROPFIND_RESP ".multistatus.response"
59 #define DAV_PROPFIND_NAME ".multistatus.response.href"
60 #define DAV_PROPFIND_COLLECTION ".multistatus.response.propstat.prop.resourcetype.collection"
62 /* DAV request body templates */
63 #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>"
64 #define PROPFIND_ALL_REQUEST "<?xml version=\"1.0\" encoding=\"utf-8\" ?>\n<D:propfind xmlns:D=\"DAV:\">\n<D:allprop/>\n</D:propfind>"
65 #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>"
67 #define LOCK_TIME 600
68 #define LOCK_REFRESH 30
70 /* Remember to update object flag allocation in object.h */
71 #define LOCAL (1u<<16)
72 #define REMOTE (1u<<17)
73 #define FETCHING (1u<<18)
74 #define PUSHING (1u<<19)
76 /* We allow "recursive" symbolic refs. Only within reason, though */
77 #define MAXDEPTH 5
79 static int pushing;
80 static int aborted;
81 static signed char remote_dir_exists[256];
83 static int push_verbosely;
84 static int push_all = MATCH_REFS_NONE;
85 static int force_all;
86 static int dry_run;
87 static int helper_status;
89 static struct object_list *objects;
91 struct repo {
92 char *url;
93 char *path;
94 int path_len;
95 int has_info_refs;
96 int can_update_info_refs;
97 int has_info_packs;
98 struct packed_git *packs;
99 struct remote_lock *locks;
102 static struct repo *repo;
104 enum transfer_state {
105 NEED_FETCH,
106 RUN_FETCH_LOOSE,
107 RUN_FETCH_PACKED,
108 NEED_PUSH,
109 RUN_MKCOL,
110 RUN_PUT,
111 RUN_MOVE,
112 ABORTED,
113 COMPLETE
116 struct transfer_request {
117 struct object *obj;
118 char *url;
119 char *dest;
120 struct remote_lock *lock;
121 struct curl_slist *headers;
122 struct buffer buffer;
123 enum transfer_state state;
124 CURLcode curl_result;
125 char errorstr[CURL_ERROR_SIZE];
126 long http_code;
127 void *userData;
128 struct active_request_slot *slot;
129 struct transfer_request *next;
132 static struct transfer_request *request_queue_head;
134 struct xml_ctx {
135 char *name;
136 int len;
137 char *cdata;
138 void (*userFunc)(struct xml_ctx *ctx, int tag_closed);
139 void *userData;
142 struct remote_lock {
143 char *url;
144 char *owner;
145 char *token;
146 char tmpfile_suffix[41];
147 time_t start_time;
148 long timeout;
149 int refreshing;
150 struct remote_lock *next;
153 /* Flags that control remote_ls processing */
154 #define PROCESS_FILES (1u << 0)
155 #define PROCESS_DIRS (1u << 1)
156 #define RECURSIVE (1u << 2)
158 /* Flags that remote_ls passes to callback functions */
159 #define IS_DIR (1u << 0)
161 struct remote_ls_ctx {
162 char *path;
163 void (*userFunc)(struct remote_ls_ctx *ls);
164 void *userData;
165 int flags;
166 char *dentry_name;
167 int dentry_flags;
168 struct remote_ls_ctx *parent;
171 /* get_dav_token_headers options */
172 enum dav_header_flag {
173 DAV_HEADER_IF = (1u << 0),
174 DAV_HEADER_LOCK = (1u << 1),
175 DAV_HEADER_TIMEOUT = (1u << 2)
178 static char *xml_entities(const char *s)
180 struct strbuf buf = STRBUF_INIT;
181 strbuf_addstr_xml_quoted(&buf, s);
182 return strbuf_detach(&buf, NULL);
185 static void curl_setup_http_get(CURL *curl, const char *url,
186 const char *custom_req)
188 curl_easy_setopt(curl, CURLOPT_HTTPGET, 1);
189 curl_easy_setopt(curl, CURLOPT_URL, url);
190 curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, custom_req);
191 curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, fwrite_null);
194 static void curl_setup_http(CURL *curl, const char *url,
195 const char *custom_req, struct buffer *buffer,
196 curl_write_callback write_fn)
198 curl_easy_setopt(curl, CURLOPT_PUT, 1);
199 curl_easy_setopt(curl, CURLOPT_URL, url);
200 curl_easy_setopt(curl, CURLOPT_INFILE, buffer);
201 curl_easy_setopt(curl, CURLOPT_INFILESIZE, buffer->buf.len);
202 curl_easy_setopt(curl, CURLOPT_READFUNCTION, fread_buffer);
203 #ifndef NO_CURL_IOCTL
204 curl_easy_setopt(curl, CURLOPT_IOCTLFUNCTION, ioctl_buffer);
205 curl_easy_setopt(curl, CURLOPT_IOCTLDATA, buffer);
206 #endif
207 curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_fn);
208 curl_easy_setopt(curl, CURLOPT_NOBODY, 0);
209 curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, custom_req);
210 curl_easy_setopt(curl, CURLOPT_UPLOAD, 1);
213 static struct curl_slist *get_dav_token_headers(struct remote_lock *lock, enum dav_header_flag options)
215 struct strbuf buf = STRBUF_INIT;
216 struct curl_slist *dav_headers = http_copy_default_headers();
218 if (options & DAV_HEADER_IF) {
219 strbuf_addf(&buf, "If: (<%s>)", lock->token);
220 dav_headers = curl_slist_append(dav_headers, buf.buf);
221 strbuf_reset(&buf);
223 if (options & DAV_HEADER_LOCK) {
224 strbuf_addf(&buf, "Lock-Token: <%s>", lock->token);
225 dav_headers = curl_slist_append(dav_headers, buf.buf);
226 strbuf_reset(&buf);
228 if (options & DAV_HEADER_TIMEOUT) {
229 strbuf_addf(&buf, "Timeout: Second-%ld", lock->timeout);
230 dav_headers = curl_slist_append(dav_headers, buf.buf);
231 strbuf_reset(&buf);
233 strbuf_release(&buf);
235 return dav_headers;
238 static void finish_request(struct transfer_request *request);
239 static void release_request(struct transfer_request *request);
241 static void process_response(void *callback_data)
243 struct transfer_request *request =
244 (struct transfer_request *)callback_data;
246 finish_request(request);
249 #ifdef USE_CURL_MULTI
251 static void start_fetch_loose(struct transfer_request *request)
253 struct active_request_slot *slot;
254 struct http_object_request *obj_req;
256 obj_req = new_http_object_request(repo->url, request->obj->oid.hash);
257 if (obj_req == NULL) {
258 request->state = ABORTED;
259 return;
262 slot = obj_req->slot;
263 slot->callback_func = process_response;
264 slot->callback_data = request;
265 request->slot = slot;
266 request->userData = obj_req;
268 /* Try to get the request started, abort the request on error */
269 request->state = RUN_FETCH_LOOSE;
270 if (!start_active_slot(slot)) {
271 fprintf(stderr, "Unable to start GET request\n");
272 repo->can_update_info_refs = 0;
273 release_http_object_request(obj_req);
274 release_request(request);
278 static void start_mkcol(struct transfer_request *request)
280 char *hex = oid_to_hex(&request->obj->oid);
281 struct active_request_slot *slot;
283 request->url = get_remote_object_url(repo->url, hex, 1);
285 slot = get_active_slot();
286 slot->callback_func = process_response;
287 slot->callback_data = request;
288 curl_setup_http_get(slot->curl, request->url, DAV_MKCOL);
289 curl_easy_setopt(slot->curl, CURLOPT_ERRORBUFFER, request->errorstr);
291 if (start_active_slot(slot)) {
292 request->slot = slot;
293 request->state = RUN_MKCOL;
294 } else {
295 request->state = ABORTED;
296 FREE_AND_NULL(request->url);
299 #endif
301 static void start_fetch_packed(struct transfer_request *request)
303 struct packed_git *target;
305 struct transfer_request *check_request = request_queue_head;
306 struct http_pack_request *preq;
308 target = find_sha1_pack(request->obj->oid.hash, repo->packs);
309 if (!target) {
310 fprintf(stderr, "Unable to fetch %s, will not be able to update server info refs\n", oid_to_hex(&request->obj->oid));
311 repo->can_update_info_refs = 0;
312 release_request(request);
313 return;
316 fprintf(stderr, "Fetching pack %s\n", sha1_to_hex(target->sha1));
317 fprintf(stderr, " which contains %s\n", oid_to_hex(&request->obj->oid));
319 preq = new_http_pack_request(target, repo->url);
320 if (preq == NULL) {
321 repo->can_update_info_refs = 0;
322 return;
324 preq->lst = &repo->packs;
326 /* Make sure there isn't another open request for this pack */
327 while (check_request) {
328 if (check_request->state == RUN_FETCH_PACKED &&
329 !strcmp(check_request->url, preq->url)) {
330 release_http_pack_request(preq);
331 release_request(request);
332 return;
334 check_request = check_request->next;
337 preq->slot->callback_func = process_response;
338 preq->slot->callback_data = request;
339 request->slot = preq->slot;
340 request->userData = preq;
342 /* Try to get the request started, abort the request on error */
343 request->state = RUN_FETCH_PACKED;
344 if (!start_active_slot(preq->slot)) {
345 fprintf(stderr, "Unable to start GET request\n");
346 release_http_pack_request(preq);
347 repo->can_update_info_refs = 0;
348 release_request(request);
352 static void start_put(struct transfer_request *request)
354 char *hex = oid_to_hex(&request->obj->oid);
355 struct active_request_slot *slot;
356 struct strbuf buf = STRBUF_INIT;
357 enum object_type type;
358 char hdr[50];
359 void *unpacked;
360 unsigned long len;
361 int hdrlen;
362 ssize_t size;
363 git_zstream stream;
365 unpacked = read_object_file(&request->obj->oid, &type, &len);
366 hdrlen = xsnprintf(hdr, sizeof(hdr), "%s %lu", type_name(type), len) + 1;
368 /* Set it up */
369 git_deflate_init(&stream, zlib_compression_level);
370 size = git_deflate_bound(&stream, len + hdrlen);
371 strbuf_init(&request->buffer.buf, size);
372 request->buffer.posn = 0;
374 /* Compress it */
375 stream.next_out = (unsigned char *)request->buffer.buf.buf;
376 stream.avail_out = size;
378 /* First header.. */
379 stream.next_in = (void *)hdr;
380 stream.avail_in = hdrlen;
381 while (git_deflate(&stream, 0) == Z_OK)
382 ; /* nothing */
384 /* Then the data itself.. */
385 stream.next_in = unpacked;
386 stream.avail_in = len;
387 while (git_deflate(&stream, Z_FINISH) == Z_OK)
388 ; /* nothing */
389 git_deflate_end(&stream);
390 free(unpacked);
392 request->buffer.buf.len = stream.total_out;
394 strbuf_addstr(&buf, "Destination: ");
395 append_remote_object_url(&buf, repo->url, hex, 0);
396 request->dest = strbuf_detach(&buf, NULL);
398 append_remote_object_url(&buf, repo->url, hex, 0);
399 strbuf_add(&buf, request->lock->tmpfile_suffix, 41);
400 request->url = strbuf_detach(&buf, NULL);
402 slot = get_active_slot();
403 slot->callback_func = process_response;
404 slot->callback_data = request;
405 curl_setup_http(slot->curl, request->url, DAV_PUT,
406 &request->buffer, fwrite_null);
408 if (start_active_slot(slot)) {
409 request->slot = slot;
410 request->state = RUN_PUT;
411 } else {
412 request->state = ABORTED;
413 FREE_AND_NULL(request->url);
417 static void start_move(struct transfer_request *request)
419 struct active_request_slot *slot;
420 struct curl_slist *dav_headers = http_copy_default_headers();
422 slot = get_active_slot();
423 slot->callback_func = process_response;
424 slot->callback_data = request;
425 curl_setup_http_get(slot->curl, request->url, DAV_MOVE);
426 dav_headers = curl_slist_append(dav_headers, request->dest);
427 dav_headers = curl_slist_append(dav_headers, "Overwrite: T");
428 curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, dav_headers);
430 if (start_active_slot(slot)) {
431 request->slot = slot;
432 request->state = RUN_MOVE;
433 } else {
434 request->state = ABORTED;
435 FREE_AND_NULL(request->url);
439 static int refresh_lock(struct remote_lock *lock)
441 struct active_request_slot *slot;
442 struct slot_results results;
443 struct curl_slist *dav_headers;
444 int rc = 0;
446 lock->refreshing = 1;
448 dav_headers = get_dav_token_headers(lock, DAV_HEADER_IF | DAV_HEADER_TIMEOUT);
450 slot = get_active_slot();
451 slot->results = &results;
452 curl_setup_http_get(slot->curl, lock->url, DAV_LOCK);
453 curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, dav_headers);
455 if (start_active_slot(slot)) {
456 run_active_slot(slot);
457 if (results.curl_result != CURLE_OK) {
458 fprintf(stderr, "LOCK HTTP error %ld\n",
459 results.http_code);
460 } else {
461 lock->start_time = time(NULL);
462 rc = 1;
466 lock->refreshing = 0;
467 curl_slist_free_all(dav_headers);
469 return rc;
472 static void check_locks(void)
474 struct remote_lock *lock = repo->locks;
475 time_t current_time = time(NULL);
476 int time_remaining;
478 while (lock) {
479 time_remaining = lock->start_time + lock->timeout -
480 current_time;
481 if (!lock->refreshing && time_remaining < LOCK_REFRESH) {
482 if (!refresh_lock(lock)) {
483 fprintf(stderr,
484 "Unable to refresh lock for %s\n",
485 lock->url);
486 aborted = 1;
487 return;
490 lock = lock->next;
494 static void release_request(struct transfer_request *request)
496 struct transfer_request *entry = request_queue_head;
498 if (request == request_queue_head) {
499 request_queue_head = request->next;
500 } else {
501 while (entry->next != NULL && entry->next != request)
502 entry = entry->next;
503 if (entry->next == request)
504 entry->next = entry->next->next;
507 free(request->url);
508 free(request);
511 static void finish_request(struct transfer_request *request)
513 struct http_pack_request *preq;
514 struct http_object_request *obj_req;
516 request->curl_result = request->slot->curl_result;
517 request->http_code = request->slot->http_code;
518 request->slot = NULL;
520 /* Keep locks active */
521 check_locks();
523 if (request->headers != NULL)
524 curl_slist_free_all(request->headers);
526 /* URL is reused for MOVE after PUT */
527 if (request->state != RUN_PUT) {
528 FREE_AND_NULL(request->url);
531 if (request->state == RUN_MKCOL) {
532 if (request->curl_result == CURLE_OK ||
533 request->http_code == 405) {
534 remote_dir_exists[request->obj->oid.hash[0]] = 1;
535 start_put(request);
536 } else {
537 fprintf(stderr, "MKCOL %s failed, aborting (%d/%ld)\n",
538 oid_to_hex(&request->obj->oid),
539 request->curl_result, request->http_code);
540 request->state = ABORTED;
541 aborted = 1;
543 } else if (request->state == RUN_PUT) {
544 if (request->curl_result == CURLE_OK) {
545 start_move(request);
546 } else {
547 fprintf(stderr, "PUT %s failed, aborting (%d/%ld)\n",
548 oid_to_hex(&request->obj->oid),
549 request->curl_result, request->http_code);
550 request->state = ABORTED;
551 aborted = 1;
553 } else if (request->state == RUN_MOVE) {
554 if (request->curl_result == CURLE_OK) {
555 if (push_verbosely)
556 fprintf(stderr, " sent %s\n",
557 oid_to_hex(&request->obj->oid));
558 request->obj->flags |= REMOTE;
559 release_request(request);
560 } else {
561 fprintf(stderr, "MOVE %s failed, aborting (%d/%ld)\n",
562 oid_to_hex(&request->obj->oid),
563 request->curl_result, request->http_code);
564 request->state = ABORTED;
565 aborted = 1;
567 } else if (request->state == RUN_FETCH_LOOSE) {
568 obj_req = (struct http_object_request *)request->userData;
570 if (finish_http_object_request(obj_req) == 0)
571 if (obj_req->rename == 0)
572 request->obj->flags |= (LOCAL | REMOTE);
574 /* Try fetching packed if necessary */
575 if (request->obj->flags & LOCAL) {
576 release_http_object_request(obj_req);
577 release_request(request);
578 } else
579 start_fetch_packed(request);
581 } else if (request->state == RUN_FETCH_PACKED) {
582 int fail = 1;
583 if (request->curl_result != CURLE_OK) {
584 fprintf(stderr, "Unable to get pack file %s\n%s",
585 request->url, curl_errorstr);
586 } else {
587 preq = (struct http_pack_request *)request->userData;
589 if (preq) {
590 if (finish_http_pack_request(preq) == 0)
591 fail = 0;
592 release_http_pack_request(preq);
595 if (fail)
596 repo->can_update_info_refs = 0;
597 release_request(request);
601 #ifdef USE_CURL_MULTI
602 static int is_running_queue;
603 static int fill_active_slot(void *unused)
605 struct transfer_request *request;
607 if (aborted || !is_running_queue)
608 return 0;
610 for (request = request_queue_head; request; request = request->next) {
611 if (request->state == NEED_FETCH) {
612 start_fetch_loose(request);
613 return 1;
614 } else if (pushing && request->state == NEED_PUSH) {
615 if (remote_dir_exists[request->obj->oid.hash[0]] == 1) {
616 start_put(request);
617 } else {
618 start_mkcol(request);
620 return 1;
623 return 0;
625 #endif
627 static void get_remote_object_list(unsigned char parent);
629 static void add_fetch_request(struct object *obj)
631 struct transfer_request *request;
633 check_locks();
636 * Don't fetch the object if it's known to exist locally
637 * or is already in the request queue
639 if (remote_dir_exists[obj->oid.hash[0]] == -1)
640 get_remote_object_list(obj->oid.hash[0]);
641 if (obj->flags & (LOCAL | FETCHING))
642 return;
644 obj->flags |= FETCHING;
645 request = xmalloc(sizeof(*request));
646 request->obj = obj;
647 request->url = NULL;
648 request->lock = NULL;
649 request->headers = NULL;
650 request->state = NEED_FETCH;
651 request->next = request_queue_head;
652 request_queue_head = request;
654 #ifdef USE_CURL_MULTI
655 fill_active_slots();
656 step_active_slots();
657 #endif
660 static int add_send_request(struct object *obj, struct remote_lock *lock)
662 struct transfer_request *request;
663 struct packed_git *target;
665 /* Keep locks active */
666 check_locks();
669 * Don't push the object if it's known to exist on the remote
670 * or is already in the request queue
672 if (remote_dir_exists[obj->oid.hash[0]] == -1)
673 get_remote_object_list(obj->oid.hash[0]);
674 if (obj->flags & (REMOTE | PUSHING))
675 return 0;
676 target = find_sha1_pack(obj->oid.hash, repo->packs);
677 if (target) {
678 obj->flags |= REMOTE;
679 return 0;
682 obj->flags |= PUSHING;
683 request = xmalloc(sizeof(*request));
684 request->obj = obj;
685 request->url = NULL;
686 request->lock = lock;
687 request->headers = NULL;
688 request->state = NEED_PUSH;
689 request->next = request_queue_head;
690 request_queue_head = request;
692 #ifdef USE_CURL_MULTI
693 fill_active_slots();
694 step_active_slots();
695 #endif
697 return 1;
700 static int fetch_indices(void)
702 int ret;
704 if (push_verbosely)
705 fprintf(stderr, "Getting pack list\n");
707 switch (http_get_info_packs(repo->url, &repo->packs)) {
708 case HTTP_OK:
709 case HTTP_MISSING_TARGET:
710 ret = 0;
711 break;
712 default:
713 ret = -1;
716 return ret;
719 static void one_remote_object(const struct object_id *oid)
721 struct object *obj;
723 obj = lookup_object(oid->hash);
724 if (!obj)
725 obj = parse_object(oid);
727 /* Ignore remote objects that don't exist locally */
728 if (!obj)
729 return;
731 obj->flags |= REMOTE;
732 if (!object_list_contains(objects, obj))
733 object_list_insert(obj, &objects);
736 static void handle_lockprop_ctx(struct xml_ctx *ctx, int tag_closed)
738 int *lock_flags = (int *)ctx->userData;
740 if (tag_closed) {
741 if (!strcmp(ctx->name, DAV_CTX_LOCKENTRY)) {
742 if ((*lock_flags & DAV_PROP_LOCKEX) &&
743 (*lock_flags & DAV_PROP_LOCKWR)) {
744 *lock_flags |= DAV_LOCK_OK;
746 *lock_flags &= DAV_LOCK_OK;
747 } else if (!strcmp(ctx->name, DAV_CTX_LOCKTYPE_WRITE)) {
748 *lock_flags |= DAV_PROP_LOCKWR;
749 } else if (!strcmp(ctx->name, DAV_CTX_LOCKTYPE_EXCLUSIVE)) {
750 *lock_flags |= DAV_PROP_LOCKEX;
755 static void handle_new_lock_ctx(struct xml_ctx *ctx, int tag_closed)
757 struct remote_lock *lock = (struct remote_lock *)ctx->userData;
758 git_SHA_CTX sha_ctx;
759 unsigned char lock_token_sha1[20];
761 if (tag_closed && ctx->cdata) {
762 if (!strcmp(ctx->name, DAV_ACTIVELOCK_OWNER)) {
763 lock->owner = xstrdup(ctx->cdata);
764 } else if (!strcmp(ctx->name, DAV_ACTIVELOCK_TIMEOUT)) {
765 const char *arg;
766 if (skip_prefix(ctx->cdata, "Second-", &arg))
767 lock->timeout = strtol(arg, NULL, 10);
768 } else if (!strcmp(ctx->name, DAV_ACTIVELOCK_TOKEN)) {
769 lock->token = xstrdup(ctx->cdata);
771 git_SHA1_Init(&sha_ctx);
772 git_SHA1_Update(&sha_ctx, lock->token, strlen(lock->token));
773 git_SHA1_Final(lock_token_sha1, &sha_ctx);
775 lock->tmpfile_suffix[0] = '_';
776 memcpy(lock->tmpfile_suffix + 1, sha1_to_hex(lock_token_sha1), 40);
781 static void one_remote_ref(const char *refname);
783 static void
784 xml_start_tag(void *userData, const char *name, const char **atts)
786 struct xml_ctx *ctx = (struct xml_ctx *)userData;
787 const char *c = strchr(name, ':');
788 int old_namelen, new_len;
790 if (c == NULL)
791 c = name;
792 else
793 c++;
795 old_namelen = strlen(ctx->name);
796 new_len = old_namelen + strlen(c) + 2;
798 if (new_len > ctx->len) {
799 ctx->name = xrealloc(ctx->name, new_len);
800 ctx->len = new_len;
802 xsnprintf(ctx->name + old_namelen, ctx->len - old_namelen, ".%s", c);
804 FREE_AND_NULL(ctx->cdata);
806 ctx->userFunc(ctx, 0);
809 static void
810 xml_end_tag(void *userData, const char *name)
812 struct xml_ctx *ctx = (struct xml_ctx *)userData;
813 const char *c = strchr(name, ':');
814 char *ep;
816 ctx->userFunc(ctx, 1);
818 if (c == NULL)
819 c = name;
820 else
821 c++;
823 ep = ctx->name + strlen(ctx->name) - strlen(c) - 1;
824 *ep = 0;
827 static void
828 xml_cdata(void *userData, const XML_Char *s, int len)
830 struct xml_ctx *ctx = (struct xml_ctx *)userData;
831 free(ctx->cdata);
832 ctx->cdata = xmemdupz(s, len);
835 static struct remote_lock *lock_remote(const char *path, long timeout)
837 struct active_request_slot *slot;
838 struct slot_results results;
839 struct buffer out_buffer = { STRBUF_INIT, 0 };
840 struct strbuf in_buffer = STRBUF_INIT;
841 char *url;
842 char *ep;
843 char timeout_header[25];
844 struct remote_lock *lock = NULL;
845 struct curl_slist *dav_headers = http_copy_default_headers();
846 struct xml_ctx ctx;
847 char *escaped;
849 url = xstrfmt("%s%s", repo->url, path);
851 /* Make sure leading directories exist for the remote ref */
852 ep = strchr(url + strlen(repo->url) + 1, '/');
853 while (ep) {
854 char saved_character = ep[1];
855 ep[1] = '\0';
856 slot = get_active_slot();
857 slot->results = &results;
858 curl_setup_http_get(slot->curl, url, DAV_MKCOL);
859 if (start_active_slot(slot)) {
860 run_active_slot(slot);
861 if (results.curl_result != CURLE_OK &&
862 results.http_code != 405) {
863 fprintf(stderr,
864 "Unable to create branch path %s\n",
865 url);
866 free(url);
867 return NULL;
869 } else {
870 fprintf(stderr, "Unable to start MKCOL request\n");
871 free(url);
872 return NULL;
874 ep[1] = saved_character;
875 ep = strchr(ep + 1, '/');
878 escaped = xml_entities(ident_default_email());
879 strbuf_addf(&out_buffer.buf, LOCK_REQUEST, escaped);
880 free(escaped);
882 xsnprintf(timeout_header, sizeof(timeout_header), "Timeout: Second-%ld", timeout);
883 dav_headers = curl_slist_append(dav_headers, timeout_header);
884 dav_headers = curl_slist_append(dav_headers, "Content-Type: text/xml");
886 slot = get_active_slot();
887 slot->results = &results;
888 curl_setup_http(slot->curl, url, DAV_LOCK, &out_buffer, fwrite_buffer);
889 curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, dav_headers);
890 curl_easy_setopt(slot->curl, CURLOPT_FILE, &in_buffer);
892 lock = xcalloc(1, sizeof(*lock));
893 lock->timeout = -1;
895 if (start_active_slot(slot)) {
896 run_active_slot(slot);
897 if (results.curl_result == CURLE_OK) {
898 XML_Parser parser = XML_ParserCreate(NULL);
899 enum XML_Status result;
900 ctx.name = xcalloc(10, 1);
901 ctx.len = 0;
902 ctx.cdata = NULL;
903 ctx.userFunc = handle_new_lock_ctx;
904 ctx.userData = lock;
905 XML_SetUserData(parser, &ctx);
906 XML_SetElementHandler(parser, xml_start_tag,
907 xml_end_tag);
908 XML_SetCharacterDataHandler(parser, xml_cdata);
909 result = XML_Parse(parser, in_buffer.buf,
910 in_buffer.len, 1);
911 free(ctx.name);
912 if (result != XML_STATUS_OK) {
913 fprintf(stderr, "XML error: %s\n",
914 XML_ErrorString(
915 XML_GetErrorCode(parser)));
916 lock->timeout = -1;
918 XML_ParserFree(parser);
919 } else {
920 fprintf(stderr,
921 "error: curl result=%d, HTTP code=%ld\n",
922 results.curl_result, results.http_code);
924 } else {
925 fprintf(stderr, "Unable to start LOCK request\n");
928 curl_slist_free_all(dav_headers);
929 strbuf_release(&out_buffer.buf);
930 strbuf_release(&in_buffer);
932 if (lock->token == NULL || lock->timeout <= 0) {
933 free(lock->token);
934 free(lock->owner);
935 free(url);
936 FREE_AND_NULL(lock);
937 } else {
938 lock->url = url;
939 lock->start_time = time(NULL);
940 lock->next = repo->locks;
941 repo->locks = lock;
944 return lock;
947 static int unlock_remote(struct remote_lock *lock)
949 struct active_request_slot *slot;
950 struct slot_results results;
951 struct remote_lock *prev = repo->locks;
952 struct curl_slist *dav_headers;
953 int rc = 0;
955 dav_headers = get_dav_token_headers(lock, DAV_HEADER_LOCK);
957 slot = get_active_slot();
958 slot->results = &results;
959 curl_setup_http_get(slot->curl, lock->url, DAV_UNLOCK);
960 curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, dav_headers);
962 if (start_active_slot(slot)) {
963 run_active_slot(slot);
964 if (results.curl_result == CURLE_OK)
965 rc = 1;
966 else
967 fprintf(stderr, "UNLOCK HTTP error %ld\n",
968 results.http_code);
969 } else {
970 fprintf(stderr, "Unable to start UNLOCK request\n");
973 curl_slist_free_all(dav_headers);
975 if (repo->locks == lock) {
976 repo->locks = lock->next;
977 } else {
978 while (prev && prev->next != lock)
979 prev = prev->next;
980 if (prev)
981 prev->next = prev->next->next;
984 free(lock->owner);
985 free(lock->url);
986 free(lock->token);
987 free(lock);
989 return rc;
992 static void remove_locks(void)
994 struct remote_lock *lock = repo->locks;
996 fprintf(stderr, "Removing remote locks...\n");
997 while (lock) {
998 struct remote_lock *next = lock->next;
999 unlock_remote(lock);
1000 lock = next;
1004 static void remove_locks_on_signal(int signo)
1006 remove_locks();
1007 sigchain_pop(signo);
1008 raise(signo);
1011 static void remote_ls(const char *path, int flags,
1012 void (*userFunc)(struct remote_ls_ctx *ls),
1013 void *userData);
1015 /* extract hex from sharded "xx/x{38}" filename */
1016 static int get_oid_hex_from_objpath(const char *path, struct object_id *oid)
1018 if (strlen(path) != GIT_SHA1_HEXSZ + 1)
1019 return -1;
1021 if (hex_to_bytes(oid->hash, path, 1))
1022 return -1;
1023 path += 2;
1024 path++; /* skip '/' */
1026 return hex_to_bytes(oid->hash + 1, path, GIT_SHA1_RAWSZ - 1);
1029 static void process_ls_object(struct remote_ls_ctx *ls)
1031 unsigned int *parent = (unsigned int *)ls->userData;
1032 const char *path = ls->dentry_name;
1033 struct object_id oid;
1035 if (!strcmp(ls->path, ls->dentry_name) && (ls->flags & IS_DIR)) {
1036 remote_dir_exists[*parent] = 1;
1037 return;
1040 if (!skip_prefix(path, "objects/", &path) ||
1041 get_oid_hex_from_objpath(path, &oid))
1042 return;
1044 one_remote_object(&oid);
1047 static void process_ls_ref(struct remote_ls_ctx *ls)
1049 if (!strcmp(ls->path, ls->dentry_name) && (ls->dentry_flags & IS_DIR)) {
1050 fprintf(stderr, " %s\n", ls->dentry_name);
1051 return;
1054 if (!(ls->dentry_flags & IS_DIR))
1055 one_remote_ref(ls->dentry_name);
1058 static void handle_remote_ls_ctx(struct xml_ctx *ctx, int tag_closed)
1060 struct remote_ls_ctx *ls = (struct remote_ls_ctx *)ctx->userData;
1062 if (tag_closed) {
1063 if (!strcmp(ctx->name, DAV_PROPFIND_RESP) && ls->dentry_name) {
1064 if (ls->dentry_flags & IS_DIR) {
1066 /* ensure collection names end with slash */
1067 str_end_url_with_slash(ls->dentry_name, &ls->dentry_name);
1069 if (ls->flags & PROCESS_DIRS) {
1070 ls->userFunc(ls);
1072 if (strcmp(ls->dentry_name, ls->path) &&
1073 ls->flags & RECURSIVE) {
1074 remote_ls(ls->dentry_name,
1075 ls->flags,
1076 ls->userFunc,
1077 ls->userData);
1079 } else if (ls->flags & PROCESS_FILES) {
1080 ls->userFunc(ls);
1082 } else if (!strcmp(ctx->name, DAV_PROPFIND_NAME) && ctx->cdata) {
1083 char *path = ctx->cdata;
1084 if (*ctx->cdata == 'h') {
1085 path = strstr(path, "//");
1086 if (path) {
1087 path = strchr(path+2, '/');
1090 if (path) {
1091 const char *url = repo->url;
1092 if (repo->path)
1093 url = repo->path;
1094 if (strncmp(path, url, repo->path_len))
1095 error("Parsed path '%s' does not match url: '%s'",
1096 path, url);
1097 else {
1098 path += repo->path_len;
1099 ls->dentry_name = xstrdup(path);
1102 } else if (!strcmp(ctx->name, DAV_PROPFIND_COLLECTION)) {
1103 ls->dentry_flags |= IS_DIR;
1105 } else if (!strcmp(ctx->name, DAV_PROPFIND_RESP)) {
1106 FREE_AND_NULL(ls->dentry_name);
1107 ls->dentry_flags = 0;
1112 * NEEDSWORK: remote_ls() ignores info/refs on the remote side. But it
1113 * should _only_ heed the information from that file, instead of trying to
1114 * determine the refs from the remote file system (badly: it does not even
1115 * know about packed-refs).
1117 static void remote_ls(const char *path, int flags,
1118 void (*userFunc)(struct remote_ls_ctx *ls),
1119 void *userData)
1121 char *url = xstrfmt("%s%s", repo->url, path);
1122 struct active_request_slot *slot;
1123 struct slot_results results;
1124 struct strbuf in_buffer = STRBUF_INIT;
1125 struct buffer out_buffer = { STRBUF_INIT, 0 };
1126 struct curl_slist *dav_headers = http_copy_default_headers();
1127 struct xml_ctx ctx;
1128 struct remote_ls_ctx ls;
1130 ls.flags = flags;
1131 ls.path = xstrdup(path);
1132 ls.dentry_name = NULL;
1133 ls.dentry_flags = 0;
1134 ls.userData = userData;
1135 ls.userFunc = userFunc;
1137 strbuf_addstr(&out_buffer.buf, PROPFIND_ALL_REQUEST);
1139 dav_headers = curl_slist_append(dav_headers, "Depth: 1");
1140 dav_headers = curl_slist_append(dav_headers, "Content-Type: text/xml");
1142 slot = get_active_slot();
1143 slot->results = &results;
1144 curl_setup_http(slot->curl, url, DAV_PROPFIND,
1145 &out_buffer, fwrite_buffer);
1146 curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, dav_headers);
1147 curl_easy_setopt(slot->curl, CURLOPT_FILE, &in_buffer);
1149 if (start_active_slot(slot)) {
1150 run_active_slot(slot);
1151 if (results.curl_result == CURLE_OK) {
1152 XML_Parser parser = XML_ParserCreate(NULL);
1153 enum XML_Status result;
1154 ctx.name = xcalloc(10, 1);
1155 ctx.len = 0;
1156 ctx.cdata = NULL;
1157 ctx.userFunc = handle_remote_ls_ctx;
1158 ctx.userData = &ls;
1159 XML_SetUserData(parser, &ctx);
1160 XML_SetElementHandler(parser, xml_start_tag,
1161 xml_end_tag);
1162 XML_SetCharacterDataHandler(parser, xml_cdata);
1163 result = XML_Parse(parser, in_buffer.buf,
1164 in_buffer.len, 1);
1165 free(ctx.name);
1167 if (result != XML_STATUS_OK) {
1168 fprintf(stderr, "XML error: %s\n",
1169 XML_ErrorString(
1170 XML_GetErrorCode(parser)));
1172 XML_ParserFree(parser);
1174 } else {
1175 fprintf(stderr, "Unable to start PROPFIND request\n");
1178 free(ls.path);
1179 free(url);
1180 strbuf_release(&out_buffer.buf);
1181 strbuf_release(&in_buffer);
1182 curl_slist_free_all(dav_headers);
1185 static void get_remote_object_list(unsigned char parent)
1187 char path[] = "objects/XX/";
1188 static const char hex[] = "0123456789abcdef";
1189 unsigned int val = parent;
1191 path[8] = hex[val >> 4];
1192 path[9] = hex[val & 0xf];
1193 remote_dir_exists[val] = 0;
1194 remote_ls(path, (PROCESS_FILES | PROCESS_DIRS),
1195 process_ls_object, &val);
1198 static int locking_available(void)
1200 struct active_request_slot *slot;
1201 struct slot_results results;
1202 struct strbuf in_buffer = STRBUF_INIT;
1203 struct buffer out_buffer = { STRBUF_INIT, 0 };
1204 struct curl_slist *dav_headers = http_copy_default_headers();
1205 struct xml_ctx ctx;
1206 int lock_flags = 0;
1207 char *escaped;
1209 escaped = xml_entities(repo->url);
1210 strbuf_addf(&out_buffer.buf, PROPFIND_SUPPORTEDLOCK_REQUEST, escaped);
1211 free(escaped);
1213 dav_headers = curl_slist_append(dav_headers, "Depth: 0");
1214 dav_headers = curl_slist_append(dav_headers, "Content-Type: text/xml");
1216 slot = get_active_slot();
1217 slot->results = &results;
1218 curl_setup_http(slot->curl, repo->url, DAV_PROPFIND,
1219 &out_buffer, fwrite_buffer);
1220 curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, dav_headers);
1221 curl_easy_setopt(slot->curl, CURLOPT_FILE, &in_buffer);
1223 if (start_active_slot(slot)) {
1224 run_active_slot(slot);
1225 if (results.curl_result == CURLE_OK) {
1226 XML_Parser parser = XML_ParserCreate(NULL);
1227 enum XML_Status result;
1228 ctx.name = xcalloc(10, 1);
1229 ctx.len = 0;
1230 ctx.cdata = NULL;
1231 ctx.userFunc = handle_lockprop_ctx;
1232 ctx.userData = &lock_flags;
1233 XML_SetUserData(parser, &ctx);
1234 XML_SetElementHandler(parser, xml_start_tag,
1235 xml_end_tag);
1236 result = XML_Parse(parser, in_buffer.buf,
1237 in_buffer.len, 1);
1238 free(ctx.name);
1240 if (result != XML_STATUS_OK) {
1241 fprintf(stderr, "XML error: %s\n",
1242 XML_ErrorString(
1243 XML_GetErrorCode(parser)));
1244 lock_flags = 0;
1246 XML_ParserFree(parser);
1247 if (!lock_flags)
1248 error("no DAV locking support on %s",
1249 repo->url);
1251 } else {
1252 error("Cannot access URL %s, return code %d",
1253 repo->url, results.curl_result);
1254 lock_flags = 0;
1256 } else {
1257 error("Unable to start PROPFIND request on %s", repo->url);
1260 strbuf_release(&out_buffer.buf);
1261 strbuf_release(&in_buffer);
1262 curl_slist_free_all(dav_headers);
1264 return lock_flags;
1267 static struct object_list **add_one_object(struct object *obj, struct object_list **p)
1269 struct object_list *entry = xmalloc(sizeof(struct object_list));
1270 entry->item = obj;
1271 entry->next = *p;
1272 *p = entry;
1273 return &entry->next;
1276 static struct object_list **process_blob(struct blob *blob,
1277 struct object_list **p)
1279 struct object *obj = &blob->object;
1281 obj->flags |= LOCAL;
1283 if (obj->flags & (UNINTERESTING | SEEN))
1284 return p;
1286 obj->flags |= SEEN;
1287 return add_one_object(obj, p);
1290 static struct object_list **process_tree(struct tree *tree,
1291 struct object_list **p)
1293 struct object *obj = &tree->object;
1294 struct tree_desc desc;
1295 struct name_entry entry;
1297 obj->flags |= LOCAL;
1299 if (obj->flags & (UNINTERESTING | SEEN))
1300 return p;
1301 if (parse_tree(tree) < 0)
1302 die("bad tree object %s", oid_to_hex(&obj->oid));
1304 obj->flags |= SEEN;
1305 p = add_one_object(obj, p);
1307 init_tree_desc(&desc, tree->buffer, tree->size);
1309 while (tree_entry(&desc, &entry))
1310 switch (object_type(entry.mode)) {
1311 case OBJ_TREE:
1312 p = process_tree(lookup_tree(entry.oid), p);
1313 break;
1314 case OBJ_BLOB:
1315 p = process_blob(lookup_blob(entry.oid), p);
1316 break;
1317 default:
1318 /* Subproject commit - not in this repository */
1319 break;
1322 free_tree_buffer(tree);
1323 return p;
1326 static int get_delta(struct rev_info *revs, struct remote_lock *lock)
1328 int i;
1329 struct commit *commit;
1330 struct object_list **p = &objects;
1331 int count = 0;
1333 while ((commit = get_revision(revs)) != NULL) {
1334 p = process_tree(get_commit_tree(commit), p);
1335 commit->object.flags |= LOCAL;
1336 if (!(commit->object.flags & UNINTERESTING))
1337 count += add_send_request(&commit->object, lock);
1340 for (i = 0; i < revs->pending.nr; i++) {
1341 struct object_array_entry *entry = revs->pending.objects + i;
1342 struct object *obj = entry->item;
1343 const char *name = entry->name;
1345 if (obj->flags & (UNINTERESTING | SEEN))
1346 continue;
1347 if (obj->type == OBJ_TAG) {
1348 obj->flags |= SEEN;
1349 p = add_one_object(obj, p);
1350 continue;
1352 if (obj->type == OBJ_TREE) {
1353 p = process_tree((struct tree *)obj, p);
1354 continue;
1356 if (obj->type == OBJ_BLOB) {
1357 p = process_blob((struct blob *)obj, p);
1358 continue;
1360 die("unknown pending object %s (%s)", oid_to_hex(&obj->oid), name);
1363 while (objects) {
1364 if (!(objects->item->flags & UNINTERESTING))
1365 count += add_send_request(objects->item, lock);
1366 objects = objects->next;
1369 return count;
1372 static int update_remote(unsigned char *sha1, struct remote_lock *lock)
1374 struct active_request_slot *slot;
1375 struct slot_results results;
1376 struct buffer out_buffer = { STRBUF_INIT, 0 };
1377 struct curl_slist *dav_headers;
1379 dav_headers = get_dav_token_headers(lock, DAV_HEADER_IF);
1381 strbuf_addf(&out_buffer.buf, "%s\n", sha1_to_hex(sha1));
1383 slot = get_active_slot();
1384 slot->results = &results;
1385 curl_setup_http(slot->curl, lock->url, DAV_PUT,
1386 &out_buffer, fwrite_null);
1387 curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, dav_headers);
1389 if (start_active_slot(slot)) {
1390 run_active_slot(slot);
1391 strbuf_release(&out_buffer.buf);
1392 if (results.curl_result != CURLE_OK) {
1393 fprintf(stderr,
1394 "PUT error: curl result=%d, HTTP code=%ld\n",
1395 results.curl_result, results.http_code);
1396 /* We should attempt recovery? */
1397 return 0;
1399 } else {
1400 strbuf_release(&out_buffer.buf);
1401 fprintf(stderr, "Unable to start PUT request\n");
1402 return 0;
1405 return 1;
1408 static struct ref *remote_refs;
1410 static void one_remote_ref(const char *refname)
1412 struct ref *ref;
1413 struct object *obj;
1415 ref = alloc_ref(refname);
1417 if (http_fetch_ref(repo->url, ref) != 0) {
1418 fprintf(stderr,
1419 "Unable to fetch ref %s from %s\n",
1420 refname, repo->url);
1421 free(ref);
1422 return;
1426 * Fetch a copy of the object if it doesn't exist locally - it
1427 * may be required for updating server info later.
1429 if (repo->can_update_info_refs && !has_object_file(&ref->old_oid)) {
1430 obj = lookup_unknown_object(ref->old_oid.hash);
1431 fprintf(stderr, " fetch %s for %s\n",
1432 oid_to_hex(&ref->old_oid), refname);
1433 add_fetch_request(obj);
1436 ref->next = remote_refs;
1437 remote_refs = ref;
1440 static void get_dav_remote_heads(void)
1442 remote_ls("refs/", (PROCESS_FILES | PROCESS_DIRS | RECURSIVE), process_ls_ref, NULL);
1445 static void add_remote_info_ref(struct remote_ls_ctx *ls)
1447 struct strbuf *buf = (struct strbuf *)ls->userData;
1448 struct object *o;
1449 struct ref *ref;
1451 ref = alloc_ref(ls->dentry_name);
1453 if (http_fetch_ref(repo->url, ref) != 0) {
1454 fprintf(stderr,
1455 "Unable to fetch ref %s from %s\n",
1456 ls->dentry_name, repo->url);
1457 aborted = 1;
1458 free(ref);
1459 return;
1462 o = parse_object(&ref->old_oid);
1463 if (!o) {
1464 fprintf(stderr,
1465 "Unable to parse object %s for remote ref %s\n",
1466 oid_to_hex(&ref->old_oid), ls->dentry_name);
1467 aborted = 1;
1468 free(ref);
1469 return;
1472 strbuf_addf(buf, "%s\t%s\n",
1473 oid_to_hex(&ref->old_oid), ls->dentry_name);
1475 if (o->type == OBJ_TAG) {
1476 o = deref_tag(o, ls->dentry_name, 0);
1477 if (o)
1478 strbuf_addf(buf, "%s\t%s^{}\n",
1479 oid_to_hex(&o->oid), ls->dentry_name);
1481 free(ref);
1484 static void update_remote_info_refs(struct remote_lock *lock)
1486 struct buffer buffer = { STRBUF_INIT, 0 };
1487 struct active_request_slot *slot;
1488 struct slot_results results;
1489 struct curl_slist *dav_headers;
1491 remote_ls("refs/", (PROCESS_FILES | RECURSIVE),
1492 add_remote_info_ref, &buffer.buf);
1493 if (!aborted) {
1494 dav_headers = get_dav_token_headers(lock, DAV_HEADER_IF);
1496 slot = get_active_slot();
1497 slot->results = &results;
1498 curl_setup_http(slot->curl, lock->url, DAV_PUT,
1499 &buffer, fwrite_null);
1500 curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, dav_headers);
1502 if (start_active_slot(slot)) {
1503 run_active_slot(slot);
1504 if (results.curl_result != CURLE_OK) {
1505 fprintf(stderr,
1506 "PUT error: curl result=%d, HTTP code=%ld\n",
1507 results.curl_result, results.http_code);
1511 strbuf_release(&buffer.buf);
1514 static int remote_exists(const char *path)
1516 char *url = xstrfmt("%s%s", repo->url, path);
1517 int ret;
1520 switch (http_get_strbuf(url, NULL, NULL)) {
1521 case HTTP_OK:
1522 ret = 1;
1523 break;
1524 case HTTP_MISSING_TARGET:
1525 ret = 0;
1526 break;
1527 case HTTP_ERROR:
1528 error("unable to access '%s': %s", url, curl_errorstr);
1529 /* fallthrough */
1530 default:
1531 ret = -1;
1533 free(url);
1534 return ret;
1537 static void fetch_symref(const char *path, char **symref, struct object_id *oid)
1539 char *url = xstrfmt("%s%s", repo->url, path);
1540 struct strbuf buffer = STRBUF_INIT;
1541 const char *name;
1543 if (http_get_strbuf(url, &buffer, NULL) != HTTP_OK)
1544 die("Couldn't get %s for remote symref\n%s", url,
1545 curl_errorstr);
1546 free(url);
1548 FREE_AND_NULL(*symref);
1549 oidclr(oid);
1551 if (buffer.len == 0)
1552 return;
1554 /* Cut off trailing newline. */
1555 strbuf_rtrim(&buffer);
1557 /* If it's a symref, set the refname; otherwise try for a sha1 */
1558 if (skip_prefix(buffer.buf, "ref: ", &name)) {
1559 *symref = xmemdupz(name, buffer.len - (name - buffer.buf));
1560 } else {
1561 get_oid_hex(buffer.buf, oid);
1564 strbuf_release(&buffer);
1567 static int verify_merge_base(struct object_id *head_oid, struct ref *remote)
1569 struct commit *head = lookup_commit_or_die(head_oid, "HEAD");
1570 struct commit *branch = lookup_commit_or_die(&remote->old_oid,
1571 remote->name);
1573 return in_merge_bases(branch, head);
1576 static int delete_remote_branch(const char *pattern, int force)
1578 struct ref *refs = remote_refs;
1579 struct ref *remote_ref = NULL;
1580 struct object_id head_oid;
1581 char *symref = NULL;
1582 int match;
1583 int patlen = strlen(pattern);
1584 int i;
1585 struct active_request_slot *slot;
1586 struct slot_results results;
1587 char *url;
1589 /* Find the remote branch(es) matching the specified branch name */
1590 for (match = 0; refs; refs = refs->next) {
1591 char *name = refs->name;
1592 int namelen = strlen(name);
1593 if (namelen < patlen ||
1594 memcmp(name + namelen - patlen, pattern, patlen))
1595 continue;
1596 if (namelen != patlen && name[namelen - patlen - 1] != '/')
1597 continue;
1598 match++;
1599 remote_ref = refs;
1601 if (match == 0)
1602 return error("No remote branch matches %s", pattern);
1603 if (match != 1)
1604 return error("More than one remote branch matches %s",
1605 pattern);
1608 * Remote HEAD must be a symref (not exactly foolproof; a remote
1609 * symlink to a symref will look like a symref)
1611 fetch_symref("HEAD", &symref, &head_oid);
1612 if (!symref)
1613 return error("Remote HEAD is not a symref");
1615 /* Remote branch must not be the remote HEAD */
1616 for (i = 0; symref && i < MAXDEPTH; i++) {
1617 if (!strcmp(remote_ref->name, symref))
1618 return error("Remote branch %s is the current HEAD",
1619 remote_ref->name);
1620 fetch_symref(symref, &symref, &head_oid);
1623 /* Run extra sanity checks if delete is not forced */
1624 if (!force) {
1625 /* Remote HEAD must resolve to a known object */
1626 if (symref)
1627 return error("Remote HEAD symrefs too deep");
1628 if (is_null_oid(&head_oid))
1629 return error("Unable to resolve remote HEAD");
1630 if (!has_object_file(&head_oid))
1631 return error("Remote HEAD resolves to object %s\nwhich does not exist locally, perhaps you need to fetch?", oid_to_hex(&head_oid));
1633 /* Remote branch must resolve to a known object */
1634 if (is_null_oid(&remote_ref->old_oid))
1635 return error("Unable to resolve remote branch %s",
1636 remote_ref->name);
1637 if (!has_object_file(&remote_ref->old_oid))
1638 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));
1640 /* Remote branch must be an ancestor of remote HEAD */
1641 if (!verify_merge_base(&head_oid, remote_ref)) {
1642 return error("The branch '%s' is not an ancestor "
1643 "of your current HEAD.\n"
1644 "If you are sure you want to delete it,"
1645 " run:\n\t'git http-push -D %s %s'",
1646 remote_ref->name, repo->url, pattern);
1650 /* Send delete request */
1651 fprintf(stderr, "Removing remote branch '%s'\n", remote_ref->name);
1652 if (dry_run)
1653 return 0;
1654 url = xstrfmt("%s%s", repo->url, remote_ref->name);
1655 slot = get_active_slot();
1656 slot->results = &results;
1657 curl_setup_http_get(slot->curl, url, DAV_DELETE);
1658 if (start_active_slot(slot)) {
1659 run_active_slot(slot);
1660 free(url);
1661 if (results.curl_result != CURLE_OK)
1662 return error("DELETE request failed (%d/%ld)",
1663 results.curl_result, results.http_code);
1664 } else {
1665 free(url);
1666 return error("Unable to start DELETE request");
1669 return 0;
1672 static void run_request_queue(void)
1674 #ifdef USE_CURL_MULTI
1675 is_running_queue = 1;
1676 fill_active_slots();
1677 add_fill_function(NULL, fill_active_slot);
1678 #endif
1679 do {
1680 finish_all_active_slots();
1681 #ifdef USE_CURL_MULTI
1682 fill_active_slots();
1683 #endif
1684 } while (request_queue_head && !aborted);
1686 #ifdef USE_CURL_MULTI
1687 is_running_queue = 0;
1688 #endif
1691 int cmd_main(int argc, const char **argv)
1693 struct transfer_request *request;
1694 struct transfer_request *next_request;
1695 struct refspec rs = REFSPEC_INIT_PUSH;
1696 struct remote_lock *ref_lock = NULL;
1697 struct remote_lock *info_ref_lock = NULL;
1698 struct rev_info revs;
1699 int delete_branch = 0;
1700 int force_delete = 0;
1701 int objects_to_send;
1702 int rc = 0;
1703 int i;
1704 int new_refs;
1705 struct ref *ref, *local_refs;
1707 repo = xcalloc(1, sizeof(*repo));
1709 argv++;
1710 for (i = 1; i < argc; i++, argv++) {
1711 const char *arg = *argv;
1713 if (*arg == '-') {
1714 if (!strcmp(arg, "--all")) {
1715 push_all = MATCH_REFS_ALL;
1716 continue;
1718 if (!strcmp(arg, "--force")) {
1719 force_all = 1;
1720 continue;
1722 if (!strcmp(arg, "--dry-run")) {
1723 dry_run = 1;
1724 continue;
1726 if (!strcmp(arg, "--helper-status")) {
1727 helper_status = 1;
1728 continue;
1730 if (!strcmp(arg, "--verbose")) {
1731 push_verbosely = 1;
1732 http_is_verbose = 1;
1733 continue;
1735 if (!strcmp(arg, "-d")) {
1736 delete_branch = 1;
1737 continue;
1739 if (!strcmp(arg, "-D")) {
1740 delete_branch = 1;
1741 force_delete = 1;
1742 continue;
1744 if (!strcmp(arg, "-h"))
1745 usage(http_push_usage);
1747 if (!repo->url) {
1748 char *path = strstr(arg, "//");
1749 str_end_url_with_slash(arg, &repo->url);
1750 repo->path_len = strlen(repo->url);
1751 if (path) {
1752 repo->path = strchr(path+2, '/');
1753 if (repo->path)
1754 repo->path_len = strlen(repo->path);
1756 continue;
1758 refspec_appendn(&rs, argv, argc - i);
1759 break;
1762 #ifndef USE_CURL_MULTI
1763 die("git-push is not available for http/https repository when not compiled with USE_CURL_MULTI");
1764 #endif
1766 if (!repo->url)
1767 usage(http_push_usage);
1769 if (delete_branch && rs.nr != 1)
1770 die("You must specify only one branch name when deleting a remote branch");
1772 setup_git_directory();
1774 memset(remote_dir_exists, -1, 256);
1776 http_init(NULL, repo->url, 1);
1778 #ifdef USE_CURL_MULTI
1779 is_running_queue = 0;
1780 #endif
1782 /* Verify DAV compliance/lock support */
1783 if (!locking_available()) {
1784 rc = 1;
1785 goto cleanup;
1788 sigchain_push_common(remove_locks_on_signal);
1790 /* Check whether the remote has server info files */
1791 repo->can_update_info_refs = 0;
1792 repo->has_info_refs = remote_exists("info/refs");
1793 repo->has_info_packs = remote_exists("objects/info/packs");
1794 if (repo->has_info_refs) {
1795 info_ref_lock = lock_remote("info/refs", LOCK_TIME);
1796 if (info_ref_lock)
1797 repo->can_update_info_refs = 1;
1798 else {
1799 error("cannot lock existing info/refs");
1800 rc = 1;
1801 goto cleanup;
1804 if (repo->has_info_packs)
1805 fetch_indices();
1807 /* Get a list of all local and remote heads to validate refspecs */
1808 local_refs = get_local_heads();
1809 fprintf(stderr, "Fetching remote heads...\n");
1810 get_dav_remote_heads();
1811 run_request_queue();
1813 /* Remove a remote branch if -d or -D was specified */
1814 if (delete_branch) {
1815 const char *branch = rs.items[i].src;
1816 if (delete_remote_branch(branch, force_delete) == -1) {
1817 fprintf(stderr, "Unable to delete remote branch %s\n",
1818 branch);
1819 if (helper_status)
1820 printf("error %s cannot remove\n", branch);
1822 goto cleanup;
1825 /* match them up */
1826 if (match_push_refs(local_refs, &remote_refs, &rs, push_all)) {
1827 rc = -1;
1828 goto cleanup;
1830 if (!remote_refs) {
1831 fprintf(stderr, "No refs in common and none specified; doing nothing.\n");
1832 if (helper_status)
1833 printf("error null no match\n");
1834 rc = 0;
1835 goto cleanup;
1838 new_refs = 0;
1839 for (ref = remote_refs; ref; ref = ref->next) {
1840 struct argv_array commit_argv = ARGV_ARRAY_INIT;
1842 if (!ref->peer_ref)
1843 continue;
1845 if (is_null_oid(&ref->peer_ref->new_oid)) {
1846 if (delete_remote_branch(ref->name, 1) == -1) {
1847 error("Could not remove %s", ref->name);
1848 if (helper_status)
1849 printf("error %s cannot remove\n", ref->name);
1850 rc = -4;
1852 else if (helper_status)
1853 printf("ok %s\n", ref->name);
1854 new_refs++;
1855 continue;
1858 if (!oidcmp(&ref->old_oid, &ref->peer_ref->new_oid)) {
1859 if (push_verbosely)
1860 fprintf(stderr, "'%s': up-to-date\n", ref->name);
1861 if (helper_status)
1862 printf("ok %s up to date\n", ref->name);
1863 continue;
1866 if (!force_all &&
1867 !is_null_oid(&ref->old_oid) &&
1868 !ref->force) {
1869 if (!has_object_file(&ref->old_oid) ||
1870 !ref_newer(&ref->peer_ref->new_oid,
1871 &ref->old_oid)) {
1873 * We do not have the remote ref, or
1874 * we know that the remote ref is not
1875 * an ancestor of what we are trying to
1876 * push. Either way this can be losing
1877 * commits at the remote end and likely
1878 * we were not up to date to begin with.
1880 error("remote '%s' is not an ancestor of\n"
1881 "local '%s'.\n"
1882 "Maybe you are not up-to-date and "
1883 "need to pull first?",
1884 ref->name,
1885 ref->peer_ref->name);
1886 if (helper_status)
1887 printf("error %s non-fast forward\n", ref->name);
1888 rc = -2;
1889 continue;
1892 oidcpy(&ref->new_oid, &ref->peer_ref->new_oid);
1893 new_refs++;
1895 fprintf(stderr, "updating '%s'", ref->name);
1896 if (strcmp(ref->name, ref->peer_ref->name))
1897 fprintf(stderr, " using '%s'", ref->peer_ref->name);
1898 fprintf(stderr, "\n from %s\n to %s\n",
1899 oid_to_hex(&ref->old_oid), oid_to_hex(&ref->new_oid));
1900 if (dry_run) {
1901 if (helper_status)
1902 printf("ok %s\n", ref->name);
1903 continue;
1906 /* Lock remote branch ref */
1907 ref_lock = lock_remote(ref->name, LOCK_TIME);
1908 if (ref_lock == NULL) {
1909 fprintf(stderr, "Unable to lock remote branch %s\n",
1910 ref->name);
1911 if (helper_status)
1912 printf("error %s lock error\n", ref->name);
1913 rc = 1;
1914 continue;
1917 /* Set up revision info for this refspec */
1918 argv_array_push(&commit_argv, ""); /* ignored */
1919 argv_array_push(&commit_argv, "--objects");
1920 argv_array_push(&commit_argv, oid_to_hex(&ref->new_oid));
1921 if (!push_all && !is_null_oid(&ref->old_oid))
1922 argv_array_pushf(&commit_argv, "^%s",
1923 oid_to_hex(&ref->old_oid));
1924 init_revisions(&revs, setup_git_directory());
1925 setup_revisions(commit_argv.argc, commit_argv.argv, &revs, NULL);
1926 revs.edge_hint = 0; /* just in case */
1928 /* Generate a list of objects that need to be pushed */
1929 pushing = 0;
1930 if (prepare_revision_walk(&revs))
1931 die("revision walk setup failed");
1932 mark_edges_uninteresting(&revs, NULL);
1933 objects_to_send = get_delta(&revs, ref_lock);
1934 finish_all_active_slots();
1936 /* Push missing objects to remote, this would be a
1937 convenient time to pack them first if appropriate. */
1938 pushing = 1;
1939 if (objects_to_send)
1940 fprintf(stderr, " sending %d objects\n",
1941 objects_to_send);
1943 run_request_queue();
1945 /* Update the remote branch if all went well */
1946 if (aborted || !update_remote(ref->new_oid.hash, ref_lock))
1947 rc = 1;
1949 if (!rc)
1950 fprintf(stderr, " done\n");
1951 if (helper_status)
1952 printf("%s %s\n", !rc ? "ok" : "error", ref->name);
1953 unlock_remote(ref_lock);
1954 check_locks();
1955 argv_array_clear(&commit_argv);
1958 /* Update remote server info if appropriate */
1959 if (repo->has_info_refs && new_refs) {
1960 if (info_ref_lock && repo->can_update_info_refs) {
1961 fprintf(stderr, "Updating remote server info\n");
1962 if (!dry_run)
1963 update_remote_info_refs(info_ref_lock);
1964 } else {
1965 fprintf(stderr, "Unable to update server info\n");
1969 cleanup:
1970 if (info_ref_lock)
1971 unlock_remote(info_ref_lock);
1972 free(repo);
1974 http_cleanup();
1976 request = request_queue_head;
1977 while (request != NULL) {
1978 next_request = request->next;
1979 release_request(request);
1980 request = next_request;
1983 return rc;