polarssl: fix compilation
[platform/upstream/curl.git] / lib / urldata.h
1 #ifndef HEADER_CURL_URLDATA_H
2 #define HEADER_CURL_URLDATA_H
3 /***************************************************************************
4  *                                  _   _ ____  _
5  *  Project                     ___| | | |  _ \| |
6  *                             / __| | | | |_) | |
7  *                            | (__| |_| |  _ <| |___
8  *                             \___|\___/|_| \_\_____|
9  *
10  * Copyright (C) 1998 - 2014, Daniel Stenberg, <daniel@haxx.se>, et al.
11  *
12  * This software is licensed as described in the file COPYING, which
13  * you should have received as part of this distribution. The terms
14  * are also available at http://curl.haxx.se/docs/copyright.html.
15  *
16  * You may opt to use, copy, modify, merge, publish, distribute and/or sell
17  * copies of the Software, and permit persons to whom the Software is
18  * furnished to do so, under the terms of the COPYING file.
19  *
20  * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
21  * KIND, either express or implied.
22  *
23  ***************************************************************************/
24
25 /* This file is for lib internal stuff */
26
27 #include "curl_setup.h"
28
29 #define PORT_FTP 21
30 #define PORT_FTPS 990
31 #define PORT_TELNET 23
32 #define PORT_HTTP 80
33 #define PORT_HTTPS 443
34 #define PORT_DICT 2628
35 #define PORT_LDAP 389
36 #define PORT_LDAPS 636
37 #define PORT_TFTP 69
38 #define PORT_SSH 22
39 #define PORT_IMAP 143
40 #define PORT_IMAPS 993
41 #define PORT_POP3 110
42 #define PORT_POP3S 995
43 #define PORT_SMTP 25
44 #define PORT_SMTPS 465 /* sometimes called SSMTP */
45 #define PORT_RTSP 554
46 #define PORT_RTMP 1935
47 #define PORT_RTMPT PORT_HTTP
48 #define PORT_RTMPS PORT_HTTPS
49 #define PORT_GOPHER 70
50
51 #define DICT_MATCH "/MATCH:"
52 #define DICT_MATCH2 "/M:"
53 #define DICT_MATCH3 "/FIND:"
54 #define DICT_DEFINE "/DEFINE:"
55 #define DICT_DEFINE2 "/D:"
56 #define DICT_DEFINE3 "/LOOKUP:"
57
58 #define CURL_DEFAULT_USER "anonymous"
59 #define CURL_DEFAULT_PASSWORD "ftp@example.com"
60
61 #define DEFAULT_CONNCACHE_SIZE 5
62
63 /* length of longest IPv6 address string including the trailing null */
64 #define MAX_IPADR_LEN sizeof("ffff:ffff:ffff:ffff:ffff:ffff:255.255.255.255")
65
66 /* Default FTP/IMAP etc response timeout in milliseconds.
67    Symbian OS panics when given a timeout much greater than 1/2 hour.
68 */
69 #define RESP_TIMEOUT (1800*1000)
70
71 #include "cookie.h"
72 #include "formdata.h"
73
74 #ifdef USE_SSLEAY
75 #ifdef USE_OPENSSL
76 #include <openssl/rsa.h>
77 #include <openssl/crypto.h>
78 #include <openssl/x509.h>
79 #include <openssl/pem.h>
80 #include <openssl/ssl.h>
81 #include <openssl/err.h>
82 #ifdef HAVE_OPENSSL_ENGINE_H
83 #include <openssl/engine.h>
84 #endif
85 #ifdef HAVE_OPENSSL_PKCS12_H
86 #include <openssl/pkcs12.h>
87 #endif
88 #else /* SSLeay-style includes */
89 #include <rsa.h>
90 #include <crypto.h>
91 #include <x509.h>
92 #include <pem.h>
93 #include <ssl.h>
94 #include <err.h>
95 #ifdef HAVE_OPENSSL_ENGINE_H
96 #include <engine.h>
97 #endif
98 #ifdef HAVE_OPENSSL_PKCS12_H
99 #include <pkcs12.h>
100 #endif
101 #endif /* USE_OPENSSL */
102 #ifdef USE_GNUTLS
103 #error Configuration error; cannot use GnuTLS *and* OpenSSL.
104 #endif
105 #endif /* USE_SSLEAY */
106
107 #ifdef USE_GNUTLS
108 #include <gnutls/gnutls.h>
109 #endif
110
111 #ifdef USE_POLARSSL
112 #include <polarssl/ssl.h>
113 #include <polarssl/version.h>
114 #if POLARSSL_VERSION_NUMBER<0x01010000
115 #include <polarssl/havege.h>
116 #else
117 #include <polarssl/entropy.h>
118 #include <polarssl/ctr_drbg.h>
119 #endif /* POLARSSL_VERSION_NUMBER<0x01010000 */
120 #endif /* USE_POLARSSL */
121
122 #ifdef USE_CYASSL
123 #undef OCSP_REQUEST  /* avoid cyassl/openssl/ssl.h clash with wincrypt.h */
124 #undef OCSP_RESPONSE /* avoid cyassl/openssl/ssl.h clash with wincrypt.h */
125 #include <cyassl/openssl/ssl.h>
126 #endif
127
128 #ifdef USE_NSS
129 #include <nspr.h>
130 #include <pk11pub.h>
131 #endif
132
133 #ifdef USE_QSOSSL
134 #include <qsossl.h>
135 #endif
136
137 #ifdef USE_GSKIT
138 #include <gskssl.h>
139 #endif
140
141 #ifdef USE_AXTLS
142 #include <axTLS/ssl.h>
143 #undef malloc
144 #undef calloc
145 #undef realloc
146 #endif /* USE_AXTLS */
147
148 #ifdef USE_SCHANNEL
149 #include "curl_sspi.h"
150 #include <schnlsp.h>
151 #include <schannel.h>
152 #endif
153
154 #ifdef USE_DARWINSSL
155 #include <Security/Security.h>
156 /* For some reason, when building for iOS, the omnibus header above does
157  * not include SecureTransport.h as of iOS SDK 5.1. */
158 #include <Security/SecureTransport.h>
159 #endif
160
161 #ifdef HAVE_NETINET_IN_H
162 #include <netinet/in.h>
163 #endif
164
165 #include "timeval.h"
166
167 #ifdef HAVE_ZLIB_H
168 #include <zlib.h>               /* for content-encoding */
169 #ifdef __SYMBIAN32__
170 /* zlib pollutes the namespace with this definition */
171 #undef WIN32
172 #endif
173 #endif
174
175 #include <curl/curl.h>
176
177 #include "http_chunks.h" /* for the structs and enum stuff */
178 #include "hostip.h"
179 #include "hash.h"
180 #include "splay.h"
181
182 #include "imap.h"
183 #include "pop3.h"
184 #include "smtp.h"
185 #include "ftp.h"
186 #include "file.h"
187 #include "ssh.h"
188 #include "http.h"
189 #include "rtsp.h"
190 #include "wildcard.h"
191 #include "multihandle.h"
192
193 #ifdef HAVE_GSSAPI
194 # ifdef HAVE_GSSGNU
195 #  include <gss.h>
196 # elif defined HAVE_GSSMIT
197 #  include <gssapi/gssapi.h>
198 #  include <gssapi/gssapi_generic.h>
199 # else
200 #  include <gssapi.h>
201 # endif
202 #endif
203
204 #ifdef HAVE_LIBSSH2_H
205 #include <libssh2.h>
206 #include <libssh2_sftp.h>
207 #endif /* HAVE_LIBSSH2_H */
208
209 /* Download buffer size, keep it fairly big for speed reasons */
210 #undef BUFSIZE
211 #define BUFSIZE CURL_MAX_WRITE_SIZE
212
213 /* Initial size of the buffer to store headers in, it'll be enlarged in case
214    of need. */
215 #define HEADERSIZE 256
216
217 #define CURLEASY_MAGIC_NUMBER 0xc0dedbadU
218
219 /* Some convenience macros to get the larger/smaller value out of two given.
220    We prefix with CURL to prevent name collisions. */
221 #define CURLMAX(x,y) ((x)>(y)?(x):(y))
222 #define CURLMIN(x,y) ((x)<(y)?(x):(y))
223
224
225 #ifdef HAVE_GSSAPI
226 /* Types needed for krb5-ftp connections */
227 struct krb5buffer {
228   void *data;
229   size_t size;
230   size_t index;
231   int eof_flag;
232 };
233
234 enum protection_level {
235   PROT_NONE, /* first in list */
236   PROT_CLEAR,
237   PROT_SAFE,
238   PROT_CONFIDENTIAL,
239   PROT_PRIVATE,
240   PROT_CMD,
241   PROT_LAST /* last in list */
242 };
243 #endif
244
245 #ifdef USE_SCHANNEL
246 /* Structs to store Schannel handles */
247 struct curl_schannel_cred {
248   CredHandle cred_handle;
249   TimeStamp time_stamp;
250   int refcount;
251   bool cached;
252 };
253
254 struct curl_schannel_ctxt {
255   CtxtHandle ctxt_handle;
256   TimeStamp time_stamp;
257 };
258 #endif
259
260 /* enum for the nonblocking SSL connection state machine */
261 typedef enum {
262   ssl_connect_1,
263   ssl_connect_2,
264   ssl_connect_2_reading,
265   ssl_connect_2_writing,
266   ssl_connect_3,
267   ssl_connect_done
268 } ssl_connect_state;
269
270 typedef enum {
271   ssl_connection_none,
272   ssl_connection_negotiating,
273   ssl_connection_complete
274 } ssl_connection_state;
275
276 /* struct for data related to each SSL connection */
277 struct ssl_connect_data {
278   /* Use ssl encrypted communications TRUE/FALSE, not necessarily using it atm
279      but at least asked to or meaning to use it. See 'state' for the exact
280      current state of the connection. */
281   bool use;
282   ssl_connection_state state;
283 #ifdef USE_SSLEAY
284   /* these ones requires specific SSL-types */
285   SSL_CTX* ctx;
286   SSL*     handle;
287   X509*    server_cert;
288   ssl_connect_state connecting_state;
289 #endif /* USE_SSLEAY */
290 #ifdef USE_GNUTLS
291   gnutls_session session;
292   gnutls_certificate_credentials cred;
293 #ifdef USE_TLS_SRP
294   gnutls_srp_client_credentials srp_client_cred;
295 #endif
296   ssl_connect_state connecting_state;
297 #endif /* USE_GNUTLS */
298 #ifdef USE_POLARSSL
299 #if POLARSSL_VERSION_NUMBER<0x01010000
300   havege_state hs;
301 #else
302   /* from v1.1.0, use ctr_drbg and entropy */
303   ctr_drbg_context ctr_drbg;
304   entropy_context entropy;
305 #endif /* POLARSSL_VERSION_NUMBER<0x01010000 */
306   ssl_context ssl;
307   ssl_session ssn;
308   int server_fd;
309   x509_crt cacert;
310   x509_crt clicert;
311   x509_crl crl;
312   rsa_context rsa;
313   ssl_connect_state connecting_state;
314 #endif /* USE_POLARSSL */
315 #ifdef USE_CYASSL
316   SSL_CTX* ctx;
317   SSL*     handle;
318   ssl_connect_state connecting_state;
319 #endif /* USE_CYASSL */
320 #ifdef USE_NSS
321   PRFileDesc *handle;
322   char *client_nickname;
323   struct SessionHandle *data;
324   struct curl_llist *obj_list;
325   PK11GenericObject *obj_clicert;
326 #endif /* USE_NSS */
327 #ifdef USE_QSOSSL
328   SSLHandle *handle;
329 #endif /* USE_QSOSSL */
330 #ifdef USE_GSKIT
331   gsk_handle handle;
332   int iocport;
333   ssl_connect_state connecting_state;
334 #endif
335 #ifdef USE_AXTLS
336   SSL_CTX* ssl_ctx;
337   SSL*     ssl;
338   ssl_connect_state connecting_state;
339 #endif /* USE_AXTLS */
340 #ifdef USE_SCHANNEL
341   struct curl_schannel_cred *cred;
342   struct curl_schannel_ctxt *ctxt;
343   SecPkgContext_StreamSizes stream_sizes;
344   ssl_connect_state connecting_state;
345   size_t encdata_length, decdata_length;
346   size_t encdata_offset, decdata_offset;
347   unsigned char *encdata_buffer, *decdata_buffer;
348   unsigned long req_flags, ret_flags;
349 #endif /* USE_SCHANNEL */
350 #ifdef USE_DARWINSSL
351   SSLContextRef ssl_ctx;
352   curl_socket_t ssl_sockfd;
353   ssl_connect_state connecting_state;
354   bool ssl_direction; /* true if writing, false if reading */
355   size_t ssl_write_buffered_length;
356 #endif /* USE_DARWINSSL */
357 };
358
359 struct ssl_config_data {
360   long version;          /* what version the client wants to use */
361   long certverifyresult; /* result from the certificate verification */
362
363   bool verifypeer;       /* set TRUE if this is desired */
364   bool verifyhost;       /* set TRUE if CN/SAN must match hostname */
365   char *CApath;          /* certificate dir (doesn't work on windows) */
366   char *CAfile;          /* certificate to verify peer against */
367   const char *CRLfile;   /* CRL to check certificate revocation */
368   const char *issuercert;/* optional issuer certificate filename */
369   char *random_file;     /* path to file containing "random" data */
370   char *egdsocket;       /* path to file containing the EGD daemon socket */
371   char *cipher_list;     /* list of ciphers to use */
372   size_t max_ssl_sessions; /* SSL session id cache size */
373   curl_ssl_ctx_callback fsslctx; /* function to initialize ssl ctx */
374   void *fsslctxp;        /* parameter for call back */
375   bool sessionid;        /* cache session IDs or not */
376   bool certinfo;         /* gather lots of certificate info */
377
378 #ifdef USE_TLS_SRP
379   char *username; /* TLS username (for, e.g., SRP) */
380   char *password; /* TLS password (for, e.g., SRP) */
381   enum CURL_TLSAUTH authtype; /* TLS authentication type (default SRP) */
382 #endif
383 };
384
385 /* information stored about one single SSL session */
386 struct curl_ssl_session {
387   char *name;       /* host name for which this ID was used */
388   void *sessionid;  /* as returned from the SSL layer */
389   size_t idsize;    /* if known, otherwise 0 */
390   long age;         /* just a number, the higher the more recent */
391   int remote_port;  /* remote port to connect to */
392   struct ssl_config_data ssl_config; /* setup for this session */
393 };
394
395 /* Struct used for Digest challenge-response authentication */
396 struct digestdata {
397   char *nonce;
398   char *cnonce;
399   char *realm;
400   int algo;
401   bool stale; /* set true for re-negotiation */
402   char *opaque;
403   char *qop;
404   char *algorithm;
405   int nc; /* nounce count */
406 };
407
408 typedef enum {
409   NTLMSTATE_NONE,
410   NTLMSTATE_TYPE1,
411   NTLMSTATE_TYPE2,
412   NTLMSTATE_TYPE3,
413   NTLMSTATE_LAST
414 } curlntlm;
415
416 #ifdef USE_WINDOWS_SSPI
417 #include "curl_sspi.h"
418 #endif
419
420 #if defined(CURL_DOES_CONVERSIONS) && defined(HAVE_ICONV)
421 #include <iconv.h>
422 #endif
423
424 /* Struct used for NTLM challenge-response authentication */
425 struct ntlmdata {
426   curlntlm state;
427 #ifdef USE_WINDOWS_SSPI
428   CredHandle handle;
429   CtxtHandle c_handle;
430   SEC_WINNT_AUTH_IDENTITY identity;
431   SEC_WINNT_AUTH_IDENTITY *p_identity;
432   int has_handles;
433   void *type_2;
434   unsigned long n_type_2;
435 #else
436   unsigned int flags;
437   unsigned char nonce[8];
438   void* target_info; /* TargetInfo received in the ntlm type-2 message */
439   unsigned int target_info_len;
440 #endif
441 };
442
443 #ifdef USE_HTTP_NEGOTIATE
444 struct negotiatedata {
445   /* when doing Negotiate we first need to receive an auth token and then we
446      need to send our header */
447   enum { GSS_AUTHNONE, GSS_AUTHRECV, GSS_AUTHSENT } state;
448   bool gss; /* Whether we're processing GSS-Negotiate or Negotiate */
449   const char* protocol; /* "GSS-Negotiate" or "Negotiate" */
450 #ifdef HAVE_GSSAPI
451   OM_uint32 status;
452   gss_ctx_id_t context;
453   gss_name_t server_name;
454   gss_buffer_desc output_token;
455 #else
456 #ifdef USE_WINDOWS_SSPI
457   DWORD status;
458   CtxtHandle *context;
459   CredHandle *credentials;
460   char server_name[1024];
461   size_t max_token_length;
462   BYTE *output_token;
463   size_t output_token_length;
464 #endif
465 #endif
466 };
467 #endif
468
469
470 /*
471  * Boolean values that concerns this connection.
472  */
473 struct ConnectBits {
474   bool close; /* if set, we close the connection after this request */
475   bool reuse; /* if set, this is a re-used connection */
476   bool proxy; /* if set, this transfer is done through a proxy - any type */
477   bool httpproxy;    /* if set, this transfer is done through a http proxy */
478   bool user_passwd;    /* do we use user+password for this connection? */
479   bool proxy_user_passwd; /* user+password for the proxy? */
480   bool ipv6_ip; /* we communicate with a remote site specified with pure IPv6
481                    IP address */
482   bool ipv6;    /* we communicate with a site using an IPv6 address */
483
484   bool do_more; /* this is set TRUE if the ->curl_do_more() function is
485                    supposed to be called, after ->curl_do() */
486   bool tcpconnect[2]; /* the TCP layer (or similar) is connected, this is set
487                          the first time on the first connect function call */
488   bool protoconnstart;/* the protocol layer has STARTED its operation after
489                          the TCP layer connect */
490
491   bool retry;         /* this connection is about to get closed and then
492                          re-attempted at another connection. */
493   bool tunnel_proxy;  /* if CONNECT is used to "tunnel" through the proxy.
494                          This is implicit when SSL-protocols are used through
495                          proxies, but can also be enabled explicitly by
496                          apps */
497   bool authneg;       /* TRUE when the auth phase has started, which means
498                          that we are creating a request with an auth header,
499                          but it is not the final request in the auth
500                          negotiation. */
501   bool rewindaftersend;/* TRUE when the sending couldn't be stopped even
502                           though it will be discarded. When the whole send
503                           operation is done, we must call the data rewind
504                           callback. */
505   bool ftp_use_epsv;  /* As set with CURLOPT_FTP_USE_EPSV, but if we find out
506                          EPSV doesn't work we disable it for the forthcoming
507                          requests */
508
509   bool ftp_use_eprt;  /* As set with CURLOPT_FTP_USE_EPRT, but if we find out
510                          EPRT doesn't work we disable it for the forthcoming
511                          requests */
512   bool netrc;         /* name+password provided by netrc */
513   bool userpwd_in_url; /* name+password found in url */
514
515   bool done;          /* set to FALSE when Curl_do() is called and set to TRUE
516                          when Curl_done() is called, to prevent Curl_done() to
517                          get invoked twice when the multi interface is
518                          used. */
519   bool stream_was_rewound; /* Indicates that the stream was rewound after a
520                               request read past the end of its response byte
521                               boundary */
522   bool proxy_connect_closed; /* set true if a proxy disconnected the
523                                 connection in a CONNECT request with auth, so
524                                 that libcurl should reconnect and continue. */
525   bool bound; /* set true if bind() has already been done on this socket/
526                  connection */
527   bool type_set;  /* type= was used in the URL */
528 };
529
530 struct hostname {
531   char *rawalloc; /* allocated "raw" version of the name */
532   char *encalloc; /* allocated IDN-encoded version of the name */
533   char *name;     /* name to use internally, might be encoded, might be raw */
534   const char *dispname; /* name to display, as 'name' might be encoded */
535 };
536
537 /*
538  * Flags on the keepon member of the Curl_transfer_keeper
539  */
540
541 #define KEEP_NONE  0
542 #define KEEP_RECV  (1<<0)     /* there is or may be data to read */
543 #define KEEP_SEND (1<<1)     /* there is or may be data to write */
544 #define KEEP_RECV_HOLD (1<<2) /* when set, no reading should be done but there
545                                  might still be data to read */
546 #define KEEP_SEND_HOLD (1<<3) /* when set, no writing should be done but there
547                                   might still be data to write */
548 #define KEEP_RECV_PAUSE (1<<4) /* reading is paused */
549 #define KEEP_SEND_PAUSE (1<<5) /* writing is paused */
550
551 #define KEEP_RECVBITS (KEEP_RECV | KEEP_RECV_HOLD | KEEP_RECV_PAUSE)
552 #define KEEP_SENDBITS (KEEP_SEND | KEEP_SEND_HOLD | KEEP_SEND_PAUSE)
553
554
555 #ifdef HAVE_LIBZ
556 typedef enum {
557   ZLIB_UNINIT,          /* uninitialized */
558   ZLIB_INIT,            /* initialized */
559   ZLIB_GZIP_HEADER,     /* reading gzip header */
560   ZLIB_GZIP_INFLATING,  /* inflating gzip stream */
561   ZLIB_INIT_GZIP        /* initialized in transparent gzip mode */
562 } zlibInitState;
563 #endif
564
565 #ifdef CURLRES_ASYNCH
566 struct Curl_async {
567   char *hostname;
568   int port;
569   struct Curl_dns_entry *dns;
570   bool done;  /* set TRUE when the lookup is complete */
571   int status; /* if done is TRUE, this is the status from the callback */
572   void *os_specific;  /* 'struct thread_data' for Windows */
573 };
574 #endif
575
576 #define FIRSTSOCKET     0
577 #define SECONDARYSOCKET 1
578
579 /* These function pointer types are here only to allow easier typecasting
580    within the source when we need to cast between data pointers (such as NULL)
581    and function pointers. */
582 typedef CURLcode (*Curl_do_more_func)(struct connectdata *, int *);
583 typedef CURLcode (*Curl_done_func)(struct connectdata *, CURLcode, bool);
584
585 enum expect100 {
586   EXP100_SEND_DATA,           /* enough waiting, just send the body now */
587   EXP100_AWAITING_CONTINUE,   /* waiting for the 100 Continue header */
588   EXP100_SENDING_REQUEST,     /* still sending the request but will wait for
589                                  the 100 header once done with the request */
590   EXP100_FAILED               /* used on 417 Expectation Failed */
591 };
592
593 enum upgrade101 {
594   UPGR101_INIT,               /* default state */
595   UPGR101_REQUESTED,          /* upgrade requested */
596   UPGR101_RECEIVED,           /* response received */
597   UPGR101_WORKING             /* talking upgraded protocol */
598 };
599
600 enum negotiatenpn {
601   NPN_INIT,                   /* default state */
602   NPN_HTTP1_1,                /* HTTP/1.1 negotiated */
603   NPN_HTTP2_DRAFT09           /* HTTP-draft-0.9/2.0 negotiated */
604 };
605
606 /*
607  * Request specific data in the easy handle (SessionHandle).  Previously,
608  * these members were on the connectdata struct but since a conn struct may
609  * now be shared between different SessionHandles, we store connection-specific
610  * data here. This struct only keeps stuff that's interesting for *this*
611  * request, as it will be cleared between multiple ones
612  */
613 struct SingleRequest {
614   curl_off_t size;        /* -1 if unknown at this point */
615   curl_off_t *bytecountp; /* return number of bytes read or NULL */
616
617   curl_off_t maxdownload; /* in bytes, the maximum amount of data to fetch,
618                              -1 means unlimited */
619   curl_off_t *writebytecountp; /* return number of bytes written or NULL */
620
621   curl_off_t bytecount;         /* total number of bytes read */
622   curl_off_t writebytecount;    /* number of bytes written */
623
624   long headerbytecount;         /* only count received headers */
625   long deductheadercount; /* this amount of bytes doesn't count when we check
626                              if anything has been transferred at the end of a
627                              connection. We use this counter to make only a
628                              100 reply (without a following second response
629                              code) result in a CURLE_GOT_NOTHING error code */
630
631   struct timeval start;         /* transfer started at this time */
632   struct timeval now;           /* current time */
633   bool header;                  /* incoming data has HTTP header */
634   enum {
635     HEADER_NORMAL,              /* no bad header at all */
636     HEADER_PARTHEADER,          /* part of the chunk is a bad header, the rest
637                                    is normal data */
638     HEADER_ALLBAD               /* all was believed to be header */
639   } badheader;                  /* the header was deemed bad and will be
640                                    written as body */
641   int headerline;               /* counts header lines to better track the
642                                    first one */
643   char *hbufp;                  /* points at *end* of header line */
644   size_t hbuflen;
645   char *str;                    /* within buf */
646   char *str_start;              /* within buf */
647   char *end_ptr;                /* within buf */
648   char *p;                      /* within headerbuff */
649   bool content_range;           /* set TRUE if Content-Range: was found */
650   curl_off_t offset;            /* possible resume offset read from the
651                                    Content-Range: header */
652   int httpcode;                 /* error code from the 'HTTP/1.? XXX' or
653                                    'RTSP/1.? XXX' line */
654   struct timeval start100;      /* time stamp to wait for the 100 code from */
655   enum expect100 exp100;        /* expect 100 continue state */
656   enum upgrade101 upgr101;      /* 101 upgrade state */
657
658   int auto_decoding;            /* What content encoding. sec 3.5, RFC2616. */
659
660 #define IDENTITY 0              /* No encoding */
661 #define DEFLATE 1               /* zlib deflate [RFC 1950 & 1951] */
662 #define GZIP 2                  /* gzip algorithm [RFC 1952] */
663 #define COMPRESS 3              /* Not handled, added for completeness */
664
665 #ifdef HAVE_LIBZ
666   zlibInitState zlib_init;      /* possible zlib init state;
667                                    undefined if Content-Encoding header. */
668   z_stream z;                   /* State structure for zlib. */
669 #endif
670
671   time_t timeofdoc;
672   long bodywrites;
673
674   char *buf;
675   char *uploadbuf;
676   curl_socket_t maxfd;
677
678   int keepon;
679
680   bool upload_done; /* set to TRUE when doing chunked transfer-encoding upload
681                        and we're uploading the last chunk */
682
683   bool ignorebody;  /* we read a response-body but we ignore it! */
684   bool ignorecl;    /* This HTTP response has no body so we ignore the Content-
685                        Length: header */
686
687   char *location;   /* This points to an allocated version of the Location:
688                        header data */
689   char *newurl;     /* Set to the new URL to use when a redirect or a retry is
690                        wanted */
691
692   /* 'upload_present' is used to keep a byte counter of how much data there is
693      still left in the buffer, aimed for upload. */
694   ssize_t upload_present;
695
696    /* 'upload_fromhere' is used as a read-pointer when we uploaded parts of a
697       buffer, so the next read should read from where this pointer points to,
698       and the 'upload_present' contains the number of bytes available at this
699       position */
700   char *upload_fromhere;
701
702   bool chunk; /* if set, this is a chunked transfer-encoding */
703   bool upload_chunky; /* set TRUE if we are doing chunked transfer-encoding
704                          on upload */
705   bool getheader;     /* TRUE if header parsing is wanted */
706
707   bool forbidchunk;   /* used only to explicitly forbid chunk-upload for
708                          specific upload buffers. See readmoredata() in
709                          http.c for details. */
710
711   void *protop;       /* Allocated protocol-specific data. Each protocol
712                          handler makes sure this points to data it needs. */
713 };
714
715 /*
716  * Specific protocol handler.
717  */
718
719 struct Curl_handler {
720   const char * scheme;        /* URL scheme name. */
721
722   /* Complement to setup_connection_internals(). */
723   CURLcode (*setup_connection)(struct connectdata *);
724
725   /* These two functions MUST be set to be protocol dependent */
726   CURLcode (*do_it)(struct connectdata *, bool *done);
727   Curl_done_func done;
728
729   /* If the curl_do() function is better made in two halves, this
730    * curl_do_more() function will be called afterwards, if set. For example
731    * for doing the FTP stuff after the PASV/PORT command.
732    */
733   Curl_do_more_func do_more;
734
735   /* This function *MAY* be set to a protocol-dependent function that is run
736    * after the connect() and everything is done, as a step in the connection.
737    * The 'done' pointer points to a bool that should be set to TRUE if the
738    * function completes before return. If it doesn't complete, the caller
739    * should call the curl_connecting() function until it is.
740    */
741   CURLcode (*connect_it)(struct connectdata *, bool *done);
742
743   /* See above. Currently only used for FTP. */
744   CURLcode (*connecting)(struct connectdata *, bool *done);
745   CURLcode (*doing)(struct connectdata *, bool *done);
746
747   /* Called from the multi interface during the PROTOCONNECT phase, and it
748      should then return a proper fd set */
749   int (*proto_getsock)(struct connectdata *conn,
750                        curl_socket_t *socks,
751                        int numsocks);
752
753   /* Called from the multi interface during the DOING phase, and it should
754      then return a proper fd set */
755   int (*doing_getsock)(struct connectdata *conn,
756                        curl_socket_t *socks,
757                        int numsocks);
758
759   /* Called from the multi interface during the DO_MORE phase, and it should
760      then return a proper fd set */
761   int (*domore_getsock)(struct connectdata *conn,
762                         curl_socket_t *socks,
763                         int numsocks);
764
765   /* Called from the multi interface during the DO_DONE, PERFORM and
766      WAITPERFORM phases, and it should then return a proper fd set. Not setting
767      this will make libcurl use the generic default one. */
768   int (*perform_getsock)(const struct connectdata *conn,
769                          curl_socket_t *socks,
770                          int numsocks);
771
772   /* This function *MAY* be set to a protocol-dependent function that is run
773    * by the curl_disconnect(), as a step in the disconnection.  If the handler
774    * is called because the connection has been considered dead, dead_connection
775    * is set to TRUE.
776    */
777   CURLcode (*disconnect)(struct connectdata *, bool dead_connection);
778
779   /* If used, this function gets called from transfer.c:readwrite_data() to
780      allow the protocol to do extra reads/writes */
781   CURLcode (*readwrite)(struct SessionHandle *data, struct connectdata *conn,
782                         ssize_t *nread, bool *readmore);
783
784   long defport;           /* Default port. */
785   unsigned int protocol;  /* See CURLPROTO_*  */
786   unsigned int flags;     /* Extra particular characteristics, see PROTOPT_* */
787 };
788
789 #define PROTOPT_NONE 0             /* nothing extra */
790 #define PROTOPT_SSL (1<<0)         /* uses SSL */
791 #define PROTOPT_DUAL (1<<1)        /* this protocol uses two connections */
792 #define PROTOPT_CLOSEACTION (1<<2) /* need action before socket close */
793 /* some protocols will have to call the underlying functions without regard to
794    what exact state the socket signals. IE even if the socket says "readable",
795    the send function might need to be called while uploading, or vice versa.
796 */
797 #define PROTOPT_DIRLOCK (1<<3)
798 #define PROTOPT_NONETWORK (1<<4)   /* protocol doesn't use the network! */
799 #define PROTOPT_NEEDSPWD (1<<5)    /* needs a password, and if none is set it
800                                       gets a default */
801 #define PROTOPT_NOURLQUERY (1<<6)   /* protocol can't handle
802                                         url query strings (?foo=bar) ! */
803
804
805 /* return the count of bytes sent, or -1 on error */
806 typedef ssize_t (Curl_send)(struct connectdata *conn, /* connection data */
807                             int sockindex,            /* socketindex */
808                             const void *buf,          /* data to write */
809                             size_t len,               /* max amount to write */
810                             CURLcode *err);           /* error to return */
811
812 /* return the count of bytes read, or -1 on error */
813 typedef ssize_t (Curl_recv)(struct connectdata *conn, /* connection data */
814                             int sockindex,            /* socketindex */
815                             char *buf,                /* store data here */
816                             size_t len,               /* max amount to read */
817                             CURLcode *err);           /* error to return */
818
819 /*
820  * The connectdata struct contains all fields and variables that should be
821  * unique for an entire connection.
822  */
823 struct connectdata {
824   /* 'data' is the CURRENT SessionHandle using this connection -- take great
825      caution that this might very well vary between different times this
826      connection is used! */
827   struct SessionHandle *data;
828
829   /* chunk is for HTTP chunked encoding, but is in the general connectdata
830      struct only because we can do just about any protocol through a HTTP proxy
831      and a HTTP proxy may in fact respond using chunked encoding */
832   struct Curl_chunker chunk;
833
834   curl_closesocket_callback fclosesocket; /* function closing the socket(s) */
835   void *closesocket_client;
836
837   bool inuse; /* This is a marker for the connection cache logic. If this is
838                  TRUE this handle is being used by an easy handle and cannot
839                  be used by any other easy handle without careful
840                  consideration (== only for pipelining). */
841
842   /**** Fields set when inited and not modified again */
843   long connection_id; /* Contains a unique number to make it easier to
844                          track the connections in the log output */
845
846   /* 'dns_entry' is the particular host we use. This points to an entry in the
847      DNS cache and it will not get pruned while locked. It gets unlocked in
848      Curl_done(). This entry will be NULL if the connection is re-used as then
849      there is no name resolve done. */
850   struct Curl_dns_entry *dns_entry;
851
852   /* 'ip_addr' is the particular IP we connected to. It points to a struct
853      within the DNS cache, so this pointer is only valid as long as the DNS
854      cache entry remains locked. It gets unlocked in Curl_done() */
855   Curl_addrinfo *ip_addr;
856   Curl_addrinfo *tempaddr[2]; /* for happy eyeballs */
857
858   /* 'ip_addr_str' is the ip_addr data as a human readable string.
859      It remains available as long as the connection does, which is longer than
860      the ip_addr itself. */
861   char ip_addr_str[MAX_IPADR_LEN];
862
863   unsigned int scope;    /* address scope for IPv6 */
864
865   int socktype;  /* SOCK_STREAM or SOCK_DGRAM */
866
867   struct hostname host;
868   struct hostname proxy;
869
870   long port;       /* which port to use locally */
871   int remote_port; /* what remote port to connect to, not the proxy port! */
872
873   /* 'primary_ip' and 'primary_port' get filled with peer's numerical
874      ip address and port number whenever an outgoing connection is
875      *attempted* from the primary socket to a remote address. When more
876      than one address is tried for a connection these will hold data
877      for the last attempt. When the connection is actually established
878      these are updated with data which comes directly from the socket. */
879
880   char primary_ip[MAX_IPADR_LEN];
881   long primary_port;
882
883   /* 'local_ip' and 'local_port' get filled with local's numerical
884      ip address and port number whenever an outgoing connection is
885      **established** from the primary socket to a remote address. */
886
887   char local_ip[MAX_IPADR_LEN];
888   long local_port;
889
890   char *user;    /* user name string, allocated */
891   char *passwd;  /* password string, allocated */
892   char *options; /* options string, allocated */
893
894   char *xoauth2_bearer; /* bearer token for xoauth2, allocated */
895
896   char *proxyuser;    /* proxy user name string, allocated */
897   char *proxypasswd;  /* proxy password string, allocated */
898   curl_proxytype proxytype; /* what kind of proxy that is in use */
899
900   int httpversion;        /* the HTTP version*10 reported by the server */
901   int rtspversion;        /* the RTSP version*10 reported by the server */
902
903   struct timeval now;     /* "current" time */
904   struct timeval created; /* creation time */
905   curl_socket_t sock[2]; /* two sockets, the second is used for the data
906                             transfer when doing FTP */
907   curl_socket_t tempsock[2]; /* temporary sockets for happy eyeballs */
908   bool sock_accepted[2]; /* TRUE if the socket on this index was created with
909                             accept() */
910   Curl_recv *recv[2];
911   Curl_send *send[2];
912
913   struct ssl_connect_data ssl[2]; /* this is for ssl-stuff */
914   struct ssl_config_data ssl_config;
915
916   struct ConnectBits bits;    /* various state-flags for this connection */
917
918  /* connecttime: when connect() is called on the current IP address. Used to
919     be able to track when to move on to try next IP - but only when the multi
920     interface is used. */
921   struct timeval connecttime;
922   /* The two fields below get set in Curl_connecthost */
923   int num_addr; /* number of addresses to try to connect to */
924   long timeoutms_per_addr; /* how long time in milliseconds to spend on
925                               trying to connect to each IP address */
926
927   const struct Curl_handler *handler; /* Connection's protocol handler */
928   const struct Curl_handler *given;   /* The protocol first given */
929
930   long ip_version; /* copied from the SessionHandle at creation time */
931
932   /**** curl_get() phase fields */
933
934   curl_socket_t sockfd;   /* socket to read from or CURL_SOCKET_BAD */
935   curl_socket_t writesockfd; /* socket to write to, it may very
936                                 well be the same we read from.
937                                 CURL_SOCKET_BAD disables */
938
939   /** Dynamicly allocated strings, MUST be freed before this **/
940   /** struct is killed.                                      **/
941   struct dynamically_allocated_data {
942     char *proxyuserpwd;
943     char *uagent;
944     char *accept_encoding;
945     char *userpwd;
946     char *rangeline;
947     char *ref;
948     char *host;
949     char *cookiehost;
950     char *rtsp_transport;
951     char *te; /* TE: request header */
952   } allocptr;
953
954   int sec_complete; /* if kerberos is enabled for this connection */
955 #ifdef HAVE_GSSAPI
956   enum protection_level command_prot;
957   enum protection_level data_prot;
958   enum protection_level request_data_prot;
959   size_t buffer_size;
960   struct krb5buffer in_buffer;
961   void *app_data;
962   const struct Curl_sec_client_mech *mech;
963   struct sockaddr_in local_addr;
964 #endif
965
966   /* the two following *_inuse fields are only flags, not counters in any way.
967      If TRUE it means the channel is in use, and if FALSE it means the channel
968      is up for grabs by one. */
969
970   bool readchannel_inuse;  /* whether the read channel is in use by an easy
971                               handle */
972   bool writechannel_inuse; /* whether the write channel is in use by an easy
973                               handle */
974   struct curl_llist *send_pipe; /* List of handles waiting to
975                                    send on this pipeline */
976   struct curl_llist *recv_pipe; /* List of handles waiting to read
977                                    their responses on this pipeline */
978   char* master_buffer; /* The master buffer allocated on-demand;
979                           used for pipelining. */
980   size_t read_pos; /* Current read position in the master buffer */
981   size_t buf_len; /* Length of the buffer?? */
982
983
984   curl_seek_callback seek_func; /* function that seeks the input */
985   void *seek_client;            /* pointer to pass to the seek() above */
986
987   /*************** Request - specific items ************/
988
989   /* previously this was in the urldata struct */
990   curl_read_callback fread_func; /* function that reads the input */
991   void *fread_in;           /* pointer to pass to the fread() above */
992
993   struct ntlmdata ntlm;     /* NTLM differs from other authentication schemes
994                                because it authenticates connections, not
995                                single requests! */
996   struct ntlmdata proxyntlm; /* NTLM data for proxy */
997
998 #if defined(USE_NTLM) && defined(NTLM_WB_ENABLED)
999   /* used for communication with Samba's winbind daemon helper ntlm_auth */
1000   curl_socket_t ntlm_auth_hlpr_socket;
1001   pid_t ntlm_auth_hlpr_pid;
1002   char* challenge_header;
1003   char* response_header;
1004 #endif
1005
1006   char syserr_buf [256]; /* buffer for Curl_strerror() */
1007
1008 #ifdef CURLRES_ASYNCH
1009   /* data used for the asynch name resolve callback */
1010   struct Curl_async async;
1011 #endif
1012
1013   /* These three are used for chunked-encoding trailer support */
1014   char *trailer; /* allocated buffer to store trailer in */
1015   int trlMax;    /* allocated buffer size */
1016   int trlPos;    /* index of where to store data */
1017
1018   union {
1019     struct ftp_conn ftpc;
1020     struct http_conn httpc;
1021     struct ssh_conn sshc;
1022     struct tftp_state_data *tftpc;
1023     struct imap_conn imapc;
1024     struct pop3_conn pop3c;
1025     struct smtp_conn smtpc;
1026     struct rtsp_conn rtspc;
1027     void *generic; /* RTMP and LDAP use this */
1028   } proto;
1029
1030   int cselect_bits; /* bitmask of socket events */
1031   int waitfor;      /* current READ/WRITE bits to wait for */
1032
1033 #if defined(HAVE_GSSAPI) || defined(USE_WINDOWS_SSPI)
1034   int socks5_gssapi_enctype;
1035 #endif
1036
1037   bool verifypeer;
1038   bool verifyhost;
1039
1040   /* When this connection is created, store the conditions for the local end
1041      bind. This is stored before the actual bind and before any connection is
1042      made and will serve the purpose of being used for comparison reasons so
1043      that subsequent bound-requested connections aren't accidentally re-using
1044      wrong connections. */
1045   char *localdev;
1046   unsigned short localport;
1047   int localportrange;
1048
1049   /* tunnel as in tunnel through a HTTP proxy with CONNECT */
1050   enum {
1051     TUNNEL_INIT,    /* init/default/no tunnel state */
1052     TUNNEL_CONNECT, /* CONNECT has been sent off */
1053     TUNNEL_COMPLETE /* CONNECT response received completely */
1054   } tunnel_state[2]; /* two separate ones to allow FTP */
1055   struct connectbundle *bundle; /* The bundle we are member of */
1056
1057   enum negotiatenpn negnpn;
1058 };
1059
1060 /* The end of connectdata. */
1061
1062 /*
1063  * Struct to keep statistical and informational data.
1064  */
1065 struct PureInfo {
1066   int httpcode;  /* Recent HTTP, FTP, or RTSP response code */
1067   int httpproxycode; /* response code from proxy when received separate */
1068   int httpversion; /* the http version number X.Y = X*10+Y */
1069   long filetime; /* If requested, this is might get set. Set to -1 if the time
1070                     was unretrievable. We cannot have this of type time_t,
1071                     since time_t is unsigned on several platforms such as
1072                     OpenVMS. */
1073   bool timecond;  /* set to TRUE if the time condition didn't match, which
1074                      thus made the document NOT get fetched */
1075   long header_size;  /* size of read header(s) in bytes */
1076   long request_size; /* the amount of bytes sent in the request(s) */
1077   unsigned long proxyauthavail; /* what proxy auth types were announced */
1078   unsigned long httpauthavail;  /* what host auth types were announced */
1079   long numconnects; /* how many new connection did libcurl created */
1080   char *contenttype; /* the content type of the object */
1081   char *wouldredirect; /* URL this would've been redirected to if asked to */
1082
1083   /* PureInfo members 'conn_primary_ip', 'conn_primary_port', 'conn_local_ip'
1084      and, 'conn_local_port' are copied over from the connectdata struct in
1085      order to allow curl_easy_getinfo() to return this information even when
1086      the session handle is no longer associated with a connection, and also
1087      allow curl_easy_reset() to clear this information from the session handle
1088      without disturbing information which is still alive, and that might be
1089      reused, in the connection cache. */
1090
1091   char conn_primary_ip[MAX_IPADR_LEN];
1092   long conn_primary_port;
1093
1094   char conn_local_ip[MAX_IPADR_LEN];
1095   long conn_local_port;
1096
1097   struct curl_certinfo certs; /* info about the certs, only populated in
1098                                  OpenSSL builds. Asked for with
1099                                  CURLOPT_CERTINFO / CURLINFO_CERTINFO */
1100 };
1101
1102
1103 struct Progress {
1104   long lastshow; /* time() of the last displayed progress meter or NULL to
1105                     force redraw at next call */
1106   curl_off_t size_dl; /* total expected size */
1107   curl_off_t size_ul; /* total expected size */
1108   curl_off_t downloaded; /* transferred so far */
1109   curl_off_t uploaded; /* transferred so far */
1110
1111   curl_off_t current_speed; /* uses the currently fastest transfer */
1112
1113   bool callback;  /* set when progress callback is used */
1114   int width; /* screen width at download start */
1115   int flags; /* see progress.h */
1116
1117   double timespent;
1118
1119   curl_off_t dlspeed;
1120   curl_off_t ulspeed;
1121
1122   double t_nslookup;
1123   double t_connect;
1124   double t_appconnect;
1125   double t_pretransfer;
1126   double t_starttransfer;
1127   double t_redirect;
1128
1129   struct timeval start;
1130   struct timeval t_startsingle;
1131   struct timeval t_acceptdata;
1132 #define CURR_TIME (5+1) /* 6 entries for 5 seconds */
1133
1134   curl_off_t speeder[ CURR_TIME ];
1135   struct timeval speeder_time[ CURR_TIME ];
1136   int speeder_c;
1137 };
1138
1139 typedef enum {
1140   HTTPREQ_NONE, /* first in list */
1141   HTTPREQ_GET,
1142   HTTPREQ_POST,
1143   HTTPREQ_POST_FORM, /* we make a difference internally */
1144   HTTPREQ_PUT,
1145   HTTPREQ_HEAD,
1146   HTTPREQ_CUSTOM,
1147   HTTPREQ_LAST /* last in list */
1148 } Curl_HttpReq;
1149
1150 typedef enum {
1151     RTSPREQ_NONE, /* first in list */
1152     RTSPREQ_OPTIONS,
1153     RTSPREQ_DESCRIBE,
1154     RTSPREQ_ANNOUNCE,
1155     RTSPREQ_SETUP,
1156     RTSPREQ_PLAY,
1157     RTSPREQ_PAUSE,
1158     RTSPREQ_TEARDOWN,
1159     RTSPREQ_GET_PARAMETER,
1160     RTSPREQ_SET_PARAMETER,
1161     RTSPREQ_RECORD,
1162     RTSPREQ_RECEIVE,
1163     RTSPREQ_LAST /* last in list */
1164 } Curl_RtspReq;
1165
1166 /*
1167  * Values that are generated, temporary or calculated internally for a
1168  * "session handle" must be defined within the 'struct UrlState'.  This struct
1169  * will be used within the SessionHandle struct. When the 'SessionHandle'
1170  * struct is cloned, this data MUST NOT be copied.
1171  *
1172  * Remember that any "state" information goes globally for the curl handle.
1173  * Session-data MUST be put in the connectdata struct and here.  */
1174 #define MAX_CURL_USER_LENGTH 256
1175 #define MAX_CURL_PASSWORD_LENGTH 256
1176
1177 struct auth {
1178   unsigned long want;  /* Bitmask set to the authentication methods wanted by
1179                           app (with CURLOPT_HTTPAUTH or CURLOPT_PROXYAUTH). */
1180   unsigned long picked;
1181   unsigned long avail; /* Bitmask for what the server reports to support for
1182                           this resource */
1183   bool done;  /* TRUE when the auth phase is done and ready to do the *actual*
1184                  request */
1185   bool multi; /* TRUE if this is not yet authenticated but within the auth
1186                  multipass negotiation */
1187   bool iestyle; /* TRUE if digest should be done IE-style or FALSE if it should
1188                    be RFC compliant */
1189 };
1190
1191 struct UrlState {
1192
1193   /* Points to the connection cache */
1194   struct conncache *conn_cache;
1195
1196   /* when curl_easy_perform() is called, the multi handle is "owned" by
1197      the easy handle so curl_easy_cleanup() on such an easy handle will
1198      also close the multi handle! */
1199   bool multi_owned_by_easy;
1200
1201   /* buffers to store authentication data in, as parsed from input options */
1202   struct timeval keeps_speed; /* for the progress meter really */
1203
1204   struct connectdata *lastconnect; /* The last connection, NULL if undefined */
1205
1206   char *headerbuff; /* allocated buffer to store headers in */
1207   size_t headersize;   /* size of the allocation */
1208
1209   char buffer[BUFSIZE+1]; /* download buffer */
1210   char uploadbuffer[BUFSIZE+1]; /* upload buffer */
1211   curl_off_t current_speed;  /* the ProgressShow() funcion sets this,
1212                                 bytes / second */
1213   bool this_is_a_follow; /* this is a followed Location: request */
1214
1215   char *first_host; /* if set, this should be the host name that we will
1216                        sent authorization to, no else. Used to make Location:
1217                        following not keep sending user+password... This is
1218                        strdup() data.
1219                     */
1220   struct curl_ssl_session *session; /* array of 'max_ssl_sessions' size */
1221   long sessionage;                  /* number of the most recent session */
1222   char *tempwrite;      /* allocated buffer to keep data in when a write
1223                            callback returns to make the connection paused */
1224   size_t tempwritesize; /* size of the 'tempwrite' allocated buffer */
1225   int tempwritetype;    /* type of the 'tempwrite' buffer as a bitmask that is
1226                            used with Curl_client_write() */
1227   char *scratch; /* huge buffer[BUFSIZE*2] when doing upload CRLF replacing */
1228   bool errorbuf; /* Set to TRUE if the error buffer is already filled in.
1229                     This must be set to FALSE every time _easy_perform() is
1230                     called. */
1231   int os_errno;  /* filled in with errno whenever an error occurs */
1232 #ifdef HAVE_SIGNAL
1233   /* storage for the previous bag^H^H^HSIGPIPE signal handler :-) */
1234   void (*prev_signal)(int sig);
1235 #endif
1236   bool allow_port; /* Is set.use_port allowed to take effect or not. This
1237                       is always set TRUE when curl_easy_perform() is called. */
1238   struct digestdata digest;      /* state data for host Digest auth */
1239   struct digestdata proxydigest; /* state data for proxy Digest auth */
1240
1241 #ifdef USE_HTTP_NEGOTIATE
1242   struct negotiatedata negotiate; /* state data for host Negotiate auth */
1243   struct negotiatedata proxyneg; /* state data for proxy Negotiate auth */
1244 #endif
1245
1246   struct auth authhost;  /* auth details for host */
1247   struct auth authproxy; /* auth details for proxy */
1248
1249   bool authproblem; /* TRUE if there's some problem authenticating */
1250
1251   void *resolver; /* resolver state, if it is used in the URL state -
1252                      ares_channel f.e. */
1253
1254 #if defined(USE_SSLEAY) && defined(HAVE_OPENSSL_ENGINE_H)
1255   ENGINE *engine;
1256 #endif /* USE_SSLEAY */
1257   struct timeval expiretime; /* set this with Curl_expire() only */
1258   struct Curl_tree timenode; /* for the splay stuff */
1259   struct curl_llist *timeoutlist; /* list of pending timeouts */
1260
1261   /* a place to store the most recently set FTP entrypath */
1262   char *most_recent_ftp_entrypath;
1263
1264   /* set after initial USER failure, to prevent an authentication loop */
1265   bool ftp_trying_alternative;
1266
1267   int httpversion;       /* the lowest HTTP version*10 reported by any server
1268                             involved in this request */
1269   bool expect100header;  /* TRUE if we added Expect: 100-continue */
1270
1271   bool pipe_broke; /* TRUE if the connection we were pipelined on broke
1272                       and we need to restart from the beginning */
1273
1274 #if !defined(WIN32) && !defined(MSDOS) && !defined(__EMX__) && \
1275     !defined(__SYMBIAN32__)
1276 /* do FTP line-end conversions on most platforms */
1277 #define CURL_DO_LINEEND_CONV
1278   /* for FTP downloads: track CRLF sequences that span blocks */
1279   bool prev_block_had_trailing_cr;
1280   /* for FTP downloads: how many CRLFs did we converted to LFs? */
1281   curl_off_t crlf_conversions;
1282 #endif
1283   char *pathbuffer;/* allocated buffer to store the URL's path part in */
1284   char *path;      /* path to use, points to somewhere within the pathbuffer
1285                       area */
1286   bool slash_removed; /* set TRUE if the 'path' points to a path where the
1287                          initial URL slash separator has been taken off */
1288   bool use_range;
1289   bool rangestringalloc; /* the range string is malloc()'ed */
1290
1291   char *range; /* range, if used. See README for detailed specification on
1292                   this syntax. */
1293   curl_off_t resume_from; /* continue [ftp] transfer from here */
1294
1295   /* This RTSP state information survives requests and connections */
1296   long rtsp_next_client_CSeq; /* the session's next client CSeq */
1297   long rtsp_next_server_CSeq; /* the session's next server CSeq */
1298   long rtsp_CSeq_recv; /* most recent CSeq received */
1299
1300   /* if true, force SSL connection retry (workaround for certain servers) */
1301   bool ssl_connect_retry;
1302 };
1303
1304
1305 /*
1306  * This 'DynamicStatic' struct defines dynamic states that actually change
1307  * values in the 'UserDefined' area, which MUST be taken into consideration
1308  * if the UserDefined struct is cloned or similar. You can probably just
1309  * copy these, but each one indicate a special action on other data.
1310  */
1311
1312 struct DynamicStatic {
1313   char *url;        /* work URL, copied from UserDefined */
1314   bool url_alloc;   /* URL string is malloc()'ed */
1315   char *referer;    /* referer string */
1316   bool referer_alloc; /* referer sting is malloc()ed */
1317   struct curl_slist *cookielist; /* list of cookie files set by
1318                                     curl_easy_setopt(COOKIEFILE) calls */
1319   struct curl_slist *resolve; /* set to point to the set.resolve list when
1320                                  this should be dealt with in pretransfer */
1321 };
1322
1323 /*
1324  * This 'UserDefined' struct must only contain data that is set once to go
1325  * for many (perhaps) independent connections. Values that are generated or
1326  * calculated internally for the "session handle" MUST be defined within the
1327  * 'struct UrlState' instead. The only exceptions MUST note the changes in
1328  * the 'DynamicStatic' struct.
1329  * Character pointer fields point to dynamic storage, unless otherwise stated.
1330  */
1331
1332 struct Curl_multi;    /* declared and used only in multi.c */
1333
1334 enum dupstring {
1335   STRING_CERT,            /* client certificate file name */
1336   STRING_CERT_TYPE,       /* format for certificate (default: PEM)*/
1337   STRING_COOKIE,          /* HTTP cookie string to send */
1338   STRING_COOKIEJAR,       /* dump all cookies to this file */
1339   STRING_CUSTOMREQUEST,   /* HTTP/FTP/RTSP request/method to use */
1340   STRING_DEVICE,          /* local network interface/address to use */
1341   STRING_ENCODING,        /* Accept-Encoding string */
1342   STRING_FTP_ACCOUNT,     /* ftp account data */
1343   STRING_FTP_ALTERNATIVE_TO_USER, /* command to send if USER/PASS fails */
1344   STRING_FTPPORT,         /* port to send with the FTP PORT command */
1345   STRING_KEY,             /* private key file name */
1346   STRING_KEY_PASSWD,      /* plain text private key password */
1347   STRING_KEY_TYPE,        /* format for private key (default: PEM) */
1348   STRING_KRB_LEVEL,       /* krb security level */
1349   STRING_NETRC_FILE,      /* if not NULL, use this instead of trying to find
1350                              $HOME/.netrc */
1351   STRING_COPYPOSTFIELDS,  /* if POST, set the fields' values here */
1352   STRING_PROXY,           /* proxy to use */
1353   STRING_SET_RANGE,       /* range, if used */
1354   STRING_SET_REFERER,     /* custom string for the HTTP referer field */
1355   STRING_SET_URL,         /* what original URL to work on */
1356   STRING_SSL_CAPATH,      /* CA directory name (doesn't work on windows) */
1357   STRING_SSL_CAFILE,      /* certificate file to verify peer against */
1358   STRING_SSL_CIPHER_LIST, /* list of ciphers to use */
1359   STRING_SSL_EGDSOCKET,   /* path to file containing the EGD daemon socket */
1360   STRING_SSL_RANDOM_FILE, /* path to file containing "random" data */
1361   STRING_USERAGENT,       /* User-Agent string */
1362   STRING_SSL_CRLFILE,     /* crl file to check certificate */
1363   STRING_SSL_ISSUERCERT,  /* issuer cert file to check certificate */
1364   STRING_USERNAME,        /* <username>, if used */
1365   STRING_PASSWORD,        /* <password>, if used */
1366   STRING_OPTIONS,         /* <options>, if used */
1367   STRING_PROXYUSERNAME,   /* Proxy <username>, if used */
1368   STRING_PROXYPASSWORD,   /* Proxy <password>, if used */
1369   STRING_NOPROXY,         /* List of hosts which should not use the proxy, if
1370                              used */
1371   STRING_RTSP_SESSION_ID, /* Session ID to use */
1372   STRING_RTSP_STREAM_URI, /* Stream URI for this request */
1373   STRING_RTSP_TRANSPORT,  /* Transport for this session */
1374 #ifdef USE_LIBSSH2
1375   STRING_SSH_PRIVATE_KEY, /* path to the private key file for auth */
1376   STRING_SSH_PUBLIC_KEY,  /* path to the public key file for auth */
1377   STRING_SSH_HOST_PUBLIC_KEY_MD5, /* md5 of host public key in ascii hex */
1378   STRING_SSH_KNOWNHOSTS,  /* file name of knownhosts file */
1379 #endif
1380 #if defined(HAVE_GSSAPI) || defined(USE_WINDOWS_SSPI)
1381   STRING_SOCKS5_GSSAPI_SERVICE,  /* GSSAPI service name */
1382 #endif
1383   STRING_MAIL_FROM,
1384   STRING_MAIL_AUTH,
1385
1386 #ifdef USE_TLS_SRP
1387   STRING_TLSAUTH_USERNAME,     /* TLS auth <username> */
1388   STRING_TLSAUTH_PASSWORD,     /* TLS auth <password> */
1389 #endif
1390
1391   STRING_BEARER,          /* <bearer>, if used */
1392
1393   /* -- end of strings -- */
1394   STRING_LAST /* not used, just an end-of-list marker */
1395 };
1396
1397 struct UserDefined {
1398   FILE *err;         /* the stderr user data goes here */
1399   void *debugdata;   /* the data that will be passed to fdebug */
1400   char *errorbuffer; /* (Static) store failure messages in here */
1401   long proxyport; /* If non-zero, use this port number by default. If the
1402                      proxy string features a ":[port]" that one will override
1403                      this. */
1404   void *out;         /* the fetched file goes here */
1405   void *in;          /* the uploaded file is read from here */
1406   void *writeheader; /* write the header to this if non-NULL */
1407   void *rtp_out;     /* write RTP to this if non-NULL */
1408   long use_port;     /* which port to use (when not using default) */
1409   unsigned long httpauth;  /* kind of HTTP authentication to use (bitmask) */
1410   unsigned long proxyauth; /* kind of proxy authentication to use (bitmask) */
1411   long followlocation; /* as in HTTP Location: */
1412   long maxredirs;    /* maximum no. of http(s) redirects to follow, set to -1
1413                         for infinity */
1414
1415   int keep_post;     /* keep POSTs as POSTs after a 30x request; each
1416                         bit represents a request, from 301 to 303 */
1417   bool free_referer; /* set TRUE if 'referer' points to a string we
1418                         allocated */
1419   void *postfields;  /* if POST, set the fields' values here */
1420   curl_seek_callback seek_func;      /* function that seeks the input */
1421   curl_off_t postfieldsize; /* if POST, this might have a size to use instead
1422                                of strlen(), and then the data *may* be binary
1423                                (contain zero bytes) */
1424   unsigned short localport; /* local port number to bind to */
1425   int localportrange; /* number of additional port numbers to test in case the
1426                          'localport' one can't be bind()ed */
1427   curl_write_callback fwrite_func;   /* function that stores the output */
1428   curl_write_callback fwrite_header; /* function that stores headers */
1429   curl_write_callback fwrite_rtp;    /* function that stores interleaved RTP */
1430   curl_read_callback fread_func;     /* function that reads the input */
1431   int is_fread_set; /* boolean, has read callback been set to non-NULL? */
1432   int is_fwrite_set; /* boolean, has write callback been set to non-NULL? */
1433   curl_progress_callback fprogress; /* OLD and deprecated progress callback  */
1434   curl_xferinfo_callback fxferinfo; /* progress callback */
1435   curl_debug_callback fdebug;      /* function that write informational data */
1436   curl_ioctl_callback ioctl_func;  /* function for I/O control */
1437   curl_sockopt_callback fsockopt;  /* function for setting socket options */
1438   void *sockopt_client; /* pointer to pass to the socket options callback */
1439   curl_opensocket_callback fopensocket; /* function for checking/translating
1440                                            the address and opening the
1441                                            socket */
1442   void* opensocket_client;
1443   curl_closesocket_callback fclosesocket; /* function for closing the
1444                                              socket */
1445   void* closesocket_client;
1446
1447   void *seek_client;    /* pointer to pass to the seek callback */
1448   /* the 3 curl_conv_callback functions below are used on non-ASCII hosts */
1449   /* function to convert from the network encoding: */
1450   curl_conv_callback convfromnetwork;
1451   /* function to convert to the network encoding: */
1452   curl_conv_callback convtonetwork;
1453   /* function to convert from UTF-8 encoding: */
1454   curl_conv_callback convfromutf8;
1455
1456   void *progress_client; /* pointer to pass to the progress callback */
1457   void *ioctl_client;   /* pointer to pass to the ioctl callback */
1458   long timeout;         /* in milliseconds, 0 means no timeout */
1459   long connecttimeout;  /* in milliseconds, 0 means no timeout */
1460   long accepttimeout;   /* in milliseconds, 0 means no timeout */
1461   long server_response_timeout; /* in milliseconds, 0 means no timeout */
1462   long tftp_blksize ; /* in bytes, 0 means use default */
1463   curl_off_t infilesize;      /* size of file to upload, -1 means unknown */
1464   long low_speed_limit; /* bytes/second */
1465   long low_speed_time;  /* number of seconds */
1466   curl_off_t max_send_speed; /* high speed limit in bytes/second for upload */
1467   curl_off_t max_recv_speed; /* high speed limit in bytes/second for
1468                                 download */
1469   curl_off_t set_resume_from;  /* continue [ftp] transfer from here */
1470   struct curl_slist *headers; /* linked list of extra headers */
1471   struct curl_httppost *httppost;  /* linked list of POST data */
1472   bool cookiesession;   /* new cookie session? */
1473   bool crlf;            /* convert crlf on ftp upload(?) */
1474   struct curl_slist *quote;     /* after connection is established */
1475   struct curl_slist *postquote; /* after the transfer */
1476   struct curl_slist *prequote; /* before the transfer, after type */
1477   struct curl_slist *source_quote;  /* 3rd party quote */
1478   struct curl_slist *source_prequote;  /* in 3rd party transfer mode - before
1479                                           the transfer on source host */
1480   struct curl_slist *source_postquote; /* in 3rd party transfer mode - after
1481                                           the transfer on source host */
1482   struct curl_slist *telnet_options; /* linked list of telnet options */
1483   struct curl_slist *resolve;     /* list of names to add/remove from
1484                                      DNS cache */
1485   curl_TimeCond timecondition; /* kind of time/date comparison */
1486   time_t timevalue;       /* what time to compare with */
1487   Curl_HttpReq httpreq;   /* what kind of HTTP request (if any) is this */
1488   long httpversion; /* when non-zero, a specific HTTP version requested to
1489                        be used in the library's request(s) */
1490   struct ssl_config_data ssl;  /* user defined SSL stuff */
1491   curl_proxytype proxytype; /* what kind of proxy that is in use */
1492   long dns_cache_timeout; /* DNS cache timeout */
1493   long buffer_size;      /* size of receive buffer to use */
1494   void *private_data; /* application-private data */
1495
1496   struct curl_slist *http200aliases; /* linked list of aliases for http200 */
1497
1498   long ipver; /* the CURL_IPRESOLVE_* defines in the public header file
1499                  0 - whatever, 1 - v2, 2 - v6 */
1500
1501   curl_off_t max_filesize; /* Maximum file size to download */
1502
1503   curl_ftpfile ftp_filemethod; /* how to get to a file when FTP is used  */
1504
1505   int ftp_create_missing_dirs; /* 1 - create directories that don't exist
1506                                   2 - the same but also allow MKD to fail once
1507                                */
1508
1509   curl_sshkeycallback ssh_keyfunc; /* key matching callback */
1510   void *ssh_keyfunc_userp;         /* custom pointer to callback */
1511
1512 /* Here follows boolean settings that define how to behave during
1513    this session. They are STATIC, set by libcurl users or at least initially
1514    and they don't change during operations. */
1515
1516   bool printhost;        /* printing host name in debug info */
1517   bool get_filetime;     /* get the time and get of the remote file */
1518   bool tunnel_thru_httpproxy; /* use CONNECT through a HTTP proxy */
1519   bool prefer_ascii;     /* ASCII rather than binary */
1520   bool ftp_append;       /* append, not overwrite, on upload */
1521   bool ftp_list_only;    /* switch FTP command for listing directories */
1522   bool ftp_use_port;     /* use the FTP PORT command */
1523   bool hide_progress;    /* don't use the progress meter */
1524   bool http_fail_on_error;  /* fail on HTTP error codes >= 300 */
1525   bool http_follow_location; /* follow HTTP redirects */
1526   bool http_transfer_encoding; /* request compressed HTTP transfer-encoding */
1527   bool http_disable_hostname_check_before_authentication;
1528   bool include_header;   /* include received protocol headers in data output */
1529   bool http_set_referer; /* is a custom referer used */
1530   bool http_auto_referer; /* set "correct" referer when following location: */
1531   bool opt_no_body;      /* as set with CURLOPT_NOBODY */
1532   bool set_port;         /* custom port number used */
1533   bool upload;           /* upload request */
1534   enum CURL_NETRC_OPTION
1535        use_netrc;        /* defined in include/curl.h */
1536   bool verbose;          /* output verbosity */
1537   bool krb;              /* kerberos connection requested */
1538   bool reuse_forbid;     /* forbidden to be reused, close after use */
1539   bool reuse_fresh;      /* do not re-use an existing connection  */
1540   bool ftp_use_epsv;     /* if EPSV is to be attempted or not */
1541   bool ftp_use_eprt;     /* if EPRT is to be attempted or not */
1542   bool ftp_use_pret;     /* if PRET is to be used before PASV or not */
1543
1544   curl_usessl use_ssl;   /* if AUTH TLS is to be attempted etc, for FTP or
1545                             IMAP or POP3 or others! */
1546   curl_ftpauth ftpsslauth; /* what AUTH XXX to be attempted */
1547   curl_ftpccc ftp_ccc;   /* FTP CCC options */
1548   bool no_signal;        /* do not use any signal/alarm handler */
1549   bool global_dns_cache; /* subject for future removal */
1550   bool tcp_nodelay;      /* whether to enable TCP_NODELAY or not */
1551   bool ignorecl;         /* ignore content length */
1552   bool ftp_skip_ip;      /* skip the IP address the FTP server passes on to
1553                             us */
1554   bool connect_only;     /* make connection, let application use the socket */
1555   bool ssl_enable_beast; /* especially allow this flaw for interoperability's
1556                             sake*/
1557   long ssh_auth_types;   /* allowed SSH auth types */
1558   bool http_te_skip;     /* pass the raw body data to the user, even when
1559                             transfer-encoded (chunked, compressed) */
1560   bool http_ce_skip;     /* pass the raw body data to the user, even when
1561                             content-encoded (chunked, compressed) */
1562   long new_file_perms;    /* Permissions to use when creating remote files */
1563   long new_directory_perms; /* Permissions to use when creating remote dirs */
1564   bool proxy_transfer_mode; /* set transfer mode (;type=<a|i>) when doing FTP
1565                                via an HTTP proxy */
1566   char *str[STRING_LAST]; /* array of strings, pointing to allocated memory */
1567   unsigned int scope;    /* address scope for IPv6 */
1568   long allowed_protocols;
1569   long redir_protocols;
1570 #if defined(HAVE_GSSAPI) || defined(USE_WINDOWS_SSPI)
1571   long socks5_gssapi_nec; /* flag to support nec socks5 server */
1572 #endif
1573   struct curl_slist *mail_rcpt; /* linked list of mail recipients */
1574   bool sasl_ir;         /* Enable/disable SASL initial response */
1575   /* Common RTSP header options */
1576   Curl_RtspReq rtspreq; /* RTSP request type */
1577   long rtspversion; /* like httpversion, for RTSP */
1578   bool wildcardmatch; /* enable wildcard matching */
1579   curl_chunk_bgn_callback chunk_bgn; /* called before part of transfer
1580                                         starts */
1581   curl_chunk_end_callback chunk_end; /* called after part transferring
1582                                         stopped */
1583   curl_fnmatch_callback fnmatch; /* callback to decide which file corresponds
1584                                     to pattern (e.g. if WILDCARDMATCH is on) */
1585   void *fnmatch_data;
1586
1587   long gssapi_delegation; /* GSSAPI credential delegation, see the
1588                              documentation of CURLOPT_GSSAPI_DELEGATION */
1589
1590   bool tcp_keepalive;    /* use TCP keepalives */
1591   long tcp_keepidle;     /* seconds in idle before sending keepalive probe */
1592   long tcp_keepintvl;    /* seconds between TCP keepalive probes */
1593
1594   size_t maxconnects;  /* Max idle connections in the connection cache */
1595
1596   bool ssl_enable_npn;  /* TLS NPN extension? */
1597   bool ssl_enable_alpn; /* TLS ALPN extension? */
1598
1599   long expect_100_timeout; /* in milliseconds */
1600 };
1601
1602 struct Names {
1603   struct curl_hash *hostcache;
1604   enum {
1605     HCACHE_NONE,    /* not pointing to anything */
1606     HCACHE_GLOBAL,  /* points to the (shrug) global one */
1607     HCACHE_MULTI,   /* points to a shared one in the multi handle */
1608     HCACHE_SHARED   /* points to a shared one in a shared object */
1609   } hostcachetype;
1610 };
1611
1612 /*
1613  * The 'connectdata' struct MUST have all the connection oriented stuff as we
1614  * may have several simultaneous connections and connection structs in memory.
1615  *
1616  * The 'struct UserDefined' must only contain data that is set once to go for
1617  * many (perhaps) independent connections. Values that are generated or
1618  * calculated internally for the "session handle" must be defined within the
1619  * 'struct UrlState' instead.
1620  */
1621
1622 struct SessionHandle {
1623   /* first, two fields for the linked list of these */
1624   struct SessionHandle *next;
1625   struct SessionHandle *prev;
1626
1627   struct connectdata *easy_conn;     /* the "unit's" connection */
1628
1629   CURLMstate mstate;  /* the handle's state */
1630   CURLcode result;   /* previous result */
1631
1632   struct Curl_message msg; /* A single posted message. */
1633
1634   /* Array with the plain socket numbers this handle takes care of, in no
1635      particular order. Note that all sockets are added to the sockhash, where
1636      the state etc are also kept. This array is mostly used to detect when a
1637      socket is to be removed from the hash. See singlesocket(). */
1638   curl_socket_t sockets[MAX_SOCKSPEREASYHANDLE];
1639   int numsocks;
1640
1641   struct Names dns;
1642   struct Curl_multi *multi;    /* if non-NULL, points to the multi handle
1643                                   struct to which this "belongs" when used by
1644                                   the multi interface */
1645   struct Curl_multi *multi_easy; /* if non-NULL, points to the multi handle
1646                                     struct to which this "belongs" when used
1647                                     by the easy interface */
1648   struct Curl_share *share;    /* Share, handles global variable mutexing */
1649   struct SingleRequest req;    /* Request-specific data */
1650   struct UserDefined set;      /* values set by the libcurl user */
1651   struct DynamicStatic change; /* possibly modified userdefined data */
1652   struct CookieInfo *cookies;  /* the cookies, read from files and servers.
1653                                   NOTE that the 'cookie' field in the
1654                                   UserDefined struct defines if the "engine"
1655                                   is to be used or not. */
1656   struct Progress progress;    /* for all the progress meter data */
1657   struct UrlState state;       /* struct for fields used for state info and
1658                                   other dynamic purposes */
1659   struct WildcardData wildcard; /* wildcard download state info */
1660   struct PureInfo info;        /* stats, reports and info data */
1661   struct curl_tlssessioninfo tsi; /* Information about the TLS session, only
1662                                      valid after a client has asked for it */
1663 #if defined(CURL_DOES_CONVERSIONS) && defined(HAVE_ICONV)
1664   iconv_t outbound_cd;         /* for translating to the network encoding */
1665   iconv_t inbound_cd;          /* for translating from the network encoding */
1666   iconv_t utf8_cd;             /* for translating to UTF8 */
1667 #endif /* CURL_DOES_CONVERSIONS && HAVE_ICONV */
1668   unsigned int magic;          /* set to a CURLEASY_MAGIC_NUMBER */
1669 };
1670
1671 #define LIBCURL_NAME "libcurl"
1672
1673 #endif /* HEADER_CURL_URLDATA_H */