use xstrdup instead of xmalloc + strcpy
[git/git-svn.git] / http-push.c
blob95650a02418fc4ed74b7fa128f6cbddc7ce33e2e
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"
14 #ifdef EXPAT_NEEDS_XMLPARSE_H
15 #include <xmlparse.h>
16 #else
17 #include <expat.h>
18 #endif
20 static const char http_push_usage[] =
21 "git http-push [--all] [--dry-run] [--force] [--verbose] <remote> [<head>...]\n";
23 #ifndef XML_STATUS_OK
24 enum XML_Status {
25 XML_STATUS_OK = 1,
26 XML_STATUS_ERROR = 0
28 #define XML_STATUS_OK 1
29 #define XML_STATUS_ERROR 0
30 #endif
32 #define PREV_BUF_SIZE 4096
34 /* DAV methods */
35 #define DAV_LOCK "LOCK"
36 #define DAV_MKCOL "MKCOL"
37 #define DAV_MOVE "MOVE"
38 #define DAV_PROPFIND "PROPFIND"
39 #define DAV_PUT "PUT"
40 #define DAV_UNLOCK "UNLOCK"
41 #define DAV_DELETE "DELETE"
43 /* DAV lock flags */
44 #define DAV_PROP_LOCKWR (1u << 0)
45 #define DAV_PROP_LOCKEX (1u << 1)
46 #define DAV_LOCK_OK (1u << 2)
48 /* DAV XML properties */
49 #define DAV_CTX_LOCKENTRY ".multistatus.response.propstat.prop.supportedlock.lockentry"
50 #define DAV_CTX_LOCKTYPE_WRITE ".multistatus.response.propstat.prop.supportedlock.lockentry.locktype.write"
51 #define DAV_CTX_LOCKTYPE_EXCLUSIVE ".multistatus.response.propstat.prop.supportedlock.lockentry.lockscope.exclusive"
52 #define DAV_ACTIVELOCK_OWNER ".prop.lockdiscovery.activelock.owner.href"
53 #define DAV_ACTIVELOCK_TIMEOUT ".prop.lockdiscovery.activelock.timeout"
54 #define DAV_ACTIVELOCK_TOKEN ".prop.lockdiscovery.activelock.locktoken.href"
55 #define DAV_PROPFIND_RESP ".multistatus.response"
56 #define DAV_PROPFIND_NAME ".multistatus.response.href"
57 #define DAV_PROPFIND_COLLECTION ".multistatus.response.propstat.prop.resourcetype.collection"
59 /* DAV request body templates */
60 #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>"
61 #define PROPFIND_ALL_REQUEST "<?xml version=\"1.0\" encoding=\"utf-8\" ?>\n<D:propfind xmlns:D=\"DAV:\">\n<D:allprop/>\n</D:propfind>"
62 #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>"
64 #define LOCK_TIME 600
65 #define LOCK_REFRESH 30
67 /* Remember to update object flag allocation in object.h */
68 #define LOCAL (1u<<16)
69 #define REMOTE (1u<<17)
70 #define FETCHING (1u<<18)
71 #define PUSHING (1u<<19)
73 /* We allow "recursive" symbolic refs. Only within reason, though */
74 #define MAXDEPTH 5
76 static int pushing;
77 static int aborted;
78 static signed char remote_dir_exists[256];
80 static int push_verbosely;
81 static int push_all = MATCH_REFS_NONE;
82 static int force_all;
83 static int dry_run;
84 static int helper_status;
86 static struct object_list *objects;
88 struct repo {
89 char *url;
90 char *path;
91 int path_len;
92 int has_info_refs;
93 int can_update_info_refs;
94 int has_info_packs;
95 struct packed_git *packs;
96 struct remote_lock *locks;
99 static struct repo *repo;
101 enum transfer_state {
102 NEED_FETCH,
103 RUN_FETCH_LOOSE,
104 RUN_FETCH_PACKED,
105 NEED_PUSH,
106 RUN_MKCOL,
107 RUN_PUT,
108 RUN_MOVE,
109 ABORTED,
110 COMPLETE
113 struct transfer_request {
114 struct object *obj;
115 char *url;
116 char *dest;
117 struct remote_lock *lock;
118 struct curl_slist *headers;
119 struct buffer buffer;
120 enum transfer_state state;
121 CURLcode curl_result;
122 char errorstr[CURL_ERROR_SIZE];
123 long http_code;
124 void *userData;
125 struct active_request_slot *slot;
126 struct transfer_request *next;
129 static struct transfer_request *request_queue_head;
131 struct xml_ctx {
132 char *name;
133 int len;
134 char *cdata;
135 void (*userFunc)(struct xml_ctx *ctx, int tag_closed);
136 void *userData;
139 struct remote_lock {
140 char *url;
141 char *owner;
142 char *token;
143 char tmpfile_suffix[41];
144 time_t start_time;
145 long timeout;
146 int refreshing;
147 struct remote_lock *next;
150 /* Flags that control remote_ls processing */
151 #define PROCESS_FILES (1u << 0)
152 #define PROCESS_DIRS (1u << 1)
153 #define RECURSIVE (1u << 2)
155 /* Flags that remote_ls passes to callback functions */
156 #define IS_DIR (1u << 0)
158 struct remote_ls_ctx {
159 char *path;
160 void (*userFunc)(struct remote_ls_ctx *ls);
161 void *userData;
162 int flags;
163 char *dentry_name;
164 int dentry_flags;
165 struct remote_ls_ctx *parent;
168 /* get_dav_token_headers options */
169 enum dav_header_flag {
170 DAV_HEADER_IF = (1u << 0),
171 DAV_HEADER_LOCK = (1u << 1),
172 DAV_HEADER_TIMEOUT = (1u << 2)
175 static char *xml_entities(const char *s)
177 struct strbuf buf = STRBUF_INIT;
178 strbuf_addstr_xml_quoted(&buf, s);
179 return strbuf_detach(&buf, NULL);
182 static void curl_setup_http_get(CURL *curl, const char *url,
183 const char *custom_req)
185 curl_easy_setopt(curl, CURLOPT_HTTPGET, 1);
186 curl_easy_setopt(curl, CURLOPT_URL, url);
187 curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, custom_req);
188 curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, fwrite_null);
191 static void curl_setup_http(CURL *curl, const char *url,
192 const char *custom_req, struct buffer *buffer,
193 curl_write_callback write_fn)
195 curl_easy_setopt(curl, CURLOPT_PUT, 1);
196 curl_easy_setopt(curl, CURLOPT_URL, url);
197 curl_easy_setopt(curl, CURLOPT_INFILE, buffer);
198 curl_easy_setopt(curl, CURLOPT_INFILESIZE, buffer->buf.len);
199 curl_easy_setopt(curl, CURLOPT_READFUNCTION, fread_buffer);
200 #ifndef NO_CURL_IOCTL
201 curl_easy_setopt(curl, CURLOPT_IOCTLFUNCTION, ioctl_buffer);
202 curl_easy_setopt(curl, CURLOPT_IOCTLDATA, &buffer);
203 #endif
204 curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_fn);
205 curl_easy_setopt(curl, CURLOPT_NOBODY, 0);
206 curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, custom_req);
207 curl_easy_setopt(curl, CURLOPT_UPLOAD, 1);
210 static struct curl_slist *get_dav_token_headers(struct remote_lock *lock, enum dav_header_flag options)
212 struct strbuf buf = STRBUF_INIT;
213 struct curl_slist *dav_headers = NULL;
215 if (options & DAV_HEADER_IF) {
216 strbuf_addf(&buf, "If: (<%s>)", lock->token);
217 dav_headers = curl_slist_append(dav_headers, buf.buf);
218 strbuf_reset(&buf);
220 if (options & DAV_HEADER_LOCK) {
221 strbuf_addf(&buf, "Lock-Token: <%s>", lock->token);
222 dav_headers = curl_slist_append(dav_headers, buf.buf);
223 strbuf_reset(&buf);
225 if (options & DAV_HEADER_TIMEOUT) {
226 strbuf_addf(&buf, "Timeout: Second-%ld", lock->timeout);
227 dav_headers = curl_slist_append(dav_headers, buf.buf);
228 strbuf_reset(&buf);
230 strbuf_release(&buf);
232 return dav_headers;
235 static void finish_request(struct transfer_request *request);
236 static void release_request(struct transfer_request *request);
238 static void process_response(void *callback_data)
240 struct transfer_request *request =
241 (struct transfer_request *)callback_data;
243 finish_request(request);
246 #ifdef USE_CURL_MULTI
248 static void start_fetch_loose(struct transfer_request *request)
250 struct active_request_slot *slot;
251 struct http_object_request *obj_req;
253 obj_req = new_http_object_request(repo->url, request->obj->sha1);
254 if (obj_req == NULL) {
255 request->state = ABORTED;
256 return;
259 slot = obj_req->slot;
260 slot->callback_func = process_response;
261 slot->callback_data = request;
262 request->slot = slot;
263 request->userData = obj_req;
265 /* Try to get the request started, abort the request on error */
266 request->state = RUN_FETCH_LOOSE;
267 if (!start_active_slot(slot)) {
268 fprintf(stderr, "Unable to start GET request\n");
269 repo->can_update_info_refs = 0;
270 release_http_object_request(obj_req);
271 release_request(request);
275 static void start_mkcol(struct transfer_request *request)
277 char *hex = sha1_to_hex(request->obj->sha1);
278 struct active_request_slot *slot;
280 request->url = get_remote_object_url(repo->url, hex, 1);
282 slot = get_active_slot();
283 slot->callback_func = process_response;
284 slot->callback_data = request;
285 curl_setup_http_get(slot->curl, request->url, DAV_MKCOL);
286 curl_easy_setopt(slot->curl, CURLOPT_ERRORBUFFER, request->errorstr);
288 if (start_active_slot(slot)) {
289 request->slot = slot;
290 request->state = RUN_MKCOL;
291 } else {
292 request->state = ABORTED;
293 free(request->url);
294 request->url = NULL;
297 #endif
299 static void start_fetch_packed(struct transfer_request *request)
301 struct packed_git *target;
303 struct transfer_request *check_request = request_queue_head;
304 struct http_pack_request *preq;
306 target = find_sha1_pack(request->obj->sha1, repo->packs);
307 if (!target) {
308 fprintf(stderr, "Unable to fetch %s, will not be able to update server info refs\n", sha1_to_hex(request->obj->sha1));
309 repo->can_update_info_refs = 0;
310 release_request(request);
311 return;
314 fprintf(stderr, "Fetching pack %s\n", sha1_to_hex(target->sha1));
315 fprintf(stderr, " which contains %s\n", sha1_to_hex(request->obj->sha1));
317 preq = new_http_pack_request(target, repo->url);
318 if (preq == NULL) {
319 release_http_pack_request(preq);
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 = sha1_to_hex(request->obj->sha1);
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->sha1, &type, &len);
365 hdrlen = sprintf(hdr, "%s %lu", typename(type), len) + 1;
367 /* Set it up */
368 memset(&stream, 0, sizeof(stream));
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(request->url);
414 request->url = NULL;
418 static void start_move(struct transfer_request *request)
420 struct active_request_slot *slot;
421 struct curl_slist *dav_headers = NULL;
423 slot = get_active_slot();
424 slot->callback_func = process_response;
425 slot->callback_data = request;
426 curl_setup_http_get(slot->curl, request->url, DAV_MOVE);
427 dav_headers = curl_slist_append(dav_headers, request->dest);
428 dav_headers = curl_slist_append(dav_headers, "Overwrite: T");
429 curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, dav_headers);
431 if (start_active_slot(slot)) {
432 request->slot = slot;
433 request->state = RUN_MOVE;
434 } else {
435 request->state = ABORTED;
436 free(request->url);
437 request->url = NULL;
441 static int refresh_lock(struct remote_lock *lock)
443 struct active_request_slot *slot;
444 struct slot_results results;
445 struct curl_slist *dav_headers;
446 int rc = 0;
448 lock->refreshing = 1;
450 dav_headers = get_dav_token_headers(lock, DAV_HEADER_IF | DAV_HEADER_TIMEOUT);
452 slot = get_active_slot();
453 slot->results = &results;
454 curl_setup_http_get(slot->curl, lock->url, DAV_LOCK);
455 curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, dav_headers);
457 if (start_active_slot(slot)) {
458 run_active_slot(slot);
459 if (results.curl_result != CURLE_OK) {
460 fprintf(stderr, "LOCK HTTP error %ld\n",
461 results.http_code);
462 } else {
463 lock->start_time = time(NULL);
464 rc = 1;
468 lock->refreshing = 0;
469 curl_slist_free_all(dav_headers);
471 return rc;
474 static void check_locks(void)
476 struct remote_lock *lock = repo->locks;
477 time_t current_time = time(NULL);
478 int time_remaining;
480 while (lock) {
481 time_remaining = lock->start_time + lock->timeout -
482 current_time;
483 if (!lock->refreshing && time_remaining < LOCK_REFRESH) {
484 if (!refresh_lock(lock)) {
485 fprintf(stderr,
486 "Unable to refresh lock for %s\n",
487 lock->url);
488 aborted = 1;
489 return;
492 lock = lock->next;
496 static void release_request(struct transfer_request *request)
498 struct transfer_request *entry = request_queue_head;
500 if (request == request_queue_head) {
501 request_queue_head = request->next;
502 } else {
503 while (entry->next != NULL && entry->next != request)
504 entry = entry->next;
505 if (entry->next == request)
506 entry->next = entry->next->next;
509 free(request->url);
510 free(request);
513 static void finish_request(struct transfer_request *request)
515 struct http_pack_request *preq;
516 struct http_object_request *obj_req;
518 request->curl_result = request->slot->curl_result;
519 request->http_code = request->slot->http_code;
520 request->slot = NULL;
522 /* Keep locks active */
523 check_locks();
525 if (request->headers != NULL)
526 curl_slist_free_all(request->headers);
528 /* URL is reused for MOVE after PUT */
529 if (request->state != RUN_PUT) {
530 free(request->url);
531 request->url = NULL;
534 if (request->state == RUN_MKCOL) {
535 if (request->curl_result == CURLE_OK ||
536 request->http_code == 405) {
537 remote_dir_exists[request->obj->sha1[0]] = 1;
538 start_put(request);
539 } else {
540 fprintf(stderr, "MKCOL %s failed, aborting (%d/%ld)\n",
541 sha1_to_hex(request->obj->sha1),
542 request->curl_result, request->http_code);
543 request->state = ABORTED;
544 aborted = 1;
546 } else if (request->state == RUN_PUT) {
547 if (request->curl_result == CURLE_OK) {
548 start_move(request);
549 } else {
550 fprintf(stderr, "PUT %s failed, aborting (%d/%ld)\n",
551 sha1_to_hex(request->obj->sha1),
552 request->curl_result, request->http_code);
553 request->state = ABORTED;
554 aborted = 1;
556 } else if (request->state == RUN_MOVE) {
557 if (request->curl_result == CURLE_OK) {
558 if (push_verbosely)
559 fprintf(stderr, " sent %s\n",
560 sha1_to_hex(request->obj->sha1));
561 request->obj->flags |= REMOTE;
562 release_request(request);
563 } else {
564 fprintf(stderr, "MOVE %s failed, aborting (%d/%ld)\n",
565 sha1_to_hex(request->obj->sha1),
566 request->curl_result, request->http_code);
567 request->state = ABORTED;
568 aborted = 1;
570 } else if (request->state == RUN_FETCH_LOOSE) {
571 obj_req = (struct http_object_request *)request->userData;
573 if (finish_http_object_request(obj_req) == 0)
574 if (obj_req->rename == 0)
575 request->obj->flags |= (LOCAL | REMOTE);
577 /* Try fetching packed if necessary */
578 if (request->obj->flags & LOCAL) {
579 release_http_object_request(obj_req);
580 release_request(request);
581 } else
582 start_fetch_packed(request);
584 } else if (request->state == RUN_FETCH_PACKED) {
585 int fail = 1;
586 if (request->curl_result != CURLE_OK) {
587 fprintf(stderr, "Unable to get pack file %s\n%s",
588 request->url, curl_errorstr);
589 } else {
590 preq = (struct http_pack_request *)request->userData;
592 if (preq) {
593 if (finish_http_pack_request(preq) == 0)
594 fail = 0;
595 release_http_pack_request(preq);
598 if (fail)
599 repo->can_update_info_refs = 0;
600 release_request(request);
604 #ifdef USE_CURL_MULTI
605 static int is_running_queue;
606 static int fill_active_slot(void *unused)
608 struct transfer_request *request;
610 if (aborted || !is_running_queue)
611 return 0;
613 for (request = request_queue_head; request; request = request->next) {
614 if (request->state == NEED_FETCH) {
615 start_fetch_loose(request);
616 return 1;
617 } else if (pushing && request->state == NEED_PUSH) {
618 if (remote_dir_exists[request->obj->sha1[0]] == 1) {
619 start_put(request);
620 } else {
621 start_mkcol(request);
623 return 1;
626 return 0;
628 #endif
630 static void get_remote_object_list(unsigned char parent);
632 static void add_fetch_request(struct object *obj)
634 struct transfer_request *request;
636 check_locks();
639 * Don't fetch the object if it's known to exist locally
640 * or is already in the request queue
642 if (remote_dir_exists[obj->sha1[0]] == -1)
643 get_remote_object_list(obj->sha1[0]);
644 if (obj->flags & (LOCAL | FETCHING))
645 return;
647 obj->flags |= FETCHING;
648 request = xmalloc(sizeof(*request));
649 request->obj = obj;
650 request->url = NULL;
651 request->lock = NULL;
652 request->headers = NULL;
653 request->state = NEED_FETCH;
654 request->next = request_queue_head;
655 request_queue_head = request;
657 #ifdef USE_CURL_MULTI
658 fill_active_slots();
659 step_active_slots();
660 #endif
663 static int add_send_request(struct object *obj, struct remote_lock *lock)
665 struct transfer_request *request;
666 struct packed_git *target;
668 /* Keep locks active */
669 check_locks();
672 * Don't push the object if it's known to exist on the remote
673 * or is already in the request queue
675 if (remote_dir_exists[obj->sha1[0]] == -1)
676 get_remote_object_list(obj->sha1[0]);
677 if (obj->flags & (REMOTE | PUSHING))
678 return 0;
679 target = find_sha1_pack(obj->sha1, repo->packs);
680 if (target) {
681 obj->flags |= REMOTE;
682 return 0;
685 obj->flags |= PUSHING;
686 request = xmalloc(sizeof(*request));
687 request->obj = obj;
688 request->url = NULL;
689 request->lock = lock;
690 request->headers = NULL;
691 request->state = NEED_PUSH;
692 request->next = request_queue_head;
693 request_queue_head = request;
695 #ifdef USE_CURL_MULTI
696 fill_active_slots();
697 step_active_slots();
698 #endif
700 return 1;
703 static int fetch_indices(void)
705 int ret;
707 if (push_verbosely)
708 fprintf(stderr, "Getting pack list\n");
710 switch (http_get_info_packs(repo->url, &repo->packs)) {
711 case HTTP_OK:
712 case HTTP_MISSING_TARGET:
713 ret = 0;
714 break;
715 default:
716 ret = -1;
719 return ret;
722 static void one_remote_object(const char *hex)
724 unsigned char sha1[20];
725 struct object *obj;
727 if (get_sha1_hex(hex, sha1) != 0)
728 return;
730 obj = lookup_object(sha1);
731 if (!obj)
732 obj = parse_object(sha1);
734 /* Ignore remote objects that don't exist locally */
735 if (!obj)
736 return;
738 obj->flags |= REMOTE;
739 if (!object_list_contains(objects, obj))
740 object_list_insert(obj, &objects);
743 static void handle_lockprop_ctx(struct xml_ctx *ctx, int tag_closed)
745 int *lock_flags = (int *)ctx->userData;
747 if (tag_closed) {
748 if (!strcmp(ctx->name, DAV_CTX_LOCKENTRY)) {
749 if ((*lock_flags & DAV_PROP_LOCKEX) &&
750 (*lock_flags & DAV_PROP_LOCKWR)) {
751 *lock_flags |= DAV_LOCK_OK;
753 *lock_flags &= DAV_LOCK_OK;
754 } else if (!strcmp(ctx->name, DAV_CTX_LOCKTYPE_WRITE)) {
755 *lock_flags |= DAV_PROP_LOCKWR;
756 } else if (!strcmp(ctx->name, DAV_CTX_LOCKTYPE_EXCLUSIVE)) {
757 *lock_flags |= DAV_PROP_LOCKEX;
762 static void handle_new_lock_ctx(struct xml_ctx *ctx, int tag_closed)
764 struct remote_lock *lock = (struct remote_lock *)ctx->userData;
765 git_SHA_CTX sha_ctx;
766 unsigned char lock_token_sha1[20];
768 if (tag_closed && ctx->cdata) {
769 if (!strcmp(ctx->name, DAV_ACTIVELOCK_OWNER)) {
770 lock->owner = xstrdup(ctx->cdata);
771 } else if (!strcmp(ctx->name, DAV_ACTIVELOCK_TIMEOUT)) {
772 if (starts_with(ctx->cdata, "Second-"))
773 lock->timeout =
774 strtol(ctx->cdata + 7, NULL, 10);
775 } else if (!strcmp(ctx->name, DAV_ACTIVELOCK_TOKEN)) {
776 lock->token = xstrdup(ctx->cdata);
778 git_SHA1_Init(&sha_ctx);
779 git_SHA1_Update(&sha_ctx, lock->token, strlen(lock->token));
780 git_SHA1_Final(lock_token_sha1, &sha_ctx);
782 lock->tmpfile_suffix[0] = '_';
783 memcpy(lock->tmpfile_suffix + 1, sha1_to_hex(lock_token_sha1), 40);
788 static void one_remote_ref(const char *refname);
790 static void
791 xml_start_tag(void *userData, const char *name, const char **atts)
793 struct xml_ctx *ctx = (struct xml_ctx *)userData;
794 const char *c = strchr(name, ':');
795 int new_len;
797 if (c == NULL)
798 c = name;
799 else
800 c++;
802 new_len = strlen(ctx->name) + strlen(c) + 2;
804 if (new_len > ctx->len) {
805 ctx->name = xrealloc(ctx->name, new_len);
806 ctx->len = new_len;
808 strcat(ctx->name, ".");
809 strcat(ctx->name, c);
811 free(ctx->cdata);
812 ctx->cdata = NULL;
814 ctx->userFunc(ctx, 0);
817 static void
818 xml_end_tag(void *userData, const char *name)
820 struct xml_ctx *ctx = (struct xml_ctx *)userData;
821 const char *c = strchr(name, ':');
822 char *ep;
824 ctx->userFunc(ctx, 1);
826 if (c == NULL)
827 c = name;
828 else
829 c++;
831 ep = ctx->name + strlen(ctx->name) - strlen(c) - 1;
832 *ep = 0;
835 static void
836 xml_cdata(void *userData, const XML_Char *s, int len)
838 struct xml_ctx *ctx = (struct xml_ctx *)userData;
839 free(ctx->cdata);
840 ctx->cdata = xmemdupz(s, len);
843 static struct remote_lock *lock_remote(const char *path, long timeout)
845 struct active_request_slot *slot;
846 struct slot_results results;
847 struct buffer out_buffer = { STRBUF_INIT, 0 };
848 struct strbuf in_buffer = STRBUF_INIT;
849 char *url;
850 char *ep;
851 char timeout_header[25];
852 struct remote_lock *lock = NULL;
853 struct curl_slist *dav_headers = NULL;
854 struct xml_ctx ctx;
855 char *escaped;
857 url = xmalloc(strlen(repo->url) + strlen(path) + 1);
858 sprintf(url, "%s%s", repo->url, path);
860 /* Make sure leading directories exist for the remote ref */
861 ep = strchr(url + strlen(repo->url) + 1, '/');
862 while (ep) {
863 char saved_character = ep[1];
864 ep[1] = '\0';
865 slot = get_active_slot();
866 slot->results = &results;
867 curl_setup_http_get(slot->curl, url, DAV_MKCOL);
868 if (start_active_slot(slot)) {
869 run_active_slot(slot);
870 if (results.curl_result != CURLE_OK &&
871 results.http_code != 405) {
872 fprintf(stderr,
873 "Unable to create branch path %s\n",
874 url);
875 free(url);
876 return NULL;
878 } else {
879 fprintf(stderr, "Unable to start MKCOL request\n");
880 free(url);
881 return NULL;
883 ep[1] = saved_character;
884 ep = strchr(ep + 1, '/');
887 escaped = xml_entities(ident_default_email());
888 strbuf_addf(&out_buffer.buf, LOCK_REQUEST, escaped);
889 free(escaped);
891 sprintf(timeout_header, "Timeout: Second-%ld", timeout);
892 dav_headers = curl_slist_append(dav_headers, timeout_header);
893 dav_headers = curl_slist_append(dav_headers, "Content-Type: text/xml");
895 slot = get_active_slot();
896 slot->results = &results;
897 curl_setup_http(slot->curl, url, DAV_LOCK, &out_buffer, fwrite_buffer);
898 curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, dav_headers);
899 curl_easy_setopt(slot->curl, CURLOPT_FILE, &in_buffer);
901 lock = xcalloc(1, sizeof(*lock));
902 lock->timeout = -1;
904 if (start_active_slot(slot)) {
905 run_active_slot(slot);
906 if (results.curl_result == CURLE_OK) {
907 XML_Parser parser = XML_ParserCreate(NULL);
908 enum XML_Status result;
909 ctx.name = xcalloc(10, 1);
910 ctx.len = 0;
911 ctx.cdata = NULL;
912 ctx.userFunc = handle_new_lock_ctx;
913 ctx.userData = lock;
914 XML_SetUserData(parser, &ctx);
915 XML_SetElementHandler(parser, xml_start_tag,
916 xml_end_tag);
917 XML_SetCharacterDataHandler(parser, xml_cdata);
918 result = XML_Parse(parser, in_buffer.buf,
919 in_buffer.len, 1);
920 free(ctx.name);
921 if (result != XML_STATUS_OK) {
922 fprintf(stderr, "XML error: %s\n",
923 XML_ErrorString(
924 XML_GetErrorCode(parser)));
925 lock->timeout = -1;
927 XML_ParserFree(parser);
929 } else {
930 fprintf(stderr, "Unable to start LOCK request\n");
933 curl_slist_free_all(dav_headers);
934 strbuf_release(&out_buffer.buf);
935 strbuf_release(&in_buffer);
937 if (lock->token == NULL || lock->timeout <= 0) {
938 free(lock->token);
939 free(lock->owner);
940 free(url);
941 free(lock);
942 lock = NULL;
943 } else {
944 lock->url = url;
945 lock->start_time = time(NULL);
946 lock->next = repo->locks;
947 repo->locks = lock;
950 return lock;
953 static int unlock_remote(struct remote_lock *lock)
955 struct active_request_slot *slot;
956 struct slot_results results;
957 struct remote_lock *prev = repo->locks;
958 struct curl_slist *dav_headers;
959 int rc = 0;
961 dav_headers = get_dav_token_headers(lock, DAV_HEADER_LOCK);
963 slot = get_active_slot();
964 slot->results = &results;
965 curl_setup_http_get(slot->curl, lock->url, DAV_UNLOCK);
966 curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, dav_headers);
968 if (start_active_slot(slot)) {
969 run_active_slot(slot);
970 if (results.curl_result == CURLE_OK)
971 rc = 1;
972 else
973 fprintf(stderr, "UNLOCK HTTP error %ld\n",
974 results.http_code);
975 } else {
976 fprintf(stderr, "Unable to start UNLOCK request\n");
979 curl_slist_free_all(dav_headers);
981 if (repo->locks == lock) {
982 repo->locks = lock->next;
983 } else {
984 while (prev && prev->next != lock)
985 prev = prev->next;
986 if (prev)
987 prev->next = prev->next->next;
990 free(lock->owner);
991 free(lock->url);
992 free(lock->token);
993 free(lock);
995 return rc;
998 static void remove_locks(void)
1000 struct remote_lock *lock = repo->locks;
1002 fprintf(stderr, "Removing remote locks...\n");
1003 while (lock) {
1004 struct remote_lock *next = lock->next;
1005 unlock_remote(lock);
1006 lock = next;
1010 static void remove_locks_on_signal(int signo)
1012 remove_locks();
1013 sigchain_pop(signo);
1014 raise(signo);
1017 static void remote_ls(const char *path, int flags,
1018 void (*userFunc)(struct remote_ls_ctx *ls),
1019 void *userData);
1021 static void process_ls_object(struct remote_ls_ctx *ls)
1023 unsigned int *parent = (unsigned int *)ls->userData;
1024 char *path = ls->dentry_name;
1025 char *obj_hex;
1027 if (!strcmp(ls->path, ls->dentry_name) && (ls->flags & IS_DIR)) {
1028 remote_dir_exists[*parent] = 1;
1029 return;
1032 if (strlen(path) != 49)
1033 return;
1034 path += 8;
1035 obj_hex = xmalloc(strlen(path));
1036 /* NB: path is not null-terminated, can not use strlcpy here */
1037 memcpy(obj_hex, path, 2);
1038 strcpy(obj_hex + 2, path + 3);
1039 one_remote_object(obj_hex);
1040 free(obj_hex);
1043 static void process_ls_ref(struct remote_ls_ctx *ls)
1045 if (!strcmp(ls->path, ls->dentry_name) && (ls->dentry_flags & IS_DIR)) {
1046 fprintf(stderr, " %s\n", ls->dentry_name);
1047 return;
1050 if (!(ls->dentry_flags & IS_DIR))
1051 one_remote_ref(ls->dentry_name);
1054 static void handle_remote_ls_ctx(struct xml_ctx *ctx, int tag_closed)
1056 struct remote_ls_ctx *ls = (struct remote_ls_ctx *)ctx->userData;
1058 if (tag_closed) {
1059 if (!strcmp(ctx->name, DAV_PROPFIND_RESP) && ls->dentry_name) {
1060 if (ls->dentry_flags & IS_DIR) {
1062 /* ensure collection names end with slash */
1063 str_end_url_with_slash(ls->dentry_name, &ls->dentry_name);
1065 if (ls->flags & PROCESS_DIRS) {
1066 ls->userFunc(ls);
1068 if (strcmp(ls->dentry_name, ls->path) &&
1069 ls->flags & RECURSIVE) {
1070 remote_ls(ls->dentry_name,
1071 ls->flags,
1072 ls->userFunc,
1073 ls->userData);
1075 } else if (ls->flags & PROCESS_FILES) {
1076 ls->userFunc(ls);
1078 } else if (!strcmp(ctx->name, DAV_PROPFIND_NAME) && ctx->cdata) {
1079 char *path = ctx->cdata;
1080 if (*ctx->cdata == 'h') {
1081 path = strstr(path, "//");
1082 if (path) {
1083 path = strchr(path+2, '/');
1086 if (path) {
1087 const char *url = repo->url;
1088 if (repo->path)
1089 url = repo->path;
1090 if (strncmp(path, url, repo->path_len))
1091 error("Parsed path '%s' does not match url: '%s'",
1092 path, url);
1093 else {
1094 path += repo->path_len;
1095 ls->dentry_name = xstrdup(path);
1098 } else if (!strcmp(ctx->name, DAV_PROPFIND_COLLECTION)) {
1099 ls->dentry_flags |= IS_DIR;
1101 } else if (!strcmp(ctx->name, DAV_PROPFIND_RESP)) {
1102 free(ls->dentry_name);
1103 ls->dentry_name = NULL;
1104 ls->dentry_flags = 0;
1109 * NEEDSWORK: remote_ls() ignores info/refs on the remote side. But it
1110 * should _only_ heed the information from that file, instead of trying to
1111 * determine the refs from the remote file system (badly: it does not even
1112 * know about packed-refs).
1114 static void remote_ls(const char *path, int flags,
1115 void (*userFunc)(struct remote_ls_ctx *ls),
1116 void *userData)
1118 char *url = xmalloc(strlen(repo->url) + strlen(path) + 1);
1119 struct active_request_slot *slot;
1120 struct slot_results results;
1121 struct strbuf in_buffer = STRBUF_INIT;
1122 struct buffer out_buffer = { STRBUF_INIT, 0 };
1123 struct curl_slist *dav_headers = NULL;
1124 struct xml_ctx ctx;
1125 struct remote_ls_ctx ls;
1127 ls.flags = flags;
1128 ls.path = xstrdup(path);
1129 ls.dentry_name = NULL;
1130 ls.dentry_flags = 0;
1131 ls.userData = userData;
1132 ls.userFunc = userFunc;
1134 sprintf(url, "%s%s", repo->url, path);
1136 strbuf_addf(&out_buffer.buf, PROPFIND_ALL_REQUEST);
1138 dav_headers = curl_slist_append(dav_headers, "Depth: 1");
1139 dav_headers = curl_slist_append(dav_headers, "Content-Type: text/xml");
1141 slot = get_active_slot();
1142 slot->results = &results;
1143 curl_setup_http(slot->curl, url, DAV_PROPFIND,
1144 &out_buffer, fwrite_buffer);
1145 curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, dav_headers);
1146 curl_easy_setopt(slot->curl, CURLOPT_FILE, &in_buffer);
1148 if (start_active_slot(slot)) {
1149 run_active_slot(slot);
1150 if (results.curl_result == CURLE_OK) {
1151 XML_Parser parser = XML_ParserCreate(NULL);
1152 enum XML_Status result;
1153 ctx.name = xcalloc(10, 1);
1154 ctx.len = 0;
1155 ctx.cdata = NULL;
1156 ctx.userFunc = handle_remote_ls_ctx;
1157 ctx.userData = &ls;
1158 XML_SetUserData(parser, &ctx);
1159 XML_SetElementHandler(parser, xml_start_tag,
1160 xml_end_tag);
1161 XML_SetCharacterDataHandler(parser, xml_cdata);
1162 result = XML_Parse(parser, in_buffer.buf,
1163 in_buffer.len, 1);
1164 free(ctx.name);
1166 if (result != XML_STATUS_OK) {
1167 fprintf(stderr, "XML error: %s\n",
1168 XML_ErrorString(
1169 XML_GetErrorCode(parser)));
1171 XML_ParserFree(parser);
1173 } else {
1174 fprintf(stderr, "Unable to start PROPFIND request\n");
1177 free(ls.path);
1178 free(url);
1179 strbuf_release(&out_buffer.buf);
1180 strbuf_release(&in_buffer);
1181 curl_slist_free_all(dav_headers);
1184 static void get_remote_object_list(unsigned char parent)
1186 char path[] = "objects/XX/";
1187 static const char hex[] = "0123456789abcdef";
1188 unsigned int val = parent;
1190 path[8] = hex[val >> 4];
1191 path[9] = hex[val & 0xf];
1192 remote_dir_exists[val] = 0;
1193 remote_ls(path, (PROCESS_FILES | PROCESS_DIRS),
1194 process_ls_object, &val);
1197 static int locking_available(void)
1199 struct active_request_slot *slot;
1200 struct slot_results results;
1201 struct strbuf in_buffer = STRBUF_INIT;
1202 struct buffer out_buffer = { STRBUF_INIT, 0 };
1203 struct curl_slist *dav_headers = NULL;
1204 struct xml_ctx ctx;
1205 int lock_flags = 0;
1206 char *escaped;
1208 escaped = xml_entities(repo->url);
1209 strbuf_addf(&out_buffer.buf, PROPFIND_SUPPORTEDLOCK_REQUEST, escaped);
1210 free(escaped);
1212 dav_headers = curl_slist_append(dav_headers, "Depth: 0");
1213 dav_headers = curl_slist_append(dav_headers, "Content-Type: text/xml");
1215 slot = get_active_slot();
1216 slot->results = &results;
1217 curl_setup_http(slot->curl, repo->url, DAV_PROPFIND,
1218 &out_buffer, fwrite_buffer);
1219 curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, dav_headers);
1220 curl_easy_setopt(slot->curl, CURLOPT_FILE, &in_buffer);
1222 if (start_active_slot(slot)) {
1223 run_active_slot(slot);
1224 if (results.curl_result == CURLE_OK) {
1225 XML_Parser parser = XML_ParserCreate(NULL);
1226 enum XML_Status result;
1227 ctx.name = xcalloc(10, 1);
1228 ctx.len = 0;
1229 ctx.cdata = NULL;
1230 ctx.userFunc = handle_lockprop_ctx;
1231 ctx.userData = &lock_flags;
1232 XML_SetUserData(parser, &ctx);
1233 XML_SetElementHandler(parser, xml_start_tag,
1234 xml_end_tag);
1235 result = XML_Parse(parser, in_buffer.buf,
1236 in_buffer.len, 1);
1237 free(ctx.name);
1239 if (result != XML_STATUS_OK) {
1240 fprintf(stderr, "XML error: %s\n",
1241 XML_ErrorString(
1242 XML_GetErrorCode(parser)));
1243 lock_flags = 0;
1245 XML_ParserFree(parser);
1246 if (!lock_flags)
1247 error("no DAV locking support on %s",
1248 repo->url);
1250 } else {
1251 error("Cannot access URL %s, return code %d",
1252 repo->url, results.curl_result);
1253 lock_flags = 0;
1255 } else {
1256 error("Unable to start PROPFIND request on %s", repo->url);
1259 strbuf_release(&out_buffer.buf);
1260 strbuf_release(&in_buffer);
1261 curl_slist_free_all(dav_headers);
1263 return lock_flags;
1266 static struct object_list **add_one_object(struct object *obj, struct object_list **p)
1268 struct object_list *entry = xmalloc(sizeof(struct object_list));
1269 entry->item = obj;
1270 entry->next = *p;
1271 *p = entry;
1272 return &entry->next;
1275 static struct object_list **process_blob(struct blob *blob,
1276 struct object_list **p,
1277 struct name_path *path,
1278 const char *name)
1280 struct object *obj = &blob->object;
1282 obj->flags |= LOCAL;
1284 if (obj->flags & (UNINTERESTING | SEEN))
1285 return p;
1287 obj->flags |= SEEN;
1288 return add_one_object(obj, p);
1291 static struct object_list **process_tree(struct tree *tree,
1292 struct object_list **p,
1293 struct name_path *path,
1294 const char *name)
1296 struct object *obj = &tree->object;
1297 struct tree_desc desc;
1298 struct name_entry entry;
1299 struct name_path me;
1301 obj->flags |= LOCAL;
1303 if (obj->flags & (UNINTERESTING | SEEN))
1304 return p;
1305 if (parse_tree(tree) < 0)
1306 die("bad tree object %s", sha1_to_hex(obj->sha1));
1308 obj->flags |= SEEN;
1309 name = xstrdup(name);
1310 p = add_one_object(obj, p);
1311 me.up = path;
1312 me.elem = name;
1313 me.elem_len = strlen(name);
1315 init_tree_desc(&desc, tree->buffer, tree->size);
1317 while (tree_entry(&desc, &entry))
1318 switch (object_type(entry.mode)) {
1319 case OBJ_TREE:
1320 p = process_tree(lookup_tree(entry.sha1), p, &me, name);
1321 break;
1322 case OBJ_BLOB:
1323 p = process_blob(lookup_blob(entry.sha1), p, &me, name);
1324 break;
1325 default:
1326 /* Subproject commit - not in this repository */
1327 break;
1330 free_tree_buffer(tree);
1331 return p;
1334 static int get_delta(struct rev_info *revs, struct remote_lock *lock)
1336 int i;
1337 struct commit *commit;
1338 struct object_list **p = &objects;
1339 int count = 0;
1341 while ((commit = get_revision(revs)) != NULL) {
1342 p = process_tree(commit->tree, p, NULL, "");
1343 commit->object.flags |= LOCAL;
1344 if (!(commit->object.flags & UNINTERESTING))
1345 count += add_send_request(&commit->object, lock);
1348 for (i = 0; i < revs->pending.nr; i++) {
1349 struct object_array_entry *entry = revs->pending.objects + i;
1350 struct object *obj = entry->item;
1351 const char *name = entry->name;
1353 if (obj->flags & (UNINTERESTING | SEEN))
1354 continue;
1355 if (obj->type == OBJ_TAG) {
1356 obj->flags |= SEEN;
1357 p = add_one_object(obj, p);
1358 continue;
1360 if (obj->type == OBJ_TREE) {
1361 p = process_tree((struct tree *)obj, p, NULL, name);
1362 continue;
1364 if (obj->type == OBJ_BLOB) {
1365 p = process_blob((struct blob *)obj, p, NULL, name);
1366 continue;
1368 die("unknown pending object %s (%s)", sha1_to_hex(obj->sha1), name);
1371 while (objects) {
1372 if (!(objects->item->flags & UNINTERESTING))
1373 count += add_send_request(objects->item, lock);
1374 objects = objects->next;
1377 return count;
1380 static int update_remote(unsigned char *sha1, struct remote_lock *lock)
1382 struct active_request_slot *slot;
1383 struct slot_results results;
1384 struct buffer out_buffer = { STRBUF_INIT, 0 };
1385 struct curl_slist *dav_headers;
1387 dav_headers = get_dav_token_headers(lock, DAV_HEADER_IF);
1389 strbuf_addf(&out_buffer.buf, "%s\n", sha1_to_hex(sha1));
1391 slot = get_active_slot();
1392 slot->results = &results;
1393 curl_setup_http(slot->curl, lock->url, DAV_PUT,
1394 &out_buffer, fwrite_null);
1395 curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, dav_headers);
1397 if (start_active_slot(slot)) {
1398 run_active_slot(slot);
1399 strbuf_release(&out_buffer.buf);
1400 if (results.curl_result != CURLE_OK) {
1401 fprintf(stderr,
1402 "PUT error: curl result=%d, HTTP code=%ld\n",
1403 results.curl_result, results.http_code);
1404 /* We should attempt recovery? */
1405 return 0;
1407 } else {
1408 strbuf_release(&out_buffer.buf);
1409 fprintf(stderr, "Unable to start PUT request\n");
1410 return 0;
1413 return 1;
1416 static struct ref *remote_refs;
1418 static void one_remote_ref(const char *refname)
1420 struct ref *ref;
1421 struct object *obj;
1423 ref = alloc_ref(refname);
1425 if (http_fetch_ref(repo->url, ref) != 0) {
1426 fprintf(stderr,
1427 "Unable to fetch ref %s from %s\n",
1428 refname, repo->url);
1429 free(ref);
1430 return;
1434 * Fetch a copy of the object if it doesn't exist locally - it
1435 * may be required for updating server info later.
1437 if (repo->can_update_info_refs && !has_sha1_file(ref->old_sha1)) {
1438 obj = lookup_unknown_object(ref->old_sha1);
1439 if (obj) {
1440 fprintf(stderr, " fetch %s for %s\n",
1441 sha1_to_hex(ref->old_sha1), refname);
1442 add_fetch_request(obj);
1446 ref->next = remote_refs;
1447 remote_refs = ref;
1450 static void get_dav_remote_heads(void)
1452 remote_ls("refs/", (PROCESS_FILES | PROCESS_DIRS | RECURSIVE), process_ls_ref, NULL);
1455 static void add_remote_info_ref(struct remote_ls_ctx *ls)
1457 struct strbuf *buf = (struct strbuf *)ls->userData;
1458 struct object *o;
1459 int len;
1460 char *ref_info;
1461 struct ref *ref;
1463 ref = alloc_ref(ls->dentry_name);
1465 if (http_fetch_ref(repo->url, ref) != 0) {
1466 fprintf(stderr,
1467 "Unable to fetch ref %s from %s\n",
1468 ls->dentry_name, repo->url);
1469 aborted = 1;
1470 free(ref);
1471 return;
1474 o = parse_object(ref->old_sha1);
1475 if (!o) {
1476 fprintf(stderr,
1477 "Unable to parse object %s for remote ref %s\n",
1478 sha1_to_hex(ref->old_sha1), ls->dentry_name);
1479 aborted = 1;
1480 free(ref);
1481 return;
1484 len = strlen(ls->dentry_name) + 42;
1485 ref_info = xcalloc(len + 1, 1);
1486 sprintf(ref_info, "%s %s\n",
1487 sha1_to_hex(ref->old_sha1), ls->dentry_name);
1488 fwrite_buffer(ref_info, 1, len, buf);
1489 free(ref_info);
1491 if (o->type == OBJ_TAG) {
1492 o = deref_tag(o, ls->dentry_name, 0);
1493 if (o) {
1494 len = strlen(ls->dentry_name) + 45;
1495 ref_info = xcalloc(len + 1, 1);
1496 sprintf(ref_info, "%s %s^{}\n",
1497 sha1_to_hex(o->sha1), ls->dentry_name);
1498 fwrite_buffer(ref_info, 1, len, buf);
1499 free(ref_info);
1502 free(ref);
1505 static void update_remote_info_refs(struct remote_lock *lock)
1507 struct buffer buffer = { STRBUF_INIT, 0 };
1508 struct active_request_slot *slot;
1509 struct slot_results results;
1510 struct curl_slist *dav_headers;
1512 remote_ls("refs/", (PROCESS_FILES | RECURSIVE),
1513 add_remote_info_ref, &buffer.buf);
1514 if (!aborted) {
1515 dav_headers = get_dav_token_headers(lock, DAV_HEADER_IF);
1517 slot = get_active_slot();
1518 slot->results = &results;
1519 curl_setup_http(slot->curl, lock->url, DAV_PUT,
1520 &buffer, fwrite_null);
1521 curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, dav_headers);
1523 if (start_active_slot(slot)) {
1524 run_active_slot(slot);
1525 if (results.curl_result != CURLE_OK) {
1526 fprintf(stderr,
1527 "PUT error: curl result=%d, HTTP code=%ld\n",
1528 results.curl_result, results.http_code);
1532 strbuf_release(&buffer.buf);
1535 static int remote_exists(const char *path)
1537 char *url = xmalloc(strlen(repo->url) + strlen(path) + 1);
1538 int ret;
1540 sprintf(url, "%s%s", repo->url, path);
1542 switch (http_get_strbuf(url, NULL, NULL)) {
1543 case HTTP_OK:
1544 ret = 1;
1545 break;
1546 case HTTP_MISSING_TARGET:
1547 ret = 0;
1548 break;
1549 case HTTP_ERROR:
1550 error("unable to access '%s': %s", url, curl_errorstr);
1551 default:
1552 ret = -1;
1554 free(url);
1555 return ret;
1558 static void fetch_symref(const char *path, char **symref, unsigned char *sha1)
1560 char *url;
1561 struct strbuf buffer = STRBUF_INIT;
1563 url = xmalloc(strlen(repo->url) + strlen(path) + 1);
1564 sprintf(url, "%s%s", repo->url, path);
1566 if (http_get_strbuf(url, &buffer, NULL) != HTTP_OK)
1567 die("Couldn't get %s for remote symref\n%s", url,
1568 curl_errorstr);
1569 free(url);
1571 free(*symref);
1572 *symref = NULL;
1573 hashclr(sha1);
1575 if (buffer.len == 0)
1576 return;
1578 /* If it's a symref, set the refname; otherwise try for a sha1 */
1579 if (starts_with((char *)buffer.buf, "ref: ")) {
1580 *symref = xmemdupz((char *)buffer.buf + 5, buffer.len - 6);
1581 } else {
1582 get_sha1_hex(buffer.buf, sha1);
1585 strbuf_release(&buffer);
1588 static int verify_merge_base(unsigned char *head_sha1, struct ref *remote)
1590 struct commit *head = lookup_commit_or_die(head_sha1, "HEAD");
1591 struct commit *branch = lookup_commit_or_die(remote->old_sha1, remote->name);
1593 return in_merge_bases(branch, head);
1596 static int delete_remote_branch(const char *pattern, int force)
1598 struct ref *refs = remote_refs;
1599 struct ref *remote_ref = NULL;
1600 unsigned char head_sha1[20];
1601 char *symref = NULL;
1602 int match;
1603 int patlen = strlen(pattern);
1604 int i;
1605 struct active_request_slot *slot;
1606 struct slot_results results;
1607 char *url;
1609 /* Find the remote branch(es) matching the specified branch name */
1610 for (match = 0; refs; refs = refs->next) {
1611 char *name = refs->name;
1612 int namelen = strlen(name);
1613 if (namelen < patlen ||
1614 memcmp(name + namelen - patlen, pattern, patlen))
1615 continue;
1616 if (namelen != patlen && name[namelen - patlen - 1] != '/')
1617 continue;
1618 match++;
1619 remote_ref = refs;
1621 if (match == 0)
1622 return error("No remote branch matches %s", pattern);
1623 if (match != 1)
1624 return error("More than one remote branch matches %s",
1625 pattern);
1628 * Remote HEAD must be a symref (not exactly foolproof; a remote
1629 * symlink to a symref will look like a symref)
1631 fetch_symref("HEAD", &symref, head_sha1);
1632 if (!symref)
1633 return error("Remote HEAD is not a symref");
1635 /* Remote branch must not be the remote HEAD */
1636 for (i = 0; symref && i < MAXDEPTH; i++) {
1637 if (!strcmp(remote_ref->name, symref))
1638 return error("Remote branch %s is the current HEAD",
1639 remote_ref->name);
1640 fetch_symref(symref, &symref, head_sha1);
1643 /* Run extra sanity checks if delete is not forced */
1644 if (!force) {
1645 /* Remote HEAD must resolve to a known object */
1646 if (symref)
1647 return error("Remote HEAD symrefs too deep");
1648 if (is_null_sha1(head_sha1))
1649 return error("Unable to resolve remote HEAD");
1650 if (!has_sha1_file(head_sha1))
1651 return error("Remote HEAD resolves to object %s\nwhich does not exist locally, perhaps you need to fetch?", sha1_to_hex(head_sha1));
1653 /* Remote branch must resolve to a known object */
1654 if (is_null_sha1(remote_ref->old_sha1))
1655 return error("Unable to resolve remote branch %s",
1656 remote_ref->name);
1657 if (!has_sha1_file(remote_ref->old_sha1))
1658 return error("Remote branch %s resolves to object %s\nwhich does not exist locally, perhaps you need to fetch?", remote_ref->name, sha1_to_hex(remote_ref->old_sha1));
1660 /* Remote branch must be an ancestor of remote HEAD */
1661 if (!verify_merge_base(head_sha1, remote_ref)) {
1662 return error("The branch '%s' is not an ancestor "
1663 "of your current HEAD.\n"
1664 "If you are sure you want to delete it,"
1665 " run:\n\t'git http-push -D %s %s'",
1666 remote_ref->name, repo->url, pattern);
1670 /* Send delete request */
1671 fprintf(stderr, "Removing remote branch '%s'\n", remote_ref->name);
1672 if (dry_run)
1673 return 0;
1674 url = xmalloc(strlen(repo->url) + strlen(remote_ref->name) + 1);
1675 sprintf(url, "%s%s", repo->url, remote_ref->name);
1676 slot = get_active_slot();
1677 slot->results = &results;
1678 curl_setup_http_get(slot->curl, url, DAV_DELETE);
1679 if (start_active_slot(slot)) {
1680 run_active_slot(slot);
1681 free(url);
1682 if (results.curl_result != CURLE_OK)
1683 return error("DELETE request failed (%d/%ld)",
1684 results.curl_result, results.http_code);
1685 } else {
1686 free(url);
1687 return error("Unable to start DELETE request");
1690 return 0;
1693 static void run_request_queue(void)
1695 #ifdef USE_CURL_MULTI
1696 is_running_queue = 1;
1697 fill_active_slots();
1698 add_fill_function(NULL, fill_active_slot);
1699 #endif
1700 do {
1701 finish_all_active_slots();
1702 #ifdef USE_CURL_MULTI
1703 fill_active_slots();
1704 #endif
1705 } while (request_queue_head && !aborted);
1707 #ifdef USE_CURL_MULTI
1708 is_running_queue = 0;
1709 #endif
1712 int main(int argc, char **argv)
1714 struct transfer_request *request;
1715 struct transfer_request *next_request;
1716 int nr_refspec = 0;
1717 char **refspec = NULL;
1718 struct remote_lock *ref_lock = NULL;
1719 struct remote_lock *info_ref_lock = NULL;
1720 struct rev_info revs;
1721 int delete_branch = 0;
1722 int force_delete = 0;
1723 int objects_to_send;
1724 int rc = 0;
1725 int i;
1726 int new_refs;
1727 struct ref *ref, *local_refs;
1729 git_setup_gettext();
1731 git_extract_argv0_path(argv[0]);
1733 repo = xcalloc(1, sizeof(*repo));
1735 argv++;
1736 for (i = 1; i < argc; i++, argv++) {
1737 char *arg = *argv;
1739 if (*arg == '-') {
1740 if (!strcmp(arg, "--all")) {
1741 push_all = MATCH_REFS_ALL;
1742 continue;
1744 if (!strcmp(arg, "--force")) {
1745 force_all = 1;
1746 continue;
1748 if (!strcmp(arg, "--dry-run")) {
1749 dry_run = 1;
1750 continue;
1752 if (!strcmp(arg, "--helper-status")) {
1753 helper_status = 1;
1754 continue;
1756 if (!strcmp(arg, "--verbose")) {
1757 push_verbosely = 1;
1758 http_is_verbose = 1;
1759 continue;
1761 if (!strcmp(arg, "-d")) {
1762 delete_branch = 1;
1763 continue;
1765 if (!strcmp(arg, "-D")) {
1766 delete_branch = 1;
1767 force_delete = 1;
1768 continue;
1770 if (!strcmp(arg, "-h"))
1771 usage(http_push_usage);
1773 if (!repo->url) {
1774 char *path = strstr(arg, "//");
1775 str_end_url_with_slash(arg, &repo->url);
1776 repo->path_len = strlen(repo->url);
1777 if (path) {
1778 repo->path = strchr(path+2, '/');
1779 if (repo->path)
1780 repo->path_len = strlen(repo->path);
1782 continue;
1784 refspec = argv;
1785 nr_refspec = argc - i;
1786 break;
1789 #ifndef USE_CURL_MULTI
1790 die("git-push is not available for http/https repository when not compiled with USE_CURL_MULTI");
1791 #endif
1793 if (!repo->url)
1794 usage(http_push_usage);
1796 if (delete_branch && nr_refspec != 1)
1797 die("You must specify only one branch name when deleting a remote branch");
1799 setup_git_directory();
1801 memset(remote_dir_exists, -1, 256);
1803 http_init(NULL, repo->url, 1);
1805 #ifdef USE_CURL_MULTI
1806 is_running_queue = 0;
1807 #endif
1809 /* Verify DAV compliance/lock support */
1810 if (!locking_available()) {
1811 rc = 1;
1812 goto cleanup;
1815 sigchain_push_common(remove_locks_on_signal);
1817 /* Check whether the remote has server info files */
1818 repo->can_update_info_refs = 0;
1819 repo->has_info_refs = remote_exists("info/refs");
1820 repo->has_info_packs = remote_exists("objects/info/packs");
1821 if (repo->has_info_refs) {
1822 info_ref_lock = lock_remote("info/refs", LOCK_TIME);
1823 if (info_ref_lock)
1824 repo->can_update_info_refs = 1;
1825 else {
1826 error("cannot lock existing info/refs");
1827 rc = 1;
1828 goto cleanup;
1831 if (repo->has_info_packs)
1832 fetch_indices();
1834 /* Get a list of all local and remote heads to validate refspecs */
1835 local_refs = get_local_heads();
1836 fprintf(stderr, "Fetching remote heads...\n");
1837 get_dav_remote_heads();
1838 run_request_queue();
1840 /* Remove a remote branch if -d or -D was specified */
1841 if (delete_branch) {
1842 if (delete_remote_branch(refspec[0], force_delete) == -1) {
1843 fprintf(stderr, "Unable to delete remote branch %s\n",
1844 refspec[0]);
1845 if (helper_status)
1846 printf("error %s cannot remove\n", refspec[0]);
1848 goto cleanup;
1851 /* match them up */
1852 if (match_push_refs(local_refs, &remote_refs,
1853 nr_refspec, (const char **) refspec, push_all)) {
1854 rc = -1;
1855 goto cleanup;
1857 if (!remote_refs) {
1858 fprintf(stderr, "No refs in common and none specified; doing nothing.\n");
1859 if (helper_status)
1860 printf("error null no match\n");
1861 rc = 0;
1862 goto cleanup;
1865 new_refs = 0;
1866 for (ref = remote_refs; ref; ref = ref->next) {
1867 char old_hex[60], *new_hex;
1868 const char *commit_argv[5];
1869 int commit_argc;
1870 char *new_sha1_hex, *old_sha1_hex;
1872 if (!ref->peer_ref)
1873 continue;
1875 if (is_null_sha1(ref->peer_ref->new_sha1)) {
1876 if (delete_remote_branch(ref->name, 1) == -1) {
1877 error("Could not remove %s", ref->name);
1878 if (helper_status)
1879 printf("error %s cannot remove\n", ref->name);
1880 rc = -4;
1882 else if (helper_status)
1883 printf("ok %s\n", ref->name);
1884 new_refs++;
1885 continue;
1888 if (!hashcmp(ref->old_sha1, ref->peer_ref->new_sha1)) {
1889 if (push_verbosely)
1890 fprintf(stderr, "'%s': up-to-date\n", ref->name);
1891 if (helper_status)
1892 printf("ok %s up to date\n", ref->name);
1893 continue;
1896 if (!force_all &&
1897 !is_null_sha1(ref->old_sha1) &&
1898 !ref->force) {
1899 if (!has_sha1_file(ref->old_sha1) ||
1900 !ref_newer(ref->peer_ref->new_sha1,
1901 ref->old_sha1)) {
1903 * We do not have the remote ref, or
1904 * we know that the remote ref is not
1905 * an ancestor of what we are trying to
1906 * push. Either way this can be losing
1907 * commits at the remote end and likely
1908 * we were not up to date to begin with.
1910 error("remote '%s' is not an ancestor of\n"
1911 "local '%s'.\n"
1912 "Maybe you are not up-to-date and "
1913 "need to pull first?",
1914 ref->name,
1915 ref->peer_ref->name);
1916 if (helper_status)
1917 printf("error %s non-fast forward\n", ref->name);
1918 rc = -2;
1919 continue;
1922 hashcpy(ref->new_sha1, ref->peer_ref->new_sha1);
1923 new_refs++;
1924 strcpy(old_hex, sha1_to_hex(ref->old_sha1));
1925 new_hex = sha1_to_hex(ref->new_sha1);
1927 fprintf(stderr, "updating '%s'", ref->name);
1928 if (strcmp(ref->name, ref->peer_ref->name))
1929 fprintf(stderr, " using '%s'", ref->peer_ref->name);
1930 fprintf(stderr, "\n from %s\n to %s\n", old_hex, new_hex);
1931 if (dry_run) {
1932 if (helper_status)
1933 printf("ok %s\n", ref->name);
1934 continue;
1937 /* Lock remote branch ref */
1938 ref_lock = lock_remote(ref->name, LOCK_TIME);
1939 if (ref_lock == NULL) {
1940 fprintf(stderr, "Unable to lock remote branch %s\n",
1941 ref->name);
1942 if (helper_status)
1943 printf("error %s lock error\n", ref->name);
1944 rc = 1;
1945 continue;
1948 /* Set up revision info for this refspec */
1949 commit_argc = 3;
1950 new_sha1_hex = xstrdup(sha1_to_hex(ref->new_sha1));
1951 old_sha1_hex = NULL;
1952 commit_argv[1] = "--objects";
1953 commit_argv[2] = new_sha1_hex;
1954 if (!push_all && !is_null_sha1(ref->old_sha1)) {
1955 old_sha1_hex = xmalloc(42);
1956 sprintf(old_sha1_hex, "^%s",
1957 sha1_to_hex(ref->old_sha1));
1958 commit_argv[3] = old_sha1_hex;
1959 commit_argc++;
1961 commit_argv[commit_argc] = NULL;
1962 init_revisions(&revs, setup_git_directory());
1963 setup_revisions(commit_argc, commit_argv, &revs, NULL);
1964 revs.edge_hint = 0; /* just in case */
1965 free(new_sha1_hex);
1966 if (old_sha1_hex) {
1967 free(old_sha1_hex);
1968 commit_argv[1] = NULL;
1971 /* Generate a list of objects that need to be pushed */
1972 pushing = 0;
1973 if (prepare_revision_walk(&revs))
1974 die("revision walk setup failed");
1975 mark_edges_uninteresting(&revs, NULL);
1976 objects_to_send = get_delta(&revs, ref_lock);
1977 finish_all_active_slots();
1979 /* Push missing objects to remote, this would be a
1980 convenient time to pack them first if appropriate. */
1981 pushing = 1;
1982 if (objects_to_send)
1983 fprintf(stderr, " sending %d objects\n",
1984 objects_to_send);
1986 run_request_queue();
1988 /* Update the remote branch if all went well */
1989 if (aborted || !update_remote(ref->new_sha1, ref_lock))
1990 rc = 1;
1992 if (!rc)
1993 fprintf(stderr, " done\n");
1994 if (helper_status)
1995 printf("%s %s\n", !rc ? "ok" : "error", ref->name);
1996 unlock_remote(ref_lock);
1997 check_locks();
2000 /* Update remote server info if appropriate */
2001 if (repo->has_info_refs && new_refs) {
2002 if (info_ref_lock && repo->can_update_info_refs) {
2003 fprintf(stderr, "Updating remote server info\n");
2004 if (!dry_run)
2005 update_remote_info_refs(info_ref_lock);
2006 } else {
2007 fprintf(stderr, "Unable to update server info\n");
2011 cleanup:
2012 if (info_ref_lock)
2013 unlock_remote(info_ref_lock);
2014 free(repo);
2016 http_cleanup();
2018 request = request_queue_head;
2019 while (request != NULL) {
2020 next_request = request->next;
2021 release_request(request);
2022 request = next_request;
2025 return rc;