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