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