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