http-push.con commit Merge branch 'jk/clean-d-pathspec' (15520a8)
   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
  14#ifdef EXPAT_NEEDS_XMLPARSE_H
  15#include <xmlparse.h>
  16#else
  17#include <expat.h>
  18#endif
  19
  20static const char http_push_usage[] =
  21"git http-push [--all] [--dry-run] [--force] [--verbose] <remote> [<head>...]\n";
  22
  23#ifndef XML_STATUS_OK
  24enum XML_Status {
  25  XML_STATUS_OK = 1,
  26  XML_STATUS_ERROR = 0
  27};
  28#define XML_STATUS_OK    1
  29#define XML_STATUS_ERROR 0
  30#endif
  31
  32#define PREV_BUF_SIZE 4096
  33
  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"
  42
  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)
  47
  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"
  58
  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>"
  63
  64#define LOCK_TIME 600
  65#define LOCK_REFRESH 30
  66
  67/* bits #0-15 in revision.h */
  68
  69#define LOCAL    (1u<<16)
  70#define REMOTE   (1u<<17)
  71#define FETCHING (1u<<18)
  72#define PUSHING  (1u<<19)
  73
  74/* We allow "recursive" symbolic refs. Only within reason, though */
  75#define MAXDEPTH 5
  76
  77static int pushing;
  78static int aborted;
  79static signed char remote_dir_exists[256];
  80
  81static int push_verbosely;
  82static int push_all = MATCH_REFS_NONE;
  83static int force_all;
  84static int dry_run;
  85static int helper_status;
  86
  87static struct object_list *objects;
  88
  89struct repo {
  90        char *url;
  91        char *path;
  92        int path_len;
  93        int has_info_refs;
  94        int can_update_info_refs;
  95        int has_info_packs;
  96        struct packed_git *packs;
  97        struct remote_lock *locks;
  98};
  99
 100static struct repo *repo;
 101
 102enum transfer_state {
 103        NEED_FETCH,
 104        RUN_FETCH_LOOSE,
 105        RUN_FETCH_PACKED,
 106        NEED_PUSH,
 107        RUN_MKCOL,
 108        RUN_PUT,
 109        RUN_MOVE,
 110        ABORTED,
 111        COMPLETE
 112};
 113
 114struct transfer_request {
 115        struct object *obj;
 116        char *url;
 117        char *dest;
 118        struct remote_lock *lock;
 119        struct curl_slist *headers;
 120        struct buffer buffer;
 121        enum transfer_state state;
 122        CURLcode curl_result;
 123        char errorstr[CURL_ERROR_SIZE];
 124        long http_code;
 125        void *userData;
 126        struct active_request_slot *slot;
 127        struct transfer_request *next;
 128};
 129
 130static struct transfer_request *request_queue_head;
 131
 132struct xml_ctx {
 133        char *name;
 134        int len;
 135        char *cdata;
 136        void (*userFunc)(struct xml_ctx *ctx, int tag_closed);
 137        void *userData;
 138};
 139
 140struct remote_lock {
 141        char *url;
 142        char *owner;
 143        char *token;
 144        char tmpfile_suffix[41];
 145        time_t start_time;
 146        long timeout;
 147        int refreshing;
 148        struct remote_lock *next;
 149};
 150
 151/* Flags that control remote_ls processing */
 152#define PROCESS_FILES (1u << 0)
 153#define PROCESS_DIRS  (1u << 1)
 154#define RECURSIVE     (1u << 2)
 155
 156/* Flags that remote_ls passes to callback functions */
 157#define IS_DIR (1u << 0)
 158
 159struct remote_ls_ctx {
 160        char *path;
 161        void (*userFunc)(struct remote_ls_ctx *ls);
 162        void *userData;
 163        int flags;
 164        char *dentry_name;
 165        int dentry_flags;
 166        struct remote_ls_ctx *parent;
 167};
 168
 169/* get_dav_token_headers options */
 170enum dav_header_flag {
 171        DAV_HEADER_IF = (1u << 0),
 172        DAV_HEADER_LOCK = (1u << 1),
 173        DAV_HEADER_TIMEOUT = (1u << 2)
 174};
 175
 176static char *xml_entities(const char *s)
 177{
 178        struct strbuf buf = STRBUF_INIT;
 179        strbuf_addstr_xml_quoted(&buf, s);
 180        return strbuf_detach(&buf, NULL);
 181}
 182
 183static void curl_setup_http_get(CURL *curl, const char *url,
 184                const char *custom_req)
 185{
 186        curl_easy_setopt(curl, CURLOPT_HTTPGET, 1);
 187        curl_easy_setopt(curl, CURLOPT_URL, url);
 188        curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, custom_req);
 189        curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, fwrite_null);
 190}
 191
 192static void curl_setup_http(CURL *curl, const char *url,
 193                const char *custom_req, struct buffer *buffer,
 194                curl_write_callback write_fn)
 195{
 196        curl_easy_setopt(curl, CURLOPT_PUT, 1);
 197        curl_easy_setopt(curl, CURLOPT_URL, url);
 198        curl_easy_setopt(curl, CURLOPT_INFILE, buffer);
 199        curl_easy_setopt(curl, CURLOPT_INFILESIZE, buffer->buf.len);
 200        curl_easy_setopt(curl, CURLOPT_READFUNCTION, fread_buffer);
 201#ifndef NO_CURL_IOCTL
 202        curl_easy_setopt(curl, CURLOPT_IOCTLFUNCTION, ioctl_buffer);
 203        curl_easy_setopt(curl, CURLOPT_IOCTLDATA, &buffer);
 204#endif
 205        curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_fn);
 206        curl_easy_setopt(curl, CURLOPT_NOBODY, 0);
 207        curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, custom_req);
 208        curl_easy_setopt(curl, CURLOPT_UPLOAD, 1);
 209}
 210
 211static struct curl_slist *get_dav_token_headers(struct remote_lock *lock, enum dav_header_flag options)
 212{
 213        struct strbuf buf = STRBUF_INIT;
 214        struct curl_slist *dav_headers = NULL;
 215
 216        if (options & DAV_HEADER_IF) {
 217                strbuf_addf(&buf, "If: (<%s>)", lock->token);
 218                dav_headers = curl_slist_append(dav_headers, buf.buf);
 219                strbuf_reset(&buf);
 220        }
 221        if (options & DAV_HEADER_LOCK) {
 222                strbuf_addf(&buf, "Lock-Token: <%s>", lock->token);
 223                dav_headers = curl_slist_append(dav_headers, buf.buf);
 224                strbuf_reset(&buf);
 225        }
 226        if (options & DAV_HEADER_TIMEOUT) {
 227                strbuf_addf(&buf, "Timeout: Second-%ld", lock->timeout);
 228                dav_headers = curl_slist_append(dav_headers, buf.buf);
 229                strbuf_reset(&buf);
 230        }
 231        strbuf_release(&buf);
 232
 233        return dav_headers;
 234}
 235
 236static void finish_request(struct transfer_request *request);
 237static void release_request(struct transfer_request *request);
 238
 239static void process_response(void *callback_data)
 240{
 241        struct transfer_request *request =
 242                (struct transfer_request *)callback_data;
 243
 244        finish_request(request);
 245}
 246
 247#ifdef USE_CURL_MULTI
 248
 249static void start_fetch_loose(struct transfer_request *request)
 250{
 251        struct active_request_slot *slot;
 252        struct http_object_request *obj_req;
 253
 254        obj_req = new_http_object_request(repo->url, request->obj->sha1);
 255        if (obj_req == NULL) {
 256                request->state = ABORTED;
 257                return;
 258        }
 259
 260        slot = obj_req->slot;
 261        slot->callback_func = process_response;
 262        slot->callback_data = request;
 263        request->slot = slot;
 264        request->userData = obj_req;
 265
 266        /* Try to get the request started, abort the request on error */
 267        request->state = RUN_FETCH_LOOSE;
 268        if (!start_active_slot(slot)) {
 269                fprintf(stderr, "Unable to start GET request\n");
 270                repo->can_update_info_refs = 0;
 271                release_http_object_request(obj_req);
 272                release_request(request);
 273        }
 274}
 275
 276static void start_mkcol(struct transfer_request *request)
 277{
 278        char *hex = sha1_to_hex(request->obj->sha1);
 279        struct active_request_slot *slot;
 280
 281        request->url = get_remote_object_url(repo->url, hex, 1);
 282
 283        slot = get_active_slot();
 284        slot->callback_func = process_response;
 285        slot->callback_data = request;
 286        curl_setup_http_get(slot->curl, request->url, DAV_MKCOL);
 287        curl_easy_setopt(slot->curl, CURLOPT_ERRORBUFFER, request->errorstr);
 288
 289        if (start_active_slot(slot)) {
 290                request->slot = slot;
 291                request->state = RUN_MKCOL;
 292        } else {
 293                request->state = ABORTED;
 294                free(request->url);
 295                request->url = NULL;
 296        }
 297}
 298#endif
 299
 300static void start_fetch_packed(struct transfer_request *request)
 301{
 302        struct packed_git *target;
 303
 304        struct transfer_request *check_request = request_queue_head;
 305        struct http_pack_request *preq;
 306
 307        target = find_sha1_pack(request->obj->sha1, repo->packs);
 308        if (!target) {
 309                fprintf(stderr, "Unable to fetch %s, will not be able to update server info refs\n", sha1_to_hex(request->obj->sha1));
 310                repo->can_update_info_refs = 0;
 311                release_request(request);
 312                return;
 313        }
 314
 315        fprintf(stderr, "Fetching pack %s\n", sha1_to_hex(target->sha1));
 316        fprintf(stderr, " which contains %s\n", sha1_to_hex(request->obj->sha1));
 317
 318        preq = new_http_pack_request(target, repo->url);
 319        if (preq == NULL) {
 320                release_http_pack_request(preq);
 321                repo->can_update_info_refs = 0;
 322                return;
 323        }
 324        preq->lst = &repo->packs;
 325
 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;
 333                }
 334                check_request = check_request->next;
 335        }
 336
 337        preq->slot->callback_func = process_response;
 338        preq->slot->callback_data = request;
 339        request->slot = preq->slot;
 340        request->userData = preq;
 341
 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);
 349        }
 350}
 351
 352static void start_put(struct transfer_request *request)
 353{
 354        char *hex = sha1_to_hex(request->obj->sha1);
 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;
 364
 365        unpacked = read_sha1_file(request->obj->sha1, &type, &len);
 366        hdrlen = sprintf(hdr, "%s %lu", typename(type), len) + 1;
 367
 368        /* Set it up */
 369        memset(&stream, 0, sizeof(stream));
 370        git_deflate_init(&stream, zlib_compression_level);
 371        size = git_deflate_bound(&stream, len + hdrlen);
 372        strbuf_init(&request->buffer.buf, size);
 373        request->buffer.posn = 0;
 374
 375        /* Compress it */
 376        stream.next_out = (unsigned char *)request->buffer.buf.buf;
 377        stream.avail_out = size;
 378
 379        /* First header.. */
 380        stream.next_in = (void *)hdr;
 381        stream.avail_in = hdrlen;
 382        while (git_deflate(&stream, 0) == Z_OK)
 383                ; /* nothing */
 384
 385        /* Then the data itself.. */
 386        stream.next_in = unpacked;
 387        stream.avail_in = len;
 388        while (git_deflate(&stream, Z_FINISH) == Z_OK)
 389                ; /* nothing */
 390        git_deflate_end(&stream);
 391        free(unpacked);
 392
 393        request->buffer.buf.len = stream.total_out;
 394
 395        strbuf_addstr(&buf, "Destination: ");
 396        append_remote_object_url(&buf, repo->url, hex, 0);
 397        request->dest = strbuf_detach(&buf, NULL);
 398
 399        append_remote_object_url(&buf, repo->url, hex, 0);
 400        strbuf_add(&buf, request->lock->tmpfile_suffix, 41);
 401        request->url = strbuf_detach(&buf, NULL);
 402
 403        slot = get_active_slot();
 404        slot->callback_func = process_response;
 405        slot->callback_data = request;
 406        curl_setup_http(slot->curl, request->url, DAV_PUT,
 407                        &request->buffer, fwrite_null);
 408
 409        if (start_active_slot(slot)) {
 410                request->slot = slot;
 411                request->state = RUN_PUT;
 412        } else {
 413                request->state = ABORTED;
 414                free(request->url);
 415                request->url = NULL;
 416        }
 417}
 418
 419static void start_move(struct transfer_request *request)
 420{
 421        struct active_request_slot *slot;
 422        struct curl_slist *dav_headers = NULL;
 423
 424        slot = get_active_slot();
 425        slot->callback_func = process_response;
 426        slot->callback_data = request;
 427        curl_setup_http_get(slot->curl, request->url, DAV_MOVE);
 428        dav_headers = curl_slist_append(dav_headers, request->dest);
 429        dav_headers = curl_slist_append(dav_headers, "Overwrite: T");
 430        curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, dav_headers);
 431
 432        if (start_active_slot(slot)) {
 433                request->slot = slot;
 434                request->state = RUN_MOVE;
 435        } else {
 436                request->state = ABORTED;
 437                free(request->url);
 438                request->url = NULL;
 439        }
 440}
 441
 442static int refresh_lock(struct remote_lock *lock)
 443{
 444        struct active_request_slot *slot;
 445        struct slot_results results;
 446        struct curl_slist *dav_headers;
 447        int rc = 0;
 448
 449        lock->refreshing = 1;
 450
 451        dav_headers = get_dav_token_headers(lock, DAV_HEADER_IF | DAV_HEADER_TIMEOUT);
 452
 453        slot = get_active_slot();
 454        slot->results = &results;
 455        curl_setup_http_get(slot->curl, lock->url, DAV_LOCK);
 456        curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, dav_headers);
 457
 458        if (start_active_slot(slot)) {
 459                run_active_slot(slot);
 460                if (results.curl_result != CURLE_OK) {
 461                        fprintf(stderr, "LOCK HTTP error %ld\n",
 462                                results.http_code);
 463                } else {
 464                        lock->start_time = time(NULL);
 465                        rc = 1;
 466                }
 467        }
 468
 469        lock->refreshing = 0;
 470        curl_slist_free_all(dav_headers);
 471
 472        return rc;
 473}
 474
 475static void check_locks(void)
 476{
 477        struct remote_lock *lock = repo->locks;
 478        time_t current_time = time(NULL);
 479        int time_remaining;
 480
 481        while (lock) {
 482                time_remaining = lock->start_time + lock->timeout -
 483                        current_time;
 484                if (!lock->refreshing && time_remaining < LOCK_REFRESH) {
 485                        if (!refresh_lock(lock)) {
 486                                fprintf(stderr,
 487                                        "Unable to refresh lock for %s\n",
 488                                        lock->url);
 489                                aborted = 1;
 490                                return;
 491                        }
 492                }
 493                lock = lock->next;
 494        }
 495}
 496
 497static void release_request(struct transfer_request *request)
 498{
 499        struct transfer_request *entry = request_queue_head;
 500
 501        if (request == request_queue_head) {
 502                request_queue_head = request->next;
 503        } else {
 504                while (entry->next != NULL && entry->next != request)
 505                        entry = entry->next;
 506                if (entry->next == request)
 507                        entry->next = entry->next->next;
 508        }
 509
 510        free(request->url);
 511        free(request);
 512}
 513
 514static void finish_request(struct transfer_request *request)
 515{
 516        struct http_pack_request *preq;
 517        struct http_object_request *obj_req;
 518
 519        request->curl_result = request->slot->curl_result;
 520        request->http_code = request->slot->http_code;
 521        request->slot = NULL;
 522
 523        /* Keep locks active */
 524        check_locks();
 525
 526        if (request->headers != NULL)
 527                curl_slist_free_all(request->headers);
 528
 529        /* URL is reused for MOVE after PUT */
 530        if (request->state != RUN_PUT) {
 531                free(request->url);
 532                request->url = NULL;
 533        }
 534
 535        if (request->state == RUN_MKCOL) {
 536                if (request->curl_result == CURLE_OK ||
 537                    request->http_code == 405) {
 538                        remote_dir_exists[request->obj->sha1[0]] = 1;
 539                        start_put(request);
 540                } else {
 541                        fprintf(stderr, "MKCOL %s failed, aborting (%d/%ld)\n",
 542                                sha1_to_hex(request->obj->sha1),
 543                                request->curl_result, request->http_code);
 544                        request->state = ABORTED;
 545                        aborted = 1;
 546                }
 547        } else if (request->state == RUN_PUT) {
 548                if (request->curl_result == CURLE_OK) {
 549                        start_move(request);
 550                } else {
 551                        fprintf(stderr, "PUT %s failed, aborting (%d/%ld)\n",
 552                                sha1_to_hex(request->obj->sha1),
 553                                request->curl_result, request->http_code);
 554                        request->state = ABORTED;
 555                        aborted = 1;
 556                }
 557        } else if (request->state == RUN_MOVE) {
 558                if (request->curl_result == CURLE_OK) {
 559                        if (push_verbosely)
 560                                fprintf(stderr, "    sent %s\n",
 561                                        sha1_to_hex(request->obj->sha1));
 562                        request->obj->flags |= REMOTE;
 563                        release_request(request);
 564                } else {
 565                        fprintf(stderr, "MOVE %s failed, aborting (%d/%ld)\n",
 566                                sha1_to_hex(request->obj->sha1),
 567                                request->curl_result, request->http_code);
 568                        request->state = ABORTED;
 569                        aborted = 1;
 570                }
 571        } else if (request->state == RUN_FETCH_LOOSE) {
 572                obj_req = (struct http_object_request *)request->userData;
 573
 574                if (finish_http_object_request(obj_req) == 0)
 575                        if (obj_req->rename == 0)
 576                                request->obj->flags |= (LOCAL | REMOTE);
 577
 578                /* Try fetching packed if necessary */
 579                if (request->obj->flags & LOCAL) {
 580                        release_http_object_request(obj_req);
 581                        release_request(request);
 582                } else
 583                        start_fetch_packed(request);
 584
 585        } else if (request->state == RUN_FETCH_PACKED) {
 586                int fail = 1;
 587                if (request->curl_result != CURLE_OK) {
 588                        fprintf(stderr, "Unable to get pack file %s\n%s",
 589                                request->url, curl_errorstr);
 590                } else {
 591                        preq = (struct http_pack_request *)request->userData;
 592
 593                        if (preq) {
 594                                if (finish_http_pack_request(preq) == 0)
 595                                        fail = 0;
 596                                release_http_pack_request(preq);
 597                        }
 598                }
 599                if (fail)
 600                        repo->can_update_info_refs = 0;
 601                release_request(request);
 602        }
 603}
 604
 605#ifdef USE_CURL_MULTI
 606static int is_running_queue;
 607static int fill_active_slot(void *unused)
 608{
 609        struct transfer_request *request;
 610
 611        if (aborted || !is_running_queue)
 612                return 0;
 613
 614        for (request = request_queue_head; request; request = request->next) {
 615                if (request->state == NEED_FETCH) {
 616                        start_fetch_loose(request);
 617                        return 1;
 618                } else if (pushing && request->state == NEED_PUSH) {
 619                        if (remote_dir_exists[request->obj->sha1[0]] == 1) {
 620                                start_put(request);
 621                        } else {
 622                                start_mkcol(request);
 623                        }
 624                        return 1;
 625                }
 626        }
 627        return 0;
 628}
 629#endif
 630
 631static void get_remote_object_list(unsigned char parent);
 632
 633static void add_fetch_request(struct object *obj)
 634{
 635        struct transfer_request *request;
 636
 637        check_locks();
 638
 639        /*
 640         * Don't fetch the object if it's known to exist locally
 641         * or is already in the request queue
 642         */
 643        if (remote_dir_exists[obj->sha1[0]] == -1)
 644                get_remote_object_list(obj->sha1[0]);
 645        if (obj->flags & (LOCAL | FETCHING))
 646                return;
 647
 648        obj->flags |= FETCHING;
 649        request = xmalloc(sizeof(*request));
 650        request->obj = obj;
 651        request->url = NULL;
 652        request->lock = NULL;
 653        request->headers = NULL;
 654        request->state = NEED_FETCH;
 655        request->next = request_queue_head;
 656        request_queue_head = request;
 657
 658#ifdef USE_CURL_MULTI
 659        fill_active_slots();
 660        step_active_slots();
 661#endif
 662}
 663
 664static int add_send_request(struct object *obj, struct remote_lock *lock)
 665{
 666        struct transfer_request *request;
 667        struct packed_git *target;
 668
 669        /* Keep locks active */
 670        check_locks();
 671
 672        /*
 673         * Don't push the object if it's known to exist on the remote
 674         * or is already in the request queue
 675         */
 676        if (remote_dir_exists[obj->sha1[0]] == -1)
 677                get_remote_object_list(obj->sha1[0]);
 678        if (obj->flags & (REMOTE | PUSHING))
 679                return 0;
 680        target = find_sha1_pack(obj->sha1, repo->packs);
 681        if (target) {
 682                obj->flags |= REMOTE;
 683                return 0;
 684        }
 685
 686        obj->flags |= PUSHING;
 687        request = xmalloc(sizeof(*request));
 688        request->obj = obj;
 689        request->url = NULL;
 690        request->lock = lock;
 691        request->headers = NULL;
 692        request->state = NEED_PUSH;
 693        request->next = request_queue_head;
 694        request_queue_head = request;
 695
 696#ifdef USE_CURL_MULTI
 697        fill_active_slots();
 698        step_active_slots();
 699#endif
 700
 701        return 1;
 702}
 703
 704static int fetch_indices(void)
 705{
 706        int ret;
 707
 708        if (push_verbosely)
 709                fprintf(stderr, "Getting pack list\n");
 710
 711        switch (http_get_info_packs(repo->url, &repo->packs)) {
 712        case HTTP_OK:
 713        case HTTP_MISSING_TARGET:
 714                ret = 0;
 715                break;
 716        default:
 717                ret = -1;
 718        }
 719
 720        return ret;
 721}
 722
 723static void one_remote_object(const char *hex)
 724{
 725        unsigned char sha1[20];
 726        struct object *obj;
 727
 728        if (get_sha1_hex(hex, sha1) != 0)
 729                return;
 730
 731        obj = lookup_object(sha1);
 732        if (!obj)
 733                obj = parse_object(sha1);
 734
 735        /* Ignore remote objects that don't exist locally */
 736        if (!obj)
 737                return;
 738
 739        obj->flags |= REMOTE;
 740        if (!object_list_contains(objects, obj))
 741                object_list_insert(obj, &objects);
 742}
 743
 744static void handle_lockprop_ctx(struct xml_ctx *ctx, int tag_closed)
 745{
 746        int *lock_flags = (int *)ctx->userData;
 747
 748        if (tag_closed) {
 749                if (!strcmp(ctx->name, DAV_CTX_LOCKENTRY)) {
 750                        if ((*lock_flags & DAV_PROP_LOCKEX) &&
 751                            (*lock_flags & DAV_PROP_LOCKWR)) {
 752                                *lock_flags |= DAV_LOCK_OK;
 753                        }
 754                        *lock_flags &= DAV_LOCK_OK;
 755                } else if (!strcmp(ctx->name, DAV_CTX_LOCKTYPE_WRITE)) {
 756                        *lock_flags |= DAV_PROP_LOCKWR;
 757                } else if (!strcmp(ctx->name, DAV_CTX_LOCKTYPE_EXCLUSIVE)) {
 758                        *lock_flags |= DAV_PROP_LOCKEX;
 759                }
 760        }
 761}
 762
 763static void handle_new_lock_ctx(struct xml_ctx *ctx, int tag_closed)
 764{
 765        struct remote_lock *lock = (struct remote_lock *)ctx->userData;
 766        git_SHA_CTX sha_ctx;
 767        unsigned char lock_token_sha1[20];
 768
 769        if (tag_closed && ctx->cdata) {
 770                if (!strcmp(ctx->name, DAV_ACTIVELOCK_OWNER)) {
 771                        lock->owner = xmalloc(strlen(ctx->cdata) + 1);
 772                        strcpy(lock->owner, ctx->cdata);
 773                } else if (!strcmp(ctx->name, DAV_ACTIVELOCK_TIMEOUT)) {
 774                        if (starts_with(ctx->cdata, "Second-"))
 775                                lock->timeout =
 776                                        strtol(ctx->cdata + 7, NULL, 10);
 777                } else if (!strcmp(ctx->name, DAV_ACTIVELOCK_TOKEN)) {
 778                        lock->token = xmalloc(strlen(ctx->cdata) + 1);
 779                        strcpy(lock->token, ctx->cdata);
 780
 781                        git_SHA1_Init(&sha_ctx);
 782                        git_SHA1_Update(&sha_ctx, lock->token, strlen(lock->token));
 783                        git_SHA1_Final(lock_token_sha1, &sha_ctx);
 784
 785                        lock->tmpfile_suffix[0] = '_';
 786                        memcpy(lock->tmpfile_suffix + 1, sha1_to_hex(lock_token_sha1), 40);
 787                }
 788        }
 789}
 790
 791static void one_remote_ref(const char *refname);
 792
 793static void
 794xml_start_tag(void *userData, const char *name, const char **atts)
 795{
 796        struct xml_ctx *ctx = (struct xml_ctx *)userData;
 797        const char *c = strchr(name, ':');
 798        int new_len;
 799
 800        if (c == NULL)
 801                c = name;
 802        else
 803                c++;
 804
 805        new_len = strlen(ctx->name) + strlen(c) + 2;
 806
 807        if (new_len > ctx->len) {
 808                ctx->name = xrealloc(ctx->name, new_len);
 809                ctx->len = new_len;
 810        }
 811        strcat(ctx->name, ".");
 812        strcat(ctx->name, c);
 813
 814        free(ctx->cdata);
 815        ctx->cdata = NULL;
 816
 817        ctx->userFunc(ctx, 0);
 818}
 819
 820static void
 821xml_end_tag(void *userData, const char *name)
 822{
 823        struct xml_ctx *ctx = (struct xml_ctx *)userData;
 824        const char *c = strchr(name, ':');
 825        char *ep;
 826
 827        ctx->userFunc(ctx, 1);
 828
 829        if (c == NULL)
 830                c = name;
 831        else
 832                c++;
 833
 834        ep = ctx->name + strlen(ctx->name) - strlen(c) - 1;
 835        *ep = 0;
 836}
 837
 838static void
 839xml_cdata(void *userData, const XML_Char *s, int len)
 840{
 841        struct xml_ctx *ctx = (struct xml_ctx *)userData;
 842        free(ctx->cdata);
 843        ctx->cdata = xmemdupz(s, len);
 844}
 845
 846static struct remote_lock *lock_remote(const char *path, long timeout)
 847{
 848        struct active_request_slot *slot;
 849        struct slot_results results;
 850        struct buffer out_buffer = { STRBUF_INIT, 0 };
 851        struct strbuf in_buffer = STRBUF_INIT;
 852        char *url;
 853        char *ep;
 854        char timeout_header[25];
 855        struct remote_lock *lock = NULL;
 856        struct curl_slist *dav_headers = NULL;
 857        struct xml_ctx ctx;
 858        char *escaped;
 859
 860        url = xmalloc(strlen(repo->url) + strlen(path) + 1);
 861        sprintf(url, "%s%s", repo->url, path);
 862
 863        /* Make sure leading directories exist for the remote ref */
 864        ep = strchr(url + strlen(repo->url) + 1, '/');
 865        while (ep) {
 866                char saved_character = ep[1];
 867                ep[1] = '\0';
 868                slot = get_active_slot();
 869                slot->results = &results;
 870                curl_setup_http_get(slot->curl, url, DAV_MKCOL);
 871                if (start_active_slot(slot)) {
 872                        run_active_slot(slot);
 873                        if (results.curl_result != CURLE_OK &&
 874                            results.http_code != 405) {
 875                                fprintf(stderr,
 876                                        "Unable to create branch path %s\n",
 877                                        url);
 878                                free(url);
 879                                return NULL;
 880                        }
 881                } else {
 882                        fprintf(stderr, "Unable to start MKCOL request\n");
 883                        free(url);
 884                        return NULL;
 885                }
 886                ep[1] = saved_character;
 887                ep = strchr(ep + 1, '/');
 888        }
 889
 890        escaped = xml_entities(ident_default_email());
 891        strbuf_addf(&out_buffer.buf, LOCK_REQUEST, escaped);
 892        free(escaped);
 893
 894        sprintf(timeout_header, "Timeout: Second-%ld", timeout);
 895        dav_headers = curl_slist_append(dav_headers, timeout_header);
 896        dav_headers = curl_slist_append(dav_headers, "Content-Type: text/xml");
 897
 898        slot = get_active_slot();
 899        slot->results = &results;
 900        curl_setup_http(slot->curl, url, DAV_LOCK, &out_buffer, fwrite_buffer);
 901        curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, dav_headers);
 902        curl_easy_setopt(slot->curl, CURLOPT_FILE, &in_buffer);
 903
 904        lock = xcalloc(1, sizeof(*lock));
 905        lock->timeout = -1;
 906
 907        if (start_active_slot(slot)) {
 908                run_active_slot(slot);
 909                if (results.curl_result == CURLE_OK) {
 910                        XML_Parser parser = XML_ParserCreate(NULL);
 911                        enum XML_Status result;
 912                        ctx.name = xcalloc(10, 1);
 913                        ctx.len = 0;
 914                        ctx.cdata = NULL;
 915                        ctx.userFunc = handle_new_lock_ctx;
 916                        ctx.userData = lock;
 917                        XML_SetUserData(parser, &ctx);
 918                        XML_SetElementHandler(parser, xml_start_tag,
 919                                              xml_end_tag);
 920                        XML_SetCharacterDataHandler(parser, xml_cdata);
 921                        result = XML_Parse(parser, in_buffer.buf,
 922                                           in_buffer.len, 1);
 923                        free(ctx.name);
 924                        if (result != XML_STATUS_OK) {
 925                                fprintf(stderr, "XML error: %s\n",
 926                                        XML_ErrorString(
 927                                                XML_GetErrorCode(parser)));
 928                                lock->timeout = -1;
 929                        }
 930                        XML_ParserFree(parser);
 931                }
 932        } else {
 933                fprintf(stderr, "Unable to start LOCK request\n");
 934        }
 935
 936        curl_slist_free_all(dav_headers);
 937        strbuf_release(&out_buffer.buf);
 938        strbuf_release(&in_buffer);
 939
 940        if (lock->token == NULL || lock->timeout <= 0) {
 941                free(lock->token);
 942                free(lock->owner);
 943                free(url);
 944                free(lock);
 945                lock = NULL;
 946        } else {
 947                lock->url = url;
 948                lock->start_time = time(NULL);
 949                lock->next = repo->locks;
 950                repo->locks = lock;
 951        }
 952
 953        return lock;
 954}
 955
 956static int unlock_remote(struct remote_lock *lock)
 957{
 958        struct active_request_slot *slot;
 959        struct slot_results results;
 960        struct remote_lock *prev = repo->locks;
 961        struct curl_slist *dav_headers;
 962        int rc = 0;
 963
 964        dav_headers = get_dav_token_headers(lock, DAV_HEADER_LOCK);
 965
 966        slot = get_active_slot();
 967        slot->results = &results;
 968        curl_setup_http_get(slot->curl, lock->url, DAV_UNLOCK);
 969        curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, dav_headers);
 970
 971        if (start_active_slot(slot)) {
 972                run_active_slot(slot);
 973                if (results.curl_result == CURLE_OK)
 974                        rc = 1;
 975                else
 976                        fprintf(stderr, "UNLOCK HTTP error %ld\n",
 977                                results.http_code);
 978        } else {
 979                fprintf(stderr, "Unable to start UNLOCK request\n");
 980        }
 981
 982        curl_slist_free_all(dav_headers);
 983
 984        if (repo->locks == lock) {
 985                repo->locks = lock->next;
 986        } else {
 987                while (prev && prev->next != lock)
 988                        prev = prev->next;
 989                if (prev)
 990                        prev->next = prev->next->next;
 991        }
 992
 993        free(lock->owner);
 994        free(lock->url);
 995        free(lock->token);
 996        free(lock);
 997
 998        return rc;
 999}
1000
1001static void remove_locks(void)
1002{
1003        struct remote_lock *lock = repo->locks;
1004
1005        fprintf(stderr, "Removing remote locks...\n");
1006        while (lock) {
1007                struct remote_lock *next = lock->next;
1008                unlock_remote(lock);
1009                lock = next;
1010        }
1011}
1012
1013static void remove_locks_on_signal(int signo)
1014{
1015        remove_locks();
1016        sigchain_pop(signo);
1017        raise(signo);
1018}
1019
1020static void remote_ls(const char *path, int flags,
1021                      void (*userFunc)(struct remote_ls_ctx *ls),
1022                      void *userData);
1023
1024static void process_ls_object(struct remote_ls_ctx *ls)
1025{
1026        unsigned int *parent = (unsigned int *)ls->userData;
1027        char *path = ls->dentry_name;
1028        char *obj_hex;
1029
1030        if (!strcmp(ls->path, ls->dentry_name) && (ls->flags & IS_DIR)) {
1031                remote_dir_exists[*parent] = 1;
1032                return;
1033        }
1034
1035        if (strlen(path) != 49)
1036                return;
1037        path += 8;
1038        obj_hex = xmalloc(strlen(path));
1039        /* NB: path is not null-terminated, can not use strlcpy here */
1040        memcpy(obj_hex, path, 2);
1041        strcpy(obj_hex + 2, path + 3);
1042        one_remote_object(obj_hex);
1043        free(obj_hex);
1044}
1045
1046static void process_ls_ref(struct remote_ls_ctx *ls)
1047{
1048        if (!strcmp(ls->path, ls->dentry_name) && (ls->dentry_flags & IS_DIR)) {
1049                fprintf(stderr, "  %s\n", ls->dentry_name);
1050                return;
1051        }
1052
1053        if (!(ls->dentry_flags & IS_DIR))
1054                one_remote_ref(ls->dentry_name);
1055}
1056
1057static void handle_remote_ls_ctx(struct xml_ctx *ctx, int tag_closed)
1058{
1059        struct remote_ls_ctx *ls = (struct remote_ls_ctx *)ctx->userData;
1060
1061        if (tag_closed) {
1062                if (!strcmp(ctx->name, DAV_PROPFIND_RESP) && ls->dentry_name) {
1063                        if (ls->dentry_flags & IS_DIR) {
1064
1065                                /* ensure collection names end with slash */
1066                                str_end_url_with_slash(ls->dentry_name, &ls->dentry_name);
1067
1068                                if (ls->flags & PROCESS_DIRS) {
1069                                        ls->userFunc(ls);
1070                                }
1071                                if (strcmp(ls->dentry_name, ls->path) &&
1072                                    ls->flags & RECURSIVE) {
1073                                        remote_ls(ls->dentry_name,
1074                                                  ls->flags,
1075                                                  ls->userFunc,
1076                                                  ls->userData);
1077                                }
1078                        } else if (ls->flags & PROCESS_FILES) {
1079                                ls->userFunc(ls);
1080                        }
1081                } else if (!strcmp(ctx->name, DAV_PROPFIND_NAME) && ctx->cdata) {
1082                        char *path = ctx->cdata;
1083                        if (*ctx->cdata == 'h') {
1084                                path = strstr(path, "//");
1085                                if (path) {
1086                                        path = strchr(path+2, '/');
1087                                }
1088                        }
1089                        if (path) {
1090                                const char *url = repo->url;
1091                                if (repo->path)
1092                                        url = repo->path;
1093                                if (strncmp(path, url, repo->path_len))
1094                                        error("Parsed path '%s' does not match url: '%s'",
1095                                              path, url);
1096                                else {
1097                                        path += repo->path_len;
1098                                        ls->dentry_name = xstrdup(path);
1099                                }
1100                        }
1101                } else if (!strcmp(ctx->name, DAV_PROPFIND_COLLECTION)) {
1102                        ls->dentry_flags |= IS_DIR;
1103                }
1104        } else if (!strcmp(ctx->name, DAV_PROPFIND_RESP)) {
1105                free(ls->dentry_name);
1106                ls->dentry_name = NULL;
1107                ls->dentry_flags = 0;
1108        }
1109}
1110
1111/*
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).
1116 */
1117static void remote_ls(const char *path, int flags,
1118                      void (*userFunc)(struct remote_ls_ctx *ls),
1119                      void *userData)
1120{
1121        char *url = xmalloc(strlen(repo->url) + strlen(path) + 1);
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 = NULL;
1127        struct xml_ctx ctx;
1128        struct remote_ls_ctx ls;
1129
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;
1136
1137        sprintf(url, "%s%s", repo->url, path);
1138
1139        strbuf_addf(&out_buffer.buf, PROPFIND_ALL_REQUEST);
1140
1141        dav_headers = curl_slist_append(dav_headers, "Depth: 1");
1142        dav_headers = curl_slist_append(dav_headers, "Content-Type: text/xml");
1143
1144        slot = get_active_slot();
1145        slot->results = &results;
1146        curl_setup_http(slot->curl, url, DAV_PROPFIND,
1147                        &out_buffer, fwrite_buffer);
1148        curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, dav_headers);
1149        curl_easy_setopt(slot->curl, CURLOPT_FILE, &in_buffer);
1150
1151        if (start_active_slot(slot)) {
1152                run_active_slot(slot);
1153                if (results.curl_result == CURLE_OK) {
1154                        XML_Parser parser = XML_ParserCreate(NULL);
1155                        enum XML_Status result;
1156                        ctx.name = xcalloc(10, 1);
1157                        ctx.len = 0;
1158                        ctx.cdata = NULL;
1159                        ctx.userFunc = handle_remote_ls_ctx;
1160                        ctx.userData = &ls;
1161                        XML_SetUserData(parser, &ctx);
1162                        XML_SetElementHandler(parser, xml_start_tag,
1163                                              xml_end_tag);
1164                        XML_SetCharacterDataHandler(parser, xml_cdata);
1165                        result = XML_Parse(parser, in_buffer.buf,
1166                                           in_buffer.len, 1);
1167                        free(ctx.name);
1168
1169                        if (result != XML_STATUS_OK) {
1170                                fprintf(stderr, "XML error: %s\n",
1171                                        XML_ErrorString(
1172                                                XML_GetErrorCode(parser)));
1173                        }
1174                        XML_ParserFree(parser);
1175                }
1176        } else {
1177                fprintf(stderr, "Unable to start PROPFIND request\n");
1178        }
1179
1180        free(ls.path);
1181        free(url);
1182        strbuf_release(&out_buffer.buf);
1183        strbuf_release(&in_buffer);
1184        curl_slist_free_all(dav_headers);
1185}
1186
1187static void get_remote_object_list(unsigned char parent)
1188{
1189        char path[] = "objects/XX/";
1190        static const char hex[] = "0123456789abcdef";
1191        unsigned int val = parent;
1192
1193        path[8] = hex[val >> 4];
1194        path[9] = hex[val & 0xf];
1195        remote_dir_exists[val] = 0;
1196        remote_ls(path, (PROCESS_FILES | PROCESS_DIRS),
1197                  process_ls_object, &val);
1198}
1199
1200static int locking_available(void)
1201{
1202        struct active_request_slot *slot;
1203        struct slot_results results;
1204        struct strbuf in_buffer = STRBUF_INIT;
1205        struct buffer out_buffer = { STRBUF_INIT, 0 };
1206        struct curl_slist *dav_headers = NULL;
1207        struct xml_ctx ctx;
1208        int lock_flags = 0;
1209        char *escaped;
1210
1211        escaped = xml_entities(repo->url);
1212        strbuf_addf(&out_buffer.buf, PROPFIND_SUPPORTEDLOCK_REQUEST, escaped);
1213        free(escaped);
1214
1215        dav_headers = curl_slist_append(dav_headers, "Depth: 0");
1216        dav_headers = curl_slist_append(dav_headers, "Content-Type: text/xml");
1217
1218        slot = get_active_slot();
1219        slot->results = &results;
1220        curl_setup_http(slot->curl, repo->url, DAV_PROPFIND,
1221                        &out_buffer, fwrite_buffer);
1222        curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, dav_headers);
1223        curl_easy_setopt(slot->curl, CURLOPT_FILE, &in_buffer);
1224
1225        if (start_active_slot(slot)) {
1226                run_active_slot(slot);
1227                if (results.curl_result == CURLE_OK) {
1228                        XML_Parser parser = XML_ParserCreate(NULL);
1229                        enum XML_Status result;
1230                        ctx.name = xcalloc(10, 1);
1231                        ctx.len = 0;
1232                        ctx.cdata = NULL;
1233                        ctx.userFunc = handle_lockprop_ctx;
1234                        ctx.userData = &lock_flags;
1235                        XML_SetUserData(parser, &ctx);
1236                        XML_SetElementHandler(parser, xml_start_tag,
1237                                              xml_end_tag);
1238                        result = XML_Parse(parser, in_buffer.buf,
1239                                           in_buffer.len, 1);
1240                        free(ctx.name);
1241
1242                        if (result != XML_STATUS_OK) {
1243                                fprintf(stderr, "XML error: %s\n",
1244                                        XML_ErrorString(
1245                                                XML_GetErrorCode(parser)));
1246                                lock_flags = 0;
1247                        }
1248                        XML_ParserFree(parser);
1249                        if (!lock_flags)
1250                                error("no DAV locking support on %s",
1251                                      repo->url);
1252
1253                } else {
1254                        error("Cannot access URL %s, return code %d",
1255                              repo->url, results.curl_result);
1256                        lock_flags = 0;
1257                }
1258        } else {
1259                error("Unable to start PROPFIND request on %s", repo->url);
1260        }
1261
1262        strbuf_release(&out_buffer.buf);
1263        strbuf_release(&in_buffer);
1264        curl_slist_free_all(dav_headers);
1265
1266        return lock_flags;
1267}
1268
1269static struct object_list **add_one_object(struct object *obj, struct object_list **p)
1270{
1271        struct object_list *entry = xmalloc(sizeof(struct object_list));
1272        entry->item = obj;
1273        entry->next = *p;
1274        *p = entry;
1275        return &entry->next;
1276}
1277
1278static struct object_list **process_blob(struct blob *blob,
1279                                         struct object_list **p,
1280                                         struct name_path *path,
1281                                         const char *name)
1282{
1283        struct object *obj = &blob->object;
1284
1285        obj->flags |= LOCAL;
1286
1287        if (obj->flags & (UNINTERESTING | SEEN))
1288                return p;
1289
1290        obj->flags |= SEEN;
1291        return add_one_object(obj, p);
1292}
1293
1294static struct object_list **process_tree(struct tree *tree,
1295                                         struct object_list **p,
1296                                         struct name_path *path,
1297                                         const char *name)
1298{
1299        struct object *obj = &tree->object;
1300        struct tree_desc desc;
1301        struct name_entry entry;
1302        struct name_path me;
1303
1304        obj->flags |= LOCAL;
1305
1306        if (obj->flags & (UNINTERESTING | SEEN))
1307                return p;
1308        if (parse_tree(tree) < 0)
1309                die("bad tree object %s", sha1_to_hex(obj->sha1));
1310
1311        obj->flags |= SEEN;
1312        name = xstrdup(name);
1313        p = add_one_object(obj, p);
1314        me.up = path;
1315        me.elem = name;
1316        me.elem_len = strlen(name);
1317
1318        init_tree_desc(&desc, tree->buffer, tree->size);
1319
1320        while (tree_entry(&desc, &entry))
1321                switch (object_type(entry.mode)) {
1322                case OBJ_TREE:
1323                        p = process_tree(lookup_tree(entry.sha1), p, &me, name);
1324                        break;
1325                case OBJ_BLOB:
1326                        p = process_blob(lookup_blob(entry.sha1), p, &me, name);
1327                        break;
1328                default:
1329                        /* Subproject commit - not in this repository */
1330                        break;
1331                }
1332
1333        free_tree_buffer(tree);
1334        return p;
1335}
1336
1337static int get_delta(struct rev_info *revs, struct remote_lock *lock)
1338{
1339        int i;
1340        struct commit *commit;
1341        struct object_list **p = &objects;
1342        int count = 0;
1343
1344        while ((commit = get_revision(revs)) != NULL) {
1345                p = process_tree(commit->tree, p, NULL, "");
1346                commit->object.flags |= LOCAL;
1347                if (!(commit->object.flags & UNINTERESTING))
1348                        count += add_send_request(&commit->object, lock);
1349        }
1350
1351        for (i = 0; i < revs->pending.nr; i++) {
1352                struct object_array_entry *entry = revs->pending.objects + i;
1353                struct object *obj = entry->item;
1354                const char *name = entry->name;
1355
1356                if (obj->flags & (UNINTERESTING | SEEN))
1357                        continue;
1358                if (obj->type == OBJ_TAG) {
1359                        obj->flags |= SEEN;
1360                        p = add_one_object(obj, p);
1361                        continue;
1362                }
1363                if (obj->type == OBJ_TREE) {
1364                        p = process_tree((struct tree *)obj, p, NULL, name);
1365                        continue;
1366                }
1367                if (obj->type == OBJ_BLOB) {
1368                        p = process_blob((struct blob *)obj, p, NULL, name);
1369                        continue;
1370                }
1371                die("unknown pending object %s (%s)", sha1_to_hex(obj->sha1), name);
1372        }
1373
1374        while (objects) {
1375                if (!(objects->item->flags & UNINTERESTING))
1376                        count += add_send_request(objects->item, lock);
1377                objects = objects->next;
1378        }
1379
1380        return count;
1381}
1382
1383static int update_remote(unsigned char *sha1, struct remote_lock *lock)
1384{
1385        struct active_request_slot *slot;
1386        struct slot_results results;
1387        struct buffer out_buffer = { STRBUF_INIT, 0 };
1388        struct curl_slist *dav_headers;
1389
1390        dav_headers = get_dav_token_headers(lock, DAV_HEADER_IF);
1391
1392        strbuf_addf(&out_buffer.buf, "%s\n", sha1_to_hex(sha1));
1393
1394        slot = get_active_slot();
1395        slot->results = &results;
1396        curl_setup_http(slot->curl, lock->url, DAV_PUT,
1397                        &out_buffer, fwrite_null);
1398        curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, dav_headers);
1399
1400        if (start_active_slot(slot)) {
1401                run_active_slot(slot);
1402                strbuf_release(&out_buffer.buf);
1403                if (results.curl_result != CURLE_OK) {
1404                        fprintf(stderr,
1405                                "PUT error: curl result=%d, HTTP code=%ld\n",
1406                                results.curl_result, results.http_code);
1407                        /* We should attempt recovery? */
1408                        return 0;
1409                }
1410        } else {
1411                strbuf_release(&out_buffer.buf);
1412                fprintf(stderr, "Unable to start PUT request\n");
1413                return 0;
1414        }
1415
1416        return 1;
1417}
1418
1419static struct ref *remote_refs;
1420
1421static void one_remote_ref(const char *refname)
1422{
1423        struct ref *ref;
1424        struct object *obj;
1425
1426        ref = alloc_ref(refname);
1427
1428        if (http_fetch_ref(repo->url, ref) != 0) {
1429                fprintf(stderr,
1430                        "Unable to fetch ref %s from %s\n",
1431                        refname, repo->url);
1432                free(ref);
1433                return;
1434        }
1435
1436        /*
1437         * Fetch a copy of the object if it doesn't exist locally - it
1438         * may be required for updating server info later.
1439         */
1440        if (repo->can_update_info_refs && !has_sha1_file(ref->old_sha1)) {
1441                obj = lookup_unknown_object(ref->old_sha1);
1442                if (obj) {
1443                        fprintf(stderr, "  fetch %s for %s\n",
1444                                sha1_to_hex(ref->old_sha1), refname);
1445                        add_fetch_request(obj);
1446                }
1447        }
1448
1449        ref->next = remote_refs;
1450        remote_refs = ref;
1451}
1452
1453static void get_dav_remote_heads(void)
1454{
1455        remote_ls("refs/", (PROCESS_FILES | PROCESS_DIRS | RECURSIVE), process_ls_ref, NULL);
1456}
1457
1458static void add_remote_info_ref(struct remote_ls_ctx *ls)
1459{
1460        struct strbuf *buf = (struct strbuf *)ls->userData;
1461        struct object *o;
1462        int len;
1463        char *ref_info;
1464        struct ref *ref;
1465
1466        ref = alloc_ref(ls->dentry_name);
1467
1468        if (http_fetch_ref(repo->url, ref) != 0) {
1469                fprintf(stderr,
1470                        "Unable to fetch ref %s from %s\n",
1471                        ls->dentry_name, repo->url);
1472                aborted = 1;
1473                free(ref);
1474                return;
1475        }
1476
1477        o = parse_object(ref->old_sha1);
1478        if (!o) {
1479                fprintf(stderr,
1480                        "Unable to parse object %s for remote ref %s\n",
1481                        sha1_to_hex(ref->old_sha1), ls->dentry_name);
1482                aborted = 1;
1483                free(ref);
1484                return;
1485        }
1486
1487        len = strlen(ls->dentry_name) + 42;
1488        ref_info = xcalloc(len + 1, 1);
1489        sprintf(ref_info, "%s   %s\n",
1490                sha1_to_hex(ref->old_sha1), ls->dentry_name);
1491        fwrite_buffer(ref_info, 1, len, buf);
1492        free(ref_info);
1493
1494        if (o->type == OBJ_TAG) {
1495                o = deref_tag(o, ls->dentry_name, 0);
1496                if (o) {
1497                        len = strlen(ls->dentry_name) + 45;
1498                        ref_info = xcalloc(len + 1, 1);
1499                        sprintf(ref_info, "%s   %s^{}\n",
1500                                sha1_to_hex(o->sha1), ls->dentry_name);
1501                        fwrite_buffer(ref_info, 1, len, buf);
1502                        free(ref_info);
1503                }
1504        }
1505        free(ref);
1506}
1507
1508static void update_remote_info_refs(struct remote_lock *lock)
1509{
1510        struct buffer buffer = { STRBUF_INIT, 0 };
1511        struct active_request_slot *slot;
1512        struct slot_results results;
1513        struct curl_slist *dav_headers;
1514
1515        remote_ls("refs/", (PROCESS_FILES | RECURSIVE),
1516                  add_remote_info_ref, &buffer.buf);
1517        if (!aborted) {
1518                dav_headers = get_dav_token_headers(lock, DAV_HEADER_IF);
1519
1520                slot = get_active_slot();
1521                slot->results = &results;
1522                curl_setup_http(slot->curl, lock->url, DAV_PUT,
1523                                &buffer, fwrite_null);
1524                curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, dav_headers);
1525
1526                if (start_active_slot(slot)) {
1527                        run_active_slot(slot);
1528                        if (results.curl_result != CURLE_OK) {
1529                                fprintf(stderr,
1530                                        "PUT error: curl result=%d, HTTP code=%ld\n",
1531                                        results.curl_result, results.http_code);
1532                        }
1533                }
1534        }
1535        strbuf_release(&buffer.buf);
1536}
1537
1538static int remote_exists(const char *path)
1539{
1540        char *url = xmalloc(strlen(repo->url) + strlen(path) + 1);
1541        int ret;
1542
1543        sprintf(url, "%s%s", repo->url, path);
1544
1545        switch (http_get_strbuf(url, NULL, NULL)) {
1546        case HTTP_OK:
1547                ret = 1;
1548                break;
1549        case HTTP_MISSING_TARGET:
1550                ret = 0;
1551                break;
1552        case HTTP_ERROR:
1553                error("unable to access '%s': %s", url, curl_errorstr);
1554        default:
1555                ret = -1;
1556        }
1557        free(url);
1558        return ret;
1559}
1560
1561static void fetch_symref(const char *path, char **symref, unsigned char *sha1)
1562{
1563        char *url;
1564        struct strbuf buffer = STRBUF_INIT;
1565
1566        url = xmalloc(strlen(repo->url) + strlen(path) + 1);
1567        sprintf(url, "%s%s", repo->url, path);
1568
1569        if (http_get_strbuf(url, &buffer, NULL) != HTTP_OK)
1570                die("Couldn't get %s for remote symref\n%s", url,
1571                    curl_errorstr);
1572        free(url);
1573
1574        free(*symref);
1575        *symref = NULL;
1576        hashclr(sha1);
1577
1578        if (buffer.len == 0)
1579                return;
1580
1581        /* If it's a symref, set the refname; otherwise try for a sha1 */
1582        if (starts_with((char *)buffer.buf, "ref: ")) {
1583                *symref = xmemdupz((char *)buffer.buf + 5, buffer.len - 6);
1584        } else {
1585                get_sha1_hex(buffer.buf, sha1);
1586        }
1587
1588        strbuf_release(&buffer);
1589}
1590
1591static int verify_merge_base(unsigned char *head_sha1, struct ref *remote)
1592{
1593        struct commit *head = lookup_commit_or_die(head_sha1, "HEAD");
1594        struct commit *branch = lookup_commit_or_die(remote->old_sha1, remote->name);
1595
1596        return in_merge_bases(branch, head);
1597}
1598
1599static int delete_remote_branch(const char *pattern, int force)
1600{
1601        struct ref *refs = remote_refs;
1602        struct ref *remote_ref = NULL;
1603        unsigned char head_sha1[20];
1604        char *symref = NULL;
1605        int match;
1606        int patlen = strlen(pattern);
1607        int i;
1608        struct active_request_slot *slot;
1609        struct slot_results results;
1610        char *url;
1611
1612        /* Find the remote branch(es) matching the specified branch name */
1613        for (match = 0; refs; refs = refs->next) {
1614                char *name = refs->name;
1615                int namelen = strlen(name);
1616                if (namelen < patlen ||
1617                    memcmp(name + namelen - patlen, pattern, patlen))
1618                        continue;
1619                if (namelen != patlen && name[namelen - patlen - 1] != '/')
1620                        continue;
1621                match++;
1622                remote_ref = refs;
1623        }
1624        if (match == 0)
1625                return error("No remote branch matches %s", pattern);
1626        if (match != 1)
1627                return error("More than one remote branch matches %s",
1628                             pattern);
1629
1630        /*
1631         * Remote HEAD must be a symref (not exactly foolproof; a remote
1632         * symlink to a symref will look like a symref)
1633         */
1634        fetch_symref("HEAD", &symref, head_sha1);
1635        if (!symref)
1636                return error("Remote HEAD is not a symref");
1637
1638        /* Remote branch must not be the remote HEAD */
1639        for (i = 0; symref && i < MAXDEPTH; i++) {
1640                if (!strcmp(remote_ref->name, symref))
1641                        return error("Remote branch %s is the current HEAD",
1642                                     remote_ref->name);
1643                fetch_symref(symref, &symref, head_sha1);
1644        }
1645
1646        /* Run extra sanity checks if delete is not forced */
1647        if (!force) {
1648                /* Remote HEAD must resolve to a known object */
1649                if (symref)
1650                        return error("Remote HEAD symrefs too deep");
1651                if (is_null_sha1(head_sha1))
1652                        return error("Unable to resolve remote HEAD");
1653                if (!has_sha1_file(head_sha1))
1654                        return error("Remote HEAD resolves to object %s\nwhich does not exist locally, perhaps you need to fetch?", sha1_to_hex(head_sha1));
1655
1656                /* Remote branch must resolve to a known object */
1657                if (is_null_sha1(remote_ref->old_sha1))
1658                        return error("Unable to resolve remote branch %s",
1659                                     remote_ref->name);
1660                if (!has_sha1_file(remote_ref->old_sha1))
1661                        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));
1662
1663                /* Remote branch must be an ancestor of remote HEAD */
1664                if (!verify_merge_base(head_sha1, remote_ref)) {
1665                        return error("The branch '%s' is not an ancestor "
1666                                     "of your current HEAD.\n"
1667                                     "If you are sure you want to delete it,"
1668                                     " run:\n\t'git http-push -D %s %s'",
1669                                     remote_ref->name, repo->url, pattern);
1670                }
1671        }
1672
1673        /* Send delete request */
1674        fprintf(stderr, "Removing remote branch '%s'\n", remote_ref->name);
1675        if (dry_run)
1676                return 0;
1677        url = xmalloc(strlen(repo->url) + strlen(remote_ref->name) + 1);
1678        sprintf(url, "%s%s", repo->url, remote_ref->name);
1679        slot = get_active_slot();
1680        slot->results = &results;
1681        curl_setup_http_get(slot->curl, url, DAV_DELETE);
1682        if (start_active_slot(slot)) {
1683                run_active_slot(slot);
1684                free(url);
1685                if (results.curl_result != CURLE_OK)
1686                        return error("DELETE request failed (%d/%ld)",
1687                                     results.curl_result, results.http_code);
1688        } else {
1689                free(url);
1690                return error("Unable to start DELETE request");
1691        }
1692
1693        return 0;
1694}
1695
1696static void run_request_queue(void)
1697{
1698#ifdef USE_CURL_MULTI
1699        is_running_queue = 1;
1700        fill_active_slots();
1701        add_fill_function(NULL, fill_active_slot);
1702#endif
1703        do {
1704                finish_all_active_slots();
1705#ifdef USE_CURL_MULTI
1706                fill_active_slots();
1707#endif
1708        } while (request_queue_head && !aborted);
1709
1710#ifdef USE_CURL_MULTI
1711        is_running_queue = 0;
1712#endif
1713}
1714
1715int main(int argc, char **argv)
1716{
1717        struct transfer_request *request;
1718        struct transfer_request *next_request;
1719        int nr_refspec = 0;
1720        char **refspec = NULL;
1721        struct remote_lock *ref_lock = NULL;
1722        struct remote_lock *info_ref_lock = NULL;
1723        struct rev_info revs;
1724        int delete_branch = 0;
1725        int force_delete = 0;
1726        int objects_to_send;
1727        int rc = 0;
1728        int i;
1729        int new_refs;
1730        struct ref *ref, *local_refs;
1731
1732        git_setup_gettext();
1733
1734        git_extract_argv0_path(argv[0]);
1735
1736        repo = xcalloc(sizeof(*repo), 1);
1737
1738        argv++;
1739        for (i = 1; i < argc; i++, argv++) {
1740                char *arg = *argv;
1741
1742                if (*arg == '-') {
1743                        if (!strcmp(arg, "--all")) {
1744                                push_all = MATCH_REFS_ALL;
1745                                continue;
1746                        }
1747                        if (!strcmp(arg, "--force")) {
1748                                force_all = 1;
1749                                continue;
1750                        }
1751                        if (!strcmp(arg, "--dry-run")) {
1752                                dry_run = 1;
1753                                continue;
1754                        }
1755                        if (!strcmp(arg, "--helper-status")) {
1756                                helper_status = 1;
1757                                continue;
1758                        }
1759                        if (!strcmp(arg, "--verbose")) {
1760                                push_verbosely = 1;
1761                                http_is_verbose = 1;
1762                                continue;
1763                        }
1764                        if (!strcmp(arg, "-d")) {
1765                                delete_branch = 1;
1766                                continue;
1767                        }
1768                        if (!strcmp(arg, "-D")) {
1769                                delete_branch = 1;
1770                                force_delete = 1;
1771                                continue;
1772                        }
1773                        if (!strcmp(arg, "-h"))
1774                                usage(http_push_usage);
1775                }
1776                if (!repo->url) {
1777                        char *path = strstr(arg, "//");
1778                        str_end_url_with_slash(arg, &repo->url);
1779                        repo->path_len = strlen(repo->url);
1780                        if (path) {
1781                                repo->path = strchr(path+2, '/');
1782                                if (repo->path)
1783                                        repo->path_len = strlen(repo->path);
1784                        }
1785                        continue;
1786                }
1787                refspec = argv;
1788                nr_refspec = argc - i;
1789                break;
1790        }
1791
1792#ifndef USE_CURL_MULTI
1793        die("git-push is not available for http/https repository when not compiled with USE_CURL_MULTI");
1794#endif
1795
1796        if (!repo->url)
1797                usage(http_push_usage);
1798
1799        if (delete_branch && nr_refspec != 1)
1800                die("You must specify only one branch name when deleting a remote branch");
1801
1802        setup_git_directory();
1803
1804        memset(remote_dir_exists, -1, 256);
1805
1806        http_init(NULL, repo->url, 1);
1807
1808#ifdef USE_CURL_MULTI
1809        is_running_queue = 0;
1810#endif
1811
1812        /* Verify DAV compliance/lock support */
1813        if (!locking_available()) {
1814                rc = 1;
1815                goto cleanup;
1816        }
1817
1818        sigchain_push_common(remove_locks_on_signal);
1819
1820        /* Check whether the remote has server info files */
1821        repo->can_update_info_refs = 0;
1822        repo->has_info_refs = remote_exists("info/refs");
1823        repo->has_info_packs = remote_exists("objects/info/packs");
1824        if (repo->has_info_refs) {
1825                info_ref_lock = lock_remote("info/refs", LOCK_TIME);
1826                if (info_ref_lock)
1827                        repo->can_update_info_refs = 1;
1828                else {
1829                        error("cannot lock existing info/refs");
1830                        rc = 1;
1831                        goto cleanup;
1832                }
1833        }
1834        if (repo->has_info_packs)
1835                fetch_indices();
1836
1837        /* Get a list of all local and remote heads to validate refspecs */
1838        local_refs = get_local_heads();
1839        fprintf(stderr, "Fetching remote heads...\n");
1840        get_dav_remote_heads();
1841        run_request_queue();
1842
1843        /* Remove a remote branch if -d or -D was specified */
1844        if (delete_branch) {
1845                if (delete_remote_branch(refspec[0], force_delete) == -1) {
1846                        fprintf(stderr, "Unable to delete remote branch %s\n",
1847                                refspec[0]);
1848                        if (helper_status)
1849                                printf("error %s cannot remove\n", refspec[0]);
1850                }
1851                goto cleanup;
1852        }
1853
1854        /* match them up */
1855        if (match_push_refs(local_refs, &remote_refs,
1856                            nr_refspec, (const char **) refspec, push_all)) {
1857                rc = -1;
1858                goto cleanup;
1859        }
1860        if (!remote_refs) {
1861                fprintf(stderr, "No refs in common and none specified; doing nothing.\n");
1862                if (helper_status)
1863                        printf("error null no match\n");
1864                rc = 0;
1865                goto cleanup;
1866        }
1867
1868        new_refs = 0;
1869        for (ref = remote_refs; ref; ref = ref->next) {
1870                char old_hex[60], *new_hex;
1871                const char *commit_argv[5];
1872                int commit_argc;
1873                char *new_sha1_hex, *old_sha1_hex;
1874
1875                if (!ref->peer_ref)
1876                        continue;
1877
1878                if (is_null_sha1(ref->peer_ref->new_sha1)) {
1879                        if (delete_remote_branch(ref->name, 1) == -1) {
1880                                error("Could not remove %s", ref->name);
1881                                if (helper_status)
1882                                        printf("error %s cannot remove\n", ref->name);
1883                                rc = -4;
1884                        }
1885                        else if (helper_status)
1886                                printf("ok %s\n", ref->name);
1887                        new_refs++;
1888                        continue;
1889                }
1890
1891                if (!hashcmp(ref->old_sha1, ref->peer_ref->new_sha1)) {
1892                        if (push_verbosely)
1893                                fprintf(stderr, "'%s': up-to-date\n", ref->name);
1894                        if (helper_status)
1895                                printf("ok %s up to date\n", ref->name);
1896                        continue;
1897                }
1898
1899                if (!force_all &&
1900                    !is_null_sha1(ref->old_sha1) &&
1901                    !ref->force) {
1902                        if (!has_sha1_file(ref->old_sha1) ||
1903                            !ref_newer(ref->peer_ref->new_sha1,
1904                                       ref->old_sha1)) {
1905                                /*
1906                                 * We do not have the remote ref, or
1907                                 * we know that the remote ref is not
1908                                 * an ancestor of what we are trying to
1909                                 * push.  Either way this can be losing
1910                                 * commits at the remote end and likely
1911                                 * we were not up to date to begin with.
1912                                 */
1913                                error("remote '%s' is not an ancestor of\n"
1914                                      "local '%s'.\n"
1915                                      "Maybe you are not up-to-date and "
1916                                      "need to pull first?",
1917                                      ref->name,
1918                                      ref->peer_ref->name);
1919                                if (helper_status)
1920                                        printf("error %s non-fast forward\n", ref->name);
1921                                rc = -2;
1922                                continue;
1923                        }
1924                }
1925                hashcpy(ref->new_sha1, ref->peer_ref->new_sha1);
1926                new_refs++;
1927                strcpy(old_hex, sha1_to_hex(ref->old_sha1));
1928                new_hex = sha1_to_hex(ref->new_sha1);
1929
1930                fprintf(stderr, "updating '%s'", ref->name);
1931                if (strcmp(ref->name, ref->peer_ref->name))
1932                        fprintf(stderr, " using '%s'", ref->peer_ref->name);
1933                fprintf(stderr, "\n  from %s\n  to   %s\n", old_hex, new_hex);
1934                if (dry_run) {
1935                        if (helper_status)
1936                                printf("ok %s\n", ref->name);
1937                        continue;
1938                }
1939
1940                /* Lock remote branch ref */
1941                ref_lock = lock_remote(ref->name, LOCK_TIME);
1942                if (ref_lock == NULL) {
1943                        fprintf(stderr, "Unable to lock remote branch %s\n",
1944                                ref->name);
1945                        if (helper_status)
1946                                printf("error %s lock error\n", ref->name);
1947                        rc = 1;
1948                        continue;
1949                }
1950
1951                /* Set up revision info for this refspec */
1952                commit_argc = 3;
1953                new_sha1_hex = xstrdup(sha1_to_hex(ref->new_sha1));
1954                old_sha1_hex = NULL;
1955                commit_argv[1] = "--objects";
1956                commit_argv[2] = new_sha1_hex;
1957                if (!push_all && !is_null_sha1(ref->old_sha1)) {
1958                        old_sha1_hex = xmalloc(42);
1959                        sprintf(old_sha1_hex, "^%s",
1960                                sha1_to_hex(ref->old_sha1));
1961                        commit_argv[3] = old_sha1_hex;
1962                        commit_argc++;
1963                }
1964                commit_argv[commit_argc] = NULL;
1965                init_revisions(&revs, setup_git_directory());
1966                setup_revisions(commit_argc, commit_argv, &revs, NULL);
1967                revs.edge_hint = 0; /* just in case */
1968                free(new_sha1_hex);
1969                if (old_sha1_hex) {
1970                        free(old_sha1_hex);
1971                        commit_argv[1] = NULL;
1972                }
1973
1974                /* Generate a list of objects that need to be pushed */
1975                pushing = 0;
1976                if (prepare_revision_walk(&revs))
1977                        die("revision walk setup failed");
1978                mark_edges_uninteresting(&revs, NULL);
1979                objects_to_send = get_delta(&revs, ref_lock);
1980                finish_all_active_slots();
1981
1982                /* Push missing objects to remote, this would be a
1983                   convenient time to pack them first if appropriate. */
1984                pushing = 1;
1985                if (objects_to_send)
1986                        fprintf(stderr, "    sending %d objects\n",
1987                                objects_to_send);
1988
1989                run_request_queue();
1990
1991                /* Update the remote branch if all went well */
1992                if (aborted || !update_remote(ref->new_sha1, ref_lock))
1993                        rc = 1;
1994
1995                if (!rc)
1996                        fprintf(stderr, "    done\n");
1997                if (helper_status)
1998                        printf("%s %s\n", !rc ? "ok" : "error", ref->name);
1999                unlock_remote(ref_lock);
2000                check_locks();
2001        }
2002
2003        /* Update remote server info if appropriate */
2004        if (repo->has_info_refs && new_refs) {
2005                if (info_ref_lock && repo->can_update_info_refs) {
2006                        fprintf(stderr, "Updating remote server info\n");
2007                        if (!dry_run)
2008                                update_remote_info_refs(info_ref_lock);
2009                } else {
2010                        fprintf(stderr, "Unable to update server info\n");
2011                }
2012        }
2013
2014 cleanup:
2015        if (info_ref_lock)
2016                unlock_remote(info_ref_lock);
2017        free(repo);
2018
2019        http_cleanup();
2020
2021        request = request_queue_head;
2022        while (request != NULL) {
2023                next_request = request->next;
2024                release_request(request);
2025                request = next_request;
2026        }
2027
2028        return rc;
2029}