Add support for pushing to a remote repository using HTTP/DAV
[git.git] / http-push.c
1 #include "cache.h"
2 #include "commit.h"
3 #include "pack.h"
4 #include "fetch.h"
5 #include "tag.h"
6 #include "blob.h"
7
8 #include <curl/curl.h>
9 #include <curl/easy.h>
10 #include "expat.h"
11
12 static const char http_push_usage[] =
13 "git-http-push [--complete] [--force] [--verbose] <url> <ref> [<ref>...]\n";
14
15 #if LIBCURL_VERSION_NUM >= 0x070908
16 #define USE_CURL_MULTI
17 #define DEFAULT_MAX_REQUESTS 5
18 #endif
19
20 #if LIBCURL_VERSION_NUM < 0x070704
21 #define curl_global_cleanup() do { /* nothing */ } while(0)
22 #endif
23 #if LIBCURL_VERSION_NUM < 0x070800
24 #define curl_global_init(a) do { /* nothing */ } while(0)
25 #endif
26
27 #if LIBCURL_VERSION_NUM < 0x070c04
28 #define NO_CURL_EASY_DUPHANDLE
29 #endif
30
31 #define RANGE_HEADER_SIZE 30
32
33 /* DAV method names and request body templates */
34 #define DAV_LOCK "LOCK"
35 #define DAV_MKCOL "MKCOL"
36 #define DAV_MOVE "MOVE"
37 #define DAV_PROPFIND "PROPFIND"
38 #define DAV_PUT "PUT"
39 #define DAV_UNLOCK "UNLOCK"
40 #define PROPFIND_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>"
41 #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>"
42
43 static int active_requests = 0;
44 static int data_received;
45 static int pushing = 0;
46 static int aborted = 0;
47
48 #ifdef USE_CURL_MULTI
49 static int max_requests = -1;
50 static CURLM *curlm;
51 #endif
52 #ifndef NO_CURL_EASY_DUPHANDLE
53 static CURL *curl_default;
54 #endif
55 static struct curl_slist *no_pragma_header;
56 static struct curl_slist *default_headers;
57 static char curl_errorstr[CURL_ERROR_SIZE];
58 static char *lock_token = NULL;
59
60 static int push_verbosely = 0;
61 static int push_all = 0;
62 static int force_all = 0;
63
64 struct buffer
65 {
66         size_t posn;
67         size_t size;
68         void *buffer;
69 };
70
71 struct repo
72 {
73         char *url;
74         struct packed_git *packs;
75 };
76
77 static struct repo *remote = NULL;
78
79 enum transfer_state {
80         NEED_CHECK,
81         RUN_HEAD,
82         NEED_PUSH,
83         RUN_MKCOL,
84         RUN_PUT,
85         RUN_MOVE,
86         ABORTED,
87         COMPLETE,
88 };
89
90 struct transfer_request
91 {
92         unsigned char sha1[20];
93         char *url;
94         char *dest;
95         char *lock_token;
96         struct curl_slist *headers;
97         struct buffer buffer;
98         char filename[PATH_MAX];
99         char tmpfile[PATH_MAX];
100         enum transfer_state state;
101         CURLcode curl_result;
102         char errorstr[CURL_ERROR_SIZE];
103         long http_code;
104         unsigned char real_sha1[20];
105         SHA_CTX c;
106         z_stream stream;
107         int zret;
108         int rename;
109         struct active_request_slot *slot;
110         struct transfer_request *next;
111 };
112
113 struct active_request_slot
114 {
115         CURL *curl;
116         FILE *local;
117         int in_use;
118         int done;
119         CURLcode curl_result;
120         long http_code;
121         struct active_request_slot *next;
122 };
123
124 static struct transfer_request *request_queue_head = NULL;
125 static struct active_request_slot *active_queue_head = NULL;
126
127 static int curl_ssl_verify = -1;
128 static char *ssl_cert = NULL;
129 #if LIBCURL_VERSION_NUM >= 0x070902
130 static char *ssl_key = NULL;
131 #endif
132 #if LIBCURL_VERSION_NUM >= 0x070908
133 static char *ssl_capath = NULL;
134 #endif
135 static char *ssl_cainfo = NULL;
136 static long curl_low_speed_limit = -1;
137 static long curl_low_speed_time = -1;
138
139 struct lockprop
140 {
141         int supported_lock;
142         int lock_entry;
143         int lock_scope;
144         int lock_type;
145         int lock_exclusive;
146         int lock_exclusive_write;
147 };
148
149 static int http_options(const char *var, const char *value)
150 {
151         if (!strcmp("http.sslverify", var)) {
152                 if (curl_ssl_verify == -1) {
153                         curl_ssl_verify = git_config_bool(var, value);
154                 }
155                 return 0;
156         }
157
158         if (!strcmp("http.sslcert", var)) {
159                 if (ssl_cert == NULL) {
160                         ssl_cert = xmalloc(strlen(value)+1);
161                         strcpy(ssl_cert, value);
162                 }
163                 return 0;
164         }
165 #if LIBCURL_VERSION_NUM >= 0x070902
166         if (!strcmp("http.sslkey", var)) {
167                 if (ssl_key == NULL) {
168                         ssl_key = xmalloc(strlen(value)+1);
169                         strcpy(ssl_key, value);
170                 }
171                 return 0;
172         }
173 #endif
174 #if LIBCURL_VERSION_NUM >= 0x070908
175         if (!strcmp("http.sslcapath", var)) {
176                 if (ssl_capath == NULL) {
177                         ssl_capath = xmalloc(strlen(value)+1);
178                         strcpy(ssl_capath, value);
179                 }
180                 return 0;
181         }
182 #endif
183         if (!strcmp("http.sslcainfo", var)) {
184                 if (ssl_cainfo == NULL) {
185                         ssl_cainfo = xmalloc(strlen(value)+1);
186                         strcpy(ssl_cainfo, value);
187                 }
188                 return 0;
189         }
190
191 #ifdef USE_CURL_MULTI   
192         if (!strcmp("http.maxrequests", var)) {
193                 if (max_requests == -1)
194                         max_requests = git_config_int(var, value);
195                 return 0;
196         }
197 #endif
198
199         if (!strcmp("http.lowspeedlimit", var)) {
200                 if (curl_low_speed_limit == -1)
201                         curl_low_speed_limit = (long)git_config_int(var, value);
202                 return 0;
203         }
204         if (!strcmp("http.lowspeedtime", var)) {
205                 if (curl_low_speed_time == -1)
206                         curl_low_speed_time = (long)git_config_int(var, value);
207                 return 0;
208         }
209
210         /* Fall back on the default ones */
211         return git_default_config(var, value);
212 }
213
214 static size_t fread_buffer(void *ptr, size_t eltsize, size_t nmemb,
215                            struct buffer *buffer)
216 {
217         size_t size = eltsize * nmemb;
218         if (size > buffer->size - buffer->posn)
219                 size = buffer->size - buffer->posn;
220         memcpy(ptr, buffer->buffer + buffer->posn, size);
221         buffer->posn += size;
222         return size;
223 }
224
225 static size_t fwrite_buffer_dynamic(const void *ptr, size_t eltsize,
226                                     size_t nmemb, struct buffer *buffer)
227 {
228         size_t size = eltsize * nmemb;
229         if (size > buffer->size - buffer->posn) {
230                 buffer->size = buffer->size * 3 / 2;
231                 if (buffer->size < buffer->posn + size)
232                         buffer->size = buffer->posn + size;
233                 buffer->buffer = xrealloc(buffer->buffer, buffer->size);
234         }
235         memcpy(buffer->buffer + buffer->posn, ptr, size);
236         buffer->posn += size;
237         data_received++;
238         return size;
239 }
240
241 static size_t fwrite_null(const void *ptr, size_t eltsize,
242                           size_t nmemb, struct buffer *buffer)
243 {
244         data_received++;
245         return eltsize * nmemb;
246 }
247
248 #ifdef USE_CURL_MULTI
249 static void process_curl_messages(void);
250 static void process_request_queue(void);
251 #endif
252
253 static CURL* get_curl_handle(void)
254 {
255         CURL* result = curl_easy_init();
256
257         curl_easy_setopt(result, CURLOPT_SSL_VERIFYPEER, curl_ssl_verify);
258 #if LIBCURL_VERSION_NUM >= 0x070907
259         curl_easy_setopt(result, CURLOPT_NETRC, CURL_NETRC_OPTIONAL);
260 #endif
261
262         if (ssl_cert != NULL)
263                 curl_easy_setopt(result, CURLOPT_SSLCERT, ssl_cert);
264 #if LIBCURL_VERSION_NUM >= 0x070902
265         if (ssl_key != NULL)
266                 curl_easy_setopt(result, CURLOPT_SSLKEY, ssl_key);
267 #endif
268 #if LIBCURL_VERSION_NUM >= 0x070908
269         if (ssl_capath != NULL)
270                 curl_easy_setopt(result, CURLOPT_CAPATH, ssl_capath);
271 #endif
272         if (ssl_cainfo != NULL)
273                 curl_easy_setopt(result, CURLOPT_CAINFO, ssl_cainfo);
274         curl_easy_setopt(result, CURLOPT_FAILONERROR, 1);
275
276         if (curl_low_speed_limit > 0 && curl_low_speed_time > 0) {
277                 curl_easy_setopt(result, CURLOPT_LOW_SPEED_LIMIT,
278                                  curl_low_speed_limit);
279                 curl_easy_setopt(result, CURLOPT_LOW_SPEED_TIME,
280                                  curl_low_speed_time);
281         }
282
283         return result;
284 }
285
286 static struct active_request_slot *get_active_slot(void)
287 {
288         struct active_request_slot *slot = active_queue_head;
289         struct active_request_slot *newslot;
290
291 #ifdef USE_CURL_MULTI
292         int num_transfers;
293
294         /* Wait for a slot to open up if the queue is full */
295         while (active_requests >= max_requests) {
296                 curl_multi_perform(curlm, &num_transfers);
297                 if (num_transfers < active_requests) {
298                         process_curl_messages();
299                 }
300         }
301 #endif
302
303         while (slot != NULL && slot->in_use) {
304                 slot = slot->next;
305         }
306         if (slot == NULL) {
307                 newslot = xmalloc(sizeof(*newslot));
308                 newslot->curl = NULL;
309                 newslot->in_use = 0;
310                 newslot->next = NULL;
311
312                 slot = active_queue_head;
313                 if (slot == NULL) {
314                         active_queue_head = newslot;
315                 } else {
316                         while (slot->next != NULL) {
317                                 slot = slot->next;
318                         }
319                         slot->next = newslot;
320                 }
321                 slot = newslot;
322         }
323
324         if (slot->curl == NULL) {
325 #ifdef NO_CURL_EASY_DUPHANDLE
326                 slot->curl = get_curl_handle();
327 #else
328                 slot->curl = curl_easy_duphandle(curl_default);
329 #endif
330         }
331
332         active_requests++;
333         slot->in_use = 1;
334         slot->done = 0;
335         slot->local = NULL;
336         curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, default_headers);
337         curl_easy_setopt(slot->curl, CURLOPT_ERRORBUFFER, curl_errorstr);
338
339         return slot;
340 }
341
342 static int start_active_slot(struct active_request_slot *slot)
343 {
344 #ifdef USE_CURL_MULTI
345         CURLMcode curlm_result = curl_multi_add_handle(curlm, slot->curl);
346
347         if (curlm_result != CURLM_OK &&
348             curlm_result != CURLM_CALL_MULTI_PERFORM) {
349                 active_requests--;
350                 slot->in_use = 0;
351                 return 0;
352         }
353 #endif
354         return 1;
355 }
356
357 static void run_active_slot(struct active_request_slot *slot)
358 {
359 #ifdef USE_CURL_MULTI
360         int num_transfers;
361         long last_pos = 0;
362         long current_pos;
363         fd_set readfds;
364         fd_set writefds;
365         fd_set excfds;
366         int max_fd;
367         struct timeval select_timeout;
368         CURLMcode curlm_result;
369
370         while (!slot->done) {
371                 data_received = 0;
372                 do {
373                         curlm_result = curl_multi_perform(curlm,
374                                                           &num_transfers);
375                 } while (curlm_result == CURLM_CALL_MULTI_PERFORM);
376                 if (num_transfers < active_requests) {
377                         process_curl_messages();
378                         process_request_queue();
379                 }
380
381                 if (!data_received && slot->local != NULL) {
382                         current_pos = ftell(slot->local);
383                         if (current_pos > last_pos)
384                                 data_received++;
385                         last_pos = current_pos;
386                 }
387
388                 if (!slot->done && !data_received) {
389                         max_fd = 0;
390                         FD_ZERO(&readfds);
391                         FD_ZERO(&writefds);
392                         FD_ZERO(&excfds);
393                         select_timeout.tv_sec = 0;
394                         select_timeout.tv_usec = 50000;
395                         select(max_fd, &readfds, &writefds,
396                                &excfds, &select_timeout);
397                 }
398         }
399 #else
400         slot->curl_result = curl_easy_perform(slot->curl);
401         active_requests--;
402 #endif
403 }
404
405 static void start_check(struct transfer_request *request)
406 {
407         char *hex = sha1_to_hex(request->sha1);
408         struct active_request_slot *slot;
409         char *posn;
410
411         request->url = xmalloc(strlen(remote->url) + 55);
412         strcpy(request->url, remote->url);
413         posn = request->url + strlen(remote->url);
414         strcpy(posn, "objects/");
415         posn += 8;
416         memcpy(posn, hex, 2);
417         posn += 2;
418         *(posn++) = '/';
419         strcpy(posn, hex + 2);
420
421         slot = get_active_slot();
422         curl_easy_setopt(slot->curl, CURLOPT_ERRORBUFFER, request->errorstr);
423         curl_easy_setopt(slot->curl, CURLOPT_URL, request->url);
424         curl_easy_setopt(slot->curl, CURLOPT_NOBODY, 1);
425
426         if (start_active_slot(slot)) {
427                 request->slot = slot;
428                 request->state = RUN_HEAD;
429         } else {
430                 request->state = ABORTED;
431                 free(request->url);
432         }
433 }
434
435 static void start_mkcol(struct transfer_request *request)
436 {
437         char *hex = sha1_to_hex(request->sha1);
438         struct active_request_slot *slot;
439         char *posn;
440
441         request->url = xmalloc(strlen(remote->url) + 13);
442         strcpy(request->url, remote->url);
443         posn = request->url + strlen(remote->url);
444         strcpy(posn, "objects/");
445         posn += 8;
446         memcpy(posn, hex, 2);
447         posn += 2;
448         strcpy(posn, "/");
449
450         slot = get_active_slot();
451         curl_easy_setopt(slot->curl, CURLOPT_HTTPGET, 1); /* undo PUT setup */
452         curl_easy_setopt(slot->curl, CURLOPT_URL, request->url);
453         curl_easy_setopt(slot->curl, CURLOPT_ERRORBUFFER, request->errorstr);
454         curl_easy_setopt(slot->curl, CURLOPT_CUSTOMREQUEST, DAV_MKCOL);
455         curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION, fwrite_null);
456
457         if (start_active_slot(slot)) {
458                 request->slot = slot;
459                 request->state = RUN_MKCOL;
460         } else {
461                 request->state = ABORTED;
462                 free(request->url);
463         }
464 }
465
466 static void start_put(struct transfer_request *request)
467 {
468         char *hex = sha1_to_hex(request->sha1);
469         struct active_request_slot *slot;
470         char *posn;
471         char type[20];
472         char hdr[50];
473         void *unpacked;
474         unsigned long len;
475         int hdrlen;
476         ssize_t size;
477         z_stream stream;
478
479         unpacked = read_sha1_file(request->sha1, type, &len);
480         hdrlen = sprintf(hdr, "%s %lu", type, len) + 1;
481
482         /* Set it up */
483         memset(&stream, 0, sizeof(stream));
484         deflateInit(&stream, Z_BEST_COMPRESSION);
485         size = deflateBound(&stream, len + hdrlen);
486         request->buffer.buffer = xmalloc(size);
487
488         /* Compress it */
489         stream.next_out = request->buffer.buffer;
490         stream.avail_out = size;
491
492         /* First header.. */
493         stream.next_in = (void *)hdr;
494         stream.avail_in = hdrlen;
495         while (deflate(&stream, 0) == Z_OK)
496                 /* nothing */;
497
498         /* Then the data itself.. */
499         stream.next_in = unpacked;
500         stream.avail_in = len;
501         while (deflate(&stream, Z_FINISH) == Z_OK)
502                 /* nothing */;
503         deflateEnd(&stream);
504         free(unpacked);
505
506         request->buffer.size = stream.total_out;
507         request->buffer.posn = 0;
508
509         if (request->url != NULL)
510                 free(request->url);
511         request->url = xmalloc(strlen(remote->url) + 
512                                strlen(request->lock_token) + 51);
513         strcpy(request->url, remote->url);
514         posn = request->url + strlen(remote->url);
515         strcpy(posn, "objects/");
516         posn += 8;
517         memcpy(posn, hex, 2);
518         posn += 2;
519         *(posn++) = '/';
520         strcpy(posn, hex + 2);
521         request->dest = xmalloc(strlen(request->url) + 14);
522         sprintf(request->dest, "Destination: %s", request->url);
523         posn += 38;
524         *(posn++) = '.';
525         strcpy(posn, request->lock_token);
526
527         slot = get_active_slot();
528         curl_easy_setopt(slot->curl, CURLOPT_INFILE, &request->buffer);
529         curl_easy_setopt(slot->curl, CURLOPT_INFILESIZE, request->buffer.size);
530         curl_easy_setopt(slot->curl, CURLOPT_READFUNCTION, fread_buffer);
531         curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION, fwrite_null);
532         curl_easy_setopt(slot->curl, CURLOPT_CUSTOMREQUEST, DAV_PUT);
533         curl_easy_setopt(slot->curl, CURLOPT_UPLOAD, 1);
534         curl_easy_setopt(slot->curl, CURLOPT_PUT, 1);
535         curl_easy_setopt(slot->curl, CURLOPT_NOBODY, 0);
536         curl_easy_setopt(slot->curl, CURLOPT_URL, request->url);
537
538         if (start_active_slot(slot)) {
539                 request->slot = slot;
540                 request->state = RUN_PUT;
541         } else {
542                 request->state = ABORTED;
543                 free(request->url);
544         }
545 }
546
547 static void start_move(struct transfer_request *request)
548 {
549         struct active_request_slot *slot;
550         struct curl_slist *dav_headers = NULL;
551
552         slot = get_active_slot();
553         curl_easy_setopt(slot->curl, CURLOPT_HTTPGET, 1); /* undo PUT setup */
554         curl_easy_setopt(slot->curl, CURLOPT_CUSTOMREQUEST, DAV_MOVE);
555         dav_headers = curl_slist_append(dav_headers, request->dest);
556         dav_headers = curl_slist_append(dav_headers, "Overwrite: T");
557         curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, dav_headers);
558         curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION, fwrite_null);
559         curl_easy_setopt(slot->curl, CURLOPT_URL, request->url);
560
561         if (start_active_slot(slot)) {
562                 request->slot = slot;
563                 request->state = RUN_MOVE;
564         } else {
565                 request->state = ABORTED;
566                 free(request->url);
567         }
568 }
569
570 static void finish_request(struct transfer_request *request)
571 {
572         request->curl_result =  request->slot->curl_result;
573         request->http_code = request->slot->http_code;
574         request->slot = NULL;
575         if (request->headers != NULL)
576                 curl_slist_free_all(request->headers);
577         if (request->state == RUN_HEAD) {
578                 if (request->http_code == 404) {
579                         request->state = NEED_PUSH;
580                 } else if (request->curl_result == CURLE_OK) {
581                         request->state = COMPLETE;
582                 } else {
583                         fprintf(stderr, "HEAD %s failed, aborting (%d/%ld)\n",
584                                 sha1_to_hex(request->sha1),
585                                 request->curl_result, request->http_code);
586                         request->state = ABORTED;
587                         aborted = 1;
588                 }
589         } else if (request->state == RUN_MKCOL) {
590                 if (request->curl_result == CURLE_OK ||
591                     request->http_code == 405) {
592                         start_put(request);
593                 } else {
594                         fprintf(stderr, "MKCOL %s failed, aborting (%d/%ld)\n",
595                                 sha1_to_hex(request->sha1),
596                                 request->curl_result, request->http_code);
597                         request->state = ABORTED;
598                         aborted = 1;
599                 }
600         } else if (request->state == RUN_PUT) {
601                 if (request->curl_result == CURLE_OK) {
602                         start_move(request);
603                 } else {
604                         fprintf(stderr, "PUT %s failed, aborting (%d/%ld)\n",
605                                 sha1_to_hex(request->sha1),
606                                 request->curl_result, request->http_code);
607                         request->state = ABORTED;
608                         aborted = 1;
609                 }
610         } else if (request->state == RUN_MOVE) {
611                 if (request->curl_result == CURLE_OK) {
612                         if (push_verbosely)
613                                 fprintf(stderr,
614                                         "sent %s\n",
615                                         sha1_to_hex(request->sha1));
616                         request->state = COMPLETE;
617                 } else {
618                         fprintf(stderr, "MOVE %s failed, aborting (%d/%ld)\n",
619                                 sha1_to_hex(request->sha1),
620                                 request->curl_result, request->http_code);
621                         request->state = ABORTED;
622                         aborted = 1;
623                 }
624         }
625 }
626
627 static void release_request(struct transfer_request *request)
628 {
629         struct transfer_request *entry = request_queue_head;
630
631         if (request == request_queue_head) {
632                 request_queue_head = request->next;
633         } else {
634                 while (entry->next != NULL && entry->next != request)
635                         entry = entry->next;
636                 if (entry->next == request)
637                         entry->next = entry->next->next;
638         }
639
640         free(request->url);
641         free(request);
642 }
643
644 #ifdef USE_CURL_MULTI
645 void process_curl_messages(void)
646 {
647         int num_messages;
648         struct active_request_slot *slot;
649         struct transfer_request *request = NULL;
650         CURLMsg *curl_message = curl_multi_info_read(curlm, &num_messages);
651
652         while (curl_message != NULL) {
653                 if (curl_message->msg == CURLMSG_DONE) {
654                         slot = active_queue_head;
655                         while (slot != NULL &&
656                                slot->curl != curl_message->easy_handle)
657                                 slot = slot->next;
658                         if (slot != NULL) {
659                                 curl_multi_remove_handle(curlm, slot->curl);
660                                 active_requests--;
661                                 slot->done = 1;
662                                 slot->in_use = 0;
663                                 slot->curl_result = curl_message->data.result;
664                                 curl_easy_getinfo(slot->curl,
665                                                   CURLINFO_HTTP_CODE,
666                                                   &slot->http_code);
667                                 request = request_queue_head;
668                                 while (request != NULL &&
669                                        request->slot != slot)
670                                         request = request->next;
671                                 if (request != NULL)
672                                         finish_request(request);
673                         } else {
674                                 fprintf(stderr, "Received DONE message for unknown request!\n");
675                         }
676                 } else {
677                         fprintf(stderr, "Unknown CURL message received: %d\n",
678                                 (int)curl_message->msg);
679                 }
680                 curl_message = curl_multi_info_read(curlm, &num_messages);
681         }
682 }
683
684 void process_request_queue(void)
685 {
686         struct transfer_request *request = request_queue_head;
687         struct active_request_slot *slot = active_queue_head;
688         int num_transfers;
689
690         if (aborted)
691                 return;
692
693         while (active_requests < max_requests && request != NULL) {
694                 if (!pushing && request->state == NEED_CHECK) {
695                         start_check(request);
696                         curl_multi_perform(curlm, &num_transfers);
697                 } else if (pushing && request->state == NEED_PUSH) {
698                         start_mkcol(request);
699                         curl_multi_perform(curlm, &num_transfers);
700                 }
701                 request = request->next;
702         }
703
704         while (slot != NULL) {
705                 if (!slot->in_use && slot->curl != NULL) {
706                         curl_easy_cleanup(slot->curl);
707                         slot->curl = NULL;
708                 }
709                 slot = slot->next;
710         }                               
711 }
712 #endif
713
714 void process_waiting_requests(void)
715 {
716         struct active_request_slot *slot = active_queue_head;
717
718         while (slot != NULL)
719                 if (slot->in_use) {
720                         run_active_slot(slot);
721                         slot = active_queue_head;
722                 } else {
723                         slot = slot->next;
724                 }
725 }
726
727 void add_request(unsigned char *sha1, char *lock_token)
728 {
729         struct transfer_request *request = request_queue_head;
730         struct transfer_request *tail;
731         struct packed_git *target;
732         
733         while (request != NULL && memcmp(request->sha1, sha1, 20))
734                 request = request->next;
735         if (request != NULL)
736                 return;
737
738         target = find_sha1_pack(sha1, remote->packs);
739         if (target)
740                 return;
741
742         request = xmalloc(sizeof(*request));
743         memcpy(request->sha1, sha1, 20);
744         request->url = NULL;
745         request->lock_token = lock_token;
746         request->headers = NULL;
747         request->state = NEED_CHECK;
748         request->next = NULL;
749
750         if (request_queue_head == NULL) {
751                 request_queue_head = request;
752         } else {
753                 tail = request_queue_head;
754                 while (tail->next != NULL) {
755                         tail = tail->next;
756                 }
757                 tail->next = request;
758         }
759 #ifdef USE_CURL_MULTI
760         process_request_queue();
761         process_curl_messages();
762 #endif
763 }
764
765 static int fetch_index(unsigned char *sha1)
766 {
767         char *hex = sha1_to_hex(sha1);
768         char *filename;
769         char *url;
770         char tmpfile[PATH_MAX];
771         long prev_posn = 0;
772         char range[RANGE_HEADER_SIZE];
773         struct curl_slist *range_header = NULL;
774
775         FILE *indexfile;
776         struct active_request_slot *slot;
777
778         if (has_pack_index(sha1))
779                 return 0;
780
781         if (push_verbosely)
782                 fprintf(stderr, "Getting index for pack %s\n", hex);
783         
784         url = xmalloc(strlen(remote->url) + 64);
785         sprintf(url, "%s/objects/pack/pack-%s.idx", remote->url, hex);
786         
787         filename = sha1_pack_index_name(sha1);
788         snprintf(tmpfile, sizeof(tmpfile), "%s.temp", filename);
789         indexfile = fopen(tmpfile, "a");
790         if (!indexfile)
791                 return error("Unable to open local file %s for pack index",
792                              filename);
793
794         slot = get_active_slot();
795         curl_easy_setopt(slot->curl, CURLOPT_FILE, indexfile);
796         curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION, fwrite);
797         curl_easy_setopt(slot->curl, CURLOPT_URL, url);
798         curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, no_pragma_header);
799         slot->local = indexfile;
800
801         /* If there is data present from a previous transfer attempt,
802            resume where it left off */
803         prev_posn = ftell(indexfile);
804         if (prev_posn>0) {
805                 if (push_verbosely)
806                         fprintf(stderr,
807                                 "Resuming fetch of index for pack %s at byte %ld\n",
808                                 hex, prev_posn);
809                 sprintf(range, "Range: bytes=%ld-", prev_posn);
810                 range_header = curl_slist_append(range_header, range);
811                 curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, range_header);
812         }
813
814         if (start_active_slot(slot)) {
815                 run_active_slot(slot);
816                 if (slot->curl_result != CURLE_OK) {
817                         free(url);
818                         fclose(indexfile);
819                         return error("Unable to get pack index %s\n%s", url,
820                                      curl_errorstr);
821                 }
822         } else {
823                 free(url);
824                 return error("Unable to start request");
825         }
826
827         free(url);
828         fclose(indexfile);
829
830         return move_temp_to_file(tmpfile, filename);
831 }
832
833 static int setup_index(unsigned char *sha1)
834 {
835         struct packed_git *new_pack;
836         if (has_pack_file(sha1))
837                 return 0; // don't list this as something we can get
838
839         if (fetch_index(sha1))
840                 return -1;
841
842         new_pack = parse_pack_index(sha1);
843         new_pack->next = remote->packs;
844         remote->packs = new_pack;
845         return 0;
846 }
847
848 static int fetch_indices()
849 {
850         unsigned char sha1[20];
851         char *url;
852         struct buffer buffer;
853         char *data;
854         int i = 0;
855
856         struct active_request_slot *slot;
857
858         data = xmalloc(4096);
859         memset(data, 0, 4096);
860         buffer.size = 4096;
861         buffer.posn = 0;
862         buffer.buffer = data;
863
864         if (push_verbosely)
865                 fprintf(stderr, "Getting pack list\n");
866         
867         url = xmalloc(strlen(remote->url) + 21);
868         sprintf(url, "%s/objects/info/packs", remote->url);
869
870         slot = get_active_slot();
871         curl_easy_setopt(slot->curl, CURLOPT_FILE, &buffer);
872         curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION,
873                          fwrite_buffer_dynamic);
874         curl_easy_setopt(slot->curl, CURLOPT_URL, url);
875         curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, NULL);
876         if (start_active_slot(slot)) {
877                 run_active_slot(slot);
878                 if (slot->curl_result != CURLE_OK) {
879                         free(buffer.buffer);
880                         free(url);
881                         if (slot->http_code == 404)
882                                 return 0;
883                         else
884                                 return error("%s", curl_errorstr);
885                 }
886         } else {
887                 free(buffer.buffer);
888                 free(url);
889                 return error("Unable to start request");
890         }
891         free(url);
892
893         data = buffer.buffer;
894         while (i < buffer.posn) {
895                 switch (data[i]) {
896                 case 'P':
897                         i++;
898                         if (i + 52 < buffer.posn &&
899                             !strncmp(data + i, " pack-", 6) &&
900                             !strncmp(data + i + 46, ".pack\n", 6)) {
901                                 get_sha1_hex(data + i + 6, sha1);
902                                 setup_index(sha1);
903                                 i += 51;
904                                 break;
905                         }
906                 default:
907                         while (data[i] != '\n')
908                                 i++;
909                 }
910                 i++;
911         }
912
913         free(buffer.buffer);
914         return 0;
915 }
916
917 static inline int needs_quote(int ch)
918 {
919         switch (ch) {
920         case '/': case '-': case '.':
921         case 'A'...'Z': case 'a'...'z': case '0'...'9':
922                 return 0;
923         default:
924                 return 1;
925         }
926 }
927
928 static inline int hex(int v)
929 {
930         if (v < 10) return '0' + v;
931         else return 'A' + v - 10;
932 }
933
934 static char *quote_ref_url(const char *base, const char *ref)
935 {
936         const char *cp;
937         char *dp, *qref;
938         int len, baselen, ch;
939
940         baselen = strlen(base);
941         len = baselen + 12; /* "refs/heads/" + NUL */
942         for (cp = ref; (ch = *cp) != 0; cp++, len++)
943                 if (needs_quote(ch))
944                         len += 2; /* extra two hex plus replacement % */
945         qref = xmalloc(len);
946         memcpy(qref, base, baselen);
947         memcpy(qref + baselen, "refs/heads/", 11);
948         for (cp = ref, dp = qref + baselen + 11; (ch = *cp) != 0; cp++) {
949                 if (needs_quote(ch)) {
950                         *dp++ = '%';
951                         *dp++ = hex((ch >> 4) & 0xF);
952                         *dp++ = hex(ch & 0xF);
953                 }
954                 else
955                         *dp++ = ch;
956         }
957         *dp = 0;
958
959         return qref;
960 }
961
962 int fetch_ref(char *ref, unsigned char *sha1)
963 {
964         char *url;
965         char hex[42];
966         struct buffer buffer;
967         char *base = remote->url;
968         struct active_request_slot *slot;
969         buffer.size = 41;
970         buffer.posn = 0;
971         buffer.buffer = hex;
972         hex[41] = '\0';
973         
974         url = quote_ref_url(base, ref);
975         slot = get_active_slot();
976         curl_easy_setopt(slot->curl, CURLOPT_FILE, &buffer);
977         curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION,
978                          fwrite_buffer_dynamic);
979         curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, NULL);
980         curl_easy_setopt(slot->curl, CURLOPT_URL, url);
981         if (start_active_slot(slot)) {
982                 run_active_slot(slot);
983                 if (slot->curl_result != CURLE_OK)
984                         return error("Couldn't get %s for %s\n%s",
985                                      url, ref, curl_errorstr);
986         } else {
987                 return error("Unable to start request");
988         }
989
990         hex[40] = '\0';
991         get_sha1_hex(hex, sha1);
992         return 0;
993 }
994
995 static void
996 start_lockprop_element(void *userData, const char *name, const char **atts)
997 {
998         struct lockprop *prop = (struct lockprop *)userData;
999
1000         if (prop->lock_type && !strcmp(name, "D:write")) {
1001                 if (prop->lock_exclusive) {
1002                         prop->lock_exclusive_write = 1;
1003                 }
1004         } else if (prop->lock_scope && !strcmp(name, "D:exclusive")) {
1005                 prop->lock_exclusive = 1;
1006         } else if (prop->lock_entry) {
1007                 if (!strcmp(name, "D:lockscope")) {
1008                         prop->lock_scope = 1;
1009                 } else if (!strcmp(name, "D:locktype")) {
1010                         prop->lock_type = 1;
1011                 }
1012         } else if (prop->supported_lock) {
1013                 if (!strcmp(name, "D:lockentry")) {
1014                         prop->lock_entry = 1;
1015                 }
1016         } else if (!strcmp(name, "D:supportedlock")) {
1017                 prop->supported_lock = 1;
1018         }
1019 }
1020
1021 static void
1022 end_lockprop_element(void *userData, const char *name)
1023 {
1024         struct lockprop *prop = (struct lockprop *)userData;
1025
1026         if (!strcmp(name, "D:lockentry")) {
1027                 prop->lock_entry = 0;
1028                 prop->lock_scope = 0;
1029                 prop->lock_type = 0;
1030                 prop->lock_exclusive = 0;
1031         } else if (!strcmp(name, "D:supportedlock")) {
1032                 prop->supported_lock = 0;
1033         }
1034 }
1035
1036 size_t process_lock_header( void *ptr, size_t size, size_t nmemb, void *stream)
1037 {
1038         size_t header_size = size*nmemb;
1039         char *start;
1040         char *end;
1041
1042         if (!strncmp(ptr, "Lock-Token: <opaquelocktoken:", 29)) {
1043                 start = ptr + 29;
1044                 for (end = ptr + header_size;
1045                      *(end - 1) == '\r' || *(end - 1) == '\n' || *(end - 1) == '>';
1046                      end--) {}
1047                 if (end > start) {
1048                         lock_token = xmalloc(end - start + 1);
1049                         memcpy(lock_token, start, end - start);
1050                         lock_token[end - start] = 0;
1051                 }
1052         }
1053
1054         return header_size;
1055 }
1056
1057 char *lock_remote(char *file, int timeout)
1058 {
1059         struct active_request_slot *slot;
1060         struct buffer out_buffer;
1061         char *out_data;
1062         char *url;
1063         char timeout_header[25];
1064         struct curl_slist *dav_headers = NULL;
1065
1066         if (lock_token != NULL)
1067                 free(lock_token);
1068
1069         out_buffer.size = strlen(LOCK_REQUEST) + strlen(git_default_email) - 2;
1070         out_data = xmalloc(out_buffer.size + 1);
1071         snprintf(out_data, out_buffer.size + 1, LOCK_REQUEST, git_default_email);
1072         out_buffer.posn = 0;
1073         out_buffer.buffer = out_data;
1074
1075         sprintf(timeout_header, "Timeout: Second-%d", timeout);
1076         url = xmalloc(strlen(remote->url) + strlen(file) + 1);
1077         sprintf(url, "%s%s", remote->url, file);
1078         dav_headers = curl_slist_append(dav_headers, timeout_header);
1079         dav_headers = curl_slist_append(dav_headers, "Content-Type: text/xml");
1080
1081         slot = get_active_slot();
1082         curl_easy_setopt(slot->curl, CURLOPT_INFILE, &out_buffer);
1083         curl_easy_setopt(slot->curl, CURLOPT_INFILESIZE, out_buffer.size);
1084         curl_easy_setopt(slot->curl, CURLOPT_READFUNCTION, fread_buffer);
1085         curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION, fwrite_null);
1086         curl_easy_setopt(slot->curl, CURLOPT_HEADERFUNCTION,
1087                 process_lock_header);
1088         curl_easy_setopt(slot->curl, CURLOPT_URL, url);
1089         curl_easy_setopt(slot->curl, CURLOPT_UPLOAD, 1);
1090         curl_easy_setopt(slot->curl, CURLOPT_CUSTOMREQUEST, DAV_LOCK);
1091         curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, dav_headers);
1092
1093         if (start_active_slot(slot)) {
1094                 run_active_slot(slot);
1095                 free(out_data);
1096                 if (slot->curl_result != CURLE_OK) {
1097                         fprintf(stderr, "Got HTTP error %ld\n", slot->http_code);
1098                         return NULL;
1099                 }
1100         } else {
1101                 free(out_data);
1102                 fprintf(stderr, "Unable to start request\n");
1103         }
1104
1105         return strdup(lock_token);
1106 }
1107
1108 int unlock_remote(char *file, char *lock_token)
1109 {
1110         struct active_request_slot *slot;
1111         char *url;
1112         char *lock_token_header;
1113         struct curl_slist *dav_headers = NULL;
1114         int rc = 0;
1115
1116         if (lock_token == NULL) {
1117                 fprintf(stderr, "Unable to unlock, no lock token");
1118                 return 0;
1119         }
1120
1121         lock_token_header = xmalloc(strlen(lock_token) + 31);
1122         sprintf(lock_token_header, "Lock-Token: <opaquelocktoken:%s>",
1123                 lock_token);
1124         url = xmalloc(strlen(remote->url) + strlen(file) + 1);
1125         sprintf(url, "%s%s", remote->url, file);
1126         dav_headers = curl_slist_append(dav_headers, lock_token_header);
1127
1128         slot = get_active_slot();
1129         curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION, fwrite_null);
1130         curl_easy_setopt(slot->curl, CURLOPT_URL, url);
1131         curl_easy_setopt(slot->curl, CURLOPT_CUSTOMREQUEST, DAV_UNLOCK);
1132         curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, dav_headers);
1133
1134         if (start_active_slot(slot)) {
1135                 run_active_slot(slot);
1136                 if (slot->curl_result == CURLE_OK)
1137                         rc = 1;
1138                 else
1139                         fprintf(stderr, "Got HTTP error %ld\n",
1140                                 slot->http_code);
1141         } else {
1142                 fprintf(stderr, "Unable to start request\n");
1143         }
1144
1145         curl_slist_free_all(dav_headers);
1146         free(lock_token_header);
1147         free(url);
1148
1149         return rc;
1150 }
1151
1152 int check_locking()
1153 {
1154         struct active_request_slot *slot;
1155         struct buffer in_buffer;
1156         struct buffer out_buffer;
1157         char *in_data;
1158         char *out_data;
1159         XML_Parser parser = XML_ParserCreate(NULL);
1160         enum XML_Status result;
1161         struct lockprop supported_lock;
1162         struct curl_slist *dav_headers = NULL;
1163
1164         out_buffer.size = strlen(PROPFIND_REQUEST) + strlen(remote->url) - 2;
1165         out_data = xmalloc(out_buffer.size + 1);
1166         snprintf(out_data, out_buffer.size + 1, PROPFIND_REQUEST, remote->url);
1167         out_buffer.posn = 0;
1168         out_buffer.buffer = out_data;
1169
1170         in_buffer.size = 4096;
1171         in_data = xmalloc(in_buffer.size);
1172         in_buffer.posn = 0;
1173         in_buffer.buffer = in_data;
1174
1175         dav_headers = curl_slist_append(dav_headers, "Depth: 0");
1176         dav_headers = curl_slist_append(dav_headers, "Content-Type: text/xml");
1177         
1178         slot = get_active_slot();
1179         curl_easy_setopt(slot->curl, CURLOPT_INFILE, &out_buffer);
1180         curl_easy_setopt(slot->curl, CURLOPT_INFILESIZE, out_buffer.size);
1181         curl_easy_setopt(slot->curl, CURLOPT_READFUNCTION, fread_buffer);
1182         curl_easy_setopt(slot->curl, CURLOPT_FILE, &in_buffer);
1183         curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION,
1184                          fwrite_buffer_dynamic);
1185         curl_easy_setopt(slot->curl, CURLOPT_URL, remote->url);
1186         curl_easy_setopt(slot->curl, CURLOPT_UPLOAD, 1);
1187         curl_easy_setopt(slot->curl, CURLOPT_CUSTOMREQUEST, DAV_PROPFIND);
1188         curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, dav_headers);
1189
1190         if (start_active_slot(slot)) {
1191                 run_active_slot(slot);
1192                 free(out_data);
1193                 if (slot->curl_result != CURLE_OK) {
1194                         free(in_buffer.buffer);
1195                         return -1;
1196                 }
1197
1198                 XML_SetUserData(parser, &supported_lock);
1199                 XML_SetElementHandler(parser, start_lockprop_element,
1200                                       end_lockprop_element);
1201                 result = XML_Parse(parser, in_buffer.buffer, in_buffer.posn, 1);
1202                 free(in_buffer.buffer);
1203                 if (result != XML_STATUS_OK)
1204                         return error("%s", XML_ErrorString(
1205                                              XML_GetErrorCode(parser)));
1206         } else {
1207                 free(out_data);
1208                 free(in_buffer.buffer);
1209                 return error("Unable to start request");
1210         }
1211
1212         if (supported_lock.lock_exclusive_write)
1213                 return 0;
1214         else
1215                 return 1;
1216 }
1217
1218 int is_ancestor(unsigned char *sha1, struct commit *commit)
1219 {
1220         struct commit_list *parents;
1221
1222         if (parse_commit(commit))
1223                 return 0;
1224         parents = commit->parents;
1225         for (; parents; parents = parents->next) {
1226                 if (!memcmp(sha1, parents->item->object.sha1, 20)) {
1227                         return 1;
1228                 } else if (parents->item->object.type == commit_type) {
1229                         if (is_ancestor(
1230                                     sha1,
1231                                     (struct commit *)&parents->item->object
1232                                     ))
1233                                 return 1;
1234                 }
1235         }
1236         return 0;
1237 }
1238
1239 void get_delta(unsigned char *sha1, struct object *obj, char *lock_token)
1240 {
1241         struct commit *commit;
1242         struct commit_list *parents;
1243         struct tree *tree;
1244         struct tree_entry_list *entry;
1245
1246         if (sha1 && !memcmp(sha1, obj->sha1, 20))
1247                 return;
1248
1249         if (aborted)
1250                 return;
1251
1252         if (obj->type == commit_type) {
1253                 if (push_verbosely)
1254                         fprintf(stderr, "walk %s\n", sha1_to_hex(obj->sha1));
1255                 add_request(obj->sha1, lock_token);
1256                 commit = (struct commit *)obj;
1257                 if (parse_commit(commit)) {
1258                         fprintf(stderr, "Error parsing commit %s\n",
1259                                 sha1_to_hex(obj->sha1));
1260                         aborted = 1;
1261                         return;
1262                 }
1263                 parents = commit->parents;
1264                 for (; parents; parents = parents->next)
1265                         if (sha1 == NULL ||
1266                             memcmp(sha1, parents->item->object.sha1, 20))
1267                                 get_delta(sha1, &parents->item->object,
1268                                           lock_token);
1269                 get_delta(sha1, &commit->tree->object, lock_token);
1270         } else if (obj->type == tree_type) {
1271                 if (push_verbosely)
1272                         fprintf(stderr, "walk %s\n", sha1_to_hex(obj->sha1));
1273                 add_request(obj->sha1, lock_token);
1274                 tree = (struct tree *)obj;
1275                 if (parse_tree(tree)) {
1276                         fprintf(stderr, "Error parsing tree %s\n",
1277                                 sha1_to_hex(obj->sha1));
1278                         aborted = 1;
1279                         return;
1280                 }
1281                 entry = tree->entries;
1282                 tree->entries = NULL;
1283                 while (entry) {
1284                         struct tree_entry_list *next = entry->next;
1285                         get_delta(sha1, entry->item.any, lock_token);
1286                         free(entry->name);
1287                         free(entry);
1288                         entry = next;
1289                 }
1290         } else if (obj->type == blob_type || obj->type == tag_type) {
1291                 add_request(obj->sha1, lock_token);
1292         }
1293 }
1294
1295 int update_remote(char *remote_path, unsigned char *sha1, char *lock_token)
1296 {
1297         struct active_request_slot *slot;
1298         char *url;
1299         char *out_data;
1300         char *if_header;
1301         struct buffer out_buffer;
1302         struct curl_slist *dav_headers = NULL;
1303         int i;
1304
1305         url = xmalloc(strlen(remote->url) + strlen(remote_path) + 1);
1306         sprintf(url, "%s%s", remote->url, remote_path);
1307
1308         if_header = xmalloc(strlen(lock_token) + 25);
1309         sprintf(if_header, "If: (<opaquelocktoken:%s>)", lock_token);
1310         dav_headers = curl_slist_append(dav_headers, if_header);
1311
1312         out_buffer.size = 41;
1313         out_data = xmalloc(out_buffer.size + 1);
1314         i = snprintf(out_data, out_buffer.size + 1, "%s\n", sha1_to_hex(sha1));
1315         if (i != out_buffer.size) {
1316                 fprintf(stderr, "Unable to initialize PUT request body\n");
1317                 return 0;
1318         }
1319         out_buffer.posn = 0;
1320         out_buffer.buffer = out_data;
1321
1322         slot = get_active_slot();
1323         curl_easy_setopt(slot->curl, CURLOPT_INFILE, &out_buffer);
1324         curl_easy_setopt(slot->curl, CURLOPT_INFILESIZE, out_buffer.size);
1325         curl_easy_setopt(slot->curl, CURLOPT_READFUNCTION, fread_buffer);
1326         curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION, fwrite_null);
1327         curl_easy_setopt(slot->curl, CURLOPT_CUSTOMREQUEST, DAV_PUT);
1328         curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, dav_headers);
1329         curl_easy_setopt(slot->curl, CURLOPT_UPLOAD, 1);
1330         curl_easy_setopt(slot->curl, CURLOPT_PUT, 1);
1331         curl_easy_setopt(slot->curl, CURLOPT_URL, url);
1332
1333         if (start_active_slot(slot)) {
1334                 run_active_slot(slot);
1335                 free(out_data);
1336                 free(if_header);
1337                 free(url);
1338                 if (slot->curl_result != CURLE_OK) {
1339                         fprintf(stderr,
1340                                 "PUT error: curl result=%d, HTTP code=%ld\n",
1341                                 slot->curl_result, slot->http_code);
1342                         /* We should attempt recovery? */
1343                         return 0;
1344                 }
1345         } else {
1346                 free(out_data);
1347                 free(if_header);
1348                 free(url);
1349                 fprintf(stderr, "Unable to start PUT request\n");
1350                 return 0;
1351         }
1352
1353         return 1;
1354 }
1355
1356 int main(int argc, char **argv)
1357 {
1358         struct active_request_slot *slot;
1359         struct active_request_slot *next_slot;
1360         struct transfer_request *request;
1361         struct transfer_request *next_request;
1362         int nr_refspec = 0;
1363         char **refspec = NULL;
1364         int do_remote_update;
1365         int new_branch;
1366         int force_this;
1367         char *local_ref;
1368         unsigned char local_sha1[20];
1369         struct object *local_object = NULL;
1370         char *remote_ref = NULL;
1371         unsigned char remote_sha1[20];
1372         char *remote_lock = NULL;
1373         char *remote_path = NULL;
1374         char *low_speed_limit;
1375         char *low_speed_time;
1376         int rc = 0;
1377         int i;
1378
1379         setup_ident();
1380
1381         remote = xmalloc(sizeof(*remote));
1382         remote->url = NULL;
1383         remote->packs = NULL;
1384
1385         argv++;
1386         for (i = 1; i < argc; i++, argv++) {
1387                 char *arg = *argv;
1388
1389                 if (*arg == '-') {
1390                         if (!strcmp(arg, "--complete")) {
1391                                 push_all = 1;
1392                                 continue;
1393                         }
1394                         if (!strcmp(arg, "--force")) {
1395                                 force_all = 1;
1396                                 continue;
1397                         }
1398                         if (!strcmp(arg, "--verbose")) {
1399                                 push_verbosely = 1;
1400                                 continue;
1401                         }
1402                         usage(http_push_usage);
1403                 }
1404                 if (!remote->url) {
1405                         remote->url = arg;
1406                         continue;
1407                 }
1408                 refspec = argv;
1409                 nr_refspec = argc - i;
1410                 break;
1411         }
1412
1413         curl_global_init(CURL_GLOBAL_ALL);
1414
1415 #ifdef USE_CURL_MULTI
1416         {
1417                 char *http_max_requests = getenv("GIT_HTTP_MAX_REQUESTS");
1418                 if (http_max_requests != NULL)
1419                         max_requests = atoi(http_max_requests);
1420         }
1421
1422         curlm = curl_multi_init();
1423         if (curlm == NULL) {
1424                 fprintf(stderr, "Error creating curl multi handle.\n");
1425                 return 1;
1426         }
1427 #endif
1428
1429         if (getenv("GIT_SSL_NO_VERIFY"))
1430                 curl_ssl_verify = 0;
1431
1432         ssl_cert = getenv("GIT_SSL_CERT");
1433 #if LIBCURL_VERSION_NUM >= 0x070902
1434         ssl_key = getenv("GIT_SSL_KEY");
1435 #endif
1436 #if LIBCURL_VERSION_NUM >= 0x070908
1437         ssl_capath = getenv("GIT_SSL_CAPATH");
1438 #endif
1439         ssl_cainfo = getenv("GIT_SSL_CAINFO");
1440
1441         low_speed_limit = getenv("GIT_HTTP_LOW_SPEED_LIMIT");
1442         if (low_speed_limit != NULL)
1443                 curl_low_speed_limit = strtol(low_speed_limit, NULL, 10);
1444         low_speed_time = getenv("GIT_HTTP_LOW_SPEED_TIME");
1445         if (low_speed_time != NULL)
1446                 curl_low_speed_time = strtol(low_speed_time, NULL, 10);
1447
1448         git_config(http_options);
1449
1450         if (curl_ssl_verify == -1)
1451                 curl_ssl_verify = 1;
1452
1453 #ifdef USE_CURL_MULTI
1454         if (max_requests < 1)
1455                 max_requests = DEFAULT_MAX_REQUESTS;
1456 #endif
1457
1458         no_pragma_header = curl_slist_append(no_pragma_header, "Pragma:");
1459         default_headers = curl_slist_append(default_headers, "Range:");
1460         default_headers = curl_slist_append(default_headers, "Destination:");
1461         default_headers = curl_slist_append(default_headers, "If:");
1462         default_headers = curl_slist_append(default_headers,
1463                                             "Pragma: no-cache");
1464
1465 #ifndef NO_CURL_EASY_DUPHANDLE
1466         curl_default = get_curl_handle();
1467 #endif
1468
1469         /* Verify DAV compliance/lock support */
1470         if (check_locking() != 0) {
1471                 fprintf(stderr, "Error: no DAV locking support on remote repo %s\n", remote->url);
1472                 rc = 1;
1473                 goto cleanup;
1474         }
1475
1476         /* Process each refspec */
1477         for (i = 0; i < nr_refspec; i++) {
1478                 char *ep;
1479                 force_this = 0;
1480                 do_remote_update = 0;
1481                 new_branch = 0;
1482                 local_ref = refspec[i];
1483                 if (*local_ref == '+') {
1484                         force_this = 1;
1485                         local_ref++;
1486                 }
1487                 ep = strchr(local_ref, ':');
1488                 if (ep) {
1489                         remote_ref = ep + 1;
1490                         *ep = 0;
1491                 }
1492                 else
1493                         remote_ref = local_ref;
1494
1495                 /* Lock remote branch ref */
1496                 if (remote_path)
1497                         free(remote_path);
1498                 remote_path = xmalloc(strlen(remote_ref) + 12);
1499                 sprintf(remote_path, "refs/heads/%s", remote_ref);
1500                 remote_lock = lock_remote(remote_path, 3600);
1501                 if (remote_lock == NULL) {
1502                         fprintf(stderr, "Unable to lock remote branch %s\n",
1503                                 remote_ref);
1504                         rc = 1;
1505                         continue;
1506                 }
1507
1508                 /* Resolve local and remote refs */
1509                 if (fetch_ref(remote_ref, remote_sha1) != 0) {
1510                         fprintf(stderr,
1511                                 "Remote branch %s does not exist on %s\n",
1512                                 remote_ref, remote->url);
1513                         new_branch = 1;
1514                 }
1515                 if (get_sha1(local_ref, local_sha1) != 0) {
1516                         fprintf(stderr, "Error resolving local branch %s\n",
1517                                 local_ref);
1518                         rc = 1;
1519                         goto unlock;
1520                 }
1521         
1522                 /* Find relationship between local and remote */
1523                 local_object = parse_object(local_sha1);
1524                 if (!local_object) {
1525                         fprintf(stderr, "Unable to parse local object %s\n",
1526                                 sha1_to_hex(local_sha1));
1527                         rc = 1;
1528                         goto unlock;
1529                 } else if (new_branch) {
1530                         do_remote_update = 1;
1531                 } else {
1532                         if (!memcmp(local_sha1, remote_sha1, 20)) {
1533                                 fprintf(stderr,
1534                                         "* %s: same as branch '%s' of %s\n",
1535                                         local_ref, remote_ref, remote->url);
1536                         } else if (is_ancestor(remote_sha1,
1537                                                (struct commit *)local_object)) {
1538                                 fprintf(stderr,
1539                                         "Remote %s will fast-forward to local %s\n",
1540                                         remote_ref, local_ref);
1541                                 do_remote_update = 1;
1542                         } else if (force_all || force_this) {
1543                                 fprintf(stderr,
1544                                         "* %s on %s does not fast forward to local branch '%s', overwriting\n",
1545                                         remote_ref, remote->url, local_ref);
1546                                 do_remote_update = 1;
1547                         } else {
1548                                 fprintf(stderr,
1549                                         "* %s on %s does not fast forward to local branch '%s'\n",
1550                                         remote_ref, remote->url, local_ref);
1551                                 rc = 1;
1552                                 goto unlock;
1553                         }
1554                 }
1555
1556                 /* Generate and check list of required objects */
1557                 pushing = 0;
1558                 if (do_remote_update || push_all)
1559                         fetch_indices();
1560                 get_delta(push_all ? NULL : remote_sha1,
1561                           local_object, remote_lock);
1562                 process_waiting_requests();
1563
1564                 /* Push missing objects to remote, this would be a
1565                    convenient time to pack them first if appropriate. */
1566                 pushing = 1;
1567                 process_request_queue();
1568                 process_waiting_requests();
1569
1570                 /* Update the remote branch if all went well */
1571                 if (do_remote_update) {
1572                         if (!aborted && update_remote(remote_path,
1573                                                       local_sha1,
1574                                                       remote_lock)) {
1575                                 fprintf(stderr, "%s remote branch %s\n",
1576                                         new_branch ? "Created" : "Updated",
1577                                         remote_ref);
1578                         } else {
1579                                 fprintf(stderr,
1580                                         "Unable to %s remote branch %s\n",
1581                                         new_branch ? "create" : "update",
1582                                         remote_ref);
1583                                 rc = 1;
1584                                 goto unlock;
1585                         }
1586                 }
1587
1588         unlock:
1589                 unlock_remote(remote_path, remote_lock);
1590                 free(remote_path);
1591                 free(remote_lock);
1592         }
1593
1594  cleanup:
1595         free(remote);
1596
1597         curl_slist_free_all(no_pragma_header);
1598         curl_slist_free_all(default_headers);
1599
1600         slot = active_queue_head;
1601         while (slot != NULL) {
1602                 next_slot = slot->next;
1603                 if (slot->curl != NULL)
1604                         curl_easy_cleanup(slot->curl);
1605                 free(slot);
1606                 slot = next_slot;
1607         }
1608
1609         request = request_queue_head;
1610         while (request != NULL) {
1611                 next_request = request->next;
1612                 release_request(request);
1613                 free(request);
1614                 request = next_request;
1615         }
1616
1617 #ifndef NO_CURL_EASY_DUPHANDLE
1618         curl_easy_cleanup(curl_default);
1619 #endif
1620 #ifdef USE_CURL_MULTI
1621         curl_multi_cleanup(curlm);
1622 #endif
1623         curl_global_cleanup();
1624         return rc;
1625 }