code
stringlengths
1
1.05M
repo_name
stringlengths
6
83
path
stringlengths
3
242
language
stringclasses
222 values
license
stringclasses
20 values
size
int64
1
1.05M
/*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2018, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "curl_setup.h" #include "urldata.h" #include <curl/curl.h> #include <stddef.h> #ifdef HAVE_ZLIB_H #include <zlib.h> #ifdef __SYMBIAN32__ /* zlib pollutes the namespace with this definition */ #undef WIN32 #endif #endif #ifdef HAVE_BROTLI #include <brotli/decode.h> #endif #include "sendf.h" #include "http.h" #include "content_encoding.h" #include "strdup.h" #include "strcase.h" #include "curl_memory.h" #include "memdebug.h" #define CONTENT_ENCODING_DEFAULT "identity" #ifndef CURL_DISABLE_HTTP #define DSIZ CURL_MAX_WRITE_SIZE /* buffer size for decompressed data */ #ifdef HAVE_LIBZ /* Comment this out if zlib is always going to be at least ver. 1.2.0.4 (doing so will reduce code size slightly). */ #define OLD_ZLIB_SUPPORT 1 #define GZIP_MAGIC_0 0x1f #define GZIP_MAGIC_1 0x8b /* gzip flag byte */ #define ASCII_FLAG 0x01 /* bit 0 set: file probably ascii text */ #define HEAD_CRC 0x02 /* bit 1 set: header CRC present */ #define EXTRA_FIELD 0x04 /* bit 2 set: extra field present */ #define ORIG_NAME 0x08 /* bit 3 set: original file name present */ #define COMMENT 0x10 /* bit 4 set: file comment present */ #define RESERVED 0xE0 /* bits 5..7: reserved */ typedef enum { ZLIB_UNINIT, /* uninitialized */ ZLIB_INIT, /* initialized */ ZLIB_INFLATING, /* inflating started. */ ZLIB_EXTERNAL_TRAILER, /* reading external trailer */ ZLIB_GZIP_HEADER, /* reading gzip header */ ZLIB_GZIP_INFLATING, /* inflating gzip stream */ ZLIB_INIT_GZIP /* initialized in transparent gzip mode */ } zlibInitState; /* Writer parameters. */ typedef struct { zlibInitState zlib_init; /* zlib init state */ uInt trailerlen; /* Remaining trailer byte count. */ z_stream z; /* State structure for zlib. */ } zlib_params; static voidpf zalloc_cb(voidpf opaque, unsigned int items, unsigned int size) { (void) opaque; /* not a typo, keep it calloc() */ return (voidpf) calloc(items, size); } static void zfree_cb(voidpf opaque, voidpf ptr) { (void) opaque; free(ptr); } static CURLcode process_zlib_error(struct connectdata *conn, z_stream *z) { struct Curl_easy *data = conn->data; if(z->msg) failf(data, "Error while processing content unencoding: %s", z->msg); else failf(data, "Error while processing content unencoding: " "Unknown failure within decompression software."); return CURLE_BAD_CONTENT_ENCODING; } static CURLcode exit_zlib(struct connectdata *conn, z_stream *z, zlibInitState *zlib_init, CURLcode result) { if(*zlib_init == ZLIB_GZIP_HEADER) Curl_safefree(z->next_in); if(*zlib_init != ZLIB_UNINIT) { if(inflateEnd(z) != Z_OK && result == CURLE_OK) result = process_zlib_error(conn, z); *zlib_init = ZLIB_UNINIT; } return result; } static CURLcode process_trailer(struct connectdata *conn, zlib_params *zp) { z_stream *z = &zp->z; CURLcode result = CURLE_OK; uInt len = z->avail_in < zp->trailerlen? z->avail_in: zp->trailerlen; /* Consume expected trailer bytes. Terminate stream if exhausted. Issue an error if unexpected bytes follow. */ zp->trailerlen -= len; z->avail_in -= len; z->next_in += len; if(z->avail_in) result = CURLE_WRITE_ERROR; if(result || !zp->trailerlen) result = exit_zlib(conn, z, &zp->zlib_init, result); else { /* Only occurs for gzip with zlib < 1.2.0.4 or raw deflate. */ zp->zlib_init = ZLIB_EXTERNAL_TRAILER; } return result; } static CURLcode inflate_stream(struct connectdata *conn, contenc_writer *writer, zlibInitState started) { zlib_params *zp = (zlib_params *) &writer->params; z_stream *z = &zp->z; /* zlib state structure */ uInt nread = z->avail_in; Bytef *orig_in = z->next_in; bool done = FALSE; CURLcode result = CURLE_OK; /* Curl_client_write status */ char *decomp; /* Put the decompressed data here. */ /* Check state. */ if(zp->zlib_init != ZLIB_INIT && zp->zlib_init != ZLIB_INFLATING && zp->zlib_init != ZLIB_INIT_GZIP && zp->zlib_init != ZLIB_GZIP_INFLATING) return exit_zlib(conn, z, &zp->zlib_init, CURLE_WRITE_ERROR); /* Dynamically allocate a buffer for decompression because it's uncommonly large to hold on the stack */ decomp = malloc(DSIZ); if(decomp == NULL) return exit_zlib(conn, z, &zp->zlib_init, CURLE_OUT_OF_MEMORY); /* because the buffer size is fixed, iteratively decompress and transfer to the client via downstream_write function. */ while(!done) { int status; /* zlib status */ done = TRUE; /* (re)set buffer for decompressed output for every iteration */ z->next_out = (Bytef *) decomp; z->avail_out = DSIZ; #ifdef Z_BLOCK /* Z_BLOCK is only available in zlib ver. >= 1.2.0.5 */ status = inflate(z, Z_BLOCK); #else /* fallback for zlib ver. < 1.2.0.5 */ status = inflate(z, Z_SYNC_FLUSH); #endif /* Flush output data if some. */ if(z->avail_out != DSIZ) { if(status == Z_OK || status == Z_STREAM_END) { zp->zlib_init = started; /* Data started. */ result = Curl_unencode_write(conn, writer->downstream, decomp, DSIZ - z->avail_out); if(result) { exit_zlib(conn, z, &zp->zlib_init, result); break; } } } /* Dispatch by inflate() status. */ switch(status) { case Z_OK: /* Always loop: there may be unflushed latched data in zlib state. */ done = FALSE; break; case Z_BUF_ERROR: /* No more data to flush: just exit loop. */ break; case Z_STREAM_END: result = process_trailer(conn, zp); break; case Z_DATA_ERROR: /* some servers seem to not generate zlib headers, so this is an attempt to fix and continue anyway */ if(zp->zlib_init == ZLIB_INIT) { /* Do not use inflateReset2(): only available since zlib 1.2.3.4. */ (void) inflateEnd(z); /* don't care about the return code */ if(inflateInit2(z, -MAX_WBITS) == Z_OK) { z->next_in = orig_in; z->avail_in = nread; zp->zlib_init = ZLIB_INFLATING; zp->trailerlen = 4; /* Tolerate up to 4 unknown trailer bytes. */ done = FALSE; break; } zp->zlib_init = ZLIB_UNINIT; /* inflateEnd() already called. */ } /* FALLTHROUGH */ default: result = exit_zlib(conn, z, &zp->zlib_init, process_zlib_error(conn, z)); break; } } free(decomp); /* We're about to leave this call so the `nread' data bytes won't be seen again. If we are in a state that would wrongly allow restart in raw mode at the next call, assume output has already started. */ if(nread && zp->zlib_init == ZLIB_INIT) zp->zlib_init = started; /* Cannot restart anymore. */ return result; } /* Deflate handler. */ static CURLcode deflate_init_writer(struct connectdata *conn, contenc_writer *writer) { zlib_params *zp = (zlib_params *) &writer->params; z_stream *z = &zp->z; /* zlib state structure */ if(!writer->downstream) return CURLE_WRITE_ERROR; /* Initialize zlib */ z->zalloc = (alloc_func) zalloc_cb; z->zfree = (free_func) zfree_cb; if(inflateInit(z) != Z_OK) return process_zlib_error(conn, z); zp->zlib_init = ZLIB_INIT; return CURLE_OK; } static CURLcode deflate_unencode_write(struct connectdata *conn, contenc_writer *writer, const char *buf, size_t nbytes) { zlib_params *zp = (zlib_params *) &writer->params; z_stream *z = &zp->z; /* zlib state structure */ /* Set the compressed input when this function is called */ z->next_in = (Bytef *) buf; z->avail_in = (uInt) nbytes; if(zp->zlib_init == ZLIB_EXTERNAL_TRAILER) return process_trailer(conn, zp); /* Now uncompress the data */ return inflate_stream(conn, writer, ZLIB_INFLATING); } static void deflate_close_writer(struct connectdata *conn, contenc_writer *writer) { zlib_params *zp = (zlib_params *) &writer->params; z_stream *z = &zp->z; /* zlib state structure */ exit_zlib(conn, z, &zp->zlib_init, CURLE_OK); } static const content_encoding deflate_encoding = { "deflate", NULL, deflate_init_writer, deflate_unencode_write, deflate_close_writer, sizeof(zlib_params) }; /* Gzip handler. */ static CURLcode gzip_init_writer(struct connectdata *conn, contenc_writer *writer) { zlib_params *zp = (zlib_params *) &writer->params; z_stream *z = &zp->z; /* zlib state structure */ if(!writer->downstream) return CURLE_WRITE_ERROR; /* Initialize zlib */ z->zalloc = (alloc_func) zalloc_cb; z->zfree = (free_func) zfree_cb; if(strcmp(zlibVersion(), "1.2.0.4") >= 0) { /* zlib ver. >= 1.2.0.4 supports transparent gzip decompressing */ if(inflateInit2(z, MAX_WBITS + 32) != Z_OK) { return process_zlib_error(conn, z); } zp->zlib_init = ZLIB_INIT_GZIP; /* Transparent gzip decompress state */ } else { /* we must parse the gzip header and trailer ourselves */ if(inflateInit2(z, -MAX_WBITS) != Z_OK) { return process_zlib_error(conn, z); } zp->trailerlen = 8; /* A CRC-32 and a 32-bit input size (RFC 1952, 2.2) */ zp->zlib_init = ZLIB_INIT; /* Initial call state */ } return CURLE_OK; } #ifdef OLD_ZLIB_SUPPORT /* Skip over the gzip header */ static enum { GZIP_OK, GZIP_BAD, GZIP_UNDERFLOW } check_gzip_header(unsigned char const *data, ssize_t len, ssize_t *headerlen) { int method, flags; const ssize_t totallen = len; /* The shortest header is 10 bytes */ if(len < 10) return GZIP_UNDERFLOW; if((data[0] != GZIP_MAGIC_0) || (data[1] != GZIP_MAGIC_1)) return GZIP_BAD; method = data[2]; flags = data[3]; if(method != Z_DEFLATED || (flags & RESERVED) != 0) { /* Can't handle this compression method or unknown flag */ return GZIP_BAD; } /* Skip over time, xflags, OS code and all previous bytes */ len -= 10; data += 10; if(flags & EXTRA_FIELD) { ssize_t extra_len; if(len < 2) return GZIP_UNDERFLOW; extra_len = (data[1] << 8) | data[0]; if(len < (extra_len + 2)) return GZIP_UNDERFLOW; len -= (extra_len + 2); data += (extra_len + 2); } if(flags & ORIG_NAME) { /* Skip over NUL-terminated file name */ while(len && *data) { --len; ++data; } if(!len || *data) return GZIP_UNDERFLOW; /* Skip over the NUL */ --len; ++data; } if(flags & COMMENT) { /* Skip over NUL-terminated comment */ while(len && *data) { --len; ++data; } if(!len || *data) return GZIP_UNDERFLOW; /* Skip over the NUL */ --len; } if(flags & HEAD_CRC) { if(len < 2) return GZIP_UNDERFLOW; len -= 2; } *headerlen = totallen - len; return GZIP_OK; } #endif static CURLcode gzip_unencode_write(struct connectdata *conn, contenc_writer *writer, const char *buf, size_t nbytes) { zlib_params *zp = (zlib_params *) &writer->params; z_stream *z = &zp->z; /* zlib state structure */ if(zp->zlib_init == ZLIB_INIT_GZIP) { /* Let zlib handle the gzip decompression entirely */ z->next_in = (Bytef *) buf; z->avail_in = (uInt) nbytes; /* Now uncompress the data */ return inflate_stream(conn, writer, ZLIB_INIT_GZIP); } #ifndef OLD_ZLIB_SUPPORT /* Support for old zlib versions is compiled away and we are running with an old version, so return an error. */ return exit_zlib(conn, z, &zp->zlib_init, CURLE_WRITE_ERROR); #else /* This next mess is to get around the potential case where there isn't * enough data passed in to skip over the gzip header. If that happens, we * malloc a block and copy what we have then wait for the next call. If * there still isn't enough (this is definitely a worst-case scenario), we * make the block bigger, copy the next part in and keep waiting. * * This is only required with zlib versions < 1.2.0.4 as newer versions * can handle the gzip header themselves. */ switch(zp->zlib_init) { /* Skip over gzip header? */ case ZLIB_INIT: { /* Initial call state */ ssize_t hlen; switch(check_gzip_header((unsigned char *) buf, nbytes, &hlen)) { case GZIP_OK: z->next_in = (Bytef *) buf + hlen; z->avail_in = (uInt) (nbytes - hlen); zp->zlib_init = ZLIB_GZIP_INFLATING; /* Inflating stream state */ break; case GZIP_UNDERFLOW: /* We need more data so we can find the end of the gzip header. It's * possible that the memory block we malloc here will never be freed if * the transfer abruptly aborts after this point. Since it's unlikely * that circumstances will be right for this code path to be followed in * the first place, and it's even more unlikely for a transfer to fail * immediately afterwards, it should seldom be a problem. */ z->avail_in = (uInt) nbytes; z->next_in = malloc(z->avail_in); if(z->next_in == NULL) { return exit_zlib(conn, z, &zp->zlib_init, CURLE_OUT_OF_MEMORY); } memcpy(z->next_in, buf, z->avail_in); zp->zlib_init = ZLIB_GZIP_HEADER; /* Need more gzip header data state */ /* We don't have any data to inflate yet */ return CURLE_OK; case GZIP_BAD: default: return exit_zlib(conn, z, &zp->zlib_init, process_zlib_error(conn, z)); } } break; case ZLIB_GZIP_HEADER: { /* Need more gzip header data state */ ssize_t hlen; z->avail_in += (uInt) nbytes; z->next_in = Curl_saferealloc(z->next_in, z->avail_in); if(z->next_in == NULL) { return exit_zlib(conn, z, &zp->zlib_init, CURLE_OUT_OF_MEMORY); } /* Append the new block of data to the previous one */ memcpy(z->next_in + z->avail_in - nbytes, buf, nbytes); switch(check_gzip_header(z->next_in, z->avail_in, &hlen)) { case GZIP_OK: /* This is the zlib stream data */ free(z->next_in); /* Don't point into the malloced block since we just freed it */ z->next_in = (Bytef *) buf + hlen + nbytes - z->avail_in; z->avail_in = (uInt) (z->avail_in - hlen); zp->zlib_init = ZLIB_GZIP_INFLATING; /* Inflating stream state */ break; case GZIP_UNDERFLOW: /* We still don't have any data to inflate! */ return CURLE_OK; case GZIP_BAD: default: return exit_zlib(conn, z, &zp->zlib_init, process_zlib_error(conn, z)); } } break; case ZLIB_EXTERNAL_TRAILER: z->next_in = (Bytef *) buf; z->avail_in = (uInt) nbytes; return process_trailer(conn, zp); case ZLIB_GZIP_INFLATING: default: /* Inflating stream state */ z->next_in = (Bytef *) buf; z->avail_in = (uInt) nbytes; break; } if(z->avail_in == 0) { /* We don't have any data to inflate; wait until next time */ return CURLE_OK; } /* We've parsed the header, now uncompress the data */ return inflate_stream(conn, writer, ZLIB_GZIP_INFLATING); #endif } static void gzip_close_writer(struct connectdata *conn, contenc_writer *writer) { zlib_params *zp = (zlib_params *) &writer->params; z_stream *z = &zp->z; /* zlib state structure */ exit_zlib(conn, z, &zp->zlib_init, CURLE_OK); } static const content_encoding gzip_encoding = { "gzip", "x-gzip", gzip_init_writer, gzip_unencode_write, gzip_close_writer, sizeof(zlib_params) }; #endif /* HAVE_LIBZ */ #ifdef HAVE_BROTLI /* Writer parameters. */ typedef struct { BrotliDecoderState *br; /* State structure for brotli. */ } brotli_params; static CURLcode brotli_map_error(BrotliDecoderErrorCode be) { switch(be) { case BROTLI_DECODER_ERROR_FORMAT_EXUBERANT_NIBBLE: case BROTLI_DECODER_ERROR_FORMAT_EXUBERANT_META_NIBBLE: case BROTLI_DECODER_ERROR_FORMAT_SIMPLE_HUFFMAN_ALPHABET: case BROTLI_DECODER_ERROR_FORMAT_SIMPLE_HUFFMAN_SAME: case BROTLI_DECODER_ERROR_FORMAT_CL_SPACE: case BROTLI_DECODER_ERROR_FORMAT_HUFFMAN_SPACE: case BROTLI_DECODER_ERROR_FORMAT_CONTEXT_MAP_REPEAT: case BROTLI_DECODER_ERROR_FORMAT_BLOCK_LENGTH_1: case BROTLI_DECODER_ERROR_FORMAT_BLOCK_LENGTH_2: case BROTLI_DECODER_ERROR_FORMAT_TRANSFORM: case BROTLI_DECODER_ERROR_FORMAT_DICTIONARY: case BROTLI_DECODER_ERROR_FORMAT_WINDOW_BITS: case BROTLI_DECODER_ERROR_FORMAT_PADDING_1: case BROTLI_DECODER_ERROR_FORMAT_PADDING_2: #ifdef BROTLI_DECODER_ERROR_COMPOUND_DICTIONARY case BROTLI_DECODER_ERROR_COMPOUND_DICTIONARY: #endif #ifdef BROTLI_DECODER_ERROR_DICTIONARY_NOT_SET case BROTLI_DECODER_ERROR_DICTIONARY_NOT_SET: #endif case BROTLI_DECODER_ERROR_INVALID_ARGUMENTS: return CURLE_BAD_CONTENT_ENCODING; case BROTLI_DECODER_ERROR_ALLOC_CONTEXT_MODES: case BROTLI_DECODER_ERROR_ALLOC_TREE_GROUPS: case BROTLI_DECODER_ERROR_ALLOC_CONTEXT_MAP: case BROTLI_DECODER_ERROR_ALLOC_RING_BUFFER_1: case BROTLI_DECODER_ERROR_ALLOC_RING_BUFFER_2: case BROTLI_DECODER_ERROR_ALLOC_BLOCK_TYPE_TREES: return CURLE_OUT_OF_MEMORY; default: break; } return CURLE_WRITE_ERROR; } static CURLcode brotli_init_writer(struct connectdata *conn, contenc_writer *writer) { brotli_params *bp = (brotli_params *) &writer->params; (void) conn; if(!writer->downstream) return CURLE_WRITE_ERROR; bp->br = BrotliDecoderCreateInstance(NULL, NULL, NULL); return bp->br? CURLE_OK: CURLE_OUT_OF_MEMORY; } static CURLcode brotli_unencode_write(struct connectdata *conn, contenc_writer *writer, const char *buf, size_t nbytes) { brotli_params *bp = (brotli_params *) &writer->params; const uint8_t *src = (const uint8_t *) buf; char *decomp; uint8_t *dst; size_t dstleft; CURLcode result = CURLE_OK; BrotliDecoderResult r = BROTLI_DECODER_RESULT_NEEDS_MORE_OUTPUT; if(!bp->br) return CURLE_WRITE_ERROR; /* Stream already ended. */ decomp = malloc(DSIZ); if(!decomp) return CURLE_OUT_OF_MEMORY; while((nbytes || r == BROTLI_DECODER_RESULT_NEEDS_MORE_OUTPUT) && result == CURLE_OK) { dst = (uint8_t *) decomp; dstleft = DSIZ; r = BrotliDecoderDecompressStream(bp->br, &nbytes, &src, &dstleft, &dst, NULL); result = Curl_unencode_write(conn, writer->downstream, decomp, DSIZ - dstleft); if(result) break; switch(r) { case BROTLI_DECODER_RESULT_NEEDS_MORE_OUTPUT: case BROTLI_DECODER_RESULT_NEEDS_MORE_INPUT: break; case BROTLI_DECODER_RESULT_SUCCESS: BrotliDecoderDestroyInstance(bp->br); bp->br = NULL; if(nbytes) result = CURLE_WRITE_ERROR; break; default: result = brotli_map_error(BrotliDecoderGetErrorCode(bp->br)); break; } } free(decomp); return result; } static void brotli_close_writer(struct connectdata *conn, contenc_writer *writer) { brotli_params *bp = (brotli_params *) &writer->params; (void) conn; if(bp->br) { BrotliDecoderDestroyInstance(bp->br); bp->br = NULL; } } static const content_encoding brotli_encoding = { "br", NULL, brotli_init_writer, brotli_unencode_write, brotli_close_writer, sizeof(brotli_params) }; #endif /* Identity handler. */ static CURLcode identity_init_writer(struct connectdata *conn, contenc_writer *writer) { (void) conn; return writer->downstream? CURLE_OK: CURLE_WRITE_ERROR; } static CURLcode identity_unencode_write(struct connectdata *conn, contenc_writer *writer, const char *buf, size_t nbytes) { return Curl_unencode_write(conn, writer->downstream, buf, nbytes); } static void identity_close_writer(struct connectdata *conn, contenc_writer *writer) { (void) conn; (void) writer; } static const content_encoding identity_encoding = { "identity", "none", identity_init_writer, identity_unencode_write, identity_close_writer, 0 }; /* supported content encodings table. */ static const content_encoding * const encodings[] = { &identity_encoding, #ifdef HAVE_LIBZ &deflate_encoding, &gzip_encoding, #endif #ifdef HAVE_BROTLI &brotli_encoding, #endif NULL }; /* Return a list of comma-separated names of supported encodings. */ char *Curl_all_content_encodings(void) { size_t len = 0; const content_encoding * const *cep; const content_encoding *ce; char *ace; for(cep = encodings; *cep; cep++) { ce = *cep; if(!strcasecompare(ce->name, CONTENT_ENCODING_DEFAULT)) len += strlen(ce->name) + 2; } if(!len) return strdup(CONTENT_ENCODING_DEFAULT); ace = malloc(len); if(ace) { char *p = ace; for(cep = encodings; *cep; cep++) { ce = *cep; if(!strcasecompare(ce->name, CONTENT_ENCODING_DEFAULT)) { strcpy(p, ce->name); p += strlen(p); *p++ = ','; *p++ = ' '; } } p[-2] = '\0'; } return ace; } /* Real client writer: no downstream. */ static CURLcode client_init_writer(struct connectdata *conn, contenc_writer *writer) { (void) conn; return writer->downstream? CURLE_WRITE_ERROR: CURLE_OK; } static CURLcode client_unencode_write(struct connectdata *conn, contenc_writer *writer, const char *buf, size_t nbytes) { struct Curl_easy *data = conn->data; struct SingleRequest *k = &data->req; (void) writer; if(!nbytes || k->ignorebody) return CURLE_OK; return Curl_client_write(conn, CLIENTWRITE_BODY, (char *) buf, nbytes); } static void client_close_writer(struct connectdata *conn, contenc_writer *writer) { (void) conn; (void) writer; } static const content_encoding client_encoding = { NULL, NULL, client_init_writer, client_unencode_write, client_close_writer, 0 }; /* Deferred error dummy writer. */ static CURLcode error_init_writer(struct connectdata *conn, contenc_writer *writer) { (void) conn; return writer->downstream? CURLE_OK: CURLE_WRITE_ERROR; } static CURLcode error_unencode_write(struct connectdata *conn, contenc_writer *writer, const char *buf, size_t nbytes) { char *all = Curl_all_content_encodings(); (void) writer; (void) buf; (void) nbytes; if(!all) return CURLE_OUT_OF_MEMORY; failf(conn->data, "Unrecognized content encoding type. " "libcurl understands %s content encodings.", all); free(all); return CURLE_BAD_CONTENT_ENCODING; } static void error_close_writer(struct connectdata *conn, contenc_writer *writer) { (void) conn; (void) writer; } static const content_encoding error_encoding = { NULL, NULL, error_init_writer, error_unencode_write, error_close_writer, 0 }; /* Create an unencoding writer stage using the given handler. */ static contenc_writer *new_unencoding_writer(struct connectdata *conn, const content_encoding *handler, contenc_writer *downstream) { size_t sz = offsetof(contenc_writer, params) + handler->paramsize; contenc_writer *writer = (contenc_writer *) calloc(1, sz); if(writer) { writer->handler = handler; writer->downstream = downstream; if(handler->init_writer(conn, writer)) { free(writer); writer = NULL; } } return writer; } /* Write data using an unencoding writer stack. */ CURLcode Curl_unencode_write(struct connectdata *conn, contenc_writer *writer, const char *buf, size_t nbytes) { if(!nbytes) return CURLE_OK; return writer->handler->unencode_write(conn, writer, buf, nbytes); } /* Close and clean-up the connection's writer stack. */ void Curl_unencode_cleanup(struct connectdata *conn) { struct Curl_easy *data = conn->data; struct SingleRequest *k = &data->req; contenc_writer *writer = k->writer_stack; while(writer) { k->writer_stack = writer->downstream; writer->handler->close_writer(conn, writer); free(writer); writer = k->writer_stack; } } /* Find the content encoding by name. */ static const content_encoding *find_encoding(const char *name, size_t len) { const content_encoding * const *cep; for(cep = encodings; *cep; cep++) { const content_encoding *ce = *cep; if((strncasecompare(name, ce->name, len) && !ce->name[len]) || (ce->alias && strncasecompare(name, ce->alias, len) && !ce->alias[len])) return ce; } return NULL; } /* Set-up the unencoding stack from the Content-Encoding header value. * See RFC 7231 section 3.1.2.2. */ CURLcode Curl_build_unencoding_stack(struct connectdata *conn, const char *enclist, int maybechunked) { struct Curl_easy *data = conn->data; struct SingleRequest *k = &data->req; do { const char *name; size_t namelen; /* Parse a single encoding name. */ while(ISSPACE(*enclist) || *enclist == ',') enclist++; name = enclist; for(namelen = 0; *enclist && *enclist != ','; enclist++) if(!ISSPACE(*enclist)) namelen = enclist - name + 1; /* Special case: chunked encoding is handled at the reader level. */ if(maybechunked && namelen == 7 && strncasecompare(name, "chunked", 7)) { k->chunk = TRUE; /* chunks coming our way. */ Curl_httpchunk_init(conn); /* init our chunky engine. */ } else if(namelen) { const content_encoding *encoding = find_encoding(name, namelen); contenc_writer *writer; if(!k->writer_stack) { k->writer_stack = new_unencoding_writer(conn, &client_encoding, NULL); if(!k->writer_stack) return CURLE_OUT_OF_MEMORY; } if(!encoding) encoding = &error_encoding; /* Defer error at stack use. */ /* Stack the unencoding stage. */ writer = new_unencoding_writer(conn, encoding, k->writer_stack); if(!writer) return CURLE_OUT_OF_MEMORY; k->writer_stack = writer; } } while(*enclist); return CURLE_OK; } #else /* Stubs for builds without HTTP. */ CURLcode Curl_build_unencoding_stack(struct connectdata *conn, const char *enclist, int maybechunked) { (void) conn; (void) enclist; (void) maybechunked; return CURLE_NOT_BUILT_IN; } CURLcode Curl_unencode_write(struct connectdata *conn, contenc_writer *writer, const char *buf, size_t nbytes) { (void) conn; (void) writer; (void) buf; (void) nbytes; return CURLE_NOT_BUILT_IN; } void Curl_unencode_cleanup(struct connectdata *conn) { (void) conn; } char *Curl_all_content_encodings(void) { return strdup(CONTENT_ENCODING_DEFAULT); /* Satisfy caller. */ } #endif /* CURL_DISABLE_HTTP */
YifuLiu/AliOS-Things
components/curl/lib/content_encoding.c
C
apache-2.0
28,623
#ifndef HEADER_CURL_CONTENT_ENCODING_H #define HEADER_CURL_CONTENT_ENCODING_H /*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2017, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "curl_setup.h" /* Decoding writer. */ typedef struct contenc_writer_s contenc_writer; typedef struct content_encoding_s content_encoding; struct contenc_writer_s { const content_encoding *handler; /* Encoding handler. */ contenc_writer *downstream; /* Downstream writer. */ void *params; /* Encoding-specific storage (variable length). */ }; /* Content encoding writer. */ struct content_encoding_s { const char *name; /* Encoding name. */ const char *alias; /* Encoding name alias. */ CURLcode (*init_writer)(struct connectdata *conn, contenc_writer *writer); CURLcode (*unencode_write)(struct connectdata *conn, contenc_writer *writer, const char *buf, size_t nbytes); void (*close_writer)(struct connectdata *conn, contenc_writer *writer); size_t paramsize; }; CURLcode Curl_build_unencoding_stack(struct connectdata *conn, const char *enclist, int maybechunked); CURLcode Curl_unencode_write(struct connectdata *conn, contenc_writer *writer, const char *buf, size_t nbytes); void Curl_unencode_cleanup(struct connectdata *conn); char *Curl_all_content_encodings(void); #endif /* HEADER_CURL_CONTENT_ENCODING_H */
YifuLiu/AliOS-Things
components/curl/lib/content_encoding.h
C
apache-2.0
2,365
#ifndef HEADER_CURL_COOKIE_H #define HEADER_CURL_COOKIE_H /*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2019, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "curl_setup.h" #include <curl/curl.h> struct Cookie { struct Cookie *next; /* next in the chain */ char *name; /* <this> = value */ char *value; /* name = <this> */ char *path; /* path = <this> which is in Set-Cookie: */ char *spath; /* sanitized cookie path */ char *domain; /* domain = <this> */ curl_off_t expires; /* expires = <this> */ char *expirestr; /* the plain text version */ bool tailmatch; /* whether we do tail-matching of the domain name */ /* RFC 2109 keywords. Version=1 means 2109-compliant cookie sending */ char *version; /* Version = <value> */ char *maxage; /* Max-Age = <value> */ bool secure; /* whether the 'secure' keyword was used */ bool livecookie; /* updated from a server, not a stored file */ bool httponly; /* true if the httponly directive is present */ int creationtime; /* time when the cookie was written */ unsigned char prefix; /* bitmap fields indicating which prefix are set */ }; /* * Available cookie prefixes, as defined in * draft-ietf-httpbis-rfc6265bis-02 */ #define COOKIE_PREFIX__SECURE (1<<0) #define COOKIE_PREFIX__HOST (1<<1) #define COOKIE_HASH_SIZE 256 struct CookieInfo { /* linked list of cookies we know of */ struct Cookie *cookies[COOKIE_HASH_SIZE]; char *filename; /* file we read from/write to */ bool running; /* state info, for cookie adding information */ long numcookies; /* number of cookies in the "jar" */ bool newsession; /* new session, discard session cookies on load */ int lastct; /* last creation-time used in the jar */ }; /* This is the maximum line length we accept for a cookie line. RFC 2109 section 6.3 says: "at least 4096 bytes per cookie (as measured by the size of the characters that comprise the cookie non-terminal in the syntax description of the Set-Cookie header)" We allow max 5000 bytes cookie header. Max 4095 bytes length per cookie name and value. Name + value may not exceed 4096 bytes. */ #define MAX_COOKIE_LINE 5000 /* This is the maximum length of a cookie name or content we deal with: */ #define MAX_NAME 4096 #define MAX_NAME_TXT "4095" struct Curl_easy; /* * Add a cookie to the internal list of cookies. The domain and path arguments * are only used if the header boolean is TRUE. */ struct Cookie *Curl_cookie_add(struct Curl_easy *data, struct CookieInfo *, bool header, bool noexpiry, char *lineptr, const char *domain, const char *path, bool secure); struct Cookie *Curl_cookie_getlist(struct CookieInfo *, const char *, const char *, bool); void Curl_cookie_freelist(struct Cookie *cookies); void Curl_cookie_clearall(struct CookieInfo *cookies); void Curl_cookie_clearsess(struct CookieInfo *cookies); #if defined(CURL_DISABLE_HTTP) || defined(CURL_DISABLE_COOKIES) #define Curl_cookie_list(x) NULL #define Curl_cookie_loadfiles(x) Curl_nop_stmt #define Curl_cookie_init(x,y,z,w) NULL #define Curl_cookie_cleanup(x) Curl_nop_stmt #define Curl_flush_cookies(x,y) Curl_nop_stmt #else void Curl_flush_cookies(struct Curl_easy *data, int cleanup); void Curl_cookie_cleanup(struct CookieInfo *); struct CookieInfo *Curl_cookie_init(struct Curl_easy *data, const char *, struct CookieInfo *, bool); struct curl_slist *Curl_cookie_list(struct Curl_easy *data); void Curl_cookie_loadfiles(struct Curl_easy *data); #endif #endif /* HEADER_CURL_COOKIE_H */
YifuLiu/AliOS-Things
components/curl/lib/cookie.h
C
apache-2.0
4,706
/*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2019, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "curl_setup.h" #include <curl/curl.h> #ifdef HAVE_NETINET_IN_H # include <netinet/in.h> #endif #ifdef HAVE_NETINET_IN6_H # include <netinet/in6.h> #endif #ifdef HAVE_NETDB_H #ifdef USE_LWIPSOCK # include <lwip/netdb.h> #else # include <netdb.h> #endif #endif #ifdef HAVE_ARPA_INET_H # include <arpa/inet.h> #endif #ifdef HAVE_SYS_UN_H # include <sys/un.h> #endif #ifdef __VMS # include <in.h> # include <inet.h> #endif #if defined(NETWARE) && defined(__NOVELL_LIBC__) # undef in_addr_t # define in_addr_t unsigned long #endif #if defined(WIN32) && defined(USE_UNIX_SOCKETS) #include <afunix.h> #endif #include <stddef.h> #include "curl_addrinfo.h" #include "inet_pton.h" #include "warnless.h" /* The last 3 #include files should be in this order */ #include "curl_printf.h" #include "curl_memory.h" #include "memdebug.h" /* * Curl_freeaddrinfo() * * This is used to free a linked list of Curl_addrinfo structs along * with all its associated allocated storage. This function should be * called once for each successful call to Curl_getaddrinfo_ex() or to * any function call which actually allocates a Curl_addrinfo struct. */ #if defined(__INTEL_COMPILER) && (__INTEL_COMPILER == 910) && \ defined(__OPTIMIZE__) && defined(__unix__) && defined(__i386__) /* workaround icc 9.1 optimizer issue */ # define vqualifier volatile #else # define vqualifier #endif void Curl_freeaddrinfo(Curl_addrinfo *cahead) { Curl_addrinfo *vqualifier canext; Curl_addrinfo *ca; for(ca = cahead; ca != NULL; ca = canext) { free(ca->ai_addr); free(ca->ai_canonname); canext = ca->ai_next; free(ca); } } #ifdef HAVE_GETADDRINFO /* * Curl_getaddrinfo_ex() * * This is a wrapper function around system's getaddrinfo(), with * the only difference that instead of returning a linked list of * addrinfo structs this one returns a linked list of Curl_addrinfo * ones. The memory allocated by this function *MUST* be free'd with * Curl_freeaddrinfo(). For each successful call to this function * there must be an associated call later to Curl_freeaddrinfo(). * * There should be no single call to system's getaddrinfo() in the * whole library, any such call should be 'routed' through this one. */ int Curl_getaddrinfo_ex(const char *nodename, const char *servname, const struct addrinfo *hints, Curl_addrinfo **result) { const struct addrinfo *ai; struct addrinfo *aihead; Curl_addrinfo *cafirst = NULL; Curl_addrinfo *calast = NULL; Curl_addrinfo *ca; size_t ss_size; int error; *result = NULL; /* assume failure */ error = getaddrinfo(nodename, servname, hints, &aihead); if(error) return error; /* traverse the addrinfo list */ for(ai = aihead; ai != NULL; ai = ai->ai_next) { /* ignore elements with unsupported address family, */ /* settle family-specific sockaddr structure size. */ if(ai->ai_family == AF_INET) ss_size = sizeof(struct sockaddr_in); #ifdef ENABLE_IPV6 else if(ai->ai_family == AF_INET6) ss_size = sizeof(struct sockaddr_in6); #endif else continue; /* ignore elements without required address info */ if((ai->ai_addr == NULL) || !(ai->ai_addrlen > 0)) continue; /* ignore elements with bogus address size */ if((size_t)ai->ai_addrlen < ss_size) continue; ca = malloc(sizeof(Curl_addrinfo)); if(!ca) { error = EAI_MEMORY; break; } /* copy each structure member individually, member ordering, */ /* size, or padding might be different for each platform. */ ca->ai_flags = ai->ai_flags; ca->ai_family = ai->ai_family; ca->ai_socktype = ai->ai_socktype; ca->ai_protocol = ai->ai_protocol; ca->ai_addrlen = (curl_socklen_t)ss_size; ca->ai_addr = NULL; ca->ai_canonname = NULL; ca->ai_next = NULL; ca->ai_addr = malloc(ss_size); if(!ca->ai_addr) { error = EAI_MEMORY; free(ca); break; } memcpy(ca->ai_addr, ai->ai_addr, ss_size); if(ai->ai_canonname != NULL) { ca->ai_canonname = strdup(ai->ai_canonname); if(!ca->ai_canonname) { error = EAI_MEMORY; free(ca->ai_addr); free(ca); break; } } /* if the return list is empty, this becomes the first element */ if(!cafirst) cafirst = ca; /* add this element last in the return list */ if(calast) calast->ai_next = ca; calast = ca; } /* destroy the addrinfo list */ if(aihead) freeaddrinfo(aihead); /* if we failed, also destroy the Curl_addrinfo list */ if(error) { Curl_freeaddrinfo(cafirst); cafirst = NULL; } else if(!cafirst) { #ifdef EAI_NONAME /* rfc3493 conformant */ error = EAI_NONAME; #else /* rfc3493 obsoleted */ error = EAI_NODATA; #endif #ifdef USE_WINSOCK SET_SOCKERRNO(error); #endif } *result = cafirst; /* This is not a CURLcode */ return error; } #endif /* HAVE_GETADDRINFO */ /* * Curl_he2ai() * * This function returns a pointer to the first element of a newly allocated * Curl_addrinfo struct linked list filled with the data of a given hostent. * Curl_addrinfo is meant to work like the addrinfo struct does for a IPv6 * stack, but usable also for IPv4, all hosts and environments. * * The memory allocated by this function *MUST* be free'd later on calling * Curl_freeaddrinfo(). For each successful call to this function there * must be an associated call later to Curl_freeaddrinfo(). * * Curl_addrinfo defined in "lib/curl_addrinfo.h" * * struct Curl_addrinfo { * int ai_flags; * int ai_family; * int ai_socktype; * int ai_protocol; * curl_socklen_t ai_addrlen; * Follow rfc3493 struct addrinfo * * char *ai_canonname; * struct sockaddr *ai_addr; * struct Curl_addrinfo *ai_next; * }; * typedef struct Curl_addrinfo Curl_addrinfo; * * hostent defined in <netdb.h> * * struct hostent { * char *h_name; * char **h_aliases; * int h_addrtype; * int h_length; * char **h_addr_list; * }; * * for backward compatibility: * * #define h_addr h_addr_list[0] */ Curl_addrinfo * Curl_he2ai(const struct hostent *he, int port) { Curl_addrinfo *ai; Curl_addrinfo *prevai = NULL; Curl_addrinfo *firstai = NULL; struct sockaddr_in *addr; #ifdef ENABLE_IPV6 struct sockaddr_in6 *addr6; #endif CURLcode result = CURLE_OK; int i; char *curr; if(!he) /* no input == no output! */ return NULL; DEBUGASSERT((he->h_name != NULL) && (he->h_addr_list != NULL)); for(i = 0; (curr = he->h_addr_list[i]) != NULL; i++) { size_t ss_size; #ifdef ENABLE_IPV6 if(he->h_addrtype == AF_INET6) ss_size = sizeof(struct sockaddr_in6); else #endif ss_size = sizeof(struct sockaddr_in); ai = calloc(1, sizeof(Curl_addrinfo)); if(!ai) { result = CURLE_OUT_OF_MEMORY; break; } ai->ai_canonname = strdup(he->h_name); if(!ai->ai_canonname) { result = CURLE_OUT_OF_MEMORY; free(ai); break; } ai->ai_addr = calloc(1, ss_size); if(!ai->ai_addr) { result = CURLE_OUT_OF_MEMORY; free(ai->ai_canonname); free(ai); break; } if(!firstai) /* store the pointer we want to return from this function */ firstai = ai; if(prevai) /* make the previous entry point to this */ prevai->ai_next = ai; ai->ai_family = he->h_addrtype; /* we return all names as STREAM, so when using this address for TFTP the type must be ignored and conn->socktype be used instead! */ ai->ai_socktype = SOCK_STREAM; ai->ai_addrlen = (curl_socklen_t)ss_size; /* leave the rest of the struct filled with zero */ switch(ai->ai_family) { case AF_INET: addr = (void *)ai->ai_addr; /* storage area for this info */ memcpy(&addr->sin_addr, curr, sizeof(struct in_addr)); addr->sin_family = (CURL_SA_FAMILY_T)(he->h_addrtype); addr->sin_port = htons((unsigned short)port); break; #ifdef ENABLE_IPV6 case AF_INET6: addr6 = (void *)ai->ai_addr; /* storage area for this info */ memcpy(&addr6->sin6_addr, curr, sizeof(struct in6_addr)); addr6->sin6_family = (CURL_SA_FAMILY_T)(he->h_addrtype); addr6->sin6_port = htons((unsigned short)port); break; #endif } prevai = ai; } if(result) { Curl_freeaddrinfo(firstai); firstai = NULL; } return firstai; } struct namebuff { struct hostent hostentry; union { struct in_addr ina4; #ifdef ENABLE_IPV6 struct in6_addr ina6; #endif } addrentry; char *h_addr_list[2]; }; /* * Curl_ip2addr() * * This function takes an internet address, in binary form, as input parameter * along with its address family and the string version of the address, and it * returns a Curl_addrinfo chain filled in correctly with information for the * given address/host */ Curl_addrinfo * Curl_ip2addr(int af, const void *inaddr, const char *hostname, int port) { Curl_addrinfo *ai; #if defined(__VMS) && \ defined(__INITIAL_POINTER_SIZE) && (__INITIAL_POINTER_SIZE == 64) #pragma pointer_size save #pragma pointer_size short #pragma message disable PTRMISMATCH #endif struct hostent *h; struct namebuff *buf; char *addrentry; char *hoststr; size_t addrsize; DEBUGASSERT(inaddr && hostname); buf = malloc(sizeof(struct namebuff)); if(!buf) return NULL; hoststr = strdup(hostname); if(!hoststr) { free(buf); return NULL; } switch(af) { case AF_INET: addrsize = sizeof(struct in_addr); addrentry = (void *)&buf->addrentry.ina4; memcpy(addrentry, inaddr, sizeof(struct in_addr)); break; #ifdef ENABLE_IPV6 case AF_INET6: addrsize = sizeof(struct in6_addr); addrentry = (void *)&buf->addrentry.ina6; memcpy(addrentry, inaddr, sizeof(struct in6_addr)); break; #endif default: free(hoststr); free(buf); return NULL; } h = &buf->hostentry; h->h_name = hoststr; h->h_aliases = NULL; h->h_addrtype = (short)af; h->h_length = (short)addrsize; h->h_addr_list = &buf->h_addr_list[0]; h->h_addr_list[0] = addrentry; h->h_addr_list[1] = NULL; /* terminate list of entries */ #if defined(__VMS) && \ defined(__INITIAL_POINTER_SIZE) && (__INITIAL_POINTER_SIZE == 64) #pragma pointer_size restore #pragma message enable PTRMISMATCH #endif ai = Curl_he2ai(h, port); free(hoststr); free(buf); return ai; } /* * Given an IPv4 or IPv6 dotted string address, this converts it to a proper * allocated Curl_addrinfo struct and returns it. */ Curl_addrinfo *Curl_str2addr(char *address, int port) { struct in_addr in; if(Curl_inet_pton(AF_INET, address, &in) > 0) /* This is a dotted IP address 123.123.123.123-style */ return Curl_ip2addr(AF_INET, &in, address, port); #ifdef ENABLE_IPV6 { struct in6_addr in6; if(Curl_inet_pton(AF_INET6, address, &in6) > 0) /* This is a dotted IPv6 address ::1-style */ return Curl_ip2addr(AF_INET6, &in6, address, port); } #endif return NULL; /* bad input format */ } #ifdef USE_UNIX_SOCKETS /** * Given a path to a Unix domain socket, return a newly allocated Curl_addrinfo * struct initialized with this path. * Set '*longpath' to TRUE if the error is a too long path. */ Curl_addrinfo *Curl_unix2addr(const char *path, bool *longpath, bool abstract) { Curl_addrinfo *ai; struct sockaddr_un *sa_un; size_t path_len; *longpath = FALSE; ai = calloc(1, sizeof(Curl_addrinfo)); if(!ai) return NULL; ai->ai_addr = calloc(1, sizeof(struct sockaddr_un)); if(!ai->ai_addr) { free(ai); return NULL; } sa_un = (void *) ai->ai_addr; sa_un->sun_family = AF_UNIX; /* sun_path must be able to store the NUL-terminated path */ path_len = strlen(path) + 1; if(path_len > sizeof(sa_un->sun_path)) { free(ai->ai_addr); free(ai); *longpath = TRUE; return NULL; } ai->ai_family = AF_UNIX; ai->ai_socktype = SOCK_STREAM; /* assume reliable transport for HTTP */ ai->ai_addrlen = (curl_socklen_t) ((offsetof(struct sockaddr_un, sun_path) + path_len) & 0x7FFFFFFF); /* Abstract Unix domain socket have NULL prefix instead of suffix */ if(abstract) memcpy(sa_un->sun_path + 1, path, path_len - 1); else memcpy(sa_un->sun_path, path, path_len); /* copy NUL byte */ return ai; } #endif #if defined(CURLDEBUG) && defined(HAVE_GETADDRINFO) && \ defined(HAVE_FREEADDRINFO) /* * curl_dbg_freeaddrinfo() * * This is strictly for memory tracing and are using the same style as the * family otherwise present in memdebug.c. I put these ones here since they * require a bunch of structs I didn't want to include in memdebug.c */ void curl_dbg_freeaddrinfo(struct addrinfo *freethis, int line, const char *source) { curl_dbg_log("ADDR %s:%d freeaddrinfo(%p)\n", source, line, (void *)freethis); #ifdef USE_LWIPSOCK lwip_freeaddrinfo(freethis); #else (freeaddrinfo)(freethis); #endif } #endif /* defined(CURLDEBUG) && defined(HAVE_FREEADDRINFO) */ #if defined(CURLDEBUG) && defined(HAVE_GETADDRINFO) /* * curl_dbg_getaddrinfo() * * This is strictly for memory tracing and are using the same style as the * family otherwise present in memdebug.c. I put these ones here since they * require a bunch of structs I didn't want to include in memdebug.c */ int curl_dbg_getaddrinfo(const char *hostname, const char *service, const struct addrinfo *hints, struct addrinfo **result, int line, const char *source) { #ifdef USE_LWIPSOCK int res = lwip_getaddrinfo(hostname, service, hints, result); #else int res = (getaddrinfo)(hostname, service, hints, result); #endif if(0 == res) /* success */ curl_dbg_log("ADDR %s:%d getaddrinfo() = %p\n", source, line, (void *)*result); else curl_dbg_log("ADDR %s:%d getaddrinfo() failed\n", source, line); return res; } #endif /* defined(CURLDEBUG) && defined(HAVE_GETADDRINFO) */ #if defined(HAVE_GETADDRINFO) && defined(USE_RESOLVE_ON_IPS) /* * Work-arounds the sin6_port is always zero bug on iOS 9.3.2 and Mac OS X * 10.11.5. */ void Curl_addrinfo_set_port(Curl_addrinfo *addrinfo, int port) { Curl_addrinfo *ca; struct sockaddr_in *addr; #ifdef ENABLE_IPV6 struct sockaddr_in6 *addr6; #endif for(ca = addrinfo; ca != NULL; ca = ca->ai_next) { switch(ca->ai_family) { case AF_INET: addr = (void *)ca->ai_addr; /* storage area for this info */ addr->sin_port = htons((unsigned short)port); break; #ifdef ENABLE_IPV6 case AF_INET6: addr6 = (void *)ca->ai_addr; /* storage area for this info */ addr6->sin6_port = htons((unsigned short)port); break; #endif } } } #endif
YifuLiu/AliOS-Things
components/curl/lib/curl_addrinfo.c
C
apache-2.0
16,173
#ifndef HEADER_CURL_ADDRINFO_H #define HEADER_CURL_ADDRINFO_H /*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2019, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "curl_setup.h" #ifdef HAVE_NETINET_IN_H # include <netinet/in.h> #endif #ifdef HAVE_NETDB_H #ifdef USE_LWIPSOCK # include <lwip/netdb.h> #else # include <netdb.h> #endif #endif #ifdef HAVE_ARPA_INET_H # include <arpa/inet.h> #endif #ifdef __VMS # include <in.h> # include <inet.h> # include <stdlib.h> #endif /* * Curl_addrinfo is our internal struct definition that we use to allow * consistent internal handling of this data. We use this even when the * system provides an addrinfo structure definition. And we use this for * all sorts of IPv4 and IPV6 builds. */ struct Curl_addrinfo { int ai_flags; int ai_family; int ai_socktype; int ai_protocol; curl_socklen_t ai_addrlen; /* Follow rfc3493 struct addrinfo */ char *ai_canonname; struct sockaddr *ai_addr; struct Curl_addrinfo *ai_next; }; typedef struct Curl_addrinfo Curl_addrinfo; void Curl_freeaddrinfo(Curl_addrinfo *cahead); #ifdef HAVE_GETADDRINFO int Curl_getaddrinfo_ex(const char *nodename, const char *servname, const struct addrinfo *hints, Curl_addrinfo **result); #endif Curl_addrinfo * Curl_he2ai(const struct hostent *he, int port); Curl_addrinfo * Curl_ip2addr(int af, const void *inaddr, const char *hostname, int port); Curl_addrinfo *Curl_str2addr(char *dotted, int port); #ifdef USE_UNIX_SOCKETS Curl_addrinfo *Curl_unix2addr(const char *path, bool *longpath, bool abstract); #endif #if defined(CURLDEBUG) && defined(HAVE_GETADDRINFO) && \ defined(HAVE_FREEADDRINFO) void curl_dbg_freeaddrinfo(struct addrinfo *freethis, int line, const char *source); #endif #if defined(CURLDEBUG) && defined(HAVE_GETADDRINFO) int curl_dbg_getaddrinfo(const char *hostname, const char *service, const struct addrinfo *hints, struct addrinfo **result, int line, const char *source); #endif #ifdef HAVE_GETADDRINFO #ifdef USE_RESOLVE_ON_IPS void Curl_addrinfo_set_port(Curl_addrinfo *addrinfo, int port); #else #define Curl_addrinfo_set_port(x,y) #endif #endif #endif /* HEADER_CURL_ADDRINFO_H */
YifuLiu/AliOS-Things
components/curl/lib/curl_addrinfo.h
C
apache-2.0
3,306
#ifndef HEADER_CURL_BASE64_H #define HEADER_CURL_BASE64_H /*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2014, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ CURLcode Curl_base64_encode(struct Curl_easy *data, const char *inputbuff, size_t insize, char **outptr, size_t *outlen); CURLcode Curl_base64url_encode(struct Curl_easy *data, const char *inputbuff, size_t insize, char **outptr, size_t *outlen); CURLcode Curl_base64_decode(const char *src, unsigned char **outptr, size_t *outlen); #endif /* HEADER_CURL_BASE64_H */
YifuLiu/AliOS-Things
components/curl/lib/curl_base64.h
C
apache-2.0
1,600
#ifndef HEADER_CURL_CONFIG_BES_H #define HEADER_CURL_CONFIG_BES_H /*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2019, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ /* =============================================================== */ /* Hand crafted config file for BES */ /* =============================================================== */ /* to enable curl debug memory tracking */ /* #undef CURLDEBUG */ /* Location of default ca bundle */ /* #undef CURL_CA_BUNDLE */ /* define "1" to use built in CA store of SSL library */ /* #undef CURL_CA_FALLBACK */ /* Location of default ca path */ /* #undef CURL_CA_PATH */ /* Default SSL backend */ /* #undef CURL_DEFAULT_SSL_BACKEND */ /* to disable cookies support */ #define CURL_DISABLE_COOKIES 1 /* to disable cryptographic authentication */ #define CURL_DISABLE_CRYPTO_AUTH 1 /* to disable DICT */ #define CURL_DISABLE_DICT 1 /* to disable FILE */ #define CURL_DISABLE_FILE 1 /* to disable FTP */ #define CURL_DISABLE_FTP 1 /* to disable Gopher */ #define CURL_DISABLE_GOPHER 1 /* to disable HTTP */ /* #undef CURL_DISABLE_HTTP */ /* to disable IMAP */ #define CURL_DISABLE_IMAP 1 /* to disable LDAP */ #define CURL_DISABLE_LDAP 1 /* to disable LDAPS */ #define CURL_DISABLE_LDAPS 1 /* to disable --libcurl C code generation option */ /* #undef CURL_DISABLE_LIBCURL_OPTION */ /* if the OpenSSL configuration won't be loaded automatically */ #define CURL_DISABLE_OPENSSL_AUTO_LOAD_CONFIG 1 #define CURL_DISABLE_NTLM 1 /* to disable POP3 */ #define CURL_DISABLE_POP3 1 /* to disable proxies */ #define CURL_DISABLE_PROXY 1 /* to disable RTSP */ #define CURL_DISABLE_RTSP 1 /* to disable SMB/CIFS */ #define CURL_DISABLE_SMB 1 /* to disable SMTP */ #define CURL_DISABLE_SMTP 1 /* to disable TELNET */ #define CURL_DISABLE_TELNET 1 /* to disable TFTP */ #define CURL_DISABLE_TFTP 1 /* to disable TLS-SRP authentication */ #define CURL_DISABLE_TLS_SRP 1 /* to disable verbose strings */ /* #undef CURL_DISABLE_VERBOSE_STRINGS */ /* Definition to make a library symbol externally visible. */ /* #undef CURL_EXTERN_SYMBOL */ /* IP address type in sockaddr */ /* #undef CURL_SA_FAMILY_T sa_family_t*/ /* built with multiple SSL backends */ /* #undef CURL_WITH_MULTI_SSL */ /* enable debug build options */ #define DEBUGBUILD 1 /* your Entropy Gathering Daemon socket pathname */ /* #undef EGD_SOCKET */ /* Define if you want to enable IPv6 support */ /* #define ENABLE_IPV6 */ /* Define to the type qualifier of arg 1 for getnameinfo. */ #define GETNAMEINFO_QUAL_ARG1 const /* Define to the type of arg 1 for getnameinfo. */ #define GETNAMEINFO_TYPE_ARG1 struct sockaddr * /* Define to the type of arg 2 for getnameinfo. */ #define GETNAMEINFO_TYPE_ARG2 socklen_t /* Define to the type of args 4 and 6 for getnameinfo. */ #define GETNAMEINFO_TYPE_ARG46 size_t /* Define to the type of arg 7 for getnameinfo. */ #define GETNAMEINFO_TYPE_ARG7 unsigned int /* Specifies the number of arguments to getservbyport_r */ #define GETSERVBYPORT_R_ARGS 6 /* Specifies the size of the buffer to pass to getservbyport_r */ #define GETSERVBYPORT_R_BUFSIZE 4096 /* Define to 1 if you have the alarm function. */ /* #undef HAVE_ALARM */ /* Define to 1 if you have the <alloca.h> header file. */ /* #undef HAVE_ALLOCA_H */ /* Define to 1 if you have the <arpa/inet.h> header file. */ /* #undef HAVE_ARPA_INET_H */ /* Define to 1 if you have the <arpa/tftp.h> header file. */ /* #undef HAVE_ARPA_TFTP_H */ /* Define to 1 if you have the <assert.h> header file. */ #define HAVE_ASSERT_H 1 /* Define to 1 if you have the `basename' function. */ /* #undef HAVE_BASENAME */ /* Define to 1 if bool is an available type. */ #define HAVE_BOOL_T 1 /* Define to 1 if you have the clock_gettime function and monotonic timer. */ /* #undef HAVE_CLOCK_GETTIME_MONOTONIC */ /* Define to 1 if you have the `closesocket' function. */ /* #undef HAVE_CLOSESOCKET */ /* Define to 1 if you have the `CRYPTO_cleanup_all_ex_data' function. */ /* #under HAVE_CRYPTO_CLEANUP_ALL_EX_DATA */ /* Define to 1 if you have the <crypto.h> header file. */ #define HAVE_CRYPTO_H 1 /* Define to 1 if you have the <des.h> header file. */ #define HAVE_DES_H 1 /* Define to 1 if you have the <dlfcn.h> header file. */ /* #define HAVE_DLFCN_H */ /* Define to 1 if you have the `ENGINE_load_builtin_engines' function. */ /* #define HAVE_ENGINE_LOAD_BUILTIN_ENGINES */ /* Define to 1 if you have the <errno.h> header file. */ #define HAVE_ERRNO_H 1 /* Define to 1 if you have the <err.h> header file. */ #define HAVE_ERR_H 1 /* Define to 1 if you have the fcntl function. */ #define HAVE_FCNTL 1 /* Define to 1 if you have the <fcntl.h> header file. */ /* #define HAVE_FCNTL_H */ /* Define to 1 if you have a working fcntl O_NONBLOCK function. */ #define HAVE_FCNTL_O_NONBLOCK 1 /* Define to 1 if you have the `fork' function. */ /* #define HAVE_FORK */ /* Define to 1 if you have the freeaddrinfo function. */ #define HAVE_FREEADDRINFO 1 /* Define to 1 if you have the freeifaddrs function. */ /* #define HAVE_FREEIFADDRS */ /* Define to 1 if you have the ftruncate function. */ /* #define HAVE_FTRUNCATE */ /* Define to 1 if you have a working getaddrinfo function. */ #define HAVE_GETADDRINFO 1 /* Define to 1 if you have the `geteuid' function. */ /* #undef HAVE_GETEUID */ /* Define to 1 if you have the gethostbyaddr function. */ /* #define HAVE_GETHOSTBYADDR */ /* Define to 1 if you have the gethostbyaddr_r function. */ /* #define HAVE_GETHOSTBYADDR_R */ /* gethostbyaddr_r() takes 5 args */ /* #undef HAVE_GETHOSTBYADDR_R_5 */ /* gethostbyaddr_r() takes 7 args */ /* #undef HAVE_GETHOSTBYADDR_R_7 */ /* gethostbyaddr_r() takes 8 args */ /* #define HAVE_GETHOSTBYADDR_R_8 */ /* Define to 1 if you have the gethostbyname function. */ #define HAVE_GETHOSTBYNAME 1 /* Define to 1 if you have the gethostbyname_r function. */ #define HAVE_GETHOSTBYNAME_R 1 /* gethostbyname_r() takes 3 args */ /* #undef HAVE_GETHOSTBYNAME_R_3 */ /* gethostbyname_r() takes 5 args */ /* #undef HAVE_GETHOSTBYNAME_R_5 */ /* gethostbyname_r() takes 6 args */ #define HAVE_GETHOSTBYNAME_R_6 1 /* Define to 1 if you have the gethostname function. */ /* #define HAVE_GETHOSTNAME */ /* Define to 1 if you have a working getifaddrs function. */ /* #undef HAVE_GETIFADDRS */ /* Define to 1 if you have the getnameinfo function. */ /* #define HAVE_GETNAMEINFO */ /* Define to 1 if you have the `getpass_r' function. */ /* #undef HAVE_GETPASS_R */ /* Define to 1 if you have the `getppid' function. */ /* #define HAVE_GETPPID */ /* Define to 1 if you have the `getprotobyname' function. */ /* #define HAVE_GETPROTOBYNAME */ /* Define to 1 if you have the `getpwuid' function. */ /* #undef HAVE_GETPWUID */ /* Define to 1 if you have the `getrlimit' function. */ /* #define HAVE_GETRLIMIT */ /* Define to 1 if you have the getservbyport_r function. */ /* #undef HAVE_GETSERVBYPORT_R */ /* Define to 1 if you have the `gettimeofday' function. */ /* #undef HAVE_GETTIMEOFDAY */ /* Define to 1 if you have a working glibc-style strerror_r function. */ /* #undef HAVE_GLIBC_STRERROR_R */ /* Define to 1 if you have a working gmtime_r function. */ /* #define HAVE_GMTIME_R */ /* if you have the gssapi libraries */ /* #undef HAVE_GSSAPI */ /* Define to 1 if you have the <gssapi/gssapi_generic.h> header file. */ /* #undef HAVE_GSSAPI_GSSAPI_GENERIC_H */ /* Define to 1 if you have the <gssapi/gssapi.h> header file. */ /* #undef HAVE_GSSAPI_GSSAPI_H */ /* Define to 1 if you have the <gssapi/gssapi_krb5.h> header file. */ /* #undef HAVE_GSSAPI_GSSAPI_KRB5_H */ /* if you have the GNU gssapi libraries */ /* #undef HAVE_GSSGNU */ /* if you have the Heimdal gssapi libraries */ /* #undef HAVE_GSSHEIMDAL */ /* if you have the MIT gssapi libraries */ /* #undef HAVE_GSSMIT */ /* Define to 1 if you have the `idna_strerror' function. */ /* #undef HAVE_IDNA_STRERROR */ /* Define to 1 if you have the `idn_free' function. */ /* #undef HAVE_IDN_FREE */ /* Define to 1 if you have the <idn-free.h> header file. */ /* #undef HAVE_IDN_FREE_H */ /* Define to 1 if you have the <ifaddrs.h> header file. */ /* #undef HAVE_IFADDRS_H */ /* Define to 1 if you have the `inet_addr' function. */ /* #define HAVE_INET_ADDR */ /* Define to 1 if you have the inet_ntoa_r function. */ /* #undef HAVE_INET_NTOA_R */ /* inet_ntoa_r() takes 2 args */ /* #undef HAVE_INET_NTOA_R_2 */ /* inet_ntoa_r() takes 3 args */ /* #undef HAVE_INET_NTOA_R_3 */ /* Define to 1 if you have a IPv6 capable working inet_ntop function. */ /* #undef HAVE_INET_NTOP */ /* Define to 1 if you have a IPv6 capable working inet_pton function. */ /* #undef HAVE_INET_PTON */ /* Define to 1 if you have the <inttypes.h> header file. */ /* #define HAVE_INTTYPES_H */ /* Define to 1 if you have the ioctl function. */ #define HAVE_IOCTL 1 /* Define to 1 if you have the ioctlsocket function. */ /* #undef HAVE_IOCTLSOCKET */ /* Define to 1 if you have the IoctlSocket camel case function. */ /* #undef HAVE_IOCTLSOCKET_CAMEL */ /* Define to 1 if you have a working IoctlSocket camel case FIONBIO function. */ /* #undef HAVE_IOCTLSOCKET_CAMEL_FIONBIO */ /* Define to 1 if you have a working ioctlsocket FIONBIO function. */ /* #undef HAVE_IOCTLSOCKET_FIONBIO */ /* Define to 1 if you have a working ioctl FIONBIO function. */ /* #define HAVE_IOCTL_FIONBIO */ /* Define to 1 if you have a working ioctl SIOCGIFADDR function. */ /* #define HAVE_IOCTL_SIOCGIFADDR */ /* Define to 1 if you have the <io.h> header file. */ /* #define HAVE_IO_H */ /* if you have the Kerberos4 libraries (including -ldes) */ /* #undef HAVE_KRB4 */ /* Define to 1 if you have the `krb_get_our_ip_for_realm' function. */ /* #undef HAVE_KRB_GET_OUR_IP_FOR_REALM */ /* Define to 1 if you have the <krb.h> header file. */ /* #undef HAVE_KRB_H */ /* Define to 1 if you have the lber.h header file. */ /* #undef HAVE_LBER_H */ /* Define to 1 if you have the ldapssl.h header file. */ /* #undef HAVE_LDAPSSL_H */ /* Define to 1 if you have the ldap.h header file. */ /* #undef HAVE_LDAP_H */ /* Use LDAPS implementation */ /* #undef HAVE_LDAP_SSL */ /* Define to 1 if you have the ldap_ssl.h header file. */ /* #undef HAVE_LDAP_SSL_H */ /* Define to 1 if you have the `ldap_url_parse' function. */ /* #undef HAVE_LDAP_URL_PARSE */ /* Define to 1 if you have the <libgen.h> header file. */ /* #undef HAVE_LIBGEN_H */ /* Define to 1 if you have the `idn' library (-lidn). */ /* #undef HAVE_LIBIDN */ /* Define to 1 if you have the `resolv' library (-lresolv). */ /* #undef HAVE_LIBRESOLV */ /* Define to 1 if you have the `resolve' library (-lresolve). */ /* #undef HAVE_LIBRESOLVE */ /* Define to 1 if you have the `socket' library (-lsocket). */ /* #undef HAVE_LIBSOCKET */ /* Define to 1 if you have the `ssh2' library (-lssh2). */ /* #undef HAVE_LIBSSH2 */ /* Define to 1 if you have the <libssh2.h> header file. */ /* #undef HAVE_LIBSSH2_H */ /* Define to 1 if you have the `libssh2_version' function. */ /* #undef HAVE_LIBSSH2_VERSION */ /* Define to 1 if you have the `ssl' library (-lssl). */ /* #define HAVE_LIBSSL */ /* if zlib is available */ /* #define HAVE_LIBZ */ /* if your compiler supports LL */ /* #define HAVE_LL */ /* Define to 1 if you have the <locale.h> header file. */ /* #define HAVE_LOCALE_H */ /* Define to 1 if you have a working localtime_r function. */ /* #define HAVE_LOCALTIME_R */ /* Define to 1 if the compiler supports the 'long long' data type. */ #define HAVE_LONGLONG 1 /* Define to 1 if you have the malloc.h header file. */ #define HAVE_MALLOC_H 1 /* Define to 1 if you have the memory.h header file. */ /* #define HAVE_MEMORY_H */ /* Define to 1 if you have the MSG_NOSIGNAL flag. */ /* #undef HAVE_MSG_NOSIGNAL */ /* Define to 1 if you have the <netdb.h> header file. */ #define HAVE_NETDB_H 1 /* Define to 1 if you have the <netinet/in.h> header file. */ /* #define HAVE_NETINET_IN_H */ /* Define to 1 if you have the <netinet/tcp.h> header file. */ /* #define HAVE_NETINET_TCP_H */ /* Define to 1 if you have the <net/if.h> header file. */ /* #define HAVE_NET_IF_H */ /* Define to 1 if NI_WITHSCOPEID exists and works. */ /* #undef HAVE_NI_WITHSCOPEID */ /* if you have an old MIT gssapi library, lacking GSS_C_NT_HOSTBASED_SERVICE */ /* #undef HAVE_OLD_GSSMIT */ /* Define to 1 if you have the <openssl/crypto.h> header file. */ /* #define HAVE_OPENSSL_CRYPTO_H */ /* Define to 1 if you have the <openssl/engine.h> header file. */ /* #define HAVE_OPENSSL_ENGINE_H */ /* Define to 1 if you have the <openssl/err.h> header file. */ /* #define HAVE_OPENSSL_ERR_H */ /* Define to 1 if you have the <openssl/pem.h> header file. */ /* #define HAVE_OPENSSL_PEM_H */ /* Define to 1 if you have the <openssl/pkcs12.h> header file. */ /* #define HAVE_OPENSSL_PKCS12_H */ /* Define to 1 if you have the <openssl/rsa.h> header file. */ /* #define HAVE_OPENSSL_RSA_H */ /* Define to 1 if you have the <openssl/ssl.h> header file. */ /* #define HAVE_OPENSSL_SSL_H */ /* Define to 1 if you have the <openssl/x509.h> header file. */ /* #define HAVE_OPENSSL_X509_H */ /* Define to 1 if you have the <pem.h> header file. */ /* #undef HAVE_PEM_H */ /* Define to 1 if you have the `perror' function. */ /* #define HAVE_PERROR */ /* Define to 1 if you have the `pipe' function. */ /* #define HAVE_PIPE */ /* Define to 1 if you have a working poll function. */ /* #undef HAVE_POLL */ /* If you have a fine poll */ /* #undef HAVE_POLL_FINE */ /* Define to 1 if you have the <poll.h> header file. */ /* #undef HAVE_POLL_H */ /* Define to 1 if you have a working POSIX-style strerror_r function. */ /* #undef HAVE_POSIX_STRERROR_R */ /* Define to 1 if you have the <pwd.h> header file. */ /* #undef HAVE_PWD_H */ /* Define to 1 if you have the `RAND_egd' function. */ /* #define HAVE_RAND_EGD */ /* Define to 1 if you have the `RAND_screen' function. */ /* #undef HAVE_RAND_SCREEN */ /* Define to 1 if you have the `RAND_status' function. */ /* #define HAVE_RAND_STATUS */ /* Define to 1 if you have the recv function. */ #define HAVE_RECV 1 /* Define to 1 if you have the recvfrom function. */ #define HAVE_RECVFROM 1 /* Define to 1 if you have the <rsa.h> header file. */ #define HAVE_RSA_H 1 /* Define to 1 if you have the select function. */ #define HAVE_SELECT 1 /* Define to 1 if you have the send function. */ #define HAVE_SEND 1 /* Define to 1 if you have the <setjmp.h> header file. */ /* #define HAVE_SETJMP_H */ /* Define to 1 if you have the `setlocale' function. */ /* #define HAVE_SETLOCALE */ /* Define to 1 if you have the `setmode' function. */ /* #define HAVE_SETMODE */ /* Define to 1 if you have the `setrlimit' function. */ /* #define HAVE_SETRLIMIT */ /* Define to 1 if you have the setsockopt function. */ #define HAVE_SETSOCKOPT 1 /* Define to 1 if you have a working setsockopt SO_NONBLOCK function. */ /* #define HAVE_SETSOCKOPT_SO_NONBLOCK */ /* Define to 1 if you have the <sgtty.h> header file. */ /* #undef HAVE_SGTTY_H */ /* Define to 1 if you have the sigaction function. */ /* #define HAVE_SIGACTION */ /* Define to 1 if you have the siginterrupt function. */ /* #define HAVE_SIGINTERRUPT */ /* Define to 1 if you have the signal function. */ /* #define HAVE_SIGNAL */ /* Define to 1 if you have the <signal.h> header file. */ /* #define HAVE_SIGNAL_H */ /* Define to 1 if you have the sigsetjmp function or macro. */ /* #undef HAVE_SIGSETJMP */ /* Define to 1 if sig_atomic_t is an available typedef. */ /* #define HAVE_SIG_ATOMIC_T */ /* Define to 1 if sig_atomic_t is already defined as volatile. */ /* #undef HAVE_SIG_ATOMIC_T_VOLATILE */ /* Define to 1 if struct sockaddr_in6 has the sin6_scope_id member */ /* #define HAVE_SOCKADDR_IN6_SIN6_SCOPE_ID */ /* Define to 1 if you have the `socket' function. */ #define HAVE_SOCKET 1 /* Define to 1 if you have the `SSL_get_shutdown' function. */ /* #define HAVE_SSL_GET_SHUTDOWN */ /* Define to 1 if you have the <ssl.h> header file. */ /* #undef HAVE_SSL_H */ /* Define to 1 if you have the <stdbool.h> header file. */ #define HAVE_STDBOOL_H 1 /* Define to 1 if you have the <stdint.h> header file. */ #define HAVE_STDINT_H 1 /* Define to 1 if you have the <stdio.h> header file. */ #define HAVE_STDIO_H 1 /* Define to 1 if you have the <stdlib.h> header file. */ #define HAVE_STDLIB_H 1 /* Define to 1 if you have the strcasecmp function. */ #define HAVE_STRCASECMP 1 /* Define to 1 if you have the strcmpi function. */ /* #undef HAVE_STRCMPI */ /* Define to 1 if you have the strdup function. */ /* #define HAVE_STRDUP */ /* Define to 1 if you have the strerror_r function. */ /* #define HAVE_STRERROR_R */ /* Define to 1 if you have the stricmp function. */ /* #undef HAVE_STRICMP */ /* Define to 1 if you have the <strings.h> header file. */ /* #define HAVE_STRINGS_H */ /* Define to 1 if you have the <string.h> header file. */ #define HAVE_STRING_H 1 /* Define to 1 if you have the `strlcpy' function. */ /* #undef HAVE_STRLCPY */ /* Define to 1 if you have the strncasecmp function. */ #define HAVE_STRNCASECMP 1 /* Define to 1 if you have the strncmpi function. */ /* #undef HAVE_STRNCMPI */ /* Define to 1 if you have the strnicmp function. */ /* #undef HAVE_STRNICMP */ /* Define to 1 if you have the <stropts.h> header file. */ /* #undef HAVE_STROPTS_H */ /* Define to 1 if you have the strstr function. */ #define HAVE_STRSTR 1 /* Define to 1 if you have the strtok_r function. */ /* #define HAVE_STRTOK_R */ /* Define to 1 if you have the strtoll function. */ /* #undef HAVE_STRTOLL */ /* if struct sockaddr_storage is defined */ /* #define HAVE_STRUCT_SOCKADDR_STORAGE */ /* Define to 1 if you have the timeval struct. */ #define HAVE_STRUCT_TIMEVAL 1 /* Define to 1 if you have the <sys/filio.h> header file. */ /* #undef HAVE_SYS_FILIO_H */ /* Define to 1 if you have the <sys/ioctl.h> header file. */ /* #define HAVE_SYS_IOCTL_H */ /* Define to 1 if you have the <sys/param.h> header file. */ /* #undef HAVE_SYS_PARAM_H */ /* Define to 1 if you have the <sys/poll.h> header file. */ /* #undef HAVE_SYS_POLL_H */ /* Define to 1 if you have the <sys/resource.h> header file. */ /* #define HAVE_SYS_RESOURCE_H */ /* Define to 1 if you have the <sys/select.h> header file. */ /* #undef HAVE_SYS_SELECT_H */ /* Define to 1 if you have the <sys/socket.h> header file. */ #define HAVE_SYS_SOCKET_H 1 /* Define to 1 if you have the <sys/sockio.h> header file. */ /* #undef HAVE_SYS_SOCKIO_H */ /* Define to 1 if you have the <sys/stat.h> header file. */ #define HAVE_SYS_STAT_H 1 /* Define to 1 if you have the <sys/time.h> header file. */ /* #undef HAVE_SYS_TIME_H */ /* Define to 1 if you have the <sys/types.h> header file. */ #define HAVE_SYS_TYPES_H 1 /* Define to 1 if you have the <sys/uio.h> header file. */ /* #define HAVE_SYS_UIO_H */ /* Define to 1 if you have the <sys/un.h> header file. */ /* #define HAVE_SYS_UN_H */ /* Define to 1 if you have the <sys/utime.h> header file. */ /* #define HAVE_SYS_UTIME_H */ /* Define to 1 if you have the <termios.h> header file. */ /* #define HAVE_TERMIOS_H */ /* Define to 1 if you have the <termio.h> header file. */ /* #define HAVE_TERMIO_H */ /* Define to 1 if you have the <time.h> header file. */ #define HAVE_TIME_H 1 /* Define to 1 if you have the <tld.h> header file. */ /* #undef HAVE_TLD_H */ /* Define to 1 if you have the `tld_strerror' function. */ /* #undef HAVE_TLD_STRERROR */ /* Define to 1 if you have the `uname' function. */ #define HAVE_UNAME 1 /* Define to 1 if you have the <unistd.h> header file. */ #define HAVE_UNISTD_H 1 /* Define to 1 if you have the `utime' function. */ #define HAVE_UTIME 1 /* Define to 1 if you have the <utime.h> header file. */ #define HAVE_UTIME_H 1 /* Define to 1 if compiler supports C99 variadic macro style. */ #define HAVE_VARIADIC_MACROS_C99 1 /* Define to 1 if compiler supports old gcc variadic macro style. */ #define HAVE_VARIADIC_MACROS_GCC 1 /* Define to 1 if you have a working vxworks-style strerror_r function. */ /* #define HAVE_VXWORKS_STRERROR_R */ /* Define to 1 if you have the winber.h header file. */ /* #undef HAVE_WINBER_H */ /* Define to 1 if you have the windows.h header file. */ /* #undef HAVE_WINDOWS_H */ /* Define to 1 if you have the winldap.h header file. */ /* #undef HAVE_WINLDAP_H */ /* Define to 1 if you have the winsock2.h header file. */ /* #undef HAVE_WINSOCK2_H */ /* Define to 1 if you have the winsock.h header file. */ /* #undef HAVE_WINSOCK_H */ /* Define this symbol if your OS supports changing the contents of argv */ /* #define HAVE_WRITABLE_ARGV */ /* Define to 1 if you have the writev function. */ /* #define HAVE_WRITEV */ /* Define to 1 if you have the ws2tcpip.h header file. */ /* #undef HAVE_WS2TCPIP_H */ /* Define to 1 if you have the <x509.h> header file. */ /* #undef HAVE_X509_H */ /* if you have the zlib.h header file */ /* #define HAVE_ZLIB_H */ /* Define to 1 if you need the lber.h header file even with ldap.h */ /* #undef NEED_LBER_H */ /* Define to 1 if you need the malloc.h header file even with stdlib.h */ /* #undef NEED_MALLOC_H */ /* Define to 1 if you need the memory.h header file even with stdlib.h */ /* #undef NEED_MEMORY_H */ /* Define to 1 if _REENTRANT preprocessor symbol must be defined. */ /* #undef NEED_REENTRANT */ /* Define to 1 if _THREAD_SAFE preprocessor symbol must be defined. */ /* #undef NEED_THREAD_SAFE */ /* Define to 1 if the open function requires three arguments. */ #define OPEN_NEEDS_ARG3 1 /* cpu-machine-OS */ #define OS "BES" /* Name of package */ #define PACKAGE "curl" /* a suitable file to read random data from */ /* #define RANDOM_FILE "/dev/urandom" */ /* Define to the type of arg 1 for recvfrom. */ #define RECVFROM_TYPE_ARG1 int /* Define to the type pointed by arg 2 for recvfrom. */ #define RECVFROM_TYPE_ARG2 void /* Define to 1 if the type pointed by arg 2 for recvfrom is void. */ #define RECVFROM_TYPE_ARG2_IS_VOID 1 /* Define to the type of arg 3 for recvfrom. */ #define RECVFROM_TYPE_ARG3 size_t /* Define to the type of arg 4 for recvfrom. */ #define RECVFROM_TYPE_ARG4 int /* Define to the type pointed by arg 5 for recvfrom. */ #define RECVFROM_TYPE_ARG5 struct sockaddr /* Define to 1 if the type pointed by arg 5 for recvfrom is void. */ /* #undef RECVFROM_TYPE_ARG5_IS_VOID */ /* Define to the type pointed by arg 6 for recvfrom. */ #define RECVFROM_TYPE_ARG6 socklen_t /* Define to 1 if the type pointed by arg 6 for recvfrom is void. */ /* #undef RECVFROM_TYPE_ARG6_IS_VOID */ /* Define to the function return type for recvfrom. */ #define RECVFROM_TYPE_RETV int /* Define to the type of arg 1 for recv. */ #define RECV_TYPE_ARG1 int /* Define to the type of arg 2 for recv. */ #define RECV_TYPE_ARG2 void * /* Define to the type of arg 3 for recv. */ #define RECV_TYPE_ARG3 size_t /* Define to the type of arg 4 for recv. */ #define RECV_TYPE_ARG4 int /* Define to the function return type for recv. */ #define RECV_TYPE_RETV int /* Define as the return type of signal handlers (`int' or `void'). */ #define RETSIGTYPE void /* Define to the type qualifier of arg 5 for select. */ #define SELECT_QUAL_ARG5 /* Define to the type of arg 1 for select. */ #define SELECT_TYPE_ARG1 int /* Define to the type of args 2, 3 and 4 for select. */ #define SELECT_TYPE_ARG234 fd_set * /* Define to the type of arg 5 for select. */ #define SELECT_TYPE_ARG5 struct timeval * /* Define to the function return type for select. */ #define SELECT_TYPE_RETV int /* Define to the type qualifier of arg 2 for send. */ #define SEND_QUAL_ARG2 const /* Define to the type of arg 1 for send. */ #define SEND_TYPE_ARG1 int /* Define to the type of arg 2 for send. */ #define SEND_TYPE_ARG2 void * /* Define to the type of arg 3 for send. */ #define SEND_TYPE_ARG3 size_t /* Define to the type of arg 4 for send. */ #define SEND_TYPE_ARG4 int /* Define to the function return type for send. */ #define SEND_TYPE_RETV int /* The number of bytes in type curl_off_t */ #define SIZEOF_CURL_OFF_T 4 /* The size of `int', as computed by sizeof. */ #define SIZEOF_INT 4 /* The size of `long', as computed by sizeof. */ #define SIZEOF_LONG 4 /* The size of `off_t', as computed by sizeof. */ #define SIZEOF_OFF_T 8 /* The size of `short', as computed by sizeof. */ #define SIZEOF_SHORT 2 /* The size of `size_t', as computed by sizeof. */ #define SIZEOF_SIZE_T 4 /* The size of `time_t', as computed by sizeof. */ #define SIZEOF_TIME_T 4 /* Define to 1 if you have the ANSI C header files. */ #define STDC_HEADERS 1 /* Define to the type of arg 3 for strerror_r. */ /* #undef STRERROR_R_TYPE_ARG3 */ /* Define to 1 if you can safely include both <sys/time.h> and <time.h>. */ /* #undef TIME_WITH_SYS_TIME */ /* Define if you want to enable c-ares support */ /* #undef USE_ARES */ /* Define to disable non-blocking sockets. */ /* #undef USE_BLOCKING_SOCKETS */ /* if GnuTLS is enabled */ /* #undef USE_GNUTLS */ /* if libSSH2 is in use */ /* #undef USE_LIBSSH2 */ /* If you want to build curl with the built-in manual */ /* #define USE_MANUAL */ /* if NSS is enabled */ /* #undef USE_NSS */ /* if OpenSSL is in use */ /* #define USE_OPENSSL */ /* Define to 1 if you are building a Windows target without large file support. */ /* #undef USE_WIN32_LARGE_FILES */ /* to enable SSPI support */ /* #undef USE_WINDOWS_SSPI */ /* Define to 1 if using yaSSL in OpenSSL compatibility mode. */ /* #undef USE_YASSLEMUL */ /* Define to avoid automatic inclusion of winsock.h */ /* #undef WIN32_LEAN_AND_MEAN */ /* Define to 1 if OS is AIX. */ #ifndef _ALL_SOURCE /* # undef _ALL_SOURCE */ #endif /* Number of bits in a file offset, on hosts where this is settable. */ /* #undef _FILE_OFFSET_BITS */ /* Define for large files, on AIX-style hosts. */ /* #undef _LARGE_FILES */ /* Define to empty if `const' does not conform to ANSI C. */ /* #undef const */ /* Type to use in place of in_addr_t when system does not provide it. */ /* #undef in_addr_t */ /* Define to `__inline__' or `__inline' if that's what the C compiler calls it, or to nothing if 'inline' is not supported under any name. */ #ifndef __cplusplus /* #undef inline */ #endif /* Define to `unsigned int' if <sys/types.h> does not define. */ /* #undef size_t */ /* the signed version of size_t */ /* #undef ssize_t */ //#define CURL_DOES_CONVERSIONS // for build //#define HAVE_ICONV #endif /* HEADER_CURL_CONFIG_BES_H */
YifuLiu/AliOS-Things
components/curl/lib/curl_config.h
C
apache-2.0
27,447
/* lib/curl_config.h.in. Generated somehow by cmake. */ /* when building libcurl itself */ #cmakedefine BUILDING_LIBCURL 1 /* Location of default ca bundle */ #cmakedefine CURL_CA_BUNDLE "${CURL_CA_BUNDLE}" /* define "1" to use built-in ca store of TLS backend */ #cmakedefine CURL_CA_FALLBACK 1 /* Location of default ca path */ #cmakedefine CURL_CA_PATH "${CURL_CA_PATH}" /* to disable cookies support */ #cmakedefine CURL_DISABLE_COOKIES 1 /* to disable cryptographic authentication */ #cmakedefine CURL_DISABLE_CRYPTO_AUTH 1 /* to disable DICT */ #cmakedefine CURL_DISABLE_DICT 1 /* to disable FILE */ #cmakedefine CURL_DISABLE_FILE 1 /* to disable FTP */ #cmakedefine CURL_DISABLE_FTP 1 /* to disable GOPHER */ #cmakedefine CURL_DISABLE_GOPHER 1 /* to disable IMAP */ #cmakedefine CURL_DISABLE_IMAP 1 /* to disable HTTP */ #cmakedefine CURL_DISABLE_HTTP 1 /* to disable LDAP */ #cmakedefine CURL_DISABLE_LDAP 1 /* to disable LDAPS */ #cmakedefine CURL_DISABLE_LDAPS 1 /* to disable POP3 */ #cmakedefine CURL_DISABLE_POP3 1 /* to disable proxies */ #cmakedefine CURL_DISABLE_PROXY 1 /* to disable RTSP */ #cmakedefine CURL_DISABLE_RTSP 1 /* to disable SMB */ #cmakedefine CURL_DISABLE_SMB 1 /* to disable SMTP */ #cmakedefine CURL_DISABLE_SMTP 1 /* to disable TELNET */ #cmakedefine CURL_DISABLE_TELNET 1 /* to disable TFTP */ #cmakedefine CURL_DISABLE_TFTP 1 /* to disable verbose strings */ #cmakedefine CURL_DISABLE_VERBOSE_STRINGS 1 /* to make a symbol visible */ #cmakedefine CURL_EXTERN_SYMBOL ${CURL_EXTERN_SYMBOL} /* Ensure using CURL_EXTERN_SYMBOL is possible */ #ifndef CURL_EXTERN_SYMBOL #define CURL_EXTERN_SYMBOL #endif /* Use Windows LDAP implementation */ #cmakedefine USE_WIN32_LDAP 1 /* when not building a shared library */ #cmakedefine CURL_STATICLIB 1 /* your Entropy Gathering Daemon socket pathname */ #cmakedefine EGD_SOCKET ${EGD_SOCKET} /* Define if you want to enable IPv6 support */ #cmakedefine ENABLE_IPV6 1 /* Define to the type qualifier of arg 1 for getnameinfo. */ #cmakedefine GETNAMEINFO_QUAL_ARG1 ${GETNAMEINFO_QUAL_ARG1} /* Define to the type of arg 1 for getnameinfo. */ #cmakedefine GETNAMEINFO_TYPE_ARG1 ${GETNAMEINFO_TYPE_ARG1} /* Define to the type of arg 2 for getnameinfo. */ #cmakedefine GETNAMEINFO_TYPE_ARG2 ${GETNAMEINFO_TYPE_ARG2} /* Define to the type of args 4 and 6 for getnameinfo. */ #cmakedefine GETNAMEINFO_TYPE_ARG46 ${GETNAMEINFO_TYPE_ARG46} /* Define to the type of arg 7 for getnameinfo. */ #cmakedefine GETNAMEINFO_TYPE_ARG7 ${GETNAMEINFO_TYPE_ARG7} /* Specifies the number of arguments to getservbyport_r */ #cmakedefine GETSERVBYPORT_R_ARGS ${GETSERVBYPORT_R_ARGS} /* Specifies the size of the buffer to pass to getservbyport_r */ #cmakedefine GETSERVBYPORT_R_BUFSIZE ${GETSERVBYPORT_R_BUFSIZE} /* Define to 1 if you have the alarm function. */ #cmakedefine HAVE_ALARM 1 /* Define to 1 if you have the <alloca.h> header file. */ #cmakedefine HAVE_ALLOCA_H 1 /* Define to 1 if you have the <arpa/inet.h> header file. */ #cmakedefine HAVE_ARPA_INET_H 1 /* Define to 1 if you have the <arpa/tftp.h> header file. */ #cmakedefine HAVE_ARPA_TFTP_H 1 /* Define to 1 if you have the <assert.h> header file. */ #cmakedefine HAVE_ASSERT_H 1 /* Define to 1 if you have the `basename' function. */ #cmakedefine HAVE_BASENAME 1 /* Define to 1 if bool is an available type. */ #cmakedefine HAVE_BOOL_T 1 /* Define to 1 if you have the __builtin_available function. */ #cmakedefine HAVE_BUILTIN_AVAILABLE 1 /* Define to 1 if you have the clock_gettime function and monotonic timer. */ #cmakedefine HAVE_CLOCK_GETTIME_MONOTONIC 1 /* Define to 1 if you have the `closesocket' function. */ #cmakedefine HAVE_CLOSESOCKET 1 /* Define to 1 if you have the `CRYPTO_cleanup_all_ex_data' function. */ #cmakedefine HAVE_CRYPTO_CLEANUP_ALL_EX_DATA 1 /* Define to 1 if you have the <crypto.h> header file. */ #cmakedefine HAVE_CRYPTO_H 1 /* Define to 1 if you have the <des.h> header file. */ #cmakedefine HAVE_DES_H 1 /* Define to 1 if you have the <dlfcn.h> header file. */ #cmakedefine HAVE_DLFCN_H 1 /* Define to 1 if you have the `ENGINE_load_builtin_engines' function. */ #cmakedefine HAVE_ENGINE_LOAD_BUILTIN_ENGINES 1 /* Define to 1 if you have the <errno.h> header file. */ #cmakedefine HAVE_ERRNO_H 1 /* Define to 1 if you have the <err.h> header file. */ #cmakedefine HAVE_ERR_H 1 /* Define to 1 if you have the fcntl function. */ #cmakedefine HAVE_FCNTL 1 /* Define to 1 if you have the <fcntl.h> header file. */ #cmakedefine HAVE_FCNTL_H 1 /* Define to 1 if you have a working fcntl O_NONBLOCK function. */ #cmakedefine HAVE_FCNTL_O_NONBLOCK 1 /* Define to 1 if you have the fdopen function. */ #cmakedefine HAVE_FDOPEN 1 /* Define to 1 if you have the `fork' function. */ #cmakedefine HAVE_FORK 1 /* Define to 1 if you have the freeaddrinfo function. */ #cmakedefine HAVE_FREEADDRINFO 1 /* Define to 1 if you have the freeifaddrs function. */ #cmakedefine HAVE_FREEIFADDRS 1 /* Define to 1 if you have the ftruncate function. */ #cmakedefine HAVE_FTRUNCATE 1 /* Define to 1 if you have a working getaddrinfo function. */ #cmakedefine HAVE_GETADDRINFO 1 /* Define to 1 if you have the `geteuid' function. */ #cmakedefine HAVE_GETEUID 1 /* Define to 1 if you have the gethostbyaddr function. */ #cmakedefine HAVE_GETHOSTBYADDR 1 /* Define to 1 if you have the gethostbyaddr_r function. */ #cmakedefine HAVE_GETHOSTBYADDR_R 1 /* gethostbyaddr_r() takes 5 args */ #cmakedefine HAVE_GETHOSTBYADDR_R_5 1 /* gethostbyaddr_r() takes 7 args */ #cmakedefine HAVE_GETHOSTBYADDR_R_7 1 /* gethostbyaddr_r() takes 8 args */ #cmakedefine HAVE_GETHOSTBYADDR_R_8 1 /* Define to 1 if you have the gethostbyname function. */ #cmakedefine HAVE_GETHOSTBYNAME 1 /* Define to 1 if you have the gethostbyname_r function. */ #cmakedefine HAVE_GETHOSTBYNAME_R 1 /* gethostbyname_r() takes 3 args */ #cmakedefine HAVE_GETHOSTBYNAME_R_3 1 /* gethostbyname_r() takes 5 args */ #cmakedefine HAVE_GETHOSTBYNAME_R_5 1 /* gethostbyname_r() takes 6 args */ #cmakedefine HAVE_GETHOSTBYNAME_R_6 1 /* Define to 1 if you have the gethostname function. */ #cmakedefine HAVE_GETHOSTNAME 1 /* Define to 1 if you have a working getifaddrs function. */ #cmakedefine HAVE_GETIFADDRS 1 /* Define to 1 if you have the getnameinfo function. */ #cmakedefine HAVE_GETNAMEINFO 1 /* Define to 1 if you have the `getpass_r' function. */ #cmakedefine HAVE_GETPASS_R 1 /* Define to 1 if you have the `getppid' function. */ #cmakedefine HAVE_GETPPID 1 /* Define to 1 if you have the `getprotobyname' function. */ #cmakedefine HAVE_GETPROTOBYNAME 1 /* Define to 1 if you have the `getpeername' function. */ #cmakedefine HAVE_GETPEERNAME 1 /* Define to 1 if you have the `getsockname' function. */ #cmakedefine HAVE_GETSOCKNAME 1 /* Define to 1 if you have the `getpwuid' function. */ #cmakedefine HAVE_GETPWUID 1 /* Define to 1 if you have the `getpwuid_r' function. */ #cmakedefine HAVE_GETPWUID_R 1 /* Define to 1 if you have the `getrlimit' function. */ #cmakedefine HAVE_GETRLIMIT 1 /* Define to 1 if you have the getservbyport_r function. */ #cmakedefine HAVE_GETSERVBYPORT_R 1 /* Define to 1 if you have the `gettimeofday' function. */ #cmakedefine HAVE_GETTIMEOFDAY 1 /* Define to 1 if you have a working glibc-style strerror_r function. */ #cmakedefine HAVE_GLIBC_STRERROR_R 1 /* Define to 1 if you have a working gmtime_r function. */ #cmakedefine HAVE_GMTIME_R 1 /* if you have the gssapi libraries */ #cmakedefine HAVE_GSSAPI 1 /* Define to 1 if you have the <gssapi/gssapi_generic.h> header file. */ #cmakedefine HAVE_GSSAPI_GSSAPI_GENERIC_H 1 /* Define to 1 if you have the <gssapi/gssapi.h> header file. */ #cmakedefine HAVE_GSSAPI_GSSAPI_H 1 /* Define to 1 if you have the <gssapi/gssapi_krb5.h> header file. */ #cmakedefine HAVE_GSSAPI_GSSAPI_KRB5_H 1 /* if you have the GNU gssapi libraries */ #cmakedefine HAVE_GSSGNU 1 /* if you have the Heimdal gssapi libraries */ #cmakedefine HAVE_GSSHEIMDAL 1 /* if you have the MIT gssapi libraries */ #cmakedefine HAVE_GSSMIT 1 /* Define to 1 if you have the `idna_strerror' function. */ #cmakedefine HAVE_IDNA_STRERROR 1 /* Define to 1 if you have the `idn_free' function. */ #cmakedefine HAVE_IDN_FREE 1 /* Define to 1 if you have the <idn-free.h> header file. */ #cmakedefine HAVE_IDN_FREE_H 1 /* Define to 1 if you have the <ifaddrs.h> header file. */ #cmakedefine HAVE_IFADDRS_H 1 /* Define to 1 if you have the `inet_addr' function. */ #cmakedefine HAVE_INET_ADDR 1 /* Define to 1 if you have the inet_ntoa_r function. */ #cmakedefine HAVE_INET_NTOA_R 1 /* inet_ntoa_r() takes 2 args */ #cmakedefine HAVE_INET_NTOA_R_2 1 /* inet_ntoa_r() takes 3 args */ #cmakedefine HAVE_INET_NTOA_R_3 1 /* Define to 1 if you have a IPv6 capable working inet_ntop function. */ #cmakedefine HAVE_INET_NTOP 1 /* Define to 1 if you have a IPv6 capable working inet_pton function. */ #cmakedefine HAVE_INET_PTON 1 /* Define to 1 if you have the <inttypes.h> header file. */ #cmakedefine HAVE_INTTYPES_H 1 /* Define to 1 if you have the ioctl function. */ #cmakedefine HAVE_IOCTL 1 /* Define to 1 if you have the ioctlsocket function. */ #cmakedefine HAVE_IOCTLSOCKET 1 /* Define to 1 if you have the IoctlSocket camel case function. */ #cmakedefine HAVE_IOCTLSOCKET_CAMEL 1 /* Define to 1 if you have a working IoctlSocket camel case FIONBIO function. */ #cmakedefine HAVE_IOCTLSOCKET_CAMEL_FIONBIO 1 /* Define to 1 if you have a working ioctlsocket FIONBIO function. */ #cmakedefine HAVE_IOCTLSOCKET_FIONBIO 1 /* Define to 1 if you have a working ioctl FIONBIO function. */ #cmakedefine HAVE_IOCTL_FIONBIO 1 /* Define to 1 if you have a working ioctl SIOCGIFADDR function. */ #cmakedefine HAVE_IOCTL_SIOCGIFADDR 1 /* Define to 1 if you have the <io.h> header file. */ #cmakedefine HAVE_IO_H 1 /* if you have the Kerberos4 libraries (including -ldes) */ #cmakedefine HAVE_KRB4 1 /* Define to 1 if you have the `krb_get_our_ip_for_realm' function. */ #cmakedefine HAVE_KRB_GET_OUR_IP_FOR_REALM 1 /* Define to 1 if you have the <krb.h> header file. */ #cmakedefine HAVE_KRB_H 1 /* Define to 1 if you have the lber.h header file. */ #cmakedefine HAVE_LBER_H 1 /* Define to 1 if you have the ldapssl.h header file. */ #cmakedefine HAVE_LDAPSSL_H 1 /* Define to 1 if you have the ldap.h header file. */ #cmakedefine HAVE_LDAP_H 1 /* Use LDAPS implementation */ #cmakedefine HAVE_LDAP_SSL 1 /* Define to 1 if you have the ldap_ssl.h header file. */ #cmakedefine HAVE_LDAP_SSL_H 1 /* Define to 1 if you have the `ldap_url_parse' function. */ #cmakedefine HAVE_LDAP_URL_PARSE 1 /* Define to 1 if you have the <libgen.h> header file. */ #cmakedefine HAVE_LIBGEN_H 1 /* Define to 1 if you have the `idn' library (-lidn). */ #cmakedefine HAVE_LIBIDN 1 /* Define to 1 if you have the `resolv' library (-lresolv). */ #cmakedefine HAVE_LIBRESOLV 1 /* Define to 1 if you have the `resolve' library (-lresolve). */ #cmakedefine HAVE_LIBRESOLVE 1 /* Define to 1 if you have the `socket' library (-lsocket). */ #cmakedefine HAVE_LIBSOCKET 1 /* Define to 1 if you have the `ssh2' library (-lssh2). */ #cmakedefine HAVE_LIBSSH2 1 /* Define to 1 if libssh2 provides `libssh2_version'. */ #cmakedefine HAVE_LIBSSH2_VERSION 1 /* Define to 1 if libssh2 provides `libssh2_init'. */ #cmakedefine HAVE_LIBSSH2_INIT 1 /* Define to 1 if libssh2 provides `libssh2_exit'. */ #cmakedefine HAVE_LIBSSH2_EXIT 1 /* Define to 1 if libssh2 provides `libssh2_scp_send64'. */ #cmakedefine HAVE_LIBSSH2_SCP_SEND64 1 /* Define to 1 if libssh2 provides `libssh2_session_handshake'. */ #cmakedefine HAVE_LIBSSH2_SESSION_HANDSHAKE 1 /* Define to 1 if you have the <libssh2.h> header file. */ #cmakedefine HAVE_LIBSSH2_H 1 /* Define to 1 if you have the `ssl' library (-lssl). */ #cmakedefine HAVE_LIBSSL 1 /* if zlib is available */ #cmakedefine HAVE_LIBZ 1 /* if brotli is available */ #cmakedefine HAVE_BROTLI 1 /* if your compiler supports LL */ #cmakedefine HAVE_LL 1 /* Define to 1 if you have the <locale.h> header file. */ #cmakedefine HAVE_LOCALE_H 1 /* Define to 1 if you have a working localtime_r function. */ #cmakedefine HAVE_LOCALTIME_R 1 /* Define to 1 if the compiler supports the 'long long' data type. */ #cmakedefine HAVE_LONGLONG 1 /* Define to 1 if you have the malloc.h header file. */ #cmakedefine HAVE_MALLOC_H 1 /* Define to 1 if you have the <memory.h> header file. */ #cmakedefine HAVE_MEMORY_H 1 /* Define to 1 if you have the MSG_NOSIGNAL flag. */ #cmakedefine HAVE_MSG_NOSIGNAL 1 /* Define to 1 if you have the <netdb.h> header file. */ #cmakedefine HAVE_NETDB_H 1 /* Define to 1 if you have the <netinet/in.h> header file. */ #cmakedefine HAVE_NETINET_IN_H 1 /* Define to 1 if you have the <netinet/tcp.h> header file. */ #cmakedefine HAVE_NETINET_TCP_H 1 /* Define to 1 if you have the <net/if.h> header file. */ #cmakedefine HAVE_NET_IF_H 1 /* Define to 1 if NI_WITHSCOPEID exists and works. */ #cmakedefine HAVE_NI_WITHSCOPEID 1 /* if you have an old MIT gssapi library, lacking GSS_C_NT_HOSTBASED_SERVICE */ #cmakedefine HAVE_OLD_GSSMIT 1 /* Define to 1 if you have the <openssl/crypto.h> header file. */ #cmakedefine HAVE_OPENSSL_CRYPTO_H 1 /* Define to 1 if you have the <openssl/engine.h> header file. */ #cmakedefine HAVE_OPENSSL_ENGINE_H 1 /* Define to 1 if you have the <openssl/err.h> header file. */ #cmakedefine HAVE_OPENSSL_ERR_H 1 /* Define to 1 if you have the <openssl/pem.h> header file. */ #cmakedefine HAVE_OPENSSL_PEM_H 1 /* Define to 1 if you have the <openssl/pkcs12.h> header file. */ #cmakedefine HAVE_OPENSSL_PKCS12_H 1 /* Define to 1 if you have the <openssl/rsa.h> header file. */ #cmakedefine HAVE_OPENSSL_RSA_H 1 /* Define to 1 if you have the <openssl/ssl.h> header file. */ #cmakedefine HAVE_OPENSSL_SSL_H 1 /* Define to 1 if you have the <openssl/x509.h> header file. */ #cmakedefine HAVE_OPENSSL_X509_H 1 /* Define to 1 if you have the <pem.h> header file. */ #cmakedefine HAVE_PEM_H 1 /* Define to 1 if you have the `perror' function. */ #cmakedefine HAVE_PERROR 1 /* Define to 1 if you have the `pipe' function. */ #cmakedefine HAVE_PIPE 1 /* Define to 1 if you have a working poll function. */ #cmakedefine HAVE_POLL 1 /* If you have a fine poll */ #cmakedefine HAVE_POLL_FINE 1 /* Define to 1 if you have the <poll.h> header file. */ #cmakedefine HAVE_POLL_H 1 /* Define to 1 if you have a working POSIX-style strerror_r function. */ #cmakedefine HAVE_POSIX_STRERROR_R 1 /* Define to 1 if you have the <pthread.h> header file */ #cmakedefine HAVE_PTHREAD_H 1 /* Define to 1 if you have the <pwd.h> header file. */ #cmakedefine HAVE_PWD_H 1 /* Define to 1 if you have the `RAND_egd' function. */ #cmakedefine HAVE_RAND_EGD 1 /* Define to 1 if you have the `RAND_screen' function. */ #cmakedefine HAVE_RAND_SCREEN 1 /* Define to 1 if you have the `RAND_status' function. */ #cmakedefine HAVE_RAND_STATUS 1 /* Define to 1 if you have the recv function. */ #cmakedefine HAVE_RECV 1 /* Define to 1 if you have the recvfrom function. */ #cmakedefine HAVE_RECVFROM 1 /* Define to 1 if you have the <rsa.h> header file. */ #cmakedefine HAVE_RSA_H 1 /* Define to 1 if you have the select function. */ #cmakedefine HAVE_SELECT 1 /* Define to 1 if you have the send function. */ #cmakedefine HAVE_SEND 1 /* Define to 1 if you have the 'fsetxattr' function. */ #cmakedefine HAVE_FSETXATTR 1 /* fsetxattr() takes 5 args */ #cmakedefine HAVE_FSETXATTR_5 1 /* fsetxattr() takes 6 args */ #cmakedefine HAVE_FSETXATTR_6 1 /* Define to 1 if you have the <setjmp.h> header file. */ #cmakedefine HAVE_SETJMP_H 1 /* Define to 1 if you have the `setlocale' function. */ #cmakedefine HAVE_SETLOCALE 1 /* Define to 1 if you have the `setmode' function. */ #cmakedefine HAVE_SETMODE 1 /* Define to 1 if you have the `setrlimit' function. */ #cmakedefine HAVE_SETRLIMIT 1 /* Define to 1 if you have the setsockopt function. */ #cmakedefine HAVE_SETSOCKOPT 1 /* Define to 1 if you have a working setsockopt SO_NONBLOCK function. */ #cmakedefine HAVE_SETSOCKOPT_SO_NONBLOCK 1 /* Define to 1 if you have the <sgtty.h> header file. */ #cmakedefine HAVE_SGTTY_H 1 /* Define to 1 if you have the sigaction function. */ #cmakedefine HAVE_SIGACTION 1 /* Define to 1 if you have the siginterrupt function. */ #cmakedefine HAVE_SIGINTERRUPT 1 /* Define to 1 if you have the signal function. */ #cmakedefine HAVE_SIGNAL 1 /* Define to 1 if you have the <signal.h> header file. */ #cmakedefine HAVE_SIGNAL_H 1 /* Define to 1 if you have the sigsetjmp function or macro. */ #cmakedefine HAVE_SIGSETJMP 1 /* Define to 1 if sig_atomic_t is an available typedef. */ #cmakedefine HAVE_SIG_ATOMIC_T 1 /* Define to 1 if sig_atomic_t is already defined as volatile. */ #cmakedefine HAVE_SIG_ATOMIC_T_VOLATILE 1 /* Define to 1 if struct sockaddr_in6 has the sin6_scope_id member */ #cmakedefine HAVE_SOCKADDR_IN6_SIN6_SCOPE_ID 1 /* Define to 1 if you have the `socket' function. */ #cmakedefine HAVE_SOCKET 1 /* Define to 1 if you have the `SSL_get_shutdown' function. */ #cmakedefine HAVE_SSL_GET_SHUTDOWN 1 /* Define to 1 if you have the <ssl.h> header file. */ #cmakedefine HAVE_SSL_H 1 /* Define to 1 if you have the <stdbool.h> header file. */ #cmakedefine HAVE_STDBOOL_H 1 /* Define to 1 if you have the <stdint.h> header file. */ #cmakedefine HAVE_STDINT_H 1 /* Define to 1 if you have the <stdio.h> header file. */ #cmakedefine HAVE_STDIO_H 1 /* Define to 1 if you have the <stdlib.h> header file. */ #cmakedefine HAVE_STDLIB_H 1 /* Define to 1 if you have the strcasecmp function. */ #cmakedefine HAVE_STRCASECMP 1 /* Define to 1 if you have the strcasestr function. */ #cmakedefine HAVE_STRCASESTR 1 /* Define to 1 if you have the strcmpi function. */ #cmakedefine HAVE_STRCMPI 1 /* Define to 1 if you have the strdup function. */ #cmakedefine HAVE_STRDUP 1 /* Define to 1 if you have the strerror_r function. */ #cmakedefine HAVE_STRERROR_R 1 /* Define to 1 if you have the stricmp function. */ #cmakedefine HAVE_STRICMP 1 /* Define to 1 if you have the <strings.h> header file. */ #cmakedefine HAVE_STRINGS_H 1 /* Define to 1 if you have the <string.h> header file. */ #cmakedefine HAVE_STRING_H 1 /* Define to 1 if you have the strlcat function. */ #cmakedefine HAVE_STRLCAT 1 /* Define to 1 if you have the `strlcpy' function. */ #cmakedefine HAVE_STRLCPY 1 /* Define to 1 if you have the strncasecmp function. */ #cmakedefine HAVE_STRNCASECMP 1 /* Define to 1 if you have the strncmpi function. */ #cmakedefine HAVE_STRNCMPI 1 /* Define to 1 if you have the strnicmp function. */ #cmakedefine HAVE_STRNICMP 1 /* Define to 1 if you have the <stropts.h> header file. */ #cmakedefine HAVE_STROPTS_H 1 /* Define to 1 if you have the strstr function. */ #cmakedefine HAVE_STRSTR 1 /* Define to 1 if you have the strtok_r function. */ #cmakedefine HAVE_STRTOK_R 1 /* Define to 1 if you have the strtoll function. */ #cmakedefine HAVE_STRTOLL 1 /* if struct sockaddr_storage is defined */ #cmakedefine HAVE_STRUCT_SOCKADDR_STORAGE 1 /* Define to 1 if you have the timeval struct. */ #cmakedefine HAVE_STRUCT_TIMEVAL 1 /* Define to 1 if you have the <sys/filio.h> header file. */ #cmakedefine HAVE_SYS_FILIO_H 1 /* Define to 1 if you have the <sys/ioctl.h> header file. */ #cmakedefine HAVE_SYS_IOCTL_H 1 /* Define to 1 if you have the <sys/param.h> header file. */ #cmakedefine HAVE_SYS_PARAM_H 1 /* Define to 1 if you have the <sys/poll.h> header file. */ #cmakedefine HAVE_SYS_POLL_H 1 /* Define to 1 if you have the <sys/resource.h> header file. */ #cmakedefine HAVE_SYS_RESOURCE_H 1 /* Define to 1 if you have the <sys/select.h> header file. */ #cmakedefine HAVE_SYS_SELECT_H 1 /* Define to 1 if you have the <sys/socket.h> header file. */ #cmakedefine HAVE_SYS_SOCKET_H 1 /* Define to 1 if you have the <sys/sockio.h> header file. */ #cmakedefine HAVE_SYS_SOCKIO_H 1 /* Define to 1 if you have the <sys/stat.h> header file. */ #cmakedefine HAVE_SYS_STAT_H 1 /* Define to 1 if you have the <sys/time.h> header file. */ #cmakedefine HAVE_SYS_TIME_H 1 /* Define to 1 if you have the <sys/types.h> header file. */ #cmakedefine HAVE_SYS_TYPES_H 1 /* Define to 1 if you have the <sys/uio.h> header file. */ #cmakedefine HAVE_SYS_UIO_H 1 /* Define to 1 if you have the <sys/un.h> header file. */ #cmakedefine HAVE_SYS_UN_H 1 /* Define to 1 if you have the <sys/utime.h> header file. */ #cmakedefine HAVE_SYS_UTIME_H 1 /* Define to 1 if you have the <termios.h> header file. */ #cmakedefine HAVE_TERMIOS_H 1 /* Define to 1 if you have the <termio.h> header file. */ #cmakedefine HAVE_TERMIO_H 1 /* Define to 1 if you have the <time.h> header file. */ #cmakedefine HAVE_TIME_H 1 /* Define to 1 if you have the <tld.h> header file. */ #cmakedefine HAVE_TLD_H 1 /* Define to 1 if you have the `tld_strerror' function. */ #cmakedefine HAVE_TLD_STRERROR 1 /* Define to 1 if you have the `uname' function. */ #cmakedefine HAVE_UNAME 1 /* Define to 1 if you have the <unistd.h> header file. */ #cmakedefine HAVE_UNISTD_H 1 /* Define to 1 if you have the `utime' function. */ #cmakedefine HAVE_UTIME 1 /* Define to 1 if you have the <utime.h> header file. */ #cmakedefine HAVE_UTIME_H 1 /* Define to 1 if compiler supports C99 variadic macro style. */ #cmakedefine HAVE_VARIADIC_MACROS_C99 1 /* Define to 1 if compiler supports old gcc variadic macro style. */ #cmakedefine HAVE_VARIADIC_MACROS_GCC 1 /* Define to 1 if you have the winber.h header file. */ #cmakedefine HAVE_WINBER_H 1 /* Define to 1 if you have the windows.h header file. */ #cmakedefine HAVE_WINDOWS_H 1 /* Define to 1 if you have the winldap.h header file. */ #cmakedefine HAVE_WINLDAP_H 1 /* Define to 1 if you have the winsock2.h header file. */ #cmakedefine HAVE_WINSOCK2_H 1 /* Define to 1 if you have the winsock.h header file. */ #cmakedefine HAVE_WINSOCK_H 1 /* Define this symbol if your OS supports changing the contents of argv */ #cmakedefine HAVE_WRITABLE_ARGV 1 /* Define to 1 if you have the writev function. */ #cmakedefine HAVE_WRITEV 1 /* Define to 1 if you have the ws2tcpip.h header file. */ #cmakedefine HAVE_WS2TCPIP_H 1 /* Define to 1 if you have the <x509.h> header file. */ #cmakedefine HAVE_X509_H 1 /* Define if you have the <process.h> header file. */ #cmakedefine HAVE_PROCESS_H 1 /* if you have the zlib.h header file */ #cmakedefine HAVE_ZLIB_H 1 /* Define to the sub-directory in which libtool stores uninstalled libraries. */ #cmakedefine LT_OBJDIR ${LT_OBJDIR} /* If you lack a fine basename() prototype */ #cmakedefine NEED_BASENAME_PROTO 1 /* Define to 1 if you need the lber.h header file even with ldap.h */ #cmakedefine NEED_LBER_H 1 /* Define to 1 if you need the malloc.h header file even with stdlib.h */ #cmakedefine NEED_MALLOC_H 1 /* Define to 1 if _REENTRANT preprocessor symbol must be defined. */ #cmakedefine NEED_REENTRANT 1 /* cpu-machine-OS */ #cmakedefine OS ${OS} /* Name of package */ #cmakedefine PACKAGE ${PACKAGE} /* Define to the address where bug reports for this package should be sent. */ #cmakedefine PACKAGE_BUGREPORT ${PACKAGE_BUGREPORT} /* Define to the full name of this package. */ #cmakedefine PACKAGE_NAME ${PACKAGE_NAME} /* Define to the full name and version of this package. */ #cmakedefine PACKAGE_STRING ${PACKAGE_STRING} /* Define to the one symbol short name of this package. */ #cmakedefine PACKAGE_TARNAME ${PACKAGE_TARNAME} /* Define to the version of this package. */ #cmakedefine PACKAGE_VERSION ${PACKAGE_VERSION} /* a suitable file to read random data from */ #cmakedefine RANDOM_FILE "${RANDOM_FILE}" /* Define to the type of arg 1 for recvfrom. */ #cmakedefine RECVFROM_TYPE_ARG1 ${RECVFROM_TYPE_ARG1} /* Define to the type pointed by arg 2 for recvfrom. */ #cmakedefine RECVFROM_TYPE_ARG2 ${RECVFROM_TYPE_ARG2} /* Define to 1 if the type pointed by arg 2 for recvfrom is void. */ #cmakedefine RECVFROM_TYPE_ARG2_IS_VOID 1 /* Define to the type of arg 3 for recvfrom. */ #cmakedefine RECVFROM_TYPE_ARG3 ${RECVFROM_TYPE_ARG3} /* Define to the type of arg 4 for recvfrom. */ #cmakedefine RECVFROM_TYPE_ARG4 ${RECVFROM_TYPE_ARG4} /* Define to the type pointed by arg 5 for recvfrom. */ #cmakedefine RECVFROM_TYPE_ARG5 ${RECVFROM_TYPE_ARG5} /* Define to 1 if the type pointed by arg 5 for recvfrom is void. */ #cmakedefine RECVFROM_TYPE_ARG5_IS_VOID 1 /* Define to the type pointed by arg 6 for recvfrom. */ #cmakedefine RECVFROM_TYPE_ARG6 ${RECVFROM_TYPE_ARG6} /* Define to 1 if the type pointed by arg 6 for recvfrom is void. */ #cmakedefine RECVFROM_TYPE_ARG6_IS_VOID 1 /* Define to the function return type for recvfrom. */ #cmakedefine RECVFROM_TYPE_RETV ${RECVFROM_TYPE_RETV} /* Define to the type of arg 1 for recv. */ #cmakedefine RECV_TYPE_ARG1 ${RECV_TYPE_ARG1} /* Define to the type of arg 2 for recv. */ #cmakedefine RECV_TYPE_ARG2 ${RECV_TYPE_ARG2} /* Define to the type of arg 3 for recv. */ #cmakedefine RECV_TYPE_ARG3 ${RECV_TYPE_ARG3} /* Define to the type of arg 4 for recv. */ #cmakedefine RECV_TYPE_ARG4 ${RECV_TYPE_ARG4} /* Define to the function return type for recv. */ #cmakedefine RECV_TYPE_RETV ${RECV_TYPE_RETV} /* Define as the return type of signal handlers (`int' or `void'). */ #cmakedefine RETSIGTYPE ${RETSIGTYPE} /* Define to the type qualifier of arg 5 for select. */ #cmakedefine SELECT_QUAL_ARG5 ${SELECT_QUAL_ARG5} /* Define to the type of arg 1 for select. */ #cmakedefine SELECT_TYPE_ARG1 ${SELECT_TYPE_ARG1} /* Define to the type of args 2, 3 and 4 for select. */ #cmakedefine SELECT_TYPE_ARG234 ${SELECT_TYPE_ARG234} /* Define to the type of arg 5 for select. */ #cmakedefine SELECT_TYPE_ARG5 ${SELECT_TYPE_ARG5} /* Define to the function return type for select. */ #cmakedefine SELECT_TYPE_RETV ${SELECT_TYPE_RETV} /* Define to the type qualifier of arg 2 for send. */ #cmakedefine SEND_QUAL_ARG2 ${SEND_QUAL_ARG2} /* Define to the type of arg 1 for send. */ #cmakedefine SEND_TYPE_ARG1 ${SEND_TYPE_ARG1} /* Define to the type of arg 2 for send. */ #cmakedefine SEND_TYPE_ARG2 ${SEND_TYPE_ARG2} /* Define to the type of arg 3 for send. */ #cmakedefine SEND_TYPE_ARG3 ${SEND_TYPE_ARG3} /* Define to the type of arg 4 for send. */ #cmakedefine SEND_TYPE_ARG4 ${SEND_TYPE_ARG4} /* Define to the function return type for send. */ #cmakedefine SEND_TYPE_RETV ${SEND_TYPE_RETV} /* The size of `int', as computed by sizeof. */ #cmakedefine SIZEOF_INT ${SIZEOF_INT} /* The size of `short', as computed by sizeof. */ #cmakedefine SIZEOF_SHORT ${SIZEOF_SHORT} /* The size of `long', as computed by sizeof. */ #cmakedefine SIZEOF_LONG ${SIZEOF_LONG} /* The size of `off_t', as computed by sizeof. */ #cmakedefine SIZEOF_OFF_T ${SIZEOF_OFF_T} /* The size of `curl_off_t', as computed by sizeof. */ #cmakedefine SIZEOF_CURL_OFF_T ${SIZEOF_CURL_OFF_T} /* The size of `size_t', as computed by sizeof. */ #cmakedefine SIZEOF_SIZE_T ${SIZEOF_SIZE_T} /* The size of `time_t', as computed by sizeof. */ #cmakedefine SIZEOF_TIME_T ${SIZEOF_TIME_T} /* Define to 1 if you have the ANSI C header files. */ #cmakedefine STDC_HEADERS 1 /* Define to the type of arg 3 for strerror_r. */ #cmakedefine STRERROR_R_TYPE_ARG3 ${STRERROR_R_TYPE_ARG3} /* Define to 1 if you can safely include both <sys/time.h> and <time.h>. */ #cmakedefine TIME_WITH_SYS_TIME 1 /* Define if you want to enable c-ares support */ #cmakedefine USE_ARES 1 /* Define if you want to enable POSIX threaded DNS lookup */ #cmakedefine USE_THREADS_POSIX 1 /* Define if you want to enable WIN32 threaded DNS lookup */ #cmakedefine USE_THREADS_WIN32 1 /* Define to disable non-blocking sockets. */ #cmakedefine USE_BLOCKING_SOCKETS 1 /* if GnuTLS is enabled */ #cmakedefine USE_GNUTLS 1 /* if PolarSSL is enabled */ #cmakedefine USE_POLARSSL 1 /* if Secure Transport is enabled */ #cmakedefine USE_SECTRANSP 1 /* if mbedTLS is enabled */ #cmakedefine USE_MBEDTLS 1 /* if libSSH2 is in use */ #cmakedefine USE_LIBSSH2 1 /* If you want to build curl with the built-in manual */ #cmakedefine USE_MANUAL 1 /* if NSS is enabled */ #cmakedefine USE_NSS 1 /* if you want to use OpenLDAP code instead of legacy ldap implementation */ #cmakedefine USE_OPENLDAP 1 /* if OpenSSL is in use */ #cmakedefine USE_OPENSSL 1 /* to enable NGHTTP2 */ #cmakedefine USE_NGHTTP2 1 /* if Unix domain sockets are enabled */ #cmakedefine USE_UNIX_SOCKETS /* Define to 1 if you are building a Windows target with large file support. */ #cmakedefine USE_WIN32_LARGE_FILES 1 /* to enable SSPI support */ #cmakedefine USE_WINDOWS_SSPI 1 /* to enable Windows SSL */ #cmakedefine USE_SCHANNEL 1 /* enable multiple SSL backends */ #cmakedefine CURL_WITH_MULTI_SSL 1 /* Define to 1 if using yaSSL in OpenSSL compatibility mode. */ #cmakedefine USE_YASSLEMUL 1 /* Version number of package */ #cmakedefine VERSION ${VERSION} /* Define to 1 if OS is AIX. */ #ifndef _ALL_SOURCE # undef _ALL_SOURCE #endif /* Number of bits in a file offset, on hosts where this is settable. */ #cmakedefine _FILE_OFFSET_BITS ${_FILE_OFFSET_BITS} /* Define for large files, on AIX-style hosts. */ #cmakedefine _LARGE_FILES ${_LARGE_FILES} /* define this if you need it to compile thread-safe code */ #cmakedefine _THREAD_SAFE ${_THREAD_SAFE} /* Define to empty if `const' does not conform to ANSI C. */ #cmakedefine const ${const} /* Type to use in place of in_addr_t when system does not provide it. */ #cmakedefine in_addr_t ${in_addr_t} /* Define to `__inline__' or `__inline' if that's what the C compiler calls it, or to nothing if 'inline' is not supported under any name. */ #ifndef __cplusplus #undef inline #endif /* Define to `unsigned int' if <sys/types.h> does not define. */ #cmakedefine size_t ${size_t} /* the signed version of size_t */ #cmakedefine ssize_t ${ssize_t} /* Define to 1 if you have the mach_absolute_time function. */ #cmakedefine HAVE_MACH_ABSOLUTE_TIME 1
YifuLiu/AliOS-Things
components/curl/lib/curl_config.h.cmake
CMake
apache-2.0
29,935
/*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2018, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "curl_setup.h" #ifndef CURL_DOES_CONVERSIONS #undef _U #define _U (1<<0) /* upper case */ #undef _L #define _L (1<<1) /* lower case */ #undef _N #define _N (1<<2) /* decimal numerical digit */ #undef _S #define _S (1<<3) /* space */ #undef _P #define _P (1<<4) /* punctuation */ #undef _C #define _C (1<<5) /* control */ #undef _X #define _X (1<<6) /* hexadecimal letter */ #undef _B #define _B (1<<7) /* blank */ static const unsigned char ascii[128] = { _C, _C, _C, _C, _C, _C, _C, _C, _C, _C|_S, _C|_S, _C|_S, _C|_S, _C|_S, _C, _C, _C, _C, _C, _C, _C, _C, _C, _C, _C, _C, _C, _C, _C, _C, _C, _C, _S|_B, _P, _P, _P, _P, _P, _P, _P, _P, _P, _P, _P, _P, _P, _P, _P, _N, _N, _N, _N, _N, _N, _N, _N, _N, _N, _P, _P, _P, _P, _P, _P, _P, _U|_X, _U|_X, _U|_X, _U|_X, _U|_X, _U|_X, _U, _U, _U, _U, _U, _U, _U, _U, _U, _U, _U, _U, _U, _U, _U, _U, _U, _U, _U, _U, _P, _P, _P, _P, _P, _P, _L|_X, _L|_X, _L|_X, _L|_X, _L|_X, _L|_X, _L, _L, _L, _L, _L, _L, _L, _L, _L, _L, _L, _L, _L, _L, _L, _L, _L, _L, _L, _L, _P, _P, _P, _P, _C }; int Curl_isspace(int c) { if((c < 0) || (c >= 0x80)) return FALSE; return (ascii[c] & _S); } int Curl_isdigit(int c) { if((c < 0) || (c >= 0x80)) return FALSE; return (ascii[c] & _N); } int Curl_isalnum(int c) { if((c < 0) || (c >= 0x80)) return FALSE; return (ascii[c] & (_N|_U|_L)); } int Curl_isxdigit(int c) { if((c < 0) || (c >= 0x80)) return FALSE; return (ascii[c] & (_N|_X)); } int Curl_isgraph(int c) { if((c < 0) || (c >= 0x80) || (c == ' ')) return FALSE; return (ascii[c] & (_N|_X|_U|_L|_P|_S)); } int Curl_isprint(int c) { if((c < 0) || (c >= 0x80)) return FALSE; return (ascii[c] & (_N|_X|_U|_L|_P|_S)); } int Curl_isalpha(int c) { if((c < 0) || (c >= 0x80)) return FALSE; return (ascii[c] & (_U|_L)); } int Curl_isupper(int c) { if((c < 0) || (c >= 0x80)) return FALSE; return (ascii[c] & (_U)); } int Curl_islower(int c) { if((c < 0) || (c >= 0x80)) return FALSE; return (ascii[c] & (_L)); } int Curl_iscntrl(int c) { if((c < 0) || (c >= 0x80)) return FALSE; return (ascii[c] & (_C)); } #endif /* !CURL_DOES_CONVERSIONS */
YifuLiu/AliOS-Things
components/curl/lib/curl_ctype.c
C
apache-2.0
3,587
#ifndef HEADER_CURL_CTYPE_H #define HEADER_CURL_CTYPE_H /*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2018, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "curl_setup.h" #ifdef CURL_DOES_CONVERSIONS /* * Uppercase macro versions of ANSI/ISO is*() functions/macros which * avoid negative number inputs with argument byte codes > 127. * * For non-ASCII platforms the C library character classification routines * are used despite being locale-dependent, because this is better than * not to work at all. */ #include <ctype.h> #define ISSPACE(x) (isspace((int) ((unsigned char)x))) #define ISDIGIT(x) (isdigit((int) ((unsigned char)x))) #define ISALNUM(x) (isalnum((int) ((unsigned char)x))) #define ISXDIGIT(x) (isxdigit((int) ((unsigned char)x))) #define ISGRAPH(x) (isgraph((int) ((unsigned char)x))) #define ISALPHA(x) (isalpha((int) ((unsigned char)x))) #define ISPRINT(x) (isprint((int) ((unsigned char)x))) #define ISUPPER(x) (isupper((int) ((unsigned char)x))) #define ISLOWER(x) (islower((int) ((unsigned char)x))) #define ISCNTRL(x) (iscntrl((int) ((unsigned char)x))) #define ISASCII(x) (isascii((int) ((unsigned char)x))) #else int Curl_isspace(int c); int Curl_isdigit(int c); int Curl_isalnum(int c); int Curl_isxdigit(int c); int Curl_isgraph(int c); int Curl_isprint(int c); int Curl_isalpha(int c); int Curl_isupper(int c); int Curl_islower(int c); int Curl_iscntrl(int c); #define ISSPACE(x) (Curl_isspace((int) ((unsigned char)x))) #define ISDIGIT(x) (Curl_isdigit((int) ((unsigned char)x))) #define ISALNUM(x) (Curl_isalnum((int) ((unsigned char)x))) #define ISXDIGIT(x) (Curl_isxdigit((int) ((unsigned char)x))) #define ISGRAPH(x) (Curl_isgraph((int) ((unsigned char)x))) #define ISALPHA(x) (Curl_isalpha((int) ((unsigned char)x))) #define ISPRINT(x) (Curl_isprint((int) ((unsigned char)x))) #define ISUPPER(x) (Curl_isupper((int) ((unsigned char)x))) #define ISLOWER(x) (Curl_islower((int) ((unsigned char)x))) #define ISCNTRL(x) (Curl_iscntrl((int) ((unsigned char)x))) #define ISASCII(x) (((x) >= 0) && ((x) <= 0x80)) #endif #define ISBLANK(x) (int)((((unsigned char)x) == ' ') || \ (((unsigned char)x) == '\t')) #endif /* HEADER_CURL_CTYPE_H */
YifuLiu/AliOS-Things
components/curl/lib/curl_ctype.h
C
apache-2.0
3,193
/*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 2015, Steve Holme, <steve_holme@hotmail.com>. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "curl_setup.h" #if defined(USE_NTLM) && !defined(USE_OPENSSL) #include "curl_des.h" /* * Curl_des_set_odd_parity() * * This is used to apply odd parity to the given byte array. It is typically * used by when a cryptography engines doesn't have it's own version. * * The function is a port of the Java based oddParity() function over at: * * https://davenport.sourceforge.io/ntlm.html * * Parameters: * * bytes [in/out] - The data whose parity bits are to be adjusted for * odd parity. * len [out] - The length of the data. */ void Curl_des_set_odd_parity(unsigned char *bytes, size_t len) { size_t i; for(i = 0; i < len; i++) { unsigned char b = bytes[i]; bool needs_parity = (((b >> 7) ^ (b >> 6) ^ (b >> 5) ^ (b >> 4) ^ (b >> 3) ^ (b >> 2) ^ (b >> 1)) & 0x01) == 0; if(needs_parity) bytes[i] |= 0x01; else bytes[i] &= 0xfe; } } #endif /* USE_NTLM && !USE_OPENSSL */
YifuLiu/AliOS-Things
components/curl/lib/curl_des.c
C
apache-2.0
2,043
#ifndef HEADER_CURL_DES_H #define HEADER_CURL_DES_H /*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 2015, Steve Holme, <steve_holme@hotmail.com>. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "curl_setup.h" #if defined(USE_NTLM) && !defined(USE_OPENSSL) /* Applies odd parity to the given byte array */ void Curl_des_set_odd_parity(unsigned char *bytes, size_t length); #endif /* USE_NTLM && !USE_OPENSSL */ #endif /* HEADER_CURL_DES_H */
YifuLiu/AliOS-Things
components/curl/lib/curl_des.h
C
apache-2.0
1,330
/*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2019, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "curl_setup.h" #include "curl_endian.h" /* * Curl_read16_le() * * This function converts a 16-bit integer from the little endian format, as * used in the incoming package to whatever endian format we're using * natively. * * Parameters: * * buf [in] - A pointer to a 2 byte buffer. * * Returns the integer. */ unsigned short Curl_read16_le(const unsigned char *buf) { return (unsigned short)(((unsigned short)buf[0]) | ((unsigned short)buf[1] << 8)); } /* * Curl_read32_le() * * This function converts a 32-bit integer from the little endian format, as * used in the incoming package to whatever endian format we're using * natively. * * Parameters: * * buf [in] - A pointer to a 4 byte buffer. * * Returns the integer. */ unsigned int Curl_read32_le(const unsigned char *buf) { return ((unsigned int)buf[0]) | ((unsigned int)buf[1] << 8) | ((unsigned int)buf[2] << 16) | ((unsigned int)buf[3] << 24); } /* * Curl_read16_be() * * This function converts a 16-bit integer from the big endian format, as * used in the incoming package to whatever endian format we're using * natively. * * Parameters: * * buf [in] - A pointer to a 2 byte buffer. * * Returns the integer. */ unsigned short Curl_read16_be(const unsigned char *buf) { return (unsigned short)(((unsigned short)buf[0] << 8) | ((unsigned short)buf[1])); } #if (CURL_SIZEOF_CURL_OFF_T > 4) /* * write32_le() * * This function converts a 32-bit integer from the native endian format, * to little endian format ready for sending down the wire. * * Parameters: * * value [in] - The 32-bit integer value. * buffer [in] - A pointer to the output buffer. */ static void write32_le(const int value, unsigned char *buffer) { buffer[0] = (char)(value & 0x000000FF); buffer[1] = (char)((value & 0x0000FF00) >> 8); buffer[2] = (char)((value & 0x00FF0000) >> 16); buffer[3] = (char)((value & 0xFF000000) >> 24); } /* * Curl_write64_le() * * This function converts a 64-bit integer from the native endian format, * to little endian format ready for sending down the wire. * * Parameters: * * value [in] - The 64-bit integer value. * buffer [in] - A pointer to the output buffer. */ #if defined(HAVE_LONGLONG) void Curl_write64_le(const long long value, unsigned char *buffer) #else void Curl_write64_le(const __int64 value, unsigned char *buffer) #endif { write32_le((int)value, buffer); write32_le((int)(value >> 32), buffer + 4); } #endif /* CURL_SIZEOF_CURL_OFF_T > 4 */
YifuLiu/AliOS-Things
components/curl/lib/curl_endian.c
C
apache-2.0
3,648
#ifndef HEADER_CURL_ENDIAN_H #define HEADER_CURL_ENDIAN_H /*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2017, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ /* Converts a 16-bit integer from little endian */ unsigned short Curl_read16_le(const unsigned char *buf); /* Converts a 32-bit integer from little endian */ unsigned int Curl_read32_le(const unsigned char *buf); /* Converts a 16-bit integer from big endian */ unsigned short Curl_read16_be(const unsigned char *buf); /* Converts a 32-bit integer to little endian */ void Curl_write32_le(const int value, unsigned char *buffer); #if (CURL_SIZEOF_CURL_OFF_T > 4) /* Converts a 64-bit integer to little endian */ #if defined(HAVE_LONGLONG) void Curl_write64_le(const long long value, unsigned char *buffer); #else void Curl_write64_le(const __int64 value, unsigned char *buffer); #endif #endif #endif /* HEADER_CURL_ENDIAN_H */
YifuLiu/AliOS-Things
components/curl/lib/curl_endian.h
C
apache-2.0
1,817
/*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2019, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "curl_setup.h" #ifndef CURL_DISABLE_FTP #include <curl/curl.h> #include "curl_fnmatch.h" #include "curl_memory.h" /* The last #include file should be: */ #include "memdebug.h" #ifndef HAVE_FNMATCH #define CURLFNM_CHARSET_LEN (sizeof(char) * 256) #define CURLFNM_CHSET_SIZE (CURLFNM_CHARSET_LEN + 15) #define CURLFNM_NEGATE CURLFNM_CHARSET_LEN #define CURLFNM_ALNUM (CURLFNM_CHARSET_LEN + 1) #define CURLFNM_DIGIT (CURLFNM_CHARSET_LEN + 2) #define CURLFNM_XDIGIT (CURLFNM_CHARSET_LEN + 3) #define CURLFNM_ALPHA (CURLFNM_CHARSET_LEN + 4) #define CURLFNM_PRINT (CURLFNM_CHARSET_LEN + 5) #define CURLFNM_BLANK (CURLFNM_CHARSET_LEN + 6) #define CURLFNM_LOWER (CURLFNM_CHARSET_LEN + 7) #define CURLFNM_GRAPH (CURLFNM_CHARSET_LEN + 8) #define CURLFNM_SPACE (CURLFNM_CHARSET_LEN + 9) #define CURLFNM_UPPER (CURLFNM_CHARSET_LEN + 10) typedef enum { CURLFNM_SCHS_DEFAULT = 0, CURLFNM_SCHS_RIGHTBR, CURLFNM_SCHS_RIGHTBRLEFTBR } setcharset_state; typedef enum { CURLFNM_PKW_INIT = 0, CURLFNM_PKW_DDOT } parsekey_state; typedef enum { CCLASS_OTHER = 0, CCLASS_DIGIT, CCLASS_UPPER, CCLASS_LOWER } char_class; #define SETCHARSET_OK 1 #define SETCHARSET_FAIL 0 static int parsekeyword(unsigned char **pattern, unsigned char *charset) { parsekey_state state = CURLFNM_PKW_INIT; #define KEYLEN 10 char keyword[KEYLEN] = { 0 }; int found = FALSE; int i; unsigned char *p = *pattern; for(i = 0; !found; i++) { char c = *p++; if(i >= KEYLEN) return SETCHARSET_FAIL; switch(state) { case CURLFNM_PKW_INIT: if(ISLOWER(c)) keyword[i] = c; else if(c == ':') state = CURLFNM_PKW_DDOT; else return SETCHARSET_FAIL; break; case CURLFNM_PKW_DDOT: if(c == ']') found = TRUE; else return SETCHARSET_FAIL; } } #undef KEYLEN *pattern = p; /* move caller's pattern pointer */ if(strcmp(keyword, "digit") == 0) charset[CURLFNM_DIGIT] = 1; else if(strcmp(keyword, "alnum") == 0) charset[CURLFNM_ALNUM] = 1; else if(strcmp(keyword, "alpha") == 0) charset[CURLFNM_ALPHA] = 1; else if(strcmp(keyword, "xdigit") == 0) charset[CURLFNM_XDIGIT] = 1; else if(strcmp(keyword, "print") == 0) charset[CURLFNM_PRINT] = 1; else if(strcmp(keyword, "graph") == 0) charset[CURLFNM_GRAPH] = 1; else if(strcmp(keyword, "space") == 0) charset[CURLFNM_SPACE] = 1; else if(strcmp(keyword, "blank") == 0) charset[CURLFNM_BLANK] = 1; else if(strcmp(keyword, "upper") == 0) charset[CURLFNM_UPPER] = 1; else if(strcmp(keyword, "lower") == 0) charset[CURLFNM_LOWER] = 1; else return SETCHARSET_FAIL; return SETCHARSET_OK; } /* Return the character class. */ static char_class charclass(unsigned char c) { if(ISUPPER(c)) return CCLASS_UPPER; if(ISLOWER(c)) return CCLASS_LOWER; if(ISDIGIT(c)) return CCLASS_DIGIT; return CCLASS_OTHER; } /* Include a character or a range in set. */ static void setcharorrange(unsigned char **pp, unsigned char *charset) { unsigned char *p = (*pp)++; unsigned char c = *p++; charset[c] = 1; if(ISALNUM(c) && *p++ == '-') { char_class cc = charclass(c); unsigned char endrange = *p++; if(endrange == '\\') endrange = *p++; if(endrange >= c && charclass(endrange) == cc) { while(c++ != endrange) if(charclass(c) == cc) /* Chars in class may be not consecutive. */ charset[c] = 1; *pp = p; } } } /* returns 1 (true) if pattern is OK, 0 if is bad ("p" is pattern pointer) */ static int setcharset(unsigned char **p, unsigned char *charset) { setcharset_state state = CURLFNM_SCHS_DEFAULT; bool something_found = FALSE; unsigned char c; memset(charset, 0, CURLFNM_CHSET_SIZE); for(;;) { c = **p; if(!c) return SETCHARSET_FAIL; switch(state) { case CURLFNM_SCHS_DEFAULT: if(c == ']') { if(something_found) return SETCHARSET_OK; something_found = TRUE; state = CURLFNM_SCHS_RIGHTBR; charset[c] = 1; (*p)++; } else if(c == '[') { unsigned char *pp = *p + 1; if(*pp++ == ':' && parsekeyword(&pp, charset)) *p = pp; else { charset[c] = 1; (*p)++; } something_found = TRUE; } else if(c == '^' || c == '!') { if(!something_found) { if(charset[CURLFNM_NEGATE]) { charset[c] = 1; something_found = TRUE; } else charset[CURLFNM_NEGATE] = 1; /* negate charset */ } else charset[c] = 1; (*p)++; } else if(c == '\\') { c = *(++(*p)); if(c) setcharorrange(p, charset); else charset['\\'] = 1; something_found = TRUE; } else { setcharorrange(p, charset); something_found = TRUE; } break; case CURLFNM_SCHS_RIGHTBR: if(c == '[') { state = CURLFNM_SCHS_RIGHTBRLEFTBR; charset[c] = 1; (*p)++; } else if(c == ']') { return SETCHARSET_OK; } else if(ISPRINT(c)) { charset[c] = 1; (*p)++; state = CURLFNM_SCHS_DEFAULT; } else /* used 'goto fail' instead of 'return SETCHARSET_FAIL' to avoid a * nonsense warning 'statement not reached' at end of the fnc when * compiling on Solaris */ goto fail; break; case CURLFNM_SCHS_RIGHTBRLEFTBR: if(c == ']') return SETCHARSET_OK; state = CURLFNM_SCHS_DEFAULT; charset[c] = 1; (*p)++; break; } } fail: return SETCHARSET_FAIL; } static int loop(const unsigned char *pattern, const unsigned char *string, int maxstars) { unsigned char *p = (unsigned char *)pattern; unsigned char *s = (unsigned char *)string; unsigned char charset[CURLFNM_CHSET_SIZE] = { 0 }; for(;;) { unsigned char *pp; switch(*p) { case '*': if(!maxstars) return CURL_FNMATCH_NOMATCH; /* Regroup consecutive stars and question marks. This can be done because '*?*?*' can be expressed as '??*'. */ for(;;) { if(*++p == '\0') return CURL_FNMATCH_MATCH; if(*p == '?') { if(!*s++) return CURL_FNMATCH_NOMATCH; } else if(*p != '*') break; } /* Skip string characters until we find a match with pattern suffix. */ for(maxstars--; *s; s++) { if(loop(p, s, maxstars) == CURL_FNMATCH_MATCH) return CURL_FNMATCH_MATCH; } return CURL_FNMATCH_NOMATCH; case '?': if(!*s) return CURL_FNMATCH_NOMATCH; s++; p++; break; case '\0': return *s? CURL_FNMATCH_NOMATCH: CURL_FNMATCH_MATCH; case '\\': if(p[1]) p++; if(*s++ != *p++) return CURL_FNMATCH_NOMATCH; break; case '[': pp = p + 1; /* Copy in case of syntax error in set. */ if(setcharset(&pp, charset)) { int found = FALSE; if(!*s) return CURL_FNMATCH_NOMATCH; if(charset[(unsigned int)*s]) found = TRUE; else if(charset[CURLFNM_ALNUM]) found = ISALNUM(*s); else if(charset[CURLFNM_ALPHA]) found = ISALPHA(*s); else if(charset[CURLFNM_DIGIT]) found = ISDIGIT(*s); else if(charset[CURLFNM_XDIGIT]) found = ISXDIGIT(*s); else if(charset[CURLFNM_PRINT]) found = ISPRINT(*s); else if(charset[CURLFNM_SPACE]) found = ISSPACE(*s); else if(charset[CURLFNM_UPPER]) found = ISUPPER(*s); else if(charset[CURLFNM_LOWER]) found = ISLOWER(*s); else if(charset[CURLFNM_BLANK]) found = ISBLANK(*s); else if(charset[CURLFNM_GRAPH]) found = ISGRAPH(*s); if(charset[CURLFNM_NEGATE]) found = !found; if(!found) return CURL_FNMATCH_NOMATCH; p = pp + 1; s++; break; } /* Syntax error in set; mismatch! */ return CURL_FNMATCH_NOMATCH; default: if(*p++ != *s++) return CURL_FNMATCH_NOMATCH; break; } } } /* * @unittest: 1307 */ int Curl_fnmatch(void *ptr, const char *pattern, const char *string) { (void)ptr; /* the argument is specified by the curl_fnmatch_callback prototype, but not used by Curl_fnmatch() */ if(!pattern || !string) { return CURL_FNMATCH_FAIL; } return loop((unsigned char *)pattern, (unsigned char *)string, 2); } #else #include <fnmatch.h> /* * @unittest: 1307 */ int Curl_fnmatch(void *ptr, const char *pattern, const char *string) { int rc; (void)ptr; /* the argument is specified by the curl_fnmatch_callback prototype, but not used by Curl_fnmatch() */ if(!pattern || !string) { return CURL_FNMATCH_FAIL; } rc = fnmatch(pattern, string, 0); switch(rc) { case 0: return CURL_FNMATCH_MATCH; case FNM_NOMATCH: return CURL_FNMATCH_NOMATCH; default: return CURL_FNMATCH_FAIL; } /* not reached */ } #endif #endif /* if FTP is disabled */
YifuLiu/AliOS-Things
components/curl/lib/curl_fnmatch.c
C
apache-2.0
10,308
#ifndef HEADER_CURL_FNMATCH_H #define HEADER_CURL_FNMATCH_H /*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2009, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #define CURL_FNMATCH_MATCH 0 #define CURL_FNMATCH_NOMATCH 1 #define CURL_FNMATCH_FAIL 2 /* default pattern matching function * ================================= * Implemented with recursive backtracking, if you want to use Curl_fnmatch, * please note that there is not implemented UTF/UNICODE support. * * Implemented features: * '?' notation, does not match UTF characters * '*' can also work with UTF string * [a-zA-Z0-9] enumeration support * * keywords: alnum, digit, xdigit, alpha, print, blank, lower, graph, space * and upper (use as "[[:alnum:]]") */ int Curl_fnmatch(void *ptr, const char *pattern, const char *string); #endif /* HEADER_CURL_FNMATCH_H */
YifuLiu/AliOS-Things
components/curl/lib/curl_fnmatch.h
C
apache-2.0
1,783
/*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2019, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "curl_setup.h" #include "curl_get_line.h" #include "curl_memory.h" /* The last #include file should be: */ #include "memdebug.h" /* * get_line() makes sure to only return complete whole lines that fit in 'len' * bytes and end with a newline. */ char *Curl_get_line(char *buf, int len, FILE *input) { bool partial = FALSE; while(1) { char *b = fgets(buf, len, input); if(b) { size_t rlen = strlen(b); if(rlen && (b[rlen-1] == '\n')) { if(partial) { partial = FALSE; continue; } return b; } /* read a partial, discard the next piece that ends with newline */ partial = TRUE; } else break; } return NULL; }
YifuLiu/AliOS-Things
components/curl/lib/curl_get_line.c
C
apache-2.0
1,749
#ifndef HEADER_CURL_GET_LINE_H #define HEADER_CURL_GET_LINE_H /*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2019, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ /* get_line() makes sure to only return complete whole lines that fit in 'len' * bytes and end with a newline. */ char *Curl_get_line(char *buf, int len, FILE *input); #endif /* HEADER_CURL_GET_LINE_H */
YifuLiu/AliOS-Things
components/curl/lib/curl_get_line.h
C
apache-2.0
1,295
/*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2016, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "curl_setup.h" #include "curl_gethostname.h" /* * Curl_gethostname() is a wrapper around gethostname() which allows * overriding the host name that the function would normally return. * This capability is used by the test suite to verify exact matching * of NTLM authentication, which exercises libcurl's MD4 and DES code * as well as by the SMTP module when a hostname is not provided. * * For libcurl debug enabled builds host name overriding takes place * when environment variable CURL_GETHOSTNAME is set, using the value * held by the variable to override returned host name. * * Note: The function always returns the un-qualified hostname rather * than being provider dependent. * * For libcurl shared library release builds the test suite preloads * another shared library named libhostname using the LD_PRELOAD * mechanism which intercepts, and might override, the gethostname() * function call. In this case a given platform must support the * LD_PRELOAD mechanism and additionally have environment variable * CURL_GETHOSTNAME set in order to override the returned host name. * * For libcurl static library release builds no overriding takes place. */ int Curl_gethostname(char *name, GETHOSTNAME_TYPE_ARG2 namelen) { #ifndef HAVE_GETHOSTNAME /* Allow compilation and return failure when unavailable */ (void) name; (void) namelen; return -1; #else int err; char *dot; #ifdef DEBUGBUILD /* Override host name when environment variable CURL_GETHOSTNAME is set */ const char *force_hostname = getenv("CURL_GETHOSTNAME"); if(force_hostname) { strncpy(name, force_hostname, namelen); err = 0; } else { name[0] = '\0'; err = gethostname(name, namelen); } #else /* DEBUGBUILD */ /* The call to system's gethostname() might get intercepted by the libhostname library when libcurl is built as a non-debug shared library when running the test suite. */ name[0] = '\0'; err = gethostname(name, namelen); #endif name[namelen - 1] = '\0'; if(err) return err; /* Truncate domain, leave only machine name */ dot = strchr(name, '.'); if(dot) *dot = '\0'; return 0; #endif }
YifuLiu/AliOS-Things
components/curl/lib/curl_gethostname.c
C
apache-2.0
3,217
#ifndef HEADER_CURL_GETHOSTNAME_H #define HEADER_CURL_GETHOSTNAME_H /*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2010, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ /* Hostname buffer size */ #define HOSTNAME_MAX 1024 /* This returns the local machine's un-qualified hostname */ int Curl_gethostname(char *name, GETHOSTNAME_TYPE_ARG2 namelen); #endif /* HEADER_CURL_GETHOSTNAME_H */
YifuLiu/AliOS-Things
components/curl/lib/curl_gethostname.h
C
apache-2.0
1,315
/*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 2011 - 2018, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "curl_setup.h" #ifdef HAVE_GSSAPI #include "curl_gssapi.h" #include "sendf.h" /* The last 3 #include files should be in this order */ #include "curl_printf.h" #include "curl_memory.h" #include "memdebug.h" static char spnego_oid_bytes[] = "\x2b\x06\x01\x05\x05\x02"; gss_OID_desc Curl_spnego_mech_oid = { 6, &spnego_oid_bytes }; static char krb5_oid_bytes[] = "\x2a\x86\x48\x86\xf7\x12\x01\x02\x02"; gss_OID_desc Curl_krb5_mech_oid = { 9, &krb5_oid_bytes }; OM_uint32 Curl_gss_init_sec_context( struct Curl_easy *data, OM_uint32 *minor_status, gss_ctx_id_t *context, gss_name_t target_name, gss_OID mech_type, gss_channel_bindings_t input_chan_bindings, gss_buffer_t input_token, gss_buffer_t output_token, const bool mutual_auth, OM_uint32 *ret_flags) { OM_uint32 req_flags = GSS_C_REPLAY_FLAG; if(mutual_auth) req_flags |= GSS_C_MUTUAL_FLAG; if(data->set.gssapi_delegation & CURLGSSAPI_DELEGATION_POLICY_FLAG) { #ifdef GSS_C_DELEG_POLICY_FLAG req_flags |= GSS_C_DELEG_POLICY_FLAG; #else infof(data, "warning: support for CURLGSSAPI_DELEGATION_POLICY_FLAG not " "compiled in\n"); #endif } if(data->set.gssapi_delegation & CURLGSSAPI_DELEGATION_FLAG) req_flags |= GSS_C_DELEG_FLAG; return gss_init_sec_context(minor_status, GSS_C_NO_CREDENTIAL, /* cred_handle */ context, target_name, mech_type, req_flags, 0, /* time_req */ input_chan_bindings, input_token, NULL, /* actual_mech_type */ output_token, ret_flags, NULL /* time_rec */); } #define GSS_LOG_BUFFER_LEN 1024 static size_t display_gss_error(OM_uint32 status, int type, char *buf, size_t len) { OM_uint32 maj_stat; OM_uint32 min_stat; OM_uint32 msg_ctx = 0; gss_buffer_desc status_string; do { maj_stat = gss_display_status(&min_stat, status, type, GSS_C_NO_OID, &msg_ctx, &status_string); if(GSS_LOG_BUFFER_LEN > len + status_string.length + 3) { len += msnprintf(buf + len, GSS_LOG_BUFFER_LEN - len, "%.*s. ", (int)status_string.length, (char *)status_string.value); } gss_release_buffer(&min_stat, &status_string); } while(!GSS_ERROR(maj_stat) && msg_ctx != 0); return len; } /* * Curl_gss_log_error() * * This is used to log a GSS-API error status. * * Parameters: * * data [in] - The session handle. * prefix [in] - The prefix of the log message. * major [in] - The major status code. * minor [in] - The minor status code. */ void Curl_gss_log_error(struct Curl_easy *data, const char *prefix, OM_uint32 major, OM_uint32 minor) { char buf[GSS_LOG_BUFFER_LEN]; size_t len = 0; if(major != GSS_S_FAILURE) len = display_gss_error(major, GSS_C_GSS_CODE, buf, len); display_gss_error(minor, GSS_C_MECH_CODE, buf, len); infof(data, "%s%s\n", prefix, buf); } #endif /* HAVE_GSSAPI */
YifuLiu/AliOS-Things
components/curl/lib/curl_gssapi.c
C
apache-2.0
4,471
#ifndef HEADER_CURL_GSSAPI_H #define HEADER_CURL_GSSAPI_H /*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 2011 - 2019, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "curl_setup.h" #include "urldata.h" #ifdef HAVE_GSSAPI extern gss_OID_desc Curl_spnego_mech_oid; extern gss_OID_desc Curl_krb5_mech_oid; /* Common method for using GSS-API */ OM_uint32 Curl_gss_init_sec_context( struct Curl_easy *data, OM_uint32 *minor_status, gss_ctx_id_t *context, gss_name_t target_name, gss_OID mech_type, gss_channel_bindings_t input_chan_bindings, gss_buffer_t input_token, gss_buffer_t output_token, const bool mutual_auth, OM_uint32 *ret_flags); /* Helper to log a GSS-API error status */ void Curl_gss_log_error(struct Curl_easy *data, const char *prefix, OM_uint32 major, OM_uint32 minor); /* Provide some definitions missing in old headers */ #ifdef HAVE_OLD_GSSMIT #define GSS_C_NT_HOSTBASED_SERVICE gss_nt_service_name #define NCOMPAT 1 #endif /* Define our privacy and integrity protection values */ #define GSSAUTH_P_NONE 1 #define GSSAUTH_P_INTEGRITY 2 #define GSSAUTH_P_PRIVACY 4 #endif /* HAVE_GSSAPI */ #endif /* HEADER_CURL_GSSAPI_H */
YifuLiu/AliOS-Things
components/curl/lib/curl_gssapi.h
C
apache-2.0
2,144
#ifndef HEADER_CURL_HMAC_H #define HEADER_CURL_HMAC_H /*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2016, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #ifndef CURL_DISABLE_CRYPTO_AUTH typedef void (* HMAC_hinit_func)(void *context); typedef void (* HMAC_hupdate_func)(void *context, const unsigned char *data, unsigned int len); typedef void (* HMAC_hfinal_func)(unsigned char *result, void *context); /* Per-hash function HMAC parameters. */ typedef struct { HMAC_hinit_func hmac_hinit; /* Initialize context procedure. */ HMAC_hupdate_func hmac_hupdate; /* Update context with data. */ HMAC_hfinal_func hmac_hfinal; /* Get final result procedure. */ unsigned int hmac_ctxtsize; /* Context structure size. */ unsigned int hmac_maxkeylen; /* Maximum key length (bytes). */ unsigned int hmac_resultlen; /* Result length (bytes). */ } HMAC_params; /* HMAC computation context. */ typedef struct { const HMAC_params *hmac_hash; /* Hash function definition. */ void *hmac_hashctxt1; /* Hash function context 1. */ void *hmac_hashctxt2; /* Hash function context 2. */ } HMAC_context; /* Prototypes. */ HMAC_context * Curl_HMAC_init(const HMAC_params *hashparams, const unsigned char *key, unsigned int keylen); int Curl_HMAC_update(HMAC_context *context, const unsigned char *data, unsigned int len); int Curl_HMAC_final(HMAC_context *context, unsigned char *result); #endif #endif /* HEADER_CURL_HMAC_H */
YifuLiu/AliOS-Things
components/curl/lib/curl_hmac.h
C
apache-2.0
2,617
#ifndef HEADER_CURL_LDAP_H #define HEADER_CURL_LDAP_H /*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2010, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #ifndef CURL_DISABLE_LDAP extern const struct Curl_handler Curl_handler_ldap; #if !defined(CURL_DISABLE_LDAPS) && \ ((defined(USE_OPENLDAP) && defined(USE_SSL)) || \ (!defined(USE_OPENLDAP) && defined(HAVE_LDAP_SSL))) extern const struct Curl_handler Curl_handler_ldaps; #endif #endif #endif /* HEADER_CURL_LDAP_H */
YifuLiu/AliOS-Things
components/curl/lib/curl_ldap.h
C
apache-2.0
1,408
#ifndef HEADER_CURL_MD4_H #define HEADER_CURL_MD4_H /*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2019, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "curl_setup.h" #if defined(USE_NSS) || defined(USE_OS400CRYPTO) || \ (defined(USE_OPENSSL) && defined(OPENSSL_NO_MD4)) || \ (defined(USE_MBEDTLS) && !defined(MBEDTLS_MD4_C)) void Curl_md4it(unsigned char *output, const unsigned char *input, size_t len); #endif /* defined(USE_NSS) || defined(USE_OS400CRYPTO) || (defined(USE_OPENSSL) && defined(OPENSSL_NO_MD4)) || (defined(USE_MBEDTLS) && !defined(MBEDTLS_MD4_C)) */ #endif /* HEADER_CURL_MD4_H */
YifuLiu/AliOS-Things
components/curl/lib/curl_md4.h
C
apache-2.0
1,557
#ifndef HEADER_CURL_MD5_H #define HEADER_CURL_MD5_H /*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2019, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #ifndef CURL_DISABLE_CRYPTO_AUTH #include "curl_hmac.h" #define MD5_DIGEST_LEN 16 typedef void (* Curl_MD5_init_func)(void *context); typedef void (* Curl_MD5_update_func)(void *context, const unsigned char *data, unsigned int len); typedef void (* Curl_MD5_final_func)(unsigned char *result, void *context); typedef struct { Curl_MD5_init_func md5_init_func; /* Initialize context procedure */ Curl_MD5_update_func md5_update_func; /* Update context with data */ Curl_MD5_final_func md5_final_func; /* Get final result procedure */ unsigned int md5_ctxtsize; /* Context structure size */ unsigned int md5_resultlen; /* Result length (bytes) */ } MD5_params; typedef struct { const MD5_params *md5_hash; /* Hash function definition */ void *md5_hashctx; /* Hash function context */ } MD5_context; extern const MD5_params Curl_DIGEST_MD5[1]; extern const HMAC_params Curl_HMAC_MD5[1]; void Curl_md5it(unsigned char *output, const unsigned char *input); MD5_context * Curl_MD5_init(const MD5_params *md5params); CURLcode Curl_MD5_update(MD5_context *context, const unsigned char *data, unsigned int len); CURLcode Curl_MD5_final(MD5_context *context, unsigned char *result); #endif #endif /* HEADER_CURL_MD5_H */
YifuLiu/AliOS-Things
components/curl/lib/curl_md5.h
C
apache-2.0
2,518
#ifndef HEADER_CURL_MEMORY_H #define HEADER_CURL_MEMORY_H /*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2019, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ /* * Nasty internal details ahead... * * File curl_memory.h must be included by _all_ *.c source files * that use memory related functions strdup, malloc, calloc, realloc * or free, and given source file is used to build libcurl library. * It should be included immediately before memdebug.h as the last files * included to avoid undesired interaction with other memory function * headers in dependent libraries. * * There is nearly no exception to above rule. All libcurl source * files in 'lib' subdirectory as well as those living deep inside * 'packages' subdirectories and linked together in order to build * libcurl library shall follow it. * * File lib/strdup.c is an exception, given that it provides a strdup * clone implementation while using malloc. Extra care needed inside * this one. * * The need for curl_memory.h inclusion is due to libcurl's feature * of allowing library user to provide memory replacement functions, * memory callbacks, at runtime with curl_global_init_mem() * * Any *.c source file used to build libcurl library that does not * include curl_memory.h and uses any memory function of the five * mentioned above will compile without any indication, but it will * trigger weird memory related issues at runtime. * * OTOH some source files from 'lib' subdirectory may additionally be * used directly as source code when using some curlx_ functions by * third party programs that don't even use libcurl at all. When using * these source files in this way it is necessary these are compiled * with CURLX_NO_MEMORY_CALLBACKS defined, in order to ensure that no * attempt of calling libcurl's memory callbacks is done from code * which can not use this machinery. * * Notice that libcurl's 'memory tracking' system works chaining into * the memory callback machinery. This implies that when compiling * 'lib' source files with CURLX_NO_MEMORY_CALLBACKS defined this file * disengages usage of libcurl's 'memory tracking' system, defining * MEMDEBUG_NODEFINES and overriding CURLDEBUG purpose. * * CURLX_NO_MEMORY_CALLBACKS takes precedence over CURLDEBUG. This is * done in order to allow building a 'memory tracking' enabled libcurl * and at the same time allow building programs which do not use it. * * Programs and libraries in 'tests' subdirectories have specific * purposes and needs, and as such each one will use whatever fits * best, depending additionally whether it links with libcurl or not. * * Caveat emptor. Proper curlx_* separation is a work in progress * the same as CURLX_NO_MEMORY_CALLBACKS usage, some adjustments may * still be required. IOW don't use them yet, there are sharp edges. */ #ifdef HEADER_CURL_MEMDEBUG_H #error "Header memdebug.h shall not be included before curl_memory.h" #endif #ifndef CURLX_NO_MEMORY_CALLBACKS #ifndef CURL_DID_MEMORY_FUNC_TYPEDEFS /* only if not already done */ /* * The following memory function replacement typedef's are COPIED from * curl/curl.h and MUST match the originals. We copy them to avoid having to * include curl/curl.h here. We avoid that include since it includes stdio.h * and other headers that may get messed up with defines done here. */ typedef void *(*curl_malloc_callback)(size_t size); typedef void (*curl_free_callback)(void *ptr); typedef void *(*curl_realloc_callback)(void *ptr, size_t size); typedef char *(*curl_strdup_callback)(const char *str); typedef void *(*curl_calloc_callback)(size_t nmemb, size_t size); #define CURL_DID_MEMORY_FUNC_TYPEDEFS #endif extern curl_malloc_callback Curl_cmalloc; extern curl_free_callback Curl_cfree; extern curl_realloc_callback Curl_crealloc; extern curl_strdup_callback Curl_cstrdup; extern curl_calloc_callback Curl_ccalloc; #if defined(WIN32) && defined(UNICODE) extern curl_wcsdup_callback Curl_cwcsdup; #endif #ifndef CURLDEBUG /* * libcurl's 'memory tracking' system defines strdup, malloc, calloc, * realloc and free, along with others, in memdebug.h in a different * way although still using memory callbacks forward declared above. * When using the 'memory tracking' system (CURLDEBUG defined) we do * not define here the five memory functions given that definitions * from memdebug.h are the ones that shall be used. */ #undef strdup #define strdup(ptr) Curl_cstrdup(ptr) #undef malloc #define malloc(size) Curl_cmalloc(size) #undef calloc #define calloc(nbelem,size) Curl_ccalloc(nbelem, size) #undef realloc #define realloc(ptr,size) Curl_crealloc(ptr, size) #undef free #define free(ptr) Curl_cfree(ptr) #ifdef WIN32 # ifdef UNICODE # undef wcsdup # define wcsdup(ptr) Curl_cwcsdup(ptr) # undef _wcsdup # define _wcsdup(ptr) Curl_cwcsdup(ptr) # undef _tcsdup # define _tcsdup(ptr) Curl_cwcsdup(ptr) # else # undef _tcsdup # define _tcsdup(ptr) Curl_cstrdup(ptr) # endif #endif #endif /* CURLDEBUG */ #else /* CURLX_NO_MEMORY_CALLBACKS */ #ifndef MEMDEBUG_NODEFINES #define MEMDEBUG_NODEFINES #endif #endif /* CURLX_NO_MEMORY_CALLBACKS */ #endif /* HEADER_CURL_MEMORY_H */
YifuLiu/AliOS-Things
components/curl/lib/curl_memory.h
C
apache-2.0
6,128
/*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2018, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "curl_setup.h" #include <curl/curl.h> #include "curl_memrchr.h" #include "curl_memory.h" /* The last #include file should be: */ #include "memdebug.h" #ifndef HAVE_MEMRCHR /* * Curl_memrchr() * * Our memrchr() function clone for systems which lack this function. The * memrchr() function is like the memchr() function, except that it searches * backwards from the end of the n bytes pointed to by s instead of forward * from the beginning. */ void * Curl_memrchr(const void *s, int c, size_t n) { if(n > 0) { const unsigned char *p = s; const unsigned char *q = s; p += n - 1; while(p >= q) { if(*p == (unsigned char)c) return (void *)p; p--; } } return NULL; } #endif /* HAVE_MEMRCHR */
YifuLiu/AliOS-Things
components/curl/lib/curl_memrchr.c
C
apache-2.0
1,786
#ifndef HEADER_CURL_MEMRCHR_H #define HEADER_CURL_MEMRCHR_H /*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2009, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "curl_setup.h" #ifdef HAVE_MEMRCHR #ifdef HAVE_STRING_H # include <string.h> #endif #ifdef HAVE_STRINGS_H # include <strings.h> #endif #else /* HAVE_MEMRCHR */ void *Curl_memrchr(const void *s, int c, size_t n); #define memrchr(x,y,z) Curl_memrchr((x),(y),(z)) #endif /* HAVE_MEMRCHR */ #endif /* HEADER_CURL_MEMRCHR_H */
YifuLiu/AliOS-Things
components/curl/lib/curl_memrchr.h
C
apache-2.0
1,427
/*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2015, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "curl_setup.h" #include <curl/curl.h> #if defined(USE_WIN32_IDN) || ((defined(USE_WINDOWS_SSPI) || \ defined(USE_WIN32_LDAP)) && defined(UNICODE)) /* * MultiByte conversions using Windows kernel32 library. */ #include "curl_multibyte.h" #include "curl_memory.h" /* The last #include file should be: */ #include "memdebug.h" wchar_t *Curl_convert_UTF8_to_wchar(const char *str_utf8) { wchar_t *str_w = NULL; if(str_utf8) { int str_w_len = MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, str_utf8, -1, NULL, 0); if(str_w_len > 0) { str_w = malloc(str_w_len * sizeof(wchar_t)); if(str_w) { if(MultiByteToWideChar(CP_UTF8, 0, str_utf8, -1, str_w, str_w_len) == 0) { free(str_w); return NULL; } } } } return str_w; } char *Curl_convert_wchar_to_UTF8(const wchar_t *str_w) { char *str_utf8 = NULL; if(str_w) { int bytes = WideCharToMultiByte(CP_UTF8, 0, str_w, -1, NULL, 0, NULL, NULL); if(bytes > 0) { str_utf8 = malloc(bytes); if(str_utf8) { if(WideCharToMultiByte(CP_UTF8, 0, str_w, -1, str_utf8, bytes, NULL, NULL) == 0) { free(str_utf8); return NULL; } } } } return str_utf8; } #endif /* USE_WIN32_IDN || ((USE_WINDOWS_SSPI || USE_WIN32_LDAP) && UNICODE) */
YifuLiu/AliOS-Things
components/curl/lib/curl_multibyte.c
C
apache-2.0
2,531
#ifndef HEADER_CURL_MULTIBYTE_H #define HEADER_CURL_MULTIBYTE_H /*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2015, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "curl_setup.h" #if defined(USE_WIN32_IDN) || ((defined(USE_WINDOWS_SSPI) || \ defined(USE_WIN32_LDAP)) && defined(UNICODE)) /* * MultiByte conversions using Windows kernel32 library. */ wchar_t *Curl_convert_UTF8_to_wchar(const char *str_utf8); char *Curl_convert_wchar_to_UTF8(const wchar_t *str_w); #endif /* USE_WIN32_IDN || ((USE_WINDOWS_SSPI || USE_WIN32_LDAP) && UNICODE) */ #if defined(USE_WIN32_IDN) || defined(USE_WINDOWS_SSPI) || \ defined(USE_WIN32_LDAP) /* * Macros Curl_convert_UTF8_to_tchar(), Curl_convert_tchar_to_UTF8() * and Curl_unicodefree() main purpose is to minimize the number of * preprocessor conditional directives needed by code using these * to differentiate UNICODE from non-UNICODE builds. * * When building with UNICODE defined, this two macros * Curl_convert_UTF8_to_tchar() and Curl_convert_tchar_to_UTF8() * return a pointer to a newly allocated memory area holding result. * When the result is no longer needed, allocated memory is intended * to be free'ed with Curl_unicodefree(). * * When building without UNICODE defined, this macros * Curl_convert_UTF8_to_tchar() and Curl_convert_tchar_to_UTF8() * return the pointer received as argument. Curl_unicodefree() does * no actual free'ing of this pointer it is simply set to NULL. */ #ifdef UNICODE #define Curl_convert_UTF8_to_tchar(ptr) Curl_convert_UTF8_to_wchar((ptr)) #define Curl_convert_tchar_to_UTF8(ptr) Curl_convert_wchar_to_UTF8((ptr)) #define Curl_unicodefree(ptr) \ do {if((ptr)) {free((ptr)); (ptr) = NULL;}} WHILE_FALSE typedef union { unsigned short *tchar_ptr; const unsigned short *const_tchar_ptr; unsigned short *tbyte_ptr; const unsigned short *const_tbyte_ptr; } xcharp_u; #else #define Curl_convert_UTF8_to_tchar(ptr) (ptr) #define Curl_convert_tchar_to_UTF8(ptr) (ptr) #define Curl_unicodefree(ptr) \ do {(ptr) = NULL;} WHILE_FALSE typedef union { char *tchar_ptr; const char *const_tchar_ptr; unsigned char *tbyte_ptr; const unsigned char *const_tbyte_ptr; } xcharp_u; #endif /* UNICODE */ #endif /* USE_WIN32_IDN || USE_WINDOWS_SSPI || USE_WIN32_LDAP */ #endif /* HEADER_CURL_MULTIBYTE_H */
YifuLiu/AliOS-Things
components/curl/lib/curl_multibyte.h
C
apache-2.0
3,337
/*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2019, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "curl_setup.h" #if defined(USE_NTLM) /* * NTLM details: * * https://davenport.sourceforge.io/ntlm.html * https://www.innovation.ch/java/ntlm.html */ /* Please keep the SSL backend-specific #if branches in this order: 1. USE_OPENSSL 2. USE_GNUTLS_NETTLE 3. USE_GNUTLS 4. USE_NSS 5. USE_MBEDTLS 6. USE_SECTRANSP 7. USE_OS400CRYPTO 8. USE_WIN32_CRYPTO This ensures that: - the same SSL branch gets activated throughout this source file even if multiple backends are enabled at the same time. - OpenSSL and NSS have higher priority than Windows Crypt, due to issues with the latter supporting NTLM2Session responses in NTLM type-3 messages. */ #if !defined(USE_WINDOWS_SSPI) || defined(USE_WIN32_CRYPTO) #ifdef USE_OPENSSL # include <openssl/des.h> # ifndef OPENSSL_NO_MD4 # include <openssl/md4.h> # else # include "curl_md4.h" # endif # include <openssl/md5.h> # include <openssl/ssl.h> # include <openssl/rand.h> # if (OPENSSL_VERSION_NUMBER < 0x00907001L) # define DES_key_schedule des_key_schedule # define DES_cblock des_cblock # define DES_set_odd_parity des_set_odd_parity # define DES_set_key des_set_key # define DES_ecb_encrypt des_ecb_encrypt # define DESKEY(x) x # define DESKEYARG(x) x # else # define DESKEYARG(x) *x # define DESKEY(x) &x # endif #elif defined(USE_GNUTLS_NETTLE) # include <nettle/des.h> # include <nettle/md4.h> #elif defined(USE_GNUTLS) # include <gcrypt.h> # define MD5_DIGEST_LENGTH 16 # define MD4_DIGEST_LENGTH 16 #elif defined(USE_NSS) # include <nss.h> # include <pk11pub.h> # include <hasht.h> # include "curl_md4.h" # define MD5_DIGEST_LENGTH MD5_LENGTH #elif defined(USE_MBEDTLS) # include <mbedtls/des.h> # include <mbedtls/md4.h> # if !defined(MBEDTLS_MD4_C) # include "curl_md4.h" # endif #elif defined(USE_SECTRANSP) # include <CommonCrypto/CommonCryptor.h> # include <CommonCrypto/CommonDigest.h> #elif defined(USE_OS400CRYPTO) # include "cipher.mih" /* mih/cipher */ # include "curl_md4.h" #elif defined(USE_WIN32_CRYPTO) # include <wincrypt.h> #else # error "Can't compile NTLM support without a crypto library." #endif #include "urldata.h" #include "non-ascii.h" #include "strcase.h" #include "curl_ntlm_core.h" #include "curl_md5.h" #include "curl_hmac.h" #include "warnless.h" #include "curl_endian.h" #include "curl_des.h" /* The last 3 #include files should be in this order */ #include "curl_printf.h" #include "curl_memory.h" #include "memdebug.h" #define NTLM_HMAC_MD5_LEN (16) #define NTLMv2_BLOB_SIGNATURE "\x01\x01\x00\x00" #define NTLMv2_BLOB_LEN (44 -16 + ntlm->target_info_len + 4) /* * Turns a 56-bit key into being 64-bit wide. */ static void extend_key_56_to_64(const unsigned char *key_56, char *key) { key[0] = key_56[0]; key[1] = (unsigned char)(((key_56[0] << 7) & 0xFF) | (key_56[1] >> 1)); key[2] = (unsigned char)(((key_56[1] << 6) & 0xFF) | (key_56[2] >> 2)); key[3] = (unsigned char)(((key_56[2] << 5) & 0xFF) | (key_56[3] >> 3)); key[4] = (unsigned char)(((key_56[3] << 4) & 0xFF) | (key_56[4] >> 4)); key[5] = (unsigned char)(((key_56[4] << 3) & 0xFF) | (key_56[5] >> 5)); key[6] = (unsigned char)(((key_56[5] << 2) & 0xFF) | (key_56[6] >> 6)); key[7] = (unsigned char) ((key_56[6] << 1) & 0xFF); } #ifdef USE_OPENSSL /* * Turns a 56 bit key into the 64 bit, odd parity key and sets the key. The * key schedule ks is also set. */ static void setup_des_key(const unsigned char *key_56, DES_key_schedule DESKEYARG(ks)) { DES_cblock key; /* Expand the 56-bit key to 64-bits */ extend_key_56_to_64(key_56, (char *) &key); /* Set the key parity to odd */ DES_set_odd_parity(&key); /* Set the key */ DES_set_key(&key, ks); } #elif defined(USE_GNUTLS_NETTLE) static void setup_des_key(const unsigned char *key_56, struct des_ctx *des) { char key[8]; /* Expand the 56-bit key to 64-bits */ extend_key_56_to_64(key_56, key); /* Set the key parity to odd */ Curl_des_set_odd_parity((unsigned char *) key, sizeof(key)); /* Set the key */ des_set_key(des, (const uint8_t *) key); } #elif defined(USE_GNUTLS) /* * Turns a 56 bit key into the 64 bit, odd parity key and sets the key. */ static void setup_des_key(const unsigned char *key_56, gcry_cipher_hd_t *des) { char key[8]; /* Expand the 56-bit key to 64-bits */ extend_key_56_to_64(key_56, key); /* Set the key parity to odd */ Curl_des_set_odd_parity((unsigned char *) key, sizeof(key)); /* Set the key */ gcry_cipher_setkey(*des, key, sizeof(key)); } #elif defined(USE_NSS) /* * Expands a 56 bit key KEY_56 to 64 bit and encrypts 64 bit of data, using * the expanded key. The caller is responsible for giving 64 bit of valid * data is IN and (at least) 64 bit large buffer as OUT. */ static bool encrypt_des(const unsigned char *in, unsigned char *out, const unsigned char *key_56) { const CK_MECHANISM_TYPE mech = CKM_DES_ECB; /* DES cipher in ECB mode */ PK11SlotInfo *slot = NULL; char key[8]; /* expanded 64 bit key */ SECItem key_item; PK11SymKey *symkey = NULL; SECItem *param = NULL; PK11Context *ctx = NULL; int out_len; /* not used, required by NSS */ bool rv = FALSE; /* use internal slot for DES encryption (requires NSS to be initialized) */ slot = PK11_GetInternalKeySlot(); if(!slot) return FALSE; /* Expand the 56-bit key to 64-bits */ extend_key_56_to_64(key_56, key); /* Set the key parity to odd */ Curl_des_set_odd_parity((unsigned char *) key, sizeof(key)); /* Import the key */ key_item.data = (unsigned char *)key; key_item.len = sizeof(key); symkey = PK11_ImportSymKey(slot, mech, PK11_OriginUnwrap, CKA_ENCRYPT, &key_item, NULL); if(!symkey) goto fail; /* Create the DES encryption context */ param = PK11_ParamFromIV(mech, /* no IV in ECB mode */ NULL); if(!param) goto fail; ctx = PK11_CreateContextBySymKey(mech, CKA_ENCRYPT, symkey, param); if(!ctx) goto fail; /* Perform the encryption */ if(SECSuccess == PK11_CipherOp(ctx, out, &out_len, /* outbuflen */ 8, (unsigned char *)in, /* inbuflen */ 8) && SECSuccess == PK11_Finalize(ctx)) rv = /* all OK */ TRUE; fail: /* cleanup */ if(ctx) PK11_DestroyContext(ctx, PR_TRUE); if(symkey) PK11_FreeSymKey(symkey); if(param) SECITEM_FreeItem(param, PR_TRUE); PK11_FreeSlot(slot); return rv; } #elif defined(USE_MBEDTLS) static bool encrypt_des(const unsigned char *in, unsigned char *out, const unsigned char *key_56) { mbedtls_des_context ctx; char key[8]; /* Expand the 56-bit key to 64-bits */ extend_key_56_to_64(key_56, key); /* Set the key parity to odd */ mbedtls_des_key_set_parity((unsigned char *) key); /* Perform the encryption */ mbedtls_des_init(&ctx); mbedtls_des_setkey_enc(&ctx, (unsigned char *) key); return mbedtls_des_crypt_ecb(&ctx, in, out) == 0; } #elif defined(USE_SECTRANSP) static bool encrypt_des(const unsigned char *in, unsigned char *out, const unsigned char *key_56) { char key[8]; size_t out_len; CCCryptorStatus err; /* Expand the 56-bit key to 64-bits */ extend_key_56_to_64(key_56, key); /* Set the key parity to odd */ Curl_des_set_odd_parity((unsigned char *) key, sizeof(key)); /* Perform the encryption */ err = CCCrypt(kCCEncrypt, kCCAlgorithmDES, kCCOptionECBMode, key, kCCKeySizeDES, NULL, in, 8 /* inbuflen */, out, 8 /* outbuflen */, &out_len); return err == kCCSuccess; } #elif defined(USE_OS400CRYPTO) static bool encrypt_des(const unsigned char *in, unsigned char *out, const unsigned char *key_56) { char key[8]; _CIPHER_Control_T ctl; /* Setup the cipher control structure */ ctl.Func_ID = ENCRYPT_ONLY; ctl.Data_Len = sizeof(key); /* Expand the 56-bit key to 64-bits */ extend_key_56_to_64(key_56, ctl.Crypto_Key); /* Set the key parity to odd */ Curl_des_set_odd_parity((unsigned char *) ctl.Crypto_Key, ctl.Data_Len); /* Perform the encryption */ _CIPHER((_SPCPTR *) &out, &ctl, (_SPCPTR *) &in); return TRUE; } #elif defined(USE_WIN32_CRYPTO) static bool encrypt_des(const unsigned char *in, unsigned char *out, const unsigned char *key_56) { HCRYPTPROV hprov; HCRYPTKEY hkey; struct { BLOBHEADER hdr; unsigned int len; char key[8]; } blob; DWORD len = 8; /* Acquire the crypto provider */ if(!CryptAcquireContext(&hprov, NULL, NULL, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT)) return FALSE; /* Setup the key blob structure */ memset(&blob, 0, sizeof(blob)); blob.hdr.bType = PLAINTEXTKEYBLOB; blob.hdr.bVersion = 2; blob.hdr.aiKeyAlg = CALG_DES; blob.len = sizeof(blob.key); /* Expand the 56-bit key to 64-bits */ extend_key_56_to_64(key_56, blob.key); /* Set the key parity to odd */ Curl_des_set_odd_parity((unsigned char *) blob.key, sizeof(blob.key)); /* Import the key */ if(!CryptImportKey(hprov, (BYTE *) &blob, sizeof(blob), 0, 0, &hkey)) { CryptReleaseContext(hprov, 0); return FALSE; } memcpy(out, in, 8); /* Perform the encryption */ CryptEncrypt(hkey, 0, FALSE, 0, out, &len, len); CryptDestroyKey(hkey); CryptReleaseContext(hprov, 0); return TRUE; } #endif /* defined(USE_WIN32_CRYPTO) */ /* * takes a 21 byte array and treats it as 3 56-bit DES keys. The * 8 byte plaintext is encrypted with each key and the resulting 24 * bytes are stored in the results array. */ void Curl_ntlm_core_lm_resp(const unsigned char *keys, const unsigned char *plaintext, unsigned char *results) { #ifdef USE_OPENSSL DES_key_schedule ks; setup_des_key(keys, DESKEY(ks)); DES_ecb_encrypt((DES_cblock*) plaintext, (DES_cblock*) results, DESKEY(ks), DES_ENCRYPT); setup_des_key(keys + 7, DESKEY(ks)); DES_ecb_encrypt((DES_cblock*) plaintext, (DES_cblock*) (results + 8), DESKEY(ks), DES_ENCRYPT); setup_des_key(keys + 14, DESKEY(ks)); DES_ecb_encrypt((DES_cblock*) plaintext, (DES_cblock*) (results + 16), DESKEY(ks), DES_ENCRYPT); #elif defined(USE_GNUTLS_NETTLE) struct des_ctx des; setup_des_key(keys, &des); des_encrypt(&des, 8, results, plaintext); setup_des_key(keys + 7, &des); des_encrypt(&des, 8, results + 8, plaintext); setup_des_key(keys + 14, &des); des_encrypt(&des, 8, results + 16, plaintext); #elif defined(USE_GNUTLS) gcry_cipher_hd_t des; gcry_cipher_open(&des, GCRY_CIPHER_DES, GCRY_CIPHER_MODE_ECB, 0); setup_des_key(keys, &des); gcry_cipher_encrypt(des, results, 8, plaintext, 8); gcry_cipher_close(des); gcry_cipher_open(&des, GCRY_CIPHER_DES, GCRY_CIPHER_MODE_ECB, 0); setup_des_key(keys + 7, &des); gcry_cipher_encrypt(des, results + 8, 8, plaintext, 8); gcry_cipher_close(des); gcry_cipher_open(&des, GCRY_CIPHER_DES, GCRY_CIPHER_MODE_ECB, 0); setup_des_key(keys + 14, &des); gcry_cipher_encrypt(des, results + 16, 8, plaintext, 8); gcry_cipher_close(des); #elif defined(USE_NSS) || defined(USE_MBEDTLS) || defined(USE_SECTRANSP) \ || defined(USE_OS400CRYPTO) || defined(USE_WIN32_CRYPTO) encrypt_des(plaintext, results, keys); encrypt_des(plaintext, results + 8, keys + 7); encrypt_des(plaintext, results + 16, keys + 14); #endif } /* * Set up lanmanager hashed password */ CURLcode Curl_ntlm_core_mk_lm_hash(struct Curl_easy *data, const char *password, unsigned char *lmbuffer /* 21 bytes */) { CURLcode result; unsigned char pw[14]; static const unsigned char magic[] = { 0x4B, 0x47, 0x53, 0x21, 0x40, 0x23, 0x24, 0x25 /* i.e. KGS!@#$% */ }; size_t len = CURLMIN(strlen(password), 14); Curl_strntoupper((char *)pw, password, len); memset(&pw[len], 0, 14 - len); /* * The LanManager hashed password needs to be created using the * password in the network encoding not the host encoding. */ result = Curl_convert_to_network(data, (char *)pw, 14); if(result) return result; { /* Create LanManager hashed password. */ #ifdef USE_OPENSSL DES_key_schedule ks; setup_des_key(pw, DESKEY(ks)); DES_ecb_encrypt((DES_cblock *)magic, (DES_cblock *)lmbuffer, DESKEY(ks), DES_ENCRYPT); setup_des_key(pw + 7, DESKEY(ks)); DES_ecb_encrypt((DES_cblock *)magic, (DES_cblock *)(lmbuffer + 8), DESKEY(ks), DES_ENCRYPT); #elif defined(USE_GNUTLS_NETTLE) struct des_ctx des; setup_des_key(pw, &des); des_encrypt(&des, 8, lmbuffer, magic); setup_des_key(pw + 7, &des); des_encrypt(&des, 8, lmbuffer + 8, magic); #elif defined(USE_GNUTLS) gcry_cipher_hd_t des; gcry_cipher_open(&des, GCRY_CIPHER_DES, GCRY_CIPHER_MODE_ECB, 0); setup_des_key(pw, &des); gcry_cipher_encrypt(des, lmbuffer, 8, magic, 8); gcry_cipher_close(des); gcry_cipher_open(&des, GCRY_CIPHER_DES, GCRY_CIPHER_MODE_ECB, 0); setup_des_key(pw + 7, &des); gcry_cipher_encrypt(des, lmbuffer + 8, 8, magic, 8); gcry_cipher_close(des); #elif defined(USE_NSS) || defined(USE_MBEDTLS) || defined(USE_SECTRANSP) \ || defined(USE_OS400CRYPTO) || defined(USE_WIN32_CRYPTO) encrypt_des(magic, lmbuffer, pw); encrypt_des(magic, lmbuffer + 8, pw + 7); #endif memset(lmbuffer + 16, 0, 21 - 16); } return CURLE_OK; } #ifdef USE_NTRESPONSES static void ascii_to_unicode_le(unsigned char *dest, const char *src, size_t srclen) { size_t i; for(i = 0; i < srclen; i++) { dest[2 * i] = (unsigned char)src[i]; dest[2 * i + 1] = '\0'; } } #if defined(USE_NTLM_V2) && !defined(USE_WINDOWS_SSPI) static void ascii_uppercase_to_unicode_le(unsigned char *dest, const char *src, size_t srclen) { size_t i; for(i = 0; i < srclen; i++) { dest[2 * i] = (unsigned char)(Curl_raw_toupper(src[i])); dest[2 * i + 1] = '\0'; } } #endif /* USE_NTLM_V2 && !USE_WINDOWS_SSPI */ /* * Set up nt hashed passwords * @unittest: 1600 */ CURLcode Curl_ntlm_core_mk_nt_hash(struct Curl_easy *data, const char *password, unsigned char *ntbuffer /* 21 bytes */) { size_t len = strlen(password); unsigned char *pw; CURLcode result; if(len > SIZE_T_MAX/2) /* avoid integer overflow */ return CURLE_OUT_OF_MEMORY; pw = len ? malloc(len * 2) : strdup(""); if(!pw) return CURLE_OUT_OF_MEMORY; ascii_to_unicode_le(pw, password, len); /* * The NT hashed password needs to be created using the password in the * network encoding not the host encoding. */ result = Curl_convert_to_network(data, (char *)pw, len * 2); if(result) return result; { /* Create NT hashed password. */ #ifdef USE_OPENSSL #if !defined(OPENSSL_NO_MD4) MD4_CTX MD4pw; MD4_Init(&MD4pw); MD4_Update(&MD4pw, pw, 2 * len); MD4_Final(ntbuffer, &MD4pw); #else Curl_md4it(ntbuffer, pw, 2 * len); #endif #elif defined(USE_GNUTLS_NETTLE) struct md4_ctx MD4pw; md4_init(&MD4pw); md4_update(&MD4pw, (unsigned int)(2 * len), pw); md4_digest(&MD4pw, MD4_DIGEST_SIZE, ntbuffer); #elif defined(USE_GNUTLS) gcry_md_hd_t MD4pw; gcry_md_open(&MD4pw, GCRY_MD_MD4, 0); gcry_md_write(MD4pw, pw, 2 * len); memcpy(ntbuffer, gcry_md_read(MD4pw, 0), MD4_DIGEST_LENGTH); gcry_md_close(MD4pw); #elif defined(USE_NSS) Curl_md4it(ntbuffer, pw, 2 * len); #elif defined(USE_MBEDTLS) #if defined(MBEDTLS_MD4_C) mbedtls_md4(pw, 2 * len, ntbuffer); #else Curl_md4it(ntbuffer, pw, 2 * len); #endif #elif defined(USE_SECTRANSP) (void)CC_MD4(pw, (CC_LONG)(2 * len), ntbuffer); #elif defined(USE_OS400CRYPTO) Curl_md4it(ntbuffer, pw, 2 * len); #elif defined(USE_WIN32_CRYPTO) HCRYPTPROV hprov; if(CryptAcquireContext(&hprov, NULL, NULL, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT)) { HCRYPTHASH hhash; if(CryptCreateHash(hprov, CALG_MD4, 0, 0, &hhash)) { DWORD length = 16; CryptHashData(hhash, pw, (unsigned int)len * 2, 0); CryptGetHashParam(hhash, HP_HASHVAL, ntbuffer, &length, 0); CryptDestroyHash(hhash); } CryptReleaseContext(hprov, 0); } #endif memset(ntbuffer + 16, 0, 21 - 16); } free(pw); return CURLE_OK; } #if defined(USE_NTLM_V2) && !defined(USE_WINDOWS_SSPI) /* This returns the HMAC MD5 digest */ static CURLcode hmac_md5(const unsigned char *key, unsigned int keylen, const unsigned char *data, unsigned int datalen, unsigned char *output) { HMAC_context *ctxt = Curl_HMAC_init(Curl_HMAC_MD5, key, keylen); if(!ctxt) return CURLE_OUT_OF_MEMORY; /* Update the digest with the given challenge */ Curl_HMAC_update(ctxt, data, datalen); /* Finalise the digest */ Curl_HMAC_final(ctxt, output); return CURLE_OK; } /* This creates the NTLMv2 hash by using NTLM hash as the key and Unicode * (uppercase UserName + Domain) as the data */ CURLcode Curl_ntlm_core_mk_ntlmv2_hash(const char *user, size_t userlen, const char *domain, size_t domlen, unsigned char *ntlmhash, unsigned char *ntlmv2hash) { /* Unicode representation */ size_t identity_len; unsigned char *identity; CURLcode result = CURLE_OK; /* we do the length checks below separately to avoid integer overflow risk on extreme data lengths */ if((userlen > SIZE_T_MAX/2) || (domlen > SIZE_T_MAX/2) || ((userlen + domlen) > SIZE_T_MAX/2)) return CURLE_OUT_OF_MEMORY; identity_len = (userlen + domlen) * 2; identity = malloc(identity_len); if(!identity) return CURLE_OUT_OF_MEMORY; ascii_uppercase_to_unicode_le(identity, user, userlen); ascii_to_unicode_le(identity + (userlen << 1), domain, domlen); result = hmac_md5(ntlmhash, 16, identity, curlx_uztoui(identity_len), ntlmv2hash); free(identity); return result; } /* * Curl_ntlm_core_mk_ntlmv2_resp() * * This creates the NTLMv2 response as set in the ntlm type-3 message. * * Parameters: * * ntlmv2hash [in] - The ntlmv2 hash (16 bytes) * challenge_client [in] - The client nonce (8 bytes) * ntlm [in] - The ntlm data struct being used to read TargetInfo and Server challenge received in the type-2 message * ntresp [out] - The address where a pointer to newly allocated * memory holding the NTLMv2 response. * ntresp_len [out] - The length of the output message. * * Returns CURLE_OK on success. */ CURLcode Curl_ntlm_core_mk_ntlmv2_resp(unsigned char *ntlmv2hash, unsigned char *challenge_client, struct ntlmdata *ntlm, unsigned char **ntresp, unsigned int *ntresp_len) { /* NTLMv2 response structure : ------------------------------------------------------------------------------ 0 HMAC MD5 16 bytes ------BLOB-------------------------------------------------------------------- 16 Signature 0x01010000 20 Reserved long (0x00000000) 24 Timestamp LE, 64-bit signed value representing the number of tenths of a microsecond since January 1, 1601. 32 Client Nonce 8 bytes 40 Unknown 4 bytes 44 Target Info N bytes (from the type-2 message) 44+N Unknown 4 bytes ------------------------------------------------------------------------------ */ unsigned int len = 0; unsigned char *ptr = NULL; unsigned char hmac_output[NTLM_HMAC_MD5_LEN]; curl_off_t tw; CURLcode result = CURLE_OK; #if CURL_SIZEOF_CURL_OFF_T < 8 #error "this section needs 64bit support to work" #endif /* Calculate the timestamp */ #ifdef DEBUGBUILD char *force_timestamp = getenv("CURL_FORCETIME"); if(force_timestamp) tw = CURL_OFF_T_C(11644473600) * 10000000; else #endif tw = ((curl_off_t)time(NULL) + CURL_OFF_T_C(11644473600)) * 10000000; /* Calculate the response len */ len = NTLM_HMAC_MD5_LEN + NTLMv2_BLOB_LEN; /* Allocate the response */ ptr = calloc(1, len); if(!ptr) return CURLE_OUT_OF_MEMORY; /* Create the BLOB structure */ msnprintf((char *)ptr + NTLM_HMAC_MD5_LEN, NTLMv2_BLOB_LEN, "%c%c%c%c" /* NTLMv2_BLOB_SIGNATURE */ "%c%c%c%c", /* Reserved = 0 */ NTLMv2_BLOB_SIGNATURE[0], NTLMv2_BLOB_SIGNATURE[1], NTLMv2_BLOB_SIGNATURE[2], NTLMv2_BLOB_SIGNATURE[3], 0, 0, 0, 0); Curl_write64_le(tw, ptr + 24); memcpy(ptr + 32, challenge_client, 8); memcpy(ptr + 44, ntlm->target_info, ntlm->target_info_len); /* Concatenate the Type 2 challenge with the BLOB and do HMAC MD5 */ memcpy(ptr + 8, &ntlm->nonce[0], 8); result = hmac_md5(ntlmv2hash, NTLM_HMAC_MD5_LEN, ptr + 8, NTLMv2_BLOB_LEN + 8, hmac_output); if(result) { free(ptr); return result; } /* Concatenate the HMAC MD5 output with the BLOB */ memcpy(ptr, hmac_output, NTLM_HMAC_MD5_LEN); /* Return the response */ *ntresp = ptr; *ntresp_len = len; return result; } /* * Curl_ntlm_core_mk_lmv2_resp() * * This creates the LMv2 response as used in the ntlm type-3 message. * * Parameters: * * ntlmv2hash [in] - The ntlmv2 hash (16 bytes) * challenge_client [in] - The client nonce (8 bytes) * challenge_client [in] - The server challenge (8 bytes) * lmresp [out] - The LMv2 response (24 bytes) * * Returns CURLE_OK on success. */ CURLcode Curl_ntlm_core_mk_lmv2_resp(unsigned char *ntlmv2hash, unsigned char *challenge_client, unsigned char *challenge_server, unsigned char *lmresp) { unsigned char data[16]; unsigned char hmac_output[16]; CURLcode result = CURLE_OK; memcpy(&data[0], challenge_server, 8); memcpy(&data[8], challenge_client, 8); result = hmac_md5(ntlmv2hash, 16, &data[0], 16, hmac_output); if(result) return result; /* Concatenate the HMAC MD5 output with the client nonce */ memcpy(lmresp, hmac_output, 16); memcpy(lmresp + 16, challenge_client, 8); return result; } #endif /* USE_NTLM_V2 && !USE_WINDOWS_SSPI */ #endif /* USE_NTRESPONSES */ #endif /* !USE_WINDOWS_SSPI || USE_WIN32_CRYPTO */ #endif /* USE_NTLM */
YifuLiu/AliOS-Things
components/curl/lib/curl_ntlm_core.c
C
apache-2.0
24,050
#ifndef HEADER_CURL_NTLM_CORE_H #define HEADER_CURL_NTLM_CORE_H /*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2019, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "curl_setup.h" #if defined(USE_NTLM) /* If NSS is the first available SSL backend (see order in curl_ntlm_core.c) then it must be initialized to be used by NTLM. */ #if !defined(USE_OPENSSL) && \ !defined(USE_GNUTLS_NETTLE) && \ !defined(USE_GNUTLS) && \ defined(USE_NSS) #define NTLM_NEEDS_NSS_INIT #endif #if !defined(USE_WINDOWS_SSPI) || defined(USE_WIN32_CRYPTO) #ifdef USE_OPENSSL # include <openssl/ssl.h> #endif /* Define USE_NTRESPONSES in order to make the type-3 message include * the NT response message. */ #define USE_NTRESPONSES /* Define USE_NTLM2SESSION in order to make the type-3 message include the NTLM2Session response message, requires USE_NTRESPONSES defined to 1 and a Crypto engine that we have curl_ssl_md5sum() for. */ #if defined(USE_NTRESPONSES) && !defined(USE_WIN32_CRYPTO) #define USE_NTLM2SESSION #endif /* Define USE_NTLM_V2 in order to allow the type-3 message to include the LMv2 and NTLMv2 response messages, requires USE_NTRESPONSES defined to 1 and support for 64-bit integers. */ #if defined(USE_NTRESPONSES) && (CURL_SIZEOF_CURL_OFF_T > 4) #define USE_NTLM_V2 #endif void Curl_ntlm_core_lm_resp(const unsigned char *keys, const unsigned char *plaintext, unsigned char *results); CURLcode Curl_ntlm_core_mk_lm_hash(struct Curl_easy *data, const char *password, unsigned char *lmbuffer /* 21 bytes */); #ifdef USE_NTRESPONSES CURLcode Curl_ntlm_core_mk_nt_hash(struct Curl_easy *data, const char *password, unsigned char *ntbuffer /* 21 bytes */); #if defined(USE_NTLM_V2) && !defined(USE_WINDOWS_SSPI) CURLcode Curl_hmac_md5(const unsigned char *key, unsigned int keylen, const unsigned char *data, unsigned int datalen, unsigned char *output); CURLcode Curl_ntlm_core_mk_ntlmv2_hash(const char *user, size_t userlen, const char *domain, size_t domlen, unsigned char *ntlmhash, unsigned char *ntlmv2hash); CURLcode Curl_ntlm_core_mk_ntlmv2_resp(unsigned char *ntlmv2hash, unsigned char *challenge_client, struct ntlmdata *ntlm, unsigned char **ntresp, unsigned int *ntresp_len); CURLcode Curl_ntlm_core_mk_lmv2_resp(unsigned char *ntlmv2hash, unsigned char *challenge_client, unsigned char *challenge_server, unsigned char *lmresp); #endif /* USE_NTLM_V2 && !USE_WINDOWS_SSPI */ #endif /* USE_NTRESPONSES */ #endif /* !USE_WINDOWS_SSPI || USE_WIN32_CRYPTO */ #endif /* USE_NTLM */ #endif /* HEADER_CURL_NTLM_CORE_H */
YifuLiu/AliOS-Things
components/curl/lib/curl_ntlm_core.h
C
apache-2.0
4,142
/*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2019, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "curl_setup.h" #if !defined(CURL_DISABLE_HTTP) && defined(USE_NTLM) && \ defined(NTLM_WB_ENABLED) /* * NTLM details: * * https://davenport.sourceforge.io/ntlm.html * https://www.innovation.ch/java/ntlm.html */ #define DEBUG_ME 0 #ifdef HAVE_SYS_WAIT_H #include <sys/wait.h> #endif #ifdef HAVE_SIGNAL_H #include <signal.h> #endif #ifdef HAVE_PWD_H #include <pwd.h> #endif #include "urldata.h" #include "sendf.h" #include "select.h" #include "vauth/ntlm.h" #include "curl_ntlm_core.h" #include "curl_ntlm_wb.h" #include "url.h" #include "strerror.h" #include "strdup.h" #include "strcase.h" /* The last 3 #include files should be in this order */ #include "curl_printf.h" #include "curl_memory.h" #include "memdebug.h" #if DEBUG_ME # define DEBUG_OUT(x) x #else # define DEBUG_OUT(x) Curl_nop_stmt #endif /* Portable 'sclose_nolog' used only in child process instead of 'sclose' to avoid fooling the socket leak detector */ #if defined(HAVE_CLOSESOCKET) # define sclose_nolog(x) closesocket((x)) #elif defined(HAVE_CLOSESOCKET_CAMEL) # define sclose_nolog(x) CloseSocket((x)) #else # define sclose_nolog(x) close((x)) #endif void Curl_http_auth_cleanup_ntlm_wb(struct connectdata *conn) { if(conn->ntlm_auth_hlpr_socket != CURL_SOCKET_BAD) { sclose(conn->ntlm_auth_hlpr_socket); conn->ntlm_auth_hlpr_socket = CURL_SOCKET_BAD; } if(conn->ntlm_auth_hlpr_pid) { int i; for(i = 0; i < 4; i++) { pid_t ret = waitpid(conn->ntlm_auth_hlpr_pid, NULL, WNOHANG); if(ret == conn->ntlm_auth_hlpr_pid || errno == ECHILD) break; switch(i) { case 0: kill(conn->ntlm_auth_hlpr_pid, SIGTERM); break; case 1: /* Give the process another moment to shut down cleanly before bringing down the axe */ Curl_wait_ms(1); break; case 2: kill(conn->ntlm_auth_hlpr_pid, SIGKILL); break; case 3: break; } } conn->ntlm_auth_hlpr_pid = 0; } free(conn->challenge_header); conn->challenge_header = NULL; free(conn->response_header); conn->response_header = NULL; } static CURLcode ntlm_wb_init(struct connectdata *conn, const char *userp) { curl_socket_t sockfds[2]; pid_t child_pid; const char *username; char *slash, *domain = NULL; const char *ntlm_auth = NULL; char *ntlm_auth_alloc = NULL; #if defined(HAVE_GETPWUID_R) && defined(HAVE_GETEUID) struct passwd pw, *pw_res; char pwbuf[1024]; #endif char buffer[STRERROR_LEN]; /* Return if communication with ntlm_auth already set up */ if(conn->ntlm_auth_hlpr_socket != CURL_SOCKET_BAD || conn->ntlm_auth_hlpr_pid) return CURLE_OK; username = userp; /* The real ntlm_auth really doesn't like being invoked with an empty username. It won't make inferences for itself, and expects the client to do so (mostly because it's really designed for servers like squid to use for auth, and client support is an afterthought for it). So try hard to provide a suitable username if we don't already have one. But if we can't, provide the empty one anyway. Perhaps they have an implementation of the ntlm_auth helper which *doesn't* need it so we might as well try */ if(!username || !username[0]) { username = getenv("NTLMUSER"); if(!username || !username[0]) username = getenv("LOGNAME"); if(!username || !username[0]) username = getenv("USER"); #if defined(HAVE_GETPWUID_R) && defined(HAVE_GETEUID) if((!username || !username[0]) && !getpwuid_r(geteuid(), &pw, pwbuf, sizeof(pwbuf), &pw_res) && pw_res) { username = pw.pw_name; } #endif if(!username || !username[0]) username = userp; } slash = strpbrk(username, "\\/"); if(slash) { domain = strdup(username); if(!domain) return CURLE_OUT_OF_MEMORY; slash = domain + (slash - username); *slash = '\0'; username = username + (slash - domain) + 1; } /* For testing purposes, when DEBUGBUILD is defined and environment variable CURL_NTLM_WB_FILE is set a fake_ntlm is used to perform NTLM challenge/response which only accepts commands and output strings pre-written in test case definitions */ #ifdef DEBUGBUILD ntlm_auth_alloc = curl_getenv("CURL_NTLM_WB_FILE"); if(ntlm_auth_alloc) ntlm_auth = ntlm_auth_alloc; else #endif ntlm_auth = NTLM_WB_FILE; if(access(ntlm_auth, X_OK) != 0) { failf(conn->data, "Could not access ntlm_auth: %s errno %d: %s", ntlm_auth, errno, Curl_strerror(errno, buffer, sizeof(buffer))); goto done; } if(socketpair(AF_UNIX, SOCK_STREAM, 0, sockfds)) { failf(conn->data, "Could not open socket pair. errno %d: %s", errno, Curl_strerror(errno, buffer, sizeof(buffer))); goto done; } child_pid = fork(); if(child_pid == -1) { sclose(sockfds[0]); sclose(sockfds[1]); failf(conn->data, "Could not fork. errno %d: %s", errno, Curl_strerror(errno, buffer, sizeof(buffer))); goto done; } else if(!child_pid) { /* * child process */ /* Don't use sclose in the child since it fools the socket leak detector */ sclose_nolog(sockfds[0]); if(dup2(sockfds[1], STDIN_FILENO) == -1) { failf(conn->data, "Could not redirect child stdin. errno %d: %s", errno, Curl_strerror(errno, buffer, sizeof(buffer))); exit(1); } if(dup2(sockfds[1], STDOUT_FILENO) == -1) { failf(conn->data, "Could not redirect child stdout. errno %d: %s", errno, Curl_strerror(errno, buffer, sizeof(buffer))); exit(1); } if(domain) execl(ntlm_auth, ntlm_auth, "--helper-protocol", "ntlmssp-client-1", "--use-cached-creds", "--username", username, "--domain", domain, NULL); else execl(ntlm_auth, ntlm_auth, "--helper-protocol", "ntlmssp-client-1", "--use-cached-creds", "--username", username, NULL); sclose_nolog(sockfds[1]); failf(conn->data, "Could not execl(). errno %d: %s", errno, Curl_strerror(errno, buffer, sizeof(buffer))); exit(1); } sclose(sockfds[1]); conn->ntlm_auth_hlpr_socket = sockfds[0]; conn->ntlm_auth_hlpr_pid = child_pid; free(domain); free(ntlm_auth_alloc); return CURLE_OK; done: free(domain); free(ntlm_auth_alloc); return CURLE_REMOTE_ACCESS_DENIED; } /* if larger than this, something is seriously wrong */ #define MAX_NTLM_WB_RESPONSE 100000 static CURLcode ntlm_wb_response(struct connectdata *conn, const char *input, curlntlm state) { char *buf = malloc(NTLM_BUFSIZE); size_t len_in = strlen(input), len_out = 0; if(!buf) return CURLE_OUT_OF_MEMORY; while(len_in > 0) { ssize_t written = swrite(conn->ntlm_auth_hlpr_socket, input, len_in); if(written == -1) { /* Interrupted by a signal, retry it */ if(errno == EINTR) continue; /* write failed if other errors happen */ goto done; } input += written; len_in -= written; } /* Read one line */ while(1) { ssize_t size; char *newbuf; size = sread(conn->ntlm_auth_hlpr_socket, buf + len_out, NTLM_BUFSIZE); if(size == -1) { if(errno == EINTR) continue; goto done; } else if(size == 0) goto done; len_out += size; if(buf[len_out - 1] == '\n') { buf[len_out - 1] = '\0'; break; } if(len_out > MAX_NTLM_WB_RESPONSE) { failf(conn->data, "too large ntlm_wb response!"); free(buf); return CURLE_OUT_OF_MEMORY; } newbuf = Curl_saferealloc(buf, len_out + NTLM_BUFSIZE); if(!newbuf) return CURLE_OUT_OF_MEMORY; buf = newbuf; } /* Samba/winbind installed but not configured */ if(state == NTLMSTATE_TYPE1 && len_out == 3 && buf[0] == 'P' && buf[1] == 'W') goto done; /* invalid response */ if(len_out < 4) goto done; if(state == NTLMSTATE_TYPE1 && (buf[0]!='Y' || buf[1]!='R' || buf[2]!=' ')) goto done; if(state == NTLMSTATE_TYPE2 && (buf[0]!='K' || buf[1]!='K' || buf[2]!=' ') && (buf[0]!='A' || buf[1]!='F' || buf[2]!=' ')) goto done; conn->response_header = aprintf("NTLM %.*s", len_out - 4, buf + 3); free(buf); if(!conn->response_header) return CURLE_OUT_OF_MEMORY; return CURLE_OK; done: free(buf); return CURLE_REMOTE_ACCESS_DENIED; } CURLcode Curl_input_ntlm_wb(struct connectdata *conn, bool proxy, const char *header) { curlntlm *state = proxy ? &conn->proxy_ntlm_state : &conn->http_ntlm_state; if(!checkprefix("NTLM", header)) return CURLE_BAD_CONTENT_ENCODING; header += strlen("NTLM"); while(*header && ISSPACE(*header)) header++; if(*header) { conn->challenge_header = strdup(header); if(!conn->challenge_header) return CURLE_OUT_OF_MEMORY; *state = NTLMSTATE_TYPE2; /* We got a type-2 message */ } else { if(*state == NTLMSTATE_LAST) { infof(conn->data, "NTLM auth restarted\n"); Curl_http_auth_cleanup_ntlm_wb(conn); } else if(*state == NTLMSTATE_TYPE3) { infof(conn->data, "NTLM handshake rejected\n"); Curl_http_auth_cleanup_ntlm_wb(conn); *state = NTLMSTATE_NONE; return CURLE_REMOTE_ACCESS_DENIED; } else if(*state >= NTLMSTATE_TYPE1) { infof(conn->data, "NTLM handshake failure (internal error)\n"); return CURLE_REMOTE_ACCESS_DENIED; } *state = NTLMSTATE_TYPE1; /* We should send away a type-1 */ } return CURLE_OK; } /* * This is for creating ntlm header output by delegating challenge/response * to Samba's winbind daemon helper ntlm_auth. */ CURLcode Curl_output_ntlm_wb(struct connectdata *conn, bool proxy) { /* point to the address of the pointer that holds the string to send to the server, which is for a plain host or for a HTTP proxy */ char **allocuserpwd; /* point to the name and password for this */ const char *userp; curlntlm *state; struct auth *authp; CURLcode res = CURLE_OK; char *input; DEBUGASSERT(conn); DEBUGASSERT(conn->data); if(proxy) { allocuserpwd = &conn->allocptr.proxyuserpwd; userp = conn->http_proxy.user; state = &conn->proxy_ntlm_state; authp = &conn->data->state.authproxy; } else { allocuserpwd = &conn->allocptr.userpwd; userp = conn->user; state = &conn->http_ntlm_state; authp = &conn->data->state.authhost; } authp->done = FALSE; /* not set means empty */ if(!userp) userp = ""; switch(*state) { case NTLMSTATE_TYPE1: default: /* Use Samba's 'winbind' daemon to support NTLM authentication, * by delegating the NTLM challenge/response protocol to a helper * in ntlm_auth. * http://devel.squid-cache.org/ntlm/squid_helper_protocol.html * https://www.samba.org/samba/docs/man/manpages-3/winbindd.8.html * https://www.samba.org/samba/docs/man/manpages-3/ntlm_auth.1.html * Preprocessor symbol 'NTLM_WB_ENABLED' is defined when this * feature is enabled and 'NTLM_WB_FILE' symbol holds absolute * filename of ntlm_auth helper. * If NTLM authentication using winbind fails, go back to original * request handling process. */ /* Create communication with ntlm_auth */ res = ntlm_wb_init(conn, userp); if(res) return res; res = ntlm_wb_response(conn, "YR\n", *state); if(res) return res; free(*allocuserpwd); *allocuserpwd = aprintf("%sAuthorization: %s\r\n", proxy ? "Proxy-" : "", conn->response_header); DEBUG_OUT(fprintf(stderr, "**** Header %s\n ", *allocuserpwd)); free(conn->response_header); if(!*allocuserpwd) return CURLE_OUT_OF_MEMORY; conn->response_header = NULL; break; case NTLMSTATE_TYPE2: input = aprintf("TT %s\n", conn->challenge_header); if(!input) return CURLE_OUT_OF_MEMORY; res = ntlm_wb_response(conn, input, *state); free(input); input = NULL; if(res) return res; free(*allocuserpwd); *allocuserpwd = aprintf("%sAuthorization: %s\r\n", proxy ? "Proxy-" : "", conn->response_header); DEBUG_OUT(fprintf(stderr, "**** %s\n ", *allocuserpwd)); *state = NTLMSTATE_TYPE3; /* we sent a type-3 */ authp->done = TRUE; Curl_http_auth_cleanup_ntlm_wb(conn); if(!*allocuserpwd) return CURLE_OUT_OF_MEMORY; break; case NTLMSTATE_TYPE3: /* connection is already authenticated, * don't send a header in future requests */ *state = NTLMSTATE_LAST; /* FALLTHROUGH */ case NTLMSTATE_LAST: Curl_safefree(*allocuserpwd); authp->done = TRUE; break; } return CURLE_OK; } #endif /* !CURL_DISABLE_HTTP && USE_NTLM && NTLM_WB_ENABLED */
YifuLiu/AliOS-Things
components/curl/lib/curl_ntlm_wb.c
C
apache-2.0
14,046
#ifndef HEADER_CURL_NTLM_WB_H #define HEADER_CURL_NTLM_WB_H /*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2019, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "curl_setup.h" #if !defined(CURL_DISABLE_HTTP) && defined(USE_NTLM) && \ defined(NTLM_WB_ENABLED) /* this is for ntlm header input */ CURLcode Curl_input_ntlm_wb(struct connectdata *conn, bool proxy, const char *header); /* this is for creating ntlm header output */ CURLcode Curl_output_ntlm_wb(struct connectdata *conn, bool proxy); void Curl_http_auth_cleanup_ntlm_wb(struct connectdata *conn); #endif /* !CURL_DISABLE_HTTP && USE_NTLM && NTLM_WB_ENABLED */ #endif /* HEADER_CURL_NTLM_WB_H */
YifuLiu/AliOS-Things
components/curl/lib/curl_ntlm_wb.h
C
apache-2.0
1,630
/*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2019, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "curl_setup.h" #if defined(USE_SSH) #include <curl/curl.h> #include "curl_memory.h" #include "curl_path.h" #include "escape.h" #include "memdebug.h" /* figure out the path to work with in this particular request */ CURLcode Curl_getworkingpath(struct connectdata *conn, char *homedir, /* when SFTP is used */ char **path) /* returns the allocated real path to work with */ { struct Curl_easy *data = conn->data; char *real_path = NULL; char *working_path; size_t working_path_len; CURLcode result = Curl_urldecode(data, data->state.up.path, 0, &working_path, &working_path_len, FALSE); if(result) return result; /* Check for /~/, indicating relative to the user's home directory */ if(conn->handler->protocol & CURLPROTO_SCP) { real_path = malloc(working_path_len + 1); if(real_path == NULL) { free(working_path); return CURLE_OUT_OF_MEMORY; } if((working_path_len > 3) && (!memcmp(working_path, "/~/", 3))) /* It is referenced to the home directory, so strip the leading '/~/' */ memcpy(real_path, working_path + 3, 4 + working_path_len-3); else memcpy(real_path, working_path, 1 + working_path_len); } else if(conn->handler->protocol & CURLPROTO_SFTP) { if((working_path_len > 1) && (working_path[1] == '~')) { size_t homelen = strlen(homedir); real_path = malloc(homelen + working_path_len + 1); if(real_path == NULL) { free(working_path); return CURLE_OUT_OF_MEMORY; } /* It is referenced to the home directory, so strip the leading '/' */ memcpy(real_path, homedir, homelen); real_path[homelen] = '/'; real_path[homelen + 1] = '\0'; if(working_path_len > 3) { memcpy(real_path + homelen + 1, working_path + 3, 1 + working_path_len -3); } } else { real_path = malloc(working_path_len + 1); if(real_path == NULL) { free(working_path); return CURLE_OUT_OF_MEMORY; } memcpy(real_path, working_path, 1 + working_path_len); } } free(working_path); /* store the pointer for the caller to receive */ *path = real_path; return CURLE_OK; } /* The get_pathname() function is being borrowed from OpenSSH sftp.c version 4.6p1. */ /* * Copyright (c) 2001-2004 Damien Miller <djm@openbsd.org> * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ CURLcode Curl_get_pathname(const char **cpp, char **path, char *homedir) { const char *cp = *cpp, *end; char quot; unsigned int i, j; size_t fullPathLength, pathLength; bool relativePath = false; static const char WHITESPACE[] = " \t\r\n"; if(!*cp) { *cpp = NULL; *path = NULL; return CURLE_QUOTE_ERROR; } /* Ignore leading whitespace */ cp += strspn(cp, WHITESPACE); /* Allocate enough space for home directory and filename + separator */ fullPathLength = strlen(cp) + strlen(homedir) + 2; *path = malloc(fullPathLength); if(*path == NULL) return CURLE_OUT_OF_MEMORY; /* Check for quoted filenames */ if(*cp == '\"' || *cp == '\'') { quot = *cp++; /* Search for terminating quote, unescape some chars */ for(i = j = 0; i <= strlen(cp); i++) { if(cp[i] == quot) { /* Found quote */ i++; (*path)[j] = '\0'; break; } if(cp[i] == '\0') { /* End of string */ /*error("Unterminated quote");*/ goto fail; } if(cp[i] == '\\') { /* Escaped characters */ i++; if(cp[i] != '\'' && cp[i] != '\"' && cp[i] != '\\') { /*error("Bad escaped character '\\%c'", cp[i]);*/ goto fail; } } (*path)[j++] = cp[i]; } if(j == 0) { /*error("Empty quotes");*/ goto fail; } *cpp = cp + i + strspn(cp + i, WHITESPACE); } else { /* Read to end of filename - either to white space or terminator */ end = strpbrk(cp, WHITESPACE); if(end == NULL) end = strchr(cp, '\0'); /* return pointer to second parameter if it exists */ *cpp = end + strspn(end, WHITESPACE); pathLength = 0; relativePath = (cp[0] == '/' && cp[1] == '~' && cp[2] == '/'); /* Handling for relative path - prepend home directory */ if(relativePath) { strcpy(*path, homedir); pathLength = strlen(homedir); (*path)[pathLength++] = '/'; (*path)[pathLength] = '\0'; cp += 3; } /* Copy path name up until first "white space" */ memcpy(&(*path)[pathLength], cp, (int)(end - cp)); pathLength += (int)(end - cp); (*path)[pathLength] = '\0'; } return CURLE_OK; fail: Curl_safefree(*path); return CURLE_QUOTE_ERROR; } #endif /* if SSH is used */
YifuLiu/AliOS-Things
components/curl/lib/curl_path.c
C
apache-2.0
6,567
#ifndef HEADER_CURL_PATH_H #define HEADER_CURL_PATH_H /*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2018, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "curl_setup.h" #include <curl/curl.h> #include "urldata.h" #ifdef WIN32 # undef PATH_MAX # define PATH_MAX MAX_PATH # ifndef R_OK # define R_OK 4 # endif #endif #ifndef PATH_MAX #define PATH_MAX 1024 /* just an extra precaution since there are systems that have their definition hidden well */ #endif CURLcode Curl_getworkingpath(struct connectdata *conn, char *homedir, char **path); CURLcode Curl_get_pathname(const char **cpp, char **path, char *homedir); #endif /* HEADER_CURL_PATH_H */
YifuLiu/AliOS-Things
components/curl/lib/curl_path.h
C
apache-2.0
1,676
#ifndef HEADER_CURL_PRINTF_H #define HEADER_CURL_PRINTF_H /*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2018, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ /* * This header should be included by ALL code in libcurl that uses any * *rintf() functions. */ #include <curl/mprintf.h> # undef printf # undef fprintf # undef msnprintf # undef vprintf # undef vfprintf # undef vsnprintf # undef aprintf # undef vaprintf # define printf curl_mprintf # define fprintf curl_mfprintf # define msnprintf curl_msnprintf # define vprintf curl_mvprintf # define vfprintf curl_mvfprintf # define mvsnprintf curl_mvsnprintf # define aprintf curl_maprintf # define vaprintf curl_mvaprintf #endif /* HEADER_CURL_PRINTF_H */
YifuLiu/AliOS-Things
components/curl/lib/curl_printf.h
C
apache-2.0
1,639
/*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2018, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "curl_setup.h" #include <curl/curl.h> #include "curl_range.h" #include "sendf.h" #include "strtoofft.h" /* Only include this function if one or more of FTP, FILE are enabled. */ #if !defined(CURL_DISABLE_FTP) || !defined(CURL_DISABLE_FILE) /* Check if this is a range download, and if so, set the internal variables properly. */ CURLcode Curl_range(struct connectdata *conn) { curl_off_t from, to; char *ptr; char *ptr2; struct Curl_easy *data = conn->data; if(data->state.use_range && data->state.range) { CURLofft from_t; CURLofft to_t; from_t = curlx_strtoofft(data->state.range, &ptr, 0, &from); if(from_t == CURL_OFFT_FLOW) return CURLE_RANGE_ERROR; while(*ptr && (ISSPACE(*ptr) || (*ptr == '-'))) ptr++; to_t = curlx_strtoofft(ptr, &ptr2, 0, &to); if(to_t == CURL_OFFT_FLOW) return CURLE_RANGE_ERROR; if((to_t == CURL_OFFT_INVAL) && !from_t) { /* X - */ data->state.resume_from = from; DEBUGF(infof(data, "RANGE %" CURL_FORMAT_CURL_OFF_T " to end of file\n", from)); } else if((from_t == CURL_OFFT_INVAL) && !to_t) { /* -Y */ data->req.maxdownload = to; data->state.resume_from = -to; DEBUGF(infof(data, "RANGE the last %" CURL_FORMAT_CURL_OFF_T " bytes\n", to)); } else { /* X-Y */ curl_off_t totalsize; /* Ensure the range is sensible - to should follow from. */ if(from > to) return CURLE_RANGE_ERROR; totalsize = to - from; if(totalsize == CURL_OFF_T_MAX) return CURLE_RANGE_ERROR; data->req.maxdownload = totalsize + 1; /* include last byte */ data->state.resume_from = from; DEBUGF(infof(data, "RANGE from %" CURL_FORMAT_CURL_OFF_T " getting %" CURL_FORMAT_CURL_OFF_T " bytes\n", from, data->req.maxdownload)); } DEBUGF(infof(data, "range-download from %" CURL_FORMAT_CURL_OFF_T " to %" CURL_FORMAT_CURL_OFF_T ", totally %" CURL_FORMAT_CURL_OFF_T " bytes\n", from, to, data->req.maxdownload)); } else data->req.maxdownload = -1; return CURLE_OK; } #endif
YifuLiu/AliOS-Things
components/curl/lib/curl_range.c
C
apache-2.0
3,249
#ifndef HEADER_CURL_RANGE_H #define HEADER_CURL_RANGE_H /*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2018, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "curl_setup.h" #include "urldata.h" CURLcode Curl_range(struct connectdata *conn); #endif /* HEADER_CURL_RANGE_H */
YifuLiu/AliOS-Things
components/curl/lib/curl_range.h
C
apache-2.0
1,210
/*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 2012 - 2019, Daniel Stenberg, <daniel@haxx.se>, et al. * Copyright (C) 2010, Howard Chu, <hyc@highlandsun.com> * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "curl_setup.h" #ifdef USE_LIBRTMP #include "curl_rtmp.h" #include "urldata.h" #include "nonblock.h" /* for curlx_nonblock */ #include "progress.h" /* for Curl_pgrsSetUploadSize */ #include "transfer.h" #include "warnless.h" #include <curl/curl.h> #include <librtmp/rtmp.h> #include "curl_memory.h" /* The last #include file should be: */ #include "memdebug.h" #if defined(WIN32) && !defined(USE_LWIPSOCK) #define setsockopt(a,b,c,d,e) (setsockopt)(a,b,c,(const char *)d,(int)e) #define SET_RCVTIMEO(tv,s) int tv = s*1000 #elif defined(LWIP_SO_SNDRCVTIMEO_NONSTANDARD) #define SET_RCVTIMEO(tv,s) int tv = s*1000 #else #define SET_RCVTIMEO(tv,s) struct timeval tv = {s,0} #endif #define DEF_BUFTIME (2*60*60*1000) /* 2 hours */ static CURLcode rtmp_setup_connection(struct connectdata *conn); static CURLcode rtmp_do(struct connectdata *conn, bool *done); static CURLcode rtmp_done(struct connectdata *conn, CURLcode, bool premature); static CURLcode rtmp_connect(struct connectdata *conn, bool *done); static CURLcode rtmp_disconnect(struct connectdata *conn, bool dead); static Curl_recv rtmp_recv; static Curl_send rtmp_send; /* * RTMP protocol handler.h, based on https://rtmpdump.mplayerhq.hu */ const struct Curl_handler Curl_handler_rtmp = { "RTMP", /* scheme */ rtmp_setup_connection, /* setup_connection */ rtmp_do, /* do_it */ rtmp_done, /* done */ ZERO_NULL, /* do_more */ rtmp_connect, /* connect_it */ ZERO_NULL, /* connecting */ ZERO_NULL, /* doing */ ZERO_NULL, /* proto_getsock */ ZERO_NULL, /* doing_getsock */ ZERO_NULL, /* domore_getsock */ ZERO_NULL, /* perform_getsock */ rtmp_disconnect, /* disconnect */ ZERO_NULL, /* readwrite */ ZERO_NULL, /* connection_check */ PORT_RTMP, /* defport */ CURLPROTO_RTMP, /* protocol */ PROTOPT_NONE /* flags*/ }; const struct Curl_handler Curl_handler_rtmpt = { "RTMPT", /* scheme */ rtmp_setup_connection, /* setup_connection */ rtmp_do, /* do_it */ rtmp_done, /* done */ ZERO_NULL, /* do_more */ rtmp_connect, /* connect_it */ ZERO_NULL, /* connecting */ ZERO_NULL, /* doing */ ZERO_NULL, /* proto_getsock */ ZERO_NULL, /* doing_getsock */ ZERO_NULL, /* domore_getsock */ ZERO_NULL, /* perform_getsock */ rtmp_disconnect, /* disconnect */ ZERO_NULL, /* readwrite */ ZERO_NULL, /* connection_check */ PORT_RTMPT, /* defport */ CURLPROTO_RTMPT, /* protocol */ PROTOPT_NONE /* flags*/ }; const struct Curl_handler Curl_handler_rtmpe = { "RTMPE", /* scheme */ rtmp_setup_connection, /* setup_connection */ rtmp_do, /* do_it */ rtmp_done, /* done */ ZERO_NULL, /* do_more */ rtmp_connect, /* connect_it */ ZERO_NULL, /* connecting */ ZERO_NULL, /* doing */ ZERO_NULL, /* proto_getsock */ ZERO_NULL, /* doing_getsock */ ZERO_NULL, /* domore_getsock */ ZERO_NULL, /* perform_getsock */ rtmp_disconnect, /* disconnect */ ZERO_NULL, /* readwrite */ ZERO_NULL, /* connection_check */ PORT_RTMP, /* defport */ CURLPROTO_RTMPE, /* protocol */ PROTOPT_NONE /* flags*/ }; const struct Curl_handler Curl_handler_rtmpte = { "RTMPTE", /* scheme */ rtmp_setup_connection, /* setup_connection */ rtmp_do, /* do_it */ rtmp_done, /* done */ ZERO_NULL, /* do_more */ rtmp_connect, /* connect_it */ ZERO_NULL, /* connecting */ ZERO_NULL, /* doing */ ZERO_NULL, /* proto_getsock */ ZERO_NULL, /* doing_getsock */ ZERO_NULL, /* domore_getsock */ ZERO_NULL, /* perform_getsock */ rtmp_disconnect, /* disconnect */ ZERO_NULL, /* readwrite */ ZERO_NULL, /* connection_check */ PORT_RTMPT, /* defport */ CURLPROTO_RTMPTE, /* protocol */ PROTOPT_NONE /* flags*/ }; const struct Curl_handler Curl_handler_rtmps = { "RTMPS", /* scheme */ rtmp_setup_connection, /* setup_connection */ rtmp_do, /* do_it */ rtmp_done, /* done */ ZERO_NULL, /* do_more */ rtmp_connect, /* connect_it */ ZERO_NULL, /* connecting */ ZERO_NULL, /* doing */ ZERO_NULL, /* proto_getsock */ ZERO_NULL, /* doing_getsock */ ZERO_NULL, /* domore_getsock */ ZERO_NULL, /* perform_getsock */ rtmp_disconnect, /* disconnect */ ZERO_NULL, /* readwrite */ ZERO_NULL, /* connection_check */ PORT_RTMPS, /* defport */ CURLPROTO_RTMPS, /* protocol */ PROTOPT_NONE /* flags*/ }; const struct Curl_handler Curl_handler_rtmpts = { "RTMPTS", /* scheme */ rtmp_setup_connection, /* setup_connection */ rtmp_do, /* do_it */ rtmp_done, /* done */ ZERO_NULL, /* do_more */ rtmp_connect, /* connect_it */ ZERO_NULL, /* connecting */ ZERO_NULL, /* doing */ ZERO_NULL, /* proto_getsock */ ZERO_NULL, /* doing_getsock */ ZERO_NULL, /* domore_getsock */ ZERO_NULL, /* perform_getsock */ rtmp_disconnect, /* disconnect */ ZERO_NULL, /* readwrite */ ZERO_NULL, /* connection_check */ PORT_RTMPS, /* defport */ CURLPROTO_RTMPTS, /* protocol */ PROTOPT_NONE /* flags*/ }; static CURLcode rtmp_setup_connection(struct connectdata *conn) { RTMP *r = RTMP_Alloc(); if(!r) return CURLE_OUT_OF_MEMORY; RTMP_Init(r); RTMP_SetBufferMS(r, DEF_BUFTIME); if(!RTMP_SetupURL(r, conn->data->change.url)) { RTMP_Free(r); return CURLE_URL_MALFORMAT; } conn->proto.generic = r; return CURLE_OK; } static CURLcode rtmp_connect(struct connectdata *conn, bool *done) { RTMP *r = conn->proto.generic; SET_RCVTIMEO(tv, 10); r->m_sb.sb_socket = (int)conn->sock[FIRSTSOCKET]; /* We have to know if it's a write before we send the * connect request packet */ if(conn->data->set.upload) r->Link.protocol |= RTMP_FEATURE_WRITE; /* For plain streams, use the buffer toggle trick to keep data flowing */ if(!(r->Link.lFlags & RTMP_LF_LIVE) && !(r->Link.protocol & RTMP_FEATURE_HTTP)) r->Link.lFlags |= RTMP_LF_BUFX; (void)curlx_nonblock(r->m_sb.sb_socket, FALSE); setsockopt(r->m_sb.sb_socket, SOL_SOCKET, SO_RCVTIMEO, (char *)&tv, sizeof(tv)); if(!RTMP_Connect1(r, NULL)) return CURLE_FAILED_INIT; /* Clients must send a periodic BytesReceived report to the server */ r->m_bSendCounter = true; *done = TRUE; conn->recv[FIRSTSOCKET] = rtmp_recv; conn->send[FIRSTSOCKET] = rtmp_send; return CURLE_OK; } static CURLcode rtmp_do(struct connectdata *conn, bool *done) { struct Curl_easy *data = conn->data; RTMP *r = conn->proto.generic; if(!RTMP_ConnectStream(r, 0)) return CURLE_FAILED_INIT; if(conn->data->set.upload) { Curl_pgrsSetUploadSize(data, data->state.infilesize); Curl_setup_transfer(data, -1, -1, FALSE, FIRSTSOCKET); } else Curl_setup_transfer(data, FIRSTSOCKET, -1, FALSE, -1); *done = TRUE; return CURLE_OK; } static CURLcode rtmp_done(struct connectdata *conn, CURLcode status, bool premature) { (void)conn; /* unused */ (void)status; /* unused */ (void)premature; /* unused */ return CURLE_OK; } static CURLcode rtmp_disconnect(struct connectdata *conn, bool dead_connection) { RTMP *r = conn->proto.generic; (void)dead_connection; if(r) { conn->proto.generic = NULL; RTMP_Close(r); RTMP_Free(r); } return CURLE_OK; } static ssize_t rtmp_recv(struct connectdata *conn, int sockindex, char *buf, size_t len, CURLcode *err) { RTMP *r = conn->proto.generic; ssize_t nread; (void)sockindex; /* unused */ nread = RTMP_Read(r, buf, curlx_uztosi(len)); if(nread < 0) { if(r->m_read.status == RTMP_READ_COMPLETE || r->m_read.status == RTMP_READ_EOF) { conn->data->req.size = conn->data->req.bytecount; nread = 0; } else *err = CURLE_RECV_ERROR; } return nread; } static ssize_t rtmp_send(struct connectdata *conn, int sockindex, const void *buf, size_t len, CURLcode *err) { RTMP *r = conn->proto.generic; ssize_t num; (void)sockindex; /* unused */ num = RTMP_Write(r, (char *)buf, curlx_uztosi(len)); if(num < 0) *err = CURLE_SEND_ERROR; return num; } #endif /* USE_LIBRTMP */
YifuLiu/AliOS-Things
components/curl/lib/curl_rtmp.c
C
apache-2.0
11,823
#ifndef HEADER_CURL_RTMP_H #define HEADER_CURL_RTMP_H /*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 2010, Howard Chu, <hyc@highlandsun.com> * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #ifdef USE_LIBRTMP extern const struct Curl_handler Curl_handler_rtmp; extern const struct Curl_handler Curl_handler_rtmpt; extern const struct Curl_handler Curl_handler_rtmpe; extern const struct Curl_handler Curl_handler_rtmpte; extern const struct Curl_handler Curl_handler_rtmps; extern const struct Curl_handler Curl_handler_rtmpts; #endif #endif /* HEADER_CURL_RTMP_H */
YifuLiu/AliOS-Things
components/curl/lib/curl_rtmp.h
C
apache-2.0
1,443
/*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 2012 - 2019, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * * RFC2195 CRAM-MD5 authentication * RFC2617 Basic and Digest Access Authentication * RFC2831 DIGEST-MD5 authentication * RFC4422 Simple Authentication and Security Layer (SASL) * RFC4616 PLAIN authentication * RFC6749 OAuth 2.0 Authorization Framework * RFC7628 A Set of SASL Mechanisms for OAuth * Draft LOGIN SASL Mechanism <draft-murchison-sasl-login-00.txt> * ***************************************************************************/ #include "curl_setup.h" #if !defined(CURL_DISABLE_IMAP) || !defined(CURL_DISABLE_SMTP) || \ !defined(CURL_DISABLE_POP3) #include <curl/curl.h> #include "urldata.h" #include "curl_base64.h" #include "curl_md5.h" #include "vauth/vauth.h" #include "vtls/vtls.h" #include "curl_hmac.h" #include "curl_sasl.h" #include "warnless.h" #include "strtok.h" #include "sendf.h" #include "non-ascii.h" /* included for Curl_convert_... prototypes */ /* The last 3 #include files should be in this order */ #include "curl_printf.h" #include "curl_memory.h" #include "memdebug.h" /* Supported mechanisms */ static const struct { const char *name; /* Name */ size_t len; /* Name length */ unsigned int bit; /* Flag bit */ } mechtable[] = { { "LOGIN", 5, SASL_MECH_LOGIN }, { "PLAIN", 5, SASL_MECH_PLAIN }, { "CRAM-MD5", 8, SASL_MECH_CRAM_MD5 }, { "DIGEST-MD5", 10, SASL_MECH_DIGEST_MD5 }, { "GSSAPI", 6, SASL_MECH_GSSAPI }, { "EXTERNAL", 8, SASL_MECH_EXTERNAL }, { "NTLM", 4, SASL_MECH_NTLM }, { "XOAUTH2", 7, SASL_MECH_XOAUTH2 }, { "OAUTHBEARER", 11, SASL_MECH_OAUTHBEARER }, { ZERO_NULL, 0, 0 } }; /* * Curl_sasl_cleanup() * * This is used to cleanup any libraries or curl modules used by the sasl * functions. * * Parameters: * * conn [in] - The connection data. * authused [in] - The authentication mechanism used. */ void Curl_sasl_cleanup(struct connectdata *conn, unsigned int authused) { #if defined(USE_KERBEROS5) /* Cleanup the gssapi structure */ if(authused == SASL_MECH_GSSAPI) { Curl_auth_cleanup_gssapi(&conn->krb5); } #endif #if defined(USE_NTLM) /* Cleanup the NTLM structure */ if(authused == SASL_MECH_NTLM) { Curl_auth_cleanup_ntlm(&conn->ntlm); } #endif #if !defined(USE_KERBEROS5) && !defined(USE_NTLM) /* Reserved for future use */ (void)conn; (void)authused; #endif } /* * Curl_sasl_decode_mech() * * Convert a SASL mechanism name into a token. * * Parameters: * * ptr [in] - The mechanism string. * maxlen [in] - Maximum mechanism string length. * len [out] - If not NULL, effective name length. * * Returns the SASL mechanism token or 0 if no match. */ unsigned int Curl_sasl_decode_mech(const char *ptr, size_t maxlen, size_t *len) { unsigned int i; char c; for(i = 0; mechtable[i].name; i++) { if(maxlen >= mechtable[i].len && !memcmp(ptr, mechtable[i].name, mechtable[i].len)) { if(len) *len = mechtable[i].len; if(maxlen == mechtable[i].len) return mechtable[i].bit; c = ptr[mechtable[i].len]; if(!ISUPPER(c) && !ISDIGIT(c) && c != '-' && c != '_') return mechtable[i].bit; } } return 0; } /* * Curl_sasl_parse_url_auth_option() * * Parse the URL login options. */ CURLcode Curl_sasl_parse_url_auth_option(struct SASL *sasl, const char *value, size_t len) { CURLcode result = CURLE_OK; size_t mechlen; if(!len) return CURLE_URL_MALFORMAT; if(sasl->resetprefs) { sasl->resetprefs = FALSE; sasl->prefmech = SASL_AUTH_NONE; } if(!strncmp(value, "*", len)) sasl->prefmech = SASL_AUTH_DEFAULT; else { unsigned int mechbit = Curl_sasl_decode_mech(value, len, &mechlen); if(mechbit && mechlen == len) sasl->prefmech |= mechbit; else result = CURLE_URL_MALFORMAT; } return result; } /* * Curl_sasl_init() * * Initializes the SASL structure. */ void Curl_sasl_init(struct SASL *sasl, const struct SASLproto *params) { sasl->params = params; /* Set protocol dependent parameters */ sasl->state = SASL_STOP; /* Not yet running */ sasl->authmechs = SASL_AUTH_NONE; /* No known authentication mechanism yet */ sasl->prefmech = SASL_AUTH_DEFAULT; /* Prefer all mechanisms */ sasl->authused = SASL_AUTH_NONE; /* No the authentication mechanism used */ sasl->resetprefs = TRUE; /* Reset prefmech upon AUTH parsing. */ sasl->mutual_auth = FALSE; /* No mutual authentication (GSSAPI only) */ sasl->force_ir = FALSE; /* Respect external option */ } /* * state() * * This is the ONLY way to change SASL state! */ static void state(struct SASL *sasl, struct connectdata *conn, saslstate newstate) { #if defined(DEBUGBUILD) && !defined(CURL_DISABLE_VERBOSE_STRINGS) /* for debug purposes */ static const char * const names[]={ "STOP", "PLAIN", "LOGIN", "LOGIN_PASSWD", "EXTERNAL", "CRAMMD5", "DIGESTMD5", "DIGESTMD5_RESP", "NTLM", "NTLM_TYPE2MSG", "GSSAPI", "GSSAPI_TOKEN", "GSSAPI_NO_DATA", "OAUTH2", "OAUTH2_RESP", "CANCEL", "FINAL", /* LAST */ }; if(sasl->state != newstate) infof(conn->data, "SASL %p state change from %s to %s\n", (void *)sasl, names[sasl->state], names[newstate]); #else (void) conn; #endif sasl->state = newstate; } /* * Curl_sasl_can_authenticate() * * Check if we have enough auth data and capabilities to authenticate. */ bool Curl_sasl_can_authenticate(struct SASL *sasl, struct connectdata *conn) { /* Have credentials been provided? */ if(conn->bits.user_passwd) return TRUE; /* EXTERNAL can authenticate without a user name and/or password */ if(sasl->authmechs & sasl->prefmech & SASL_MECH_EXTERNAL) return TRUE; return FALSE; } /* * Curl_sasl_start() * * Calculate the required login details for SASL authentication. */ CURLcode Curl_sasl_start(struct SASL *sasl, struct connectdata *conn, bool force_ir, saslprogress *progress) { CURLcode result = CURLE_OK; struct Curl_easy *data = conn->data; unsigned int enabledmechs; const char *mech = NULL; char *resp = NULL; size_t len = 0; saslstate state1 = SASL_STOP; saslstate state2 = SASL_FINAL; const char * const hostname = SSL_IS_PROXY() ? conn->http_proxy.host.name : conn->host.name; const long int port = SSL_IS_PROXY() ? conn->port : conn->remote_port; #if defined(USE_KERBEROS5) || defined(USE_NTLM) const char *service = data->set.str[STRING_SERVICE_NAME] ? data->set.str[STRING_SERVICE_NAME] : sasl->params->service; #endif sasl->force_ir = force_ir; /* Latch for future use */ sasl->authused = 0; /* No mechanism used yet */ enabledmechs = sasl->authmechs & sasl->prefmech; *progress = SASL_IDLE; /* Calculate the supported authentication mechanism, by decreasing order of security, as well as the initial response where appropriate */ if((enabledmechs & SASL_MECH_EXTERNAL) && !conn->passwd[0]) { mech = SASL_MECH_STRING_EXTERNAL; state1 = SASL_EXTERNAL; sasl->authused = SASL_MECH_EXTERNAL; if(force_ir || data->set.sasl_ir) result = Curl_auth_create_external_message(data, conn->user, &resp, &len); } else if(conn->bits.user_passwd) { #if defined(USE_KERBEROS5) if((enabledmechs & SASL_MECH_GSSAPI) && Curl_auth_is_gssapi_supported() && Curl_auth_user_contains_domain(conn->user)) { sasl->mutual_auth = FALSE; mech = SASL_MECH_STRING_GSSAPI; state1 = SASL_GSSAPI; state2 = SASL_GSSAPI_TOKEN; sasl->authused = SASL_MECH_GSSAPI; if(force_ir || data->set.sasl_ir) result = Curl_auth_create_gssapi_user_message(data, conn->user, conn->passwd, service, data->conn->host.name, sasl->mutual_auth, NULL, &conn->krb5, &resp, &len); } else #endif #ifndef CURL_DISABLE_CRYPTO_AUTH if((enabledmechs & SASL_MECH_DIGEST_MD5) && Curl_auth_is_digest_supported()) { mech = SASL_MECH_STRING_DIGEST_MD5; state1 = SASL_DIGESTMD5; sasl->authused = SASL_MECH_DIGEST_MD5; } else if(enabledmechs & SASL_MECH_CRAM_MD5) { mech = SASL_MECH_STRING_CRAM_MD5; state1 = SASL_CRAMMD5; sasl->authused = SASL_MECH_CRAM_MD5; } else #endif #ifdef USE_NTLM if((enabledmechs & SASL_MECH_NTLM) && Curl_auth_is_ntlm_supported()) { mech = SASL_MECH_STRING_NTLM; state1 = SASL_NTLM; state2 = SASL_NTLM_TYPE2MSG; sasl->authused = SASL_MECH_NTLM; if(force_ir || data->set.sasl_ir) result = Curl_auth_create_ntlm_type1_message(data, conn->user, conn->passwd, service, hostname, &conn->ntlm, &resp, &len); } else #endif if((enabledmechs & SASL_MECH_OAUTHBEARER) && conn->oauth_bearer) { mech = SASL_MECH_STRING_OAUTHBEARER; state1 = SASL_OAUTH2; state2 = SASL_OAUTH2_RESP; sasl->authused = SASL_MECH_OAUTHBEARER; if(force_ir || data->set.sasl_ir) result = Curl_auth_create_oauth_bearer_message(data, conn->user, hostname, port, conn->oauth_bearer, &resp, &len); } else if((enabledmechs & SASL_MECH_XOAUTH2) && conn->oauth_bearer) { mech = SASL_MECH_STRING_XOAUTH2; state1 = SASL_OAUTH2; sasl->authused = SASL_MECH_XOAUTH2; if(force_ir || data->set.sasl_ir) result = Curl_auth_create_xoauth_bearer_message(data, conn->user, conn->oauth_bearer, &resp, &len); } else if(enabledmechs & SASL_MECH_PLAIN) { mech = SASL_MECH_STRING_PLAIN; state1 = SASL_PLAIN; sasl->authused = SASL_MECH_PLAIN; if(force_ir || data->set.sasl_ir) result = Curl_auth_create_plain_message(data, NULL, conn->user, conn->passwd, &resp, &len); } else if(enabledmechs & SASL_MECH_LOGIN) { mech = SASL_MECH_STRING_LOGIN; state1 = SASL_LOGIN; state2 = SASL_LOGIN_PASSWD; sasl->authused = SASL_MECH_LOGIN; if(force_ir || data->set.sasl_ir) result = Curl_auth_create_login_message(data, conn->user, &resp, &len); } } if(!result && mech) { if(resp && sasl->params->maxirlen && strlen(mech) + len > sasl->params->maxirlen) { free(resp); resp = NULL; } result = sasl->params->sendauth(conn, mech, resp); if(!result) { *progress = SASL_INPROGRESS; state(sasl, conn, resp ? state2 : state1); } } free(resp); return result; } /* * Curl_sasl_continue() * * Continue the authentication. */ CURLcode Curl_sasl_continue(struct SASL *sasl, struct connectdata *conn, int code, saslprogress *progress) { CURLcode result = CURLE_OK; struct Curl_easy *data = conn->data; saslstate newstate = SASL_FINAL; char *resp = NULL; const char * const hostname = SSL_IS_PROXY() ? conn->http_proxy.host.name : conn->host.name; const long int port = SSL_IS_PROXY() ? conn->port : conn->remote_port; #if !defined(CURL_DISABLE_CRYPTO_AUTH) char *chlg = NULL; size_t chlglen = 0; #endif #if !defined(CURL_DISABLE_CRYPTO_AUTH) || defined(USE_KERBEROS5) || \ defined(USE_NTLM) const char *service = data->set.str[STRING_SERVICE_NAME] ? data->set.str[STRING_SERVICE_NAME] : sasl->params->service; char *serverdata; #endif size_t len = 0; *progress = SASL_INPROGRESS; if(sasl->state == SASL_FINAL) { if(code != sasl->params->finalcode) result = CURLE_LOGIN_DENIED; *progress = SASL_DONE; state(sasl, conn, SASL_STOP); return result; } if(sasl->state != SASL_CANCEL && sasl->state != SASL_OAUTH2_RESP && code != sasl->params->contcode) { *progress = SASL_DONE; state(sasl, conn, SASL_STOP); return CURLE_LOGIN_DENIED; } switch(sasl->state) { case SASL_STOP: *progress = SASL_DONE; return result; case SASL_PLAIN: result = Curl_auth_create_plain_message(data, NULL, conn->user, conn->passwd, &resp, &len); break; case SASL_LOGIN: result = Curl_auth_create_login_message(data, conn->user, &resp, &len); newstate = SASL_LOGIN_PASSWD; break; case SASL_LOGIN_PASSWD: result = Curl_auth_create_login_message(data, conn->passwd, &resp, &len); break; case SASL_EXTERNAL: result = Curl_auth_create_external_message(data, conn->user, &resp, &len); break; #ifndef CURL_DISABLE_CRYPTO_AUTH case SASL_CRAMMD5: sasl->params->getmessage(data->state.buffer, &serverdata); result = Curl_auth_decode_cram_md5_message(serverdata, &chlg, &chlglen); if(!result) result = Curl_auth_create_cram_md5_message(data, chlg, conn->user, conn->passwd, &resp, &len); free(chlg); break; case SASL_DIGESTMD5: sasl->params->getmessage(data->state.buffer, &serverdata); result = Curl_auth_create_digest_md5_message(data, serverdata, conn->user, conn->passwd, service, &resp, &len); newstate = SASL_DIGESTMD5_RESP; break; case SASL_DIGESTMD5_RESP: resp = strdup(""); if(!resp) result = CURLE_OUT_OF_MEMORY; break; #endif #ifdef USE_NTLM case SASL_NTLM: /* Create the type-1 message */ result = Curl_auth_create_ntlm_type1_message(data, conn->user, conn->passwd, service, hostname, &conn->ntlm, &resp, &len); newstate = SASL_NTLM_TYPE2MSG; break; case SASL_NTLM_TYPE2MSG: /* Decode the type-2 message */ sasl->params->getmessage(data->state.buffer, &serverdata); result = Curl_auth_decode_ntlm_type2_message(data, serverdata, &conn->ntlm); if(!result) result = Curl_auth_create_ntlm_type3_message(data, conn->user, conn->passwd, &conn->ntlm, &resp, &len); break; #endif #if defined(USE_KERBEROS5) case SASL_GSSAPI: result = Curl_auth_create_gssapi_user_message(data, conn->user, conn->passwd, service, data->conn->host.name, sasl->mutual_auth, NULL, &conn->krb5, &resp, &len); newstate = SASL_GSSAPI_TOKEN; break; case SASL_GSSAPI_TOKEN: sasl->params->getmessage(data->state.buffer, &serverdata); if(sasl->mutual_auth) { /* Decode the user token challenge and create the optional response message */ result = Curl_auth_create_gssapi_user_message(data, NULL, NULL, NULL, NULL, sasl->mutual_auth, serverdata, &conn->krb5, &resp, &len); newstate = SASL_GSSAPI_NO_DATA; } else /* Decode the security challenge and create the response message */ result = Curl_auth_create_gssapi_security_message(data, serverdata, &conn->krb5, &resp, &len); break; case SASL_GSSAPI_NO_DATA: sasl->params->getmessage(data->state.buffer, &serverdata); /* Decode the security challenge and create the response message */ result = Curl_auth_create_gssapi_security_message(data, serverdata, &conn->krb5, &resp, &len); break; #endif case SASL_OAUTH2: /* Create the authorisation message */ if(sasl->authused == SASL_MECH_OAUTHBEARER) { result = Curl_auth_create_oauth_bearer_message(data, conn->user, hostname, port, conn->oauth_bearer, &resp, &len); /* Failures maybe sent by the server as continuations for OAUTHBEARER */ newstate = SASL_OAUTH2_RESP; } else result = Curl_auth_create_xoauth_bearer_message(data, conn->user, conn->oauth_bearer, &resp, &len); break; case SASL_OAUTH2_RESP: /* The continuation is optional so check the response code */ if(code == sasl->params->finalcode) { /* Final response was received so we are done */ *progress = SASL_DONE; state(sasl, conn, SASL_STOP); return result; } else if(code == sasl->params->contcode) { /* Acknowledge the continuation by sending a 0x01 response base64 encoded */ resp = strdup("AQ=="); if(!resp) result = CURLE_OUT_OF_MEMORY; break; } else { *progress = SASL_DONE; state(sasl, conn, SASL_STOP); return CURLE_LOGIN_DENIED; } case SASL_CANCEL: /* Remove the offending mechanism from the supported list */ sasl->authmechs ^= sasl->authused; /* Start an alternative SASL authentication */ result = Curl_sasl_start(sasl, conn, sasl->force_ir, progress); newstate = sasl->state; /* Use state from Curl_sasl_start() */ break; default: failf(data, "Unsupported SASL authentication mechanism"); result = CURLE_UNSUPPORTED_PROTOCOL; /* Should not happen */ break; } switch(result) { case CURLE_BAD_CONTENT_ENCODING: /* Cancel dialog */ result = sasl->params->sendcont(conn, "*"); newstate = SASL_CANCEL; break; case CURLE_OK: if(resp) result = sasl->params->sendcont(conn, resp); break; default: newstate = SASL_STOP; /* Stop on error */ *progress = SASL_DONE; break; } free(resp); state(sasl, conn, newstate); return result; } #endif /* protocols are enabled that use SASL */
YifuLiu/AliOS-Things
components/curl/lib/curl_sasl.c
C
apache-2.0
20,468
#ifndef HEADER_CURL_SASL_H #define HEADER_CURL_SASL_H /*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 2012 - 2016, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include <curl/curl.h> struct Curl_easy; struct connectdata; /* Authentication mechanism flags */ #define SASL_MECH_LOGIN (1 << 0) #define SASL_MECH_PLAIN (1 << 1) #define SASL_MECH_CRAM_MD5 (1 << 2) #define SASL_MECH_DIGEST_MD5 (1 << 3) #define SASL_MECH_GSSAPI (1 << 4) #define SASL_MECH_EXTERNAL (1 << 5) #define SASL_MECH_NTLM (1 << 6) #define SASL_MECH_XOAUTH2 (1 << 7) #define SASL_MECH_OAUTHBEARER (1 << 8) /* Authentication mechanism values */ #define SASL_AUTH_NONE 0 #define SASL_AUTH_ANY ~0U #define SASL_AUTH_DEFAULT (SASL_AUTH_ANY & ~SASL_MECH_EXTERNAL) /* Authentication mechanism strings */ #define SASL_MECH_STRING_LOGIN "LOGIN" #define SASL_MECH_STRING_PLAIN "PLAIN" #define SASL_MECH_STRING_CRAM_MD5 "CRAM-MD5" #define SASL_MECH_STRING_DIGEST_MD5 "DIGEST-MD5" #define SASL_MECH_STRING_GSSAPI "GSSAPI" #define SASL_MECH_STRING_EXTERNAL "EXTERNAL" #define SASL_MECH_STRING_NTLM "NTLM" #define SASL_MECH_STRING_XOAUTH2 "XOAUTH2" #define SASL_MECH_STRING_OAUTHBEARER "OAUTHBEARER" /* SASL machine states */ typedef enum { SASL_STOP, SASL_PLAIN, SASL_LOGIN, SASL_LOGIN_PASSWD, SASL_EXTERNAL, SASL_CRAMMD5, SASL_DIGESTMD5, SASL_DIGESTMD5_RESP, SASL_NTLM, SASL_NTLM_TYPE2MSG, SASL_GSSAPI, SASL_GSSAPI_TOKEN, SASL_GSSAPI_NO_DATA, SASL_OAUTH2, SASL_OAUTH2_RESP, SASL_CANCEL, SASL_FINAL } saslstate; /* Progress indicator */ typedef enum { SASL_IDLE, SASL_INPROGRESS, SASL_DONE } saslprogress; /* Protocol dependent SASL parameters */ struct SASLproto { const char *service; /* The service name */ int contcode; /* Code to receive when continuation is expected */ int finalcode; /* Code to receive upon authentication success */ size_t maxirlen; /* Maximum initial response length */ CURLcode (*sendauth)(struct connectdata *conn, const char *mech, const char *ir); /* Send authentication command */ CURLcode (*sendcont)(struct connectdata *conn, const char *contauth); /* Send authentication continuation */ void (*getmessage)(char *buffer, char **outptr); /* Get SASL response message */ }; /* Per-connection parameters */ struct SASL { const struct SASLproto *params; /* Protocol dependent parameters */ saslstate state; /* Current machine state */ unsigned int authmechs; /* Accepted authentication mechanisms */ unsigned int prefmech; /* Preferred authentication mechanism */ unsigned int authused; /* Auth mechanism used for the connection */ bool resetprefs; /* For URL auth option parsing. */ bool mutual_auth; /* Mutual authentication enabled (GSSAPI only) */ bool force_ir; /* Protocol always supports initial response */ }; /* This is used to test whether the line starts with the given mechanism */ #define sasl_mech_equal(line, wordlen, mech) \ (wordlen == (sizeof(mech) - 1) / sizeof(char) && \ !memcmp(line, mech, wordlen)) /* This is used to cleanup any libraries or curl modules used by the sasl functions */ void Curl_sasl_cleanup(struct connectdata *conn, unsigned int authused); /* Convert a mechanism name to a token */ unsigned int Curl_sasl_decode_mech(const char *ptr, size_t maxlen, size_t *len); /* Parse the URL login options */ CURLcode Curl_sasl_parse_url_auth_option(struct SASL *sasl, const char *value, size_t len); /* Initializes an SASL structure */ void Curl_sasl_init(struct SASL *sasl, const struct SASLproto *params); /* Check if we have enough auth data and capabilities to authenticate */ bool Curl_sasl_can_authenticate(struct SASL *sasl, struct connectdata *conn); /* Calculate the required login details for SASL authentication */ CURLcode Curl_sasl_start(struct SASL *sasl, struct connectdata *conn, bool force_ir, saslprogress *progress); /* Continue an SASL authentication */ CURLcode Curl_sasl_continue(struct SASL *sasl, struct connectdata *conn, int code, saslprogress *progress); #endif /* HEADER_CURL_SASL_H */
YifuLiu/AliOS-Things
components/curl/lib/curl_sasl.h
C
apache-2.0
5,410
#ifndef HEADER_CURL_SECURITY_H #define HEADER_CURL_SECURITY_H /*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2016, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ struct Curl_sec_client_mech { const char *name; size_t size; int (*init)(void *); int (*auth)(void *, struct connectdata *); void (*end)(void *); int (*check_prot)(void *, int); int (*overhead)(void *, int, int); int (*encode)(void *, const void *, int, int, void **); int (*decode)(void *, void *, int, int, struct connectdata *); }; #define AUTH_OK 0 #define AUTH_CONTINUE 1 #define AUTH_ERROR 2 #ifdef HAVE_GSSAPI int Curl_sec_read_msg(struct connectdata *conn, char *, enum protection_level); void Curl_sec_end(struct connectdata *); CURLcode Curl_sec_login(struct connectdata *); int Curl_sec_request_prot(struct connectdata *conn, const char *level); extern struct Curl_sec_client_mech Curl_krb5_client_mech; #endif #endif /* HEADER_CURL_SECURITY_H */
YifuLiu/AliOS-Things
components/curl/lib/curl_sec.h
C
apache-2.0
1,906
#ifndef HEADER_CURL_SETUP_H #define HEADER_CURL_SETUP_H /*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2019, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #if defined(BUILDING_LIBCURL) && !defined(CURL_NO_OLDIES) #define CURL_NO_OLDIES #endif /* * Define WIN32 when build target is Win32 API */ #if (defined(_WIN32) || defined(__WIN32__)) && !defined(WIN32) && \ !defined(__SYMBIAN32__) #define WIN32 #endif #ifdef WIN32 /* * Don't include unneeded stuff in Windows headers to avoid compiler * warnings and macro clashes. * Make sure to define this macro before including any Windows headers. */ # ifndef WIN32_LEAN_AND_MEAN # define WIN32_LEAN_AND_MEAN # endif # ifndef NOGDI # define NOGDI # endif #endif /* * Include configuration script results or hand-crafted * configuration file for platforms which lack config tool. */ #ifdef HAVE_CONFIG_H #include "curl_config.h" #else /* HAVE_CONFIG_H */ #ifdef _WIN32_WCE # include "config-win32ce.h" #else # ifdef WIN32 # include "config-win32.h" # endif #endif #if defined(macintosh) && defined(__MRC__) # include "config-mac.h" #endif #ifdef __riscos__ # include "config-riscos.h" #endif #ifdef __AMIGA__ # include "config-amigaos.h" #endif #ifdef __SYMBIAN32__ # include "config-symbian.h" #endif #ifdef __OS400__ # include "config-os400.h" #endif #ifdef TPF # include "config-tpf.h" #endif #ifdef __VXWORKS__ # include "config-vxworks.h" #endif #endif /* HAVE_CONFIG_H */ /* ================================================================ */ /* Definition of preprocessor macros/symbols which modify compiler */ /* behavior or generated code characteristics must be done here, */ /* as appropriate, before any system header file is included. It is */ /* also possible to have them defined in the config file included */ /* before this point. As a result of all this we frown inclusion of */ /* system header files in our config files, avoid this at any cost. */ /* ================================================================ */ /* * AIX 4.3 and newer needs _THREAD_SAFE defined to build * proper reentrant code. Others may also need it. */ #ifdef NEED_THREAD_SAFE # ifndef _THREAD_SAFE # define _THREAD_SAFE # endif #endif /* * Tru64 needs _REENTRANT set for a few function prototypes and * things to appear in the system header files. Unixware needs it * to build proper reentrant code. Others may also need it. */ #ifdef NEED_REENTRANT # ifndef _REENTRANT # define _REENTRANT # endif #endif /* Solaris needs this to get a POSIX-conformant getpwuid_r */ #if defined(sun) || defined(__sun) # ifndef _POSIX_PTHREAD_SEMANTICS # define _POSIX_PTHREAD_SEMANTICS 1 # endif #endif /* ================================================================ */ /* If you need to include a system header file for your platform, */ /* please, do it beyond the point further indicated in this file. */ /* ================================================================ */ #include <curl/curl.h> #define CURL_SIZEOF_CURL_OFF_T SIZEOF_CURL_OFF_T /* * Disable other protocols when http is the only one desired. */ #ifdef HTTP_ONLY # ifndef CURL_DISABLE_TFTP # define CURL_DISABLE_TFTP # endif # ifndef CURL_DISABLE_FTP # define CURL_DISABLE_FTP # endif # ifndef CURL_DISABLE_LDAP # define CURL_DISABLE_LDAP # endif # ifndef CURL_DISABLE_TELNET # define CURL_DISABLE_TELNET # endif # ifndef CURL_DISABLE_DICT # define CURL_DISABLE_DICT # endif # ifndef CURL_DISABLE_FILE # define CURL_DISABLE_FILE # endif # ifndef CURL_DISABLE_RTSP # define CURL_DISABLE_RTSP # endif # ifndef CURL_DISABLE_POP3 # define CURL_DISABLE_POP3 # endif # ifndef CURL_DISABLE_IMAP # define CURL_DISABLE_IMAP # endif # ifndef CURL_DISABLE_SMTP # define CURL_DISABLE_SMTP # endif # ifndef CURL_DISABLE_GOPHER # define CURL_DISABLE_GOPHER # endif # ifndef CURL_DISABLE_SMB # define CURL_DISABLE_SMB # endif #endif /* * When http is disabled rtsp is not supported. */ #if defined(CURL_DISABLE_HTTP) && !defined(CURL_DISABLE_RTSP) # define CURL_DISABLE_RTSP #endif /* ================================================================ */ /* No system header file shall be included in this file before this */ /* point. The only allowed ones are those included from curl/system.h */ /* ================================================================ */ /* * OS/400 setup file includes some system headers. */ #ifdef __OS400__ # include "setup-os400.h" #endif /* * VMS setup file includes some system headers. */ #ifdef __VMS # include "setup-vms.h" #endif /* * Use getaddrinfo to resolve the IPv4 address literal. If the current network * interface doesn't support IPv4, but supports IPv6, NAT64, and DNS64, * performing this task will result in a synthesized IPv6 address. */ #ifdef __APPLE__ #define USE_RESOLVE_ON_IPS 1 #endif /* * Include header files for windows builds before redefining anything. * Use this preprocessor block only to include or exclude windows.h, * winsock2.h, ws2tcpip.h or winsock.h. Any other windows thing belongs * to any other further and independent block. Under Cygwin things work * just as under linux (e.g. <sys/socket.h>) and the winsock headers should * never be included when __CYGWIN__ is defined. configure script takes * care of this, not defining HAVE_WINDOWS_H, HAVE_WINSOCK_H, HAVE_WINSOCK2_H, * neither HAVE_WS2TCPIP_H when __CYGWIN__ is defined. */ #ifdef HAVE_WINDOWS_H # if defined(UNICODE) && !defined(_UNICODE) # define _UNICODE # endif # if defined(_UNICODE) && !defined(UNICODE) # define UNICODE # endif # include <winerror.h> # include <windows.h> # ifdef HAVE_WINSOCK2_H # include <winsock2.h> # ifdef HAVE_WS2TCPIP_H # include <ws2tcpip.h> # endif # else # ifdef HAVE_WINSOCK_H # include <winsock.h> # endif # endif # include <tchar.h> # ifdef UNICODE typedef wchar_t *(*curl_wcsdup_callback)(const wchar_t *str); # endif #endif /* * Define USE_WINSOCK to 2 if we have and use WINSOCK2 API, else * define USE_WINSOCK to 1 if we have and use WINSOCK API, else * undefine USE_WINSOCK. */ #undef USE_WINSOCK #ifdef HAVE_WINSOCK2_H # define USE_WINSOCK 2 #else # ifdef HAVE_WINSOCK_H # define USE_WINSOCK 1 # endif #endif #ifdef USE_LWIPSOCK # include <lwip/init.h> # include <lwip/sockets.h> # include <lwip/netdb.h> #endif #ifdef HAVE_EXTRA_STRICMP_H # include <extra/stricmp.h> #endif #ifdef HAVE_EXTRA_STRDUP_H # include <extra/strdup.h> #endif #ifdef TPF # include <strings.h> /* for bzero, strcasecmp, and strncasecmp */ # include <string.h> /* for strcpy and strlen */ # include <stdlib.h> /* for rand and srand */ # include <sys/socket.h> /* for select and ioctl*/ # include <netdb.h> /* for in_addr_t definition */ # include <tpf/sysapi.h> /* for tpf_process_signals */ /* change which select is used for libcurl */ # define select(a,b,c,d,e) tpf_select_libcurl(a,b,c,d,e) #endif #ifdef __VXWORKS__ # include <sockLib.h> /* for generic BSD socket functions */ # include <ioLib.h> /* for basic I/O interface functions */ #endif #ifdef __AMIGA__ # include <exec/types.h> # include <exec/execbase.h> # include <proto/exec.h> # include <proto/dos.h> # ifdef HAVE_PROTO_BSDSOCKET_H # include <proto/bsdsocket.h> /* ensure bsdsocket.library use */ # define select(a,b,c,d,e) WaitSelect(a,b,c,d,e,0) # endif #endif #include <stdio.h> #ifdef HAVE_ASSERT_H #include <assert.h> #endif #ifdef __TANDEM /* for nsr-tandem-nsk systems */ #include <floss.h> #endif #ifndef STDC_HEADERS /* no standard C headers! */ #include <curl/stdcheaders.h> #endif #ifdef __POCC__ # include <sys/types.h> # include <unistd.h> # define sys_nerr EILSEQ #endif /* * Salford-C kludge section (mostly borrowed from wxWidgets). */ #ifdef __SALFORDC__ #pragma suppress 353 /* Possible nested comments */ #pragma suppress 593 /* Define not used */ #pragma suppress 61 /* enum has no name */ #pragma suppress 106 /* unnamed, unused parameter */ #include <clib.h> #endif /* * Large file (>2Gb) support using WIN32 functions. */ #ifdef USE_WIN32_LARGE_FILES # include <io.h> # include <sys/types.h> # include <sys/stat.h> # undef lseek # define lseek(fdes,offset,whence) _lseeki64(fdes, offset, whence) # undef fstat # define fstat(fdes,stp) _fstati64(fdes, stp) # undef stat # define stat(fname,stp) _stati64(fname, stp) # define struct_stat struct _stati64 # define LSEEK_ERROR (__int64)-1 #endif /* * Small file (<2Gb) support using WIN32 functions. */ #ifdef USE_WIN32_SMALL_FILES # include <io.h> # include <sys/types.h> # include <sys/stat.h> # ifndef _WIN32_WCE # undef lseek # define lseek(fdes,offset,whence) _lseek(fdes, (long)offset, whence) # define fstat(fdes,stp) _fstat(fdes, stp) # define stat(fname,stp) _stat(fname, stp) # define struct_stat struct _stat # endif # define LSEEK_ERROR (long)-1 #endif #ifndef struct_stat # define struct_stat struct stat #endif #ifndef LSEEK_ERROR # define LSEEK_ERROR (off_t)-1 #endif #ifndef SIZEOF_TIME_T /* assume default size of time_t to be 32 bit */ #define SIZEOF_TIME_T 4 #endif /* * Default sizeof(off_t) in case it hasn't been defined in config file. */ #ifndef SIZEOF_OFF_T # if defined(__VMS) && !defined(__VAX) # if defined(_LARGEFILE) # define SIZEOF_OFF_T 8 # endif # elif defined(__OS400__) && defined(__ILEC400__) # if defined(_LARGE_FILES) # define SIZEOF_OFF_T 8 # endif # elif defined(__MVS__) && defined(__IBMC__) # if defined(_LP64) || defined(_LARGE_FILES) # define SIZEOF_OFF_T 8 # endif # elif defined(__370__) && defined(__IBMC__) # if defined(_LP64) || defined(_LARGE_FILES) # define SIZEOF_OFF_T 8 # endif # endif # ifndef SIZEOF_OFF_T # define SIZEOF_OFF_T 4 # endif #endif #if (SIZEOF_CURL_OFF_T == 4) # define CURL_OFF_T_MAX CURL_OFF_T_C(0x7FFFFFFF) #else /* assume CURL_SIZEOF_CURL_OFF_T == 8 */ # define CURL_OFF_T_MAX CURL_OFF_T_C(0x7FFFFFFFFFFFFFFF) #endif #define CURL_OFF_T_MIN (-CURL_OFF_T_MAX - CURL_OFF_T_C(1)) #if (SIZEOF_TIME_T == 4) # ifdef HAVE_TIME_T_UNSIGNED # define TIME_T_MAX UINT_MAX # define TIME_T_MIN 0 # else # define TIME_T_MAX INT_MAX # define TIME_T_MIN INT_MIN # endif #else # ifdef HAVE_TIME_T_UNSIGNED # define TIME_T_MAX 0xFFFFFFFFFFFFFFFF # define TIME_T_MIN 0 # else # define TIME_T_MAX 0x7FFFFFFFFFFFFFFF # define TIME_T_MIN (-TIME_T_MAX - 1) # endif #endif #ifndef SIZE_T_MAX /* some limits.h headers have this defined, some don't */ #if defined(SIZEOF_SIZE_T) && (SIZEOF_SIZE_T > 4) #define SIZE_T_MAX 18446744073709551615U #else #define SIZE_T_MAX 4294967295U #endif #endif /* * Arg 2 type for gethostname in case it hasn't been defined in config file. */ #ifndef GETHOSTNAME_TYPE_ARG2 # ifdef USE_WINSOCK # define GETHOSTNAME_TYPE_ARG2 int # else # define GETHOSTNAME_TYPE_ARG2 size_t # endif #endif /* Below we define some functions. They should 4. set the SIGALRM signal timeout 5. set dir/file naming defines */ #ifdef WIN32 # define DIR_CHAR "\\" # define DOT_CHAR "_" #else /* WIN32 */ # ifdef MSDOS /* Watt-32 */ # include <sys/ioctl.h> # define select(n,r,w,x,t) select_s(n,r,w,x,t) # define ioctl(x,y,z) ioctlsocket(x,y,(char *)(z)) # include <tcp.h> # ifdef word # undef word # endif # ifdef byte # undef byte # endif # endif /* MSDOS */ # ifdef __minix /* Minix 3 versions up to at least 3.1.3 are missing these prototypes */ extern char *strtok_r(char *s, const char *delim, char **last); extern struct tm *gmtime_r(const time_t * const timep, struct tm *tmp); # endif # define DIR_CHAR "/" # ifndef DOT_CHAR # define DOT_CHAR "." # endif # ifdef MSDOS # undef DOT_CHAR # define DOT_CHAR "_" # endif # ifndef fileno /* sunos 4 have this as a macro! */ int fileno(FILE *stream); # endif #endif /* WIN32 */ /* * msvc 6.0 requires PSDK in order to have INET6_ADDRSTRLEN * defined in ws2tcpip.h as well as to provide IPv6 support. * Does not apply if lwIP is used. */ #if defined(_MSC_VER) && !defined(__POCC__) && !defined(USE_LWIPSOCK) # if !defined(HAVE_WS2TCPIP_H) || \ ((_MSC_VER < 1300) && !defined(INET6_ADDRSTRLEN)) # undef HAVE_GETADDRINFO_THREADSAFE # undef HAVE_FREEADDRINFO # undef HAVE_GETADDRINFO # undef HAVE_GETNAMEINFO # undef ENABLE_IPV6 # endif #endif /* ---------------------------------------------------------------- */ /* resolver specialty compile-time defines */ /* CURLRES_* defines to use in the host*.c sources */ /* ---------------------------------------------------------------- */ /* * lcc-win32 doesn't have _beginthreadex(), lacks threads support. */ #if defined(__LCC__) && defined(WIN32) # undef USE_THREADS_POSIX # undef USE_THREADS_WIN32 #endif /* * MSVC threads support requires a multi-threaded runtime library. * _beginthreadex() is not available in single-threaded ones. */ #if defined(_MSC_VER) && !defined(__POCC__) && !defined(_MT) # undef USE_THREADS_POSIX # undef USE_THREADS_WIN32 #endif /* * Mutually exclusive CURLRES_* definitions. */ #ifdef USE_ARES # define CURLRES_ASYNCH # define CURLRES_ARES /* now undef the stock libc functions just to avoid them being used */ # undef HAVE_GETADDRINFO # undef HAVE_FREEADDRINFO # undef HAVE_GETHOSTBYNAME #elif defined(USE_THREADS_POSIX) || defined(USE_THREADS_WIN32) # define CURLRES_ASYNCH # define CURLRES_THREADED #else # define CURLRES_SYNCH #endif #ifdef ENABLE_IPV6 # define CURLRES_IPV6 #else # define CURLRES_IPV4 #endif /* ---------------------------------------------------------------- */ /* * When using WINSOCK, TELNET protocol requires WINSOCK2 API. */ #if defined(USE_WINSOCK) && (USE_WINSOCK != 2) # define CURL_DISABLE_TELNET 1 #endif /* * msvc 6.0 does not have struct sockaddr_storage and * does not define IPPROTO_ESP in winsock2.h. But both * are available if PSDK is properly installed. */ #if defined(_MSC_VER) && !defined(__POCC__) # if !defined(HAVE_WINSOCK2_H) || ((_MSC_VER < 1300) && !defined(IPPROTO_ESP)) # undef HAVE_STRUCT_SOCKADDR_STORAGE # endif #endif /* * Intentionally fail to build when using msvc 6.0 without PSDK installed. * The brave of heart can circumvent this, defining ALLOW_MSVC6_WITHOUT_PSDK * in lib/config-win32.h although absolutely discouraged and unsupported. */ #if defined(_MSC_VER) && !defined(__POCC__) # if !defined(HAVE_WINDOWS_H) || ((_MSC_VER < 1300) && !defined(_FILETIME_)) # if !defined(ALLOW_MSVC6_WITHOUT_PSDK) # error MSVC 6.0 requires "February 2003 Platform SDK" a.k.a. \ "Windows Server 2003 PSDK" # else # define CURL_DISABLE_LDAP 1 # endif # endif #endif #ifdef NETWARE int netware_init(void); #ifndef __NOVELL_LIBC__ #include <sys/bsdskt.h> #include <sys/timeval.h> #endif #endif #if defined(HAVE_LIBIDN2) && defined(HAVE_IDN2_H) && !defined(USE_WIN32_IDN) /* The lib and header are present */ #define USE_LIBIDN2 #endif #if defined(USE_LIBIDN2) && defined(USE_WIN32_IDN) #error "Both libidn2 and WinIDN are enabled, choose one." #endif #define LIBIDN_REQUIRED_VERSION "0.4.1" #if defined(USE_GNUTLS) || defined(USE_OPENSSL) || defined(USE_NSS) || \ defined(USE_POLARSSL) || defined(USE_MBEDTLS) || \ defined(USE_CYASSL) || defined(USE_SCHANNEL) || \ defined(USE_SECTRANSP) || defined(USE_GSKIT) || defined(USE_MESALINK) #define USE_SSL /* SSL support has been enabled */ #endif /* Single point where USE_SPNEGO definition might be defined */ #if !defined(CURL_DISABLE_CRYPTO_AUTH) && \ (defined(HAVE_GSSAPI) || defined(USE_WINDOWS_SSPI)) #define USE_SPNEGO #endif /* Single point where USE_KERBEROS5 definition might be defined */ #if !defined(CURL_DISABLE_CRYPTO_AUTH) && \ (defined(HAVE_GSSAPI) || defined(USE_WINDOWS_SSPI)) #define USE_KERBEROS5 #endif /* Single point where USE_NTLM definition might be defined */ #if !defined(CURL_DISABLE_NTLM) && !defined(CURL_DISABLE_CRYPTO_AUTH) #if defined(USE_OPENSSL) || defined(USE_WINDOWS_SSPI) || \ defined(USE_GNUTLS) || defined(USE_NSS) || defined(USE_SECTRANSP) || \ defined(USE_OS400CRYPTO) || defined(USE_WIN32_CRYPTO) || \ defined(USE_MBEDTLS) #define USE_NTLM # if defined(USE_MBEDTLS) /* Get definition of MBEDTLS_MD4_C */ # include <mbedtls/md4.h> # endif #endif #endif #ifdef CURL_WANTS_CA_BUNDLE_ENV #error "No longer supported. Set CURLOPT_CAINFO at runtime instead." #endif #if defined(USE_LIBSSH2) || defined(USE_LIBSSH) || defined(USE_WOLFSSH) #define USE_SSH #endif /* * Provide a mechanism to silence picky compilers, such as gcc 4.6+. * Parameters should of course normally not be unused, but for example when * we have multiple implementations of the same interface it may happen. */ #if defined(__GNUC__) && ((__GNUC__ >= 3) || \ ((__GNUC__ == 2) && defined(__GNUC_MINOR__) && (__GNUC_MINOR__ >= 7))) # define UNUSED_PARAM __attribute__((__unused__)) # define WARN_UNUSED_RESULT __attribute__((warn_unused_result)) #else # define UNUSED_PARAM /*NOTHING*/ # define WARN_UNUSED_RESULT #endif /* * Include macros and defines that should only be processed once. */ #ifndef HEADER_CURL_SETUP_ONCE_H #include "curl_setup_once.h" #endif /* * Definition of our NOP statement Object-like macro */ #ifndef Curl_nop_stmt # define Curl_nop_stmt do { } WHILE_FALSE #endif /* * Ensure that Winsock and lwIP TCP/IP stacks are not mixed. */ #if defined(__LWIP_OPT_H__) || defined(LWIP_HDR_OPT_H) # if defined(SOCKET) || \ defined(USE_WINSOCK) || \ defined(HAVE_WINSOCK_H) || \ defined(HAVE_WINSOCK2_H) || \ defined(HAVE_WS2TCPIP_H) # error "Winsock and lwIP TCP/IP stack definitions shall not coexist!" # endif #endif /* * Portable symbolic names for Winsock shutdown() mode flags. */ #ifdef USE_WINSOCK # define SHUT_RD 0x00 # define SHUT_WR 0x01 # define SHUT_RDWR 0x02 #endif /* Define S_ISREG if not defined by system headers, f.e. MSVC */ #if !defined(S_ISREG) && defined(S_IFMT) && defined(S_IFREG) #define S_ISREG(m) (((m) & S_IFMT) == S_IFREG) #endif /* Define S_ISDIR if not defined by system headers, f.e. MSVC */ #if !defined(S_ISDIR) && defined(S_IFMT) && defined(S_IFDIR) #define S_ISDIR(m) (((m) & S_IFMT) == S_IFDIR) #endif /* In Windows the default file mode is text but an application can override it. Therefore we specify it explicitly. https://github.com/curl/curl/pull/258 */ #if defined(WIN32) || defined(MSDOS) #define FOPEN_READTEXT "rt" #define FOPEN_WRITETEXT "wt" #define FOPEN_APPENDTEXT "at" #elif defined(__CYGWIN__) /* Cygwin has specific behavior we need to address when WIN32 is not defined. https://cygwin.com/cygwin-ug-net/using-textbinary.html For write we want our output to have line endings of LF and be compatible with other Cygwin utilities. For read we want to handle input that may have line endings either CRLF or LF so 't' is appropriate. */ #define FOPEN_READTEXT "rt" #define FOPEN_WRITETEXT "w" #define FOPEN_APPENDTEXT "a" #else #define FOPEN_READTEXT "r" #define FOPEN_WRITETEXT "w" #define FOPEN_APPENDTEXT "a" #endif /* WinSock destroys recv() buffer when send() failed. * Enabled automatically for Windows and for Cygwin as Cygwin sockets are * wrappers for WinSock sockets. https://github.com/curl/curl/issues/657 * Define DONT_USE_RECV_BEFORE_SEND_WORKAROUND to force disable workaround. */ #if !defined(DONT_USE_RECV_BEFORE_SEND_WORKAROUND) # if defined(WIN32) || defined(__CYGWIN__) # define USE_RECV_BEFORE_SEND_WORKAROUND # endif #else /* DONT_USE_RECV_BEFORE_SEND_WORKAROUND */ # ifdef USE_RECV_BEFORE_SEND_WORKAROUND # undef USE_RECV_BEFORE_SEND_WORKAROUND # endif #endif /* DONT_USE_RECV_BEFORE_SEND_WORKAROUND */ /* Detect Windows App environment which has a restricted access * to the Win32 APIs. */ # if (defined(_WIN32_WINNT) && (_WIN32_WINNT >= 0x0602)) || \ defined(WINAPI_FAMILY) # include <winapifamily.h> # if WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_APP) && \ !WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP) # define CURL_WINDOWS_APP # endif # endif /* for systems that don't detect this in configure, use a sensible default */ #ifndef CURL_SA_FAMILY_T #define CURL_SA_FAMILY_T unsigned short #endif /* Some convenience macros to get the larger/smaller value out of two given. We prefix with CURL to prevent name collisions. */ #define CURLMAX(x,y) ((x)>(y)?(x):(y)) #define CURLMIN(x,y) ((x)<(y)?(x):(y)) /* Some versions of the Android SDK is missing the declaration */ #if defined(HAVE_GETPWUID_R) && defined(HAVE_DECL_GETPWUID_R_MISSING) struct passwd; int getpwuid_r(uid_t uid, struct passwd *pwd, char *buf, size_t buflen, struct passwd **result); #endif #ifdef DEBUGBUILD #define UNITTEST #else #define UNITTEST static #endif #endif /* HEADER_CURL_SETUP_H */
YifuLiu/AliOS-Things
components/curl/lib/curl_setup.h
C
apache-2.0
22,116
#ifndef HEADER_CURL_SETUP_ONCE_H #define HEADER_CURL_SETUP_ONCE_H /*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2018, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ /* * Inclusion of common header files. */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <stdarg.h> #include <ctype.h> #ifdef HAVE_ERRNO_H #include <errno.h> #endif #ifdef HAVE_SYS_TYPES_H #include <sys/types.h> #endif #ifdef NEED_MALLOC_H #include <malloc.h> #endif #ifdef NEED_MEMORY_H #include <memory.h> #endif #ifdef HAVE_SYS_STAT_H #include <sys/stat.h> #endif #ifdef HAVE_SYS_TIME_H #include <sys/time.h> #ifdef TIME_WITH_SYS_TIME #include <time.h> #endif #else #ifdef HAVE_TIME_H #include <time.h> #endif #endif #ifdef WIN32 #include <io.h> #include <fcntl.h> #endif #if defined(HAVE_STDBOOL_H) && defined(HAVE_BOOL_T) #include <stdbool.h> #endif #ifdef HAVE_UNISTD_H #include <unistd.h> #endif #ifdef __hpux # if !defined(_XOPEN_SOURCE_EXTENDED) || defined(_KERNEL) # ifdef _APP32_64BIT_OFF_T # define OLD_APP32_64BIT_OFF_T _APP32_64BIT_OFF_T # undef _APP32_64BIT_OFF_T # else # undef OLD_APP32_64BIT_OFF_T # endif # endif #endif #ifdef HAVE_SYS_SOCKET_H #ifdef USE_LWIPSOCK #include <lwip/sockets.h> #else #include <sys/socket.h> #endif #endif #ifdef __hpux # if !defined(_XOPEN_SOURCE_EXTENDED) || defined(_KERNEL) # ifdef OLD_APP32_64BIT_OFF_T # define _APP32_64BIT_OFF_T OLD_APP32_64BIT_OFF_T # undef OLD_APP32_64BIT_OFF_T # endif # endif #endif /* * Definition of timeval struct for platforms that don't have it. */ #ifndef HAVE_STRUCT_TIMEVAL struct timeval { long tv_sec; long tv_usec; }; #endif /* * If we have the MSG_NOSIGNAL define, make sure we use * it as the fourth argument of function send() */ #ifdef HAVE_MSG_NOSIGNAL #define SEND_4TH_ARG MSG_NOSIGNAL #else #define SEND_4TH_ARG 0 #endif #if defined(__minix) /* Minix doesn't support recv on TCP sockets */ #define sread(x,y,z) (ssize_t)read((RECV_TYPE_ARG1)(x), \ (RECV_TYPE_ARG2)(y), \ (RECV_TYPE_ARG3)(z)) #elif defined(HAVE_RECV) /* * The definitions for the return type and arguments types * of functions recv() and send() belong and come from the * configuration file. Do not define them in any other place. * * HAVE_RECV is defined if you have a function named recv() * which is used to read incoming data from sockets. If your * function has another name then don't define HAVE_RECV. * * If HAVE_RECV is defined then RECV_TYPE_ARG1, RECV_TYPE_ARG2, * RECV_TYPE_ARG3, RECV_TYPE_ARG4 and RECV_TYPE_RETV must also * be defined. * * HAVE_SEND is defined if you have a function named send() * which is used to write outgoing data on a connected socket. * If yours has another name then don't define HAVE_SEND. * * If HAVE_SEND is defined then SEND_TYPE_ARG1, SEND_QUAL_ARG2, * SEND_TYPE_ARG2, SEND_TYPE_ARG3, SEND_TYPE_ARG4 and * SEND_TYPE_RETV must also be defined. */ #if !defined(RECV_TYPE_ARG1) || \ !defined(RECV_TYPE_ARG2) || \ !defined(RECV_TYPE_ARG3) || \ !defined(RECV_TYPE_ARG4) || \ !defined(RECV_TYPE_RETV) /* */ Error Missing_definition_of_return_and_arguments_types_of_recv /* */ #else #define sread(x,y,z) (ssize_t)recv((RECV_TYPE_ARG1)(x), \ (RECV_TYPE_ARG2)(y), \ (RECV_TYPE_ARG3)(z), \ (RECV_TYPE_ARG4)(0)) #endif #else /* HAVE_RECV */ #ifndef sread /* */ Error Missing_definition_of_macro_sread /* */ #endif #endif /* HAVE_RECV */ #if defined(__minix) /* Minix doesn't support send on TCP sockets */ #define swrite(x,y,z) (ssize_t)write((SEND_TYPE_ARG1)(x), \ (SEND_TYPE_ARG2)(y), \ (SEND_TYPE_ARG3)(z)) #elif defined(HAVE_SEND) #if !defined(SEND_TYPE_ARG1) || \ !defined(SEND_QUAL_ARG2) || \ !defined(SEND_TYPE_ARG2) || \ !defined(SEND_TYPE_ARG3) || \ !defined(SEND_TYPE_ARG4) || \ !defined(SEND_TYPE_RETV) /* */ Error Missing_definition_of_return_and_arguments_types_of_send /* */ #else #define swrite(x,y,z) (ssize_t)send((SEND_TYPE_ARG1)(x), \ (SEND_QUAL_ARG2 SEND_TYPE_ARG2)(y), \ (SEND_TYPE_ARG3)(z), \ (SEND_TYPE_ARG4)(SEND_4TH_ARG)) #endif #else /* HAVE_SEND */ #ifndef swrite /* */ Error Missing_definition_of_macro_swrite /* */ #endif #endif /* HAVE_SEND */ #if 0 #if defined(HAVE_RECVFROM) /* * Currently recvfrom is only used on udp sockets. */ #if !defined(RECVFROM_TYPE_ARG1) || \ !defined(RECVFROM_TYPE_ARG2) || \ !defined(RECVFROM_TYPE_ARG3) || \ !defined(RECVFROM_TYPE_ARG4) || \ !defined(RECVFROM_TYPE_ARG5) || \ !defined(RECVFROM_TYPE_ARG6) || \ !defined(RECVFROM_TYPE_RETV) /* */ Error Missing_definition_of_return_and_arguments_types_of_recvfrom /* */ #else #define sreadfrom(s,b,bl,f,fl) (ssize_t)recvfrom((RECVFROM_TYPE_ARG1) (s), \ (RECVFROM_TYPE_ARG2 *)(b), \ (RECVFROM_TYPE_ARG3) (bl), \ (RECVFROM_TYPE_ARG4) (0), \ (RECVFROM_TYPE_ARG5 *)(f), \ (RECVFROM_TYPE_ARG6 *)(fl)) #endif #else /* HAVE_RECVFROM */ #ifndef sreadfrom /* */ Error Missing_definition_of_macro_sreadfrom /* */ #endif #endif /* HAVE_RECVFROM */ #ifdef RECVFROM_TYPE_ARG6_IS_VOID # define RECVFROM_ARG6_T int #else # define RECVFROM_ARG6_T RECVFROM_TYPE_ARG6 #endif #endif /* if 0 */ /* * Function-like macro definition used to close a socket. */ #if defined(HAVE_CLOSESOCKET) # define sclose(x) closesocket((x)) #elif defined(HAVE_CLOSESOCKET_CAMEL) # define sclose(x) CloseSocket((x)) #elif defined(HAVE_CLOSE_S) # define sclose(x) close_s((x)) #elif defined(USE_LWIPSOCK) # define sclose(x) lwip_close((x)) #else # define sclose(x) close((x)) #endif /* * Stack-independent version of fcntl() on sockets: */ #if defined(USE_LWIPSOCK) # define sfcntl lwip_fcntl #else # define sfcntl fcntl #endif #define TOLOWER(x) (tolower((int) ((unsigned char)x))) /* * 'bool' stuff compatible with HP-UX headers. */ #if defined(__hpux) && !defined(HAVE_BOOL_T) typedef int bool; # define false 0 # define true 1 # define HAVE_BOOL_T #endif /* * 'bool' exists on platforms with <stdbool.h>, i.e. C99 platforms. * On non-C99 platforms there's no bool, so define an enum for that. * On C99 platforms 'false' and 'true' also exist. Enum uses a * global namespace though, so use bool_false and bool_true. */ #ifndef HAVE_BOOL_T typedef enum { bool_false = 0, bool_true = 1 } bool; /* * Use a define to let 'true' and 'false' use those enums. There * are currently no use of true and false in libcurl proper, but * there are some in the examples. This will cater for any later * code happening to use true and false. */ # define false bool_false # define true bool_true # define HAVE_BOOL_T #endif /* * Redefine TRUE and FALSE too, to catch current use. With this * change, 'bool found = 1' will give a warning on MIPSPro, but * 'bool found = TRUE' will not. Change tested on IRIX/MIPSPro, * AIX 5.1/Xlc, Tru64 5.1/cc, w/make test too. */ #ifndef TRUE #define TRUE true #endif #ifndef FALSE #define FALSE false #endif #include "curl_ctype.h" /* * Macro WHILE_FALSE may be used to build single-iteration do-while loops, * avoiding compiler warnings. Mostly intended for other macro definitions. */ #define WHILE_FALSE while(0) #if defined(_MSC_VER) && !defined(__POCC__) # undef WHILE_FALSE # if (_MSC_VER < 1500) # define WHILE_FALSE while(1, 0) # else # define WHILE_FALSE \ __pragma(warning(push)) \ __pragma(warning(disable:4127)) \ while(0) \ __pragma(warning(pop)) # endif #endif /* * Typedef to 'int' if sig_atomic_t is not an available 'typedefed' type. */ #ifndef HAVE_SIG_ATOMIC_T typedef int sig_atomic_t; #define HAVE_SIG_ATOMIC_T #endif /* * Convenience SIG_ATOMIC_T definition */ #ifdef HAVE_SIG_ATOMIC_T_VOLATILE #define SIG_ATOMIC_T static sig_atomic_t #else #define SIG_ATOMIC_T static volatile sig_atomic_t #endif /* * Default return type for signal handlers. */ #ifndef RETSIGTYPE #define RETSIGTYPE void #endif /* * Macro used to include code only in debug builds. */ #ifdef DEBUGBUILD #define DEBUGF(x) x #else #define DEBUGF(x) do { } WHILE_FALSE #endif /* * Macro used to include assertion code only in debug builds. */ #if defined(DEBUGBUILD) && defined(HAVE_ASSERT_H) #define DEBUGASSERT(x) assert(x) #else #define DEBUGASSERT(x) do { } WHILE_FALSE #endif /* * Macro SOCKERRNO / SET_SOCKERRNO() returns / sets the *socket-related* errno * (or equivalent) on this platform to hide platform details to code using it. */ #ifdef USE_WINSOCK #define SOCKERRNO ((int)WSAGetLastError()) #define SET_SOCKERRNO(x) (WSASetLastError((int)(x))) #else #define SOCKERRNO (errno) #define SET_SOCKERRNO(x) (errno = (x)) #endif /* * Portable error number symbolic names defined to Winsock error codes. */ #ifdef USE_WINSOCK #undef EBADF /* override definition in errno.h */ #define EBADF WSAEBADF #undef EINTR /* override definition in errno.h */ #define EINTR WSAEINTR #undef EINVAL /* override definition in errno.h */ #define EINVAL WSAEINVAL #undef EWOULDBLOCK /* override definition in errno.h */ #define EWOULDBLOCK WSAEWOULDBLOCK #undef EINPROGRESS /* override definition in errno.h */ #define EINPROGRESS WSAEINPROGRESS #undef EALREADY /* override definition in errno.h */ #define EALREADY WSAEALREADY #undef ENOTSOCK /* override definition in errno.h */ #define ENOTSOCK WSAENOTSOCK #undef EDESTADDRREQ /* override definition in errno.h */ #define EDESTADDRREQ WSAEDESTADDRREQ #undef EMSGSIZE /* override definition in errno.h */ #define EMSGSIZE WSAEMSGSIZE #undef EPROTOTYPE /* override definition in errno.h */ #define EPROTOTYPE WSAEPROTOTYPE #undef ENOPROTOOPT /* override definition in errno.h */ #define ENOPROTOOPT WSAENOPROTOOPT #undef EPROTONOSUPPORT /* override definition in errno.h */ #define EPROTONOSUPPORT WSAEPROTONOSUPPORT #define ESOCKTNOSUPPORT WSAESOCKTNOSUPPORT #undef EOPNOTSUPP /* override definition in errno.h */ #define EOPNOTSUPP WSAEOPNOTSUPP #define EPFNOSUPPORT WSAEPFNOSUPPORT #undef EAFNOSUPPORT /* override definition in errno.h */ #define EAFNOSUPPORT WSAEAFNOSUPPORT #undef EADDRINUSE /* override definition in errno.h */ #define EADDRINUSE WSAEADDRINUSE #undef EADDRNOTAVAIL /* override definition in errno.h */ #define EADDRNOTAVAIL WSAEADDRNOTAVAIL #undef ENETDOWN /* override definition in errno.h */ #define ENETDOWN WSAENETDOWN #undef ENETUNREACH /* override definition in errno.h */ #define ENETUNREACH WSAENETUNREACH #undef ENETRESET /* override definition in errno.h */ #define ENETRESET WSAENETRESET #undef ECONNABORTED /* override definition in errno.h */ #define ECONNABORTED WSAECONNABORTED #undef ECONNRESET /* override definition in errno.h */ #define ECONNRESET WSAECONNRESET #undef ENOBUFS /* override definition in errno.h */ #define ENOBUFS WSAENOBUFS #undef EISCONN /* override definition in errno.h */ #define EISCONN WSAEISCONN #undef ENOTCONN /* override definition in errno.h */ #define ENOTCONN WSAENOTCONN #define ESHUTDOWN WSAESHUTDOWN #define ETOOMANYREFS WSAETOOMANYREFS #undef ETIMEDOUT /* override definition in errno.h */ #define ETIMEDOUT WSAETIMEDOUT #undef ECONNREFUSED /* override definition in errno.h */ #define ECONNREFUSED WSAECONNREFUSED #undef ELOOP /* override definition in errno.h */ #define ELOOP WSAELOOP #ifndef ENAMETOOLONG /* possible previous definition in errno.h */ #define ENAMETOOLONG WSAENAMETOOLONG #endif #define EHOSTDOWN WSAEHOSTDOWN #undef EHOSTUNREACH /* override definition in errno.h */ #define EHOSTUNREACH WSAEHOSTUNREACH #ifndef ENOTEMPTY /* possible previous definition in errno.h */ #define ENOTEMPTY WSAENOTEMPTY #endif #define EPROCLIM WSAEPROCLIM #define EUSERS WSAEUSERS #define EDQUOT WSAEDQUOT #define ESTALE WSAESTALE #define EREMOTE WSAEREMOTE #endif /* * Macro argv_item_t hides platform details to code using it. */ #ifdef __VMS #define argv_item_t __char_ptr32 #else #define argv_item_t char * #endif /* * We use this ZERO_NULL to avoid picky compiler warnings, * when assigning a NULL pointer to a function pointer var. */ #define ZERO_NULL 0 #endif /* HEADER_CURL_SETUP_ONCE_H */
YifuLiu/AliOS-Things
components/curl/lib/curl_setup_once.h
C
apache-2.0
14,067
#ifndef HEADER_CURL_SHA256_H #define HEADER_CURL_SHA256_H /*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2010, Florin Petriuc, <petriuc.florin@gmail.com> * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #ifndef CURL_DISABLE_CRYPTO_AUTH void Curl_sha256it(unsigned char *outbuffer, const unsigned char *input); #endif #endif /* HEADER_CURL_SHA256_H */
YifuLiu/AliOS-Things
components/curl/lib/curl_sha256.h
C
apache-2.0
1,253
/*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2016, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "curl_setup.h" #ifdef USE_WINDOWS_SSPI #include <curl/curl.h> #include "curl_sspi.h" #include "curl_multibyte.h" #include "system_win32.h" #include "warnless.h" /* The last #include files should be: */ #include "curl_memory.h" #include "memdebug.h" /* We use our own typedef here since some headers might lack these */ typedef PSecurityFunctionTable (APIENTRY *INITSECURITYINTERFACE_FN)(VOID); /* See definition of SECURITY_ENTRYPOINT in sspi.h */ #ifdef UNICODE # ifdef _WIN32_WCE # define SECURITYENTRYPOINT L"InitSecurityInterfaceW" # else # define SECURITYENTRYPOINT "InitSecurityInterfaceW" # endif #else # define SECURITYENTRYPOINT "InitSecurityInterfaceA" #endif /* Handle of security.dll or secur32.dll, depending on Windows version */ HMODULE s_hSecDll = NULL; /* Pointer to SSPI dispatch table */ PSecurityFunctionTable s_pSecFn = NULL; /* * Curl_sspi_global_init() * * This is used to load the Security Service Provider Interface (SSPI) * dynamic link library portably across all Windows versions, without * the need to directly link libcurl, nor the application using it, at * build time. * * Once this function has been executed, Windows SSPI functions can be * called through the Security Service Provider Interface dispatch table. * * Parameters: * * None. * * Returns CURLE_OK on success. */ CURLcode Curl_sspi_global_init(void) { INITSECURITYINTERFACE_FN pInitSecurityInterface; /* If security interface is not yet initialized try to do this */ if(!s_hSecDll) { /* Security Service Provider Interface (SSPI) functions are located in * security.dll on WinNT 4.0 and in secur32.dll on Win9x. Win2K and XP * have both these DLLs (security.dll forwards calls to secur32.dll) */ /* Load SSPI dll into the address space of the calling process */ if(Curl_verify_windows_version(4, 0, PLATFORM_WINNT, VERSION_EQUAL)) s_hSecDll = Curl_load_library(TEXT("security.dll")); else s_hSecDll = Curl_load_library(TEXT("secur32.dll")); if(!s_hSecDll) return CURLE_FAILED_INIT; /* Get address of the InitSecurityInterfaceA function from the SSPI dll */ pInitSecurityInterface = CURLX_FUNCTION_CAST(INITSECURITYINTERFACE_FN, (GetProcAddress(s_hSecDll, SECURITYENTRYPOINT))); if(!pInitSecurityInterface) return CURLE_FAILED_INIT; /* Get pointer to Security Service Provider Interface dispatch table */ s_pSecFn = pInitSecurityInterface(); if(!s_pSecFn) return CURLE_FAILED_INIT; } return CURLE_OK; } /* * Curl_sspi_global_cleanup() * * This deinitializes the Security Service Provider Interface from libcurl. * * Parameters: * * None. */ void Curl_sspi_global_cleanup(void) { if(s_hSecDll) { FreeLibrary(s_hSecDll); s_hSecDll = NULL; s_pSecFn = NULL; } } /* * Curl_create_sspi_identity() * * This is used to populate a SSPI identity structure based on the supplied * username and password. * * Parameters: * * userp [in] - The user name in the format User or Domain\User. * passwdp [in] - The user's password. * identity [in/out] - The identity structure. * * Returns CURLE_OK on success. */ CURLcode Curl_create_sspi_identity(const char *userp, const char *passwdp, SEC_WINNT_AUTH_IDENTITY *identity) { xcharp_u useranddomain; xcharp_u user, dup_user; xcharp_u domain, dup_domain; xcharp_u passwd, dup_passwd; size_t domlen = 0; domain.const_tchar_ptr = TEXT(""); /* Initialize the identity */ memset(identity, 0, sizeof(*identity)); useranddomain.tchar_ptr = Curl_convert_UTF8_to_tchar((char *)userp); if(!useranddomain.tchar_ptr) return CURLE_OUT_OF_MEMORY; user.const_tchar_ptr = _tcschr(useranddomain.const_tchar_ptr, TEXT('\\')); if(!user.const_tchar_ptr) user.const_tchar_ptr = _tcschr(useranddomain.const_tchar_ptr, TEXT('/')); if(user.tchar_ptr) { domain.tchar_ptr = useranddomain.tchar_ptr; domlen = user.tchar_ptr - useranddomain.tchar_ptr; user.tchar_ptr++; } else { user.tchar_ptr = useranddomain.tchar_ptr; domain.const_tchar_ptr = TEXT(""); domlen = 0; } /* Setup the identity's user and length */ dup_user.tchar_ptr = _tcsdup(user.tchar_ptr); if(!dup_user.tchar_ptr) { Curl_unicodefree(useranddomain.tchar_ptr); return CURLE_OUT_OF_MEMORY; } identity->User = dup_user.tbyte_ptr; identity->UserLength = curlx_uztoul(_tcslen(dup_user.tchar_ptr)); dup_user.tchar_ptr = NULL; /* Setup the identity's domain and length */ dup_domain.tchar_ptr = malloc(sizeof(TCHAR) * (domlen + 1)); if(!dup_domain.tchar_ptr) { Curl_unicodefree(useranddomain.tchar_ptr); return CURLE_OUT_OF_MEMORY; } _tcsncpy(dup_domain.tchar_ptr, domain.tchar_ptr, domlen); *(dup_domain.tchar_ptr + domlen) = TEXT('\0'); identity->Domain = dup_domain.tbyte_ptr; identity->DomainLength = curlx_uztoul(domlen); dup_domain.tchar_ptr = NULL; Curl_unicodefree(useranddomain.tchar_ptr); /* Setup the identity's password and length */ passwd.tchar_ptr = Curl_convert_UTF8_to_tchar((char *)passwdp); if(!passwd.tchar_ptr) return CURLE_OUT_OF_MEMORY; dup_passwd.tchar_ptr = _tcsdup(passwd.tchar_ptr); if(!dup_passwd.tchar_ptr) { Curl_unicodefree(passwd.tchar_ptr); return CURLE_OUT_OF_MEMORY; } identity->Password = dup_passwd.tbyte_ptr; identity->PasswordLength = curlx_uztoul(_tcslen(dup_passwd.tchar_ptr)); dup_passwd.tchar_ptr = NULL; Curl_unicodefree(passwd.tchar_ptr); /* Setup the identity's flags */ identity->Flags = SECFLAG_WINNT_AUTH_IDENTITY; return CURLE_OK; } /* * Curl_sspi_free_identity() * * This is used to free the contents of a SSPI identifier structure. * * Parameters: * * identity [in/out] - The identity structure. */ void Curl_sspi_free_identity(SEC_WINNT_AUTH_IDENTITY *identity) { if(identity) { Curl_safefree(identity->User); Curl_safefree(identity->Password); Curl_safefree(identity->Domain); } } #endif /* USE_WINDOWS_SSPI */
YifuLiu/AliOS-Things
components/curl/lib/curl_sspi.c
C
apache-2.0
7,100
#ifndef HEADER_CURL_SSPI_H #define HEADER_CURL_SSPI_H /*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2014, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "curl_setup.h" #ifdef USE_WINDOWS_SSPI #include <curl/curl.h> /* * When including the following three headers, it is mandatory to define either * SECURITY_WIN32 or SECURITY_KERNEL, indicating who is compiling the code. */ #undef SECURITY_WIN32 #undef SECURITY_KERNEL #define SECURITY_WIN32 1 #include <security.h> #include <sspi.h> #include <rpc.h> CURLcode Curl_sspi_global_init(void); void Curl_sspi_global_cleanup(void); /* This is used to populate the domain in a SSPI identity structure */ CURLcode Curl_override_sspi_http_realm(const char *chlg, SEC_WINNT_AUTH_IDENTITY *identity); /* This is used to generate an SSPI identity structure */ CURLcode Curl_create_sspi_identity(const char *userp, const char *passwdp, SEC_WINNT_AUTH_IDENTITY *identity); /* This is used to free an SSPI identity structure */ void Curl_sspi_free_identity(SEC_WINNT_AUTH_IDENTITY *identity); /* Forward-declaration of global variables defined in curl_sspi.c */ extern HMODULE s_hSecDll; extern PSecurityFunctionTable s_pSecFn; /* Provide some definitions missing in old headers */ #define SP_NAME_DIGEST "WDigest" #define SP_NAME_NTLM "NTLM" #define SP_NAME_NEGOTIATE "Negotiate" #define SP_NAME_KERBEROS "Kerberos" #ifndef ISC_REQ_USE_HTTP_STYLE #define ISC_REQ_USE_HTTP_STYLE 0x01000000 #endif #ifndef ISC_RET_REPLAY_DETECT #define ISC_RET_REPLAY_DETECT 0x00000004 #endif #ifndef ISC_RET_SEQUENCE_DETECT #define ISC_RET_SEQUENCE_DETECT 0x00000008 #endif #ifndef ISC_RET_CONFIDENTIALITY #define ISC_RET_CONFIDENTIALITY 0x00000010 #endif #ifndef ISC_RET_ALLOCATED_MEMORY #define ISC_RET_ALLOCATED_MEMORY 0x00000100 #endif #ifndef ISC_RET_STREAM #define ISC_RET_STREAM 0x00008000 #endif #ifndef SEC_E_INSUFFICIENT_MEMORY # define SEC_E_INSUFFICIENT_MEMORY ((HRESULT)0x80090300L) #endif #ifndef SEC_E_INVALID_HANDLE # define SEC_E_INVALID_HANDLE ((HRESULT)0x80090301L) #endif #ifndef SEC_E_UNSUPPORTED_FUNCTION # define SEC_E_UNSUPPORTED_FUNCTION ((HRESULT)0x80090302L) #endif #ifndef SEC_E_TARGET_UNKNOWN # define SEC_E_TARGET_UNKNOWN ((HRESULT)0x80090303L) #endif #ifndef SEC_E_INTERNAL_ERROR # define SEC_E_INTERNAL_ERROR ((HRESULT)0x80090304L) #endif #ifndef SEC_E_SECPKG_NOT_FOUND # define SEC_E_SECPKG_NOT_FOUND ((HRESULT)0x80090305L) #endif #ifndef SEC_E_NOT_OWNER # define SEC_E_NOT_OWNER ((HRESULT)0x80090306L) #endif #ifndef SEC_E_CANNOT_INSTALL # define SEC_E_CANNOT_INSTALL ((HRESULT)0x80090307L) #endif #ifndef SEC_E_INVALID_TOKEN # define SEC_E_INVALID_TOKEN ((HRESULT)0x80090308L) #endif #ifndef SEC_E_CANNOT_PACK # define SEC_E_CANNOT_PACK ((HRESULT)0x80090309L) #endif #ifndef SEC_E_QOP_NOT_SUPPORTED # define SEC_E_QOP_NOT_SUPPORTED ((HRESULT)0x8009030AL) #endif #ifndef SEC_E_NO_IMPERSONATION # define SEC_E_NO_IMPERSONATION ((HRESULT)0x8009030BL) #endif #ifndef SEC_E_LOGON_DENIED # define SEC_E_LOGON_DENIED ((HRESULT)0x8009030CL) #endif #ifndef SEC_E_UNKNOWN_CREDENTIALS # define SEC_E_UNKNOWN_CREDENTIALS ((HRESULT)0x8009030DL) #endif #ifndef SEC_E_NO_CREDENTIALS # define SEC_E_NO_CREDENTIALS ((HRESULT)0x8009030EL) #endif #ifndef SEC_E_MESSAGE_ALTERED # define SEC_E_MESSAGE_ALTERED ((HRESULT)0x8009030FL) #endif #ifndef SEC_E_OUT_OF_SEQUENCE # define SEC_E_OUT_OF_SEQUENCE ((HRESULT)0x80090310L) #endif #ifndef SEC_E_NO_AUTHENTICATING_AUTHORITY # define SEC_E_NO_AUTHENTICATING_AUTHORITY ((HRESULT)0x80090311L) #endif #ifndef SEC_E_BAD_PKGID # define SEC_E_BAD_PKGID ((HRESULT)0x80090316L) #endif #ifndef SEC_E_CONTEXT_EXPIRED # define SEC_E_CONTEXT_EXPIRED ((HRESULT)0x80090317L) #endif #ifndef SEC_E_INCOMPLETE_MESSAGE # define SEC_E_INCOMPLETE_MESSAGE ((HRESULT)0x80090318L) #endif #ifndef SEC_E_INCOMPLETE_CREDENTIALS # define SEC_E_INCOMPLETE_CREDENTIALS ((HRESULT)0x80090320L) #endif #ifndef SEC_E_BUFFER_TOO_SMALL # define SEC_E_BUFFER_TOO_SMALL ((HRESULT)0x80090321L) #endif #ifndef SEC_E_WRONG_PRINCIPAL # define SEC_E_WRONG_PRINCIPAL ((HRESULT)0x80090322L) #endif #ifndef SEC_E_TIME_SKEW # define SEC_E_TIME_SKEW ((HRESULT)0x80090324L) #endif #ifndef SEC_E_UNTRUSTED_ROOT # define SEC_E_UNTRUSTED_ROOT ((HRESULT)0x80090325L) #endif #ifndef SEC_E_ILLEGAL_MESSAGE # define SEC_E_ILLEGAL_MESSAGE ((HRESULT)0x80090326L) #endif #ifndef SEC_E_CERT_UNKNOWN # define SEC_E_CERT_UNKNOWN ((HRESULT)0x80090327L) #endif #ifndef SEC_E_CERT_EXPIRED # define SEC_E_CERT_EXPIRED ((HRESULT)0x80090328L) #endif #ifndef SEC_E_ENCRYPT_FAILURE # define SEC_E_ENCRYPT_FAILURE ((HRESULT)0x80090329L) #endif #ifndef SEC_E_DECRYPT_FAILURE # define SEC_E_DECRYPT_FAILURE ((HRESULT)0x80090330L) #endif #ifndef SEC_E_ALGORITHM_MISMATCH # define SEC_E_ALGORITHM_MISMATCH ((HRESULT)0x80090331L) #endif #ifndef SEC_E_SECURITY_QOS_FAILED # define SEC_E_SECURITY_QOS_FAILED ((HRESULT)0x80090332L) #endif #ifndef SEC_E_UNFINISHED_CONTEXT_DELETED # define SEC_E_UNFINISHED_CONTEXT_DELETED ((HRESULT)0x80090333L) #endif #ifndef SEC_E_NO_TGT_REPLY # define SEC_E_NO_TGT_REPLY ((HRESULT)0x80090334L) #endif #ifndef SEC_E_NO_IP_ADDRESSES # define SEC_E_NO_IP_ADDRESSES ((HRESULT)0x80090335L) #endif #ifndef SEC_E_WRONG_CREDENTIAL_HANDLE # define SEC_E_WRONG_CREDENTIAL_HANDLE ((HRESULT)0x80090336L) #endif #ifndef SEC_E_CRYPTO_SYSTEM_INVALID # define SEC_E_CRYPTO_SYSTEM_INVALID ((HRESULT)0x80090337L) #endif #ifndef SEC_E_MAX_REFERRALS_EXCEEDED # define SEC_E_MAX_REFERRALS_EXCEEDED ((HRESULT)0x80090338L) #endif #ifndef SEC_E_MUST_BE_KDC # define SEC_E_MUST_BE_KDC ((HRESULT)0x80090339L) #endif #ifndef SEC_E_STRONG_CRYPTO_NOT_SUPPORTED # define SEC_E_STRONG_CRYPTO_NOT_SUPPORTED ((HRESULT)0x8009033AL) #endif #ifndef SEC_E_TOO_MANY_PRINCIPALS # define SEC_E_TOO_MANY_PRINCIPALS ((HRESULT)0x8009033BL) #endif #ifndef SEC_E_NO_PA_DATA # define SEC_E_NO_PA_DATA ((HRESULT)0x8009033CL) #endif #ifndef SEC_E_PKINIT_NAME_MISMATCH # define SEC_E_PKINIT_NAME_MISMATCH ((HRESULT)0x8009033DL) #endif #ifndef SEC_E_SMARTCARD_LOGON_REQUIRED # define SEC_E_SMARTCARD_LOGON_REQUIRED ((HRESULT)0x8009033EL) #endif #ifndef SEC_E_SHUTDOWN_IN_PROGRESS # define SEC_E_SHUTDOWN_IN_PROGRESS ((HRESULT)0x8009033FL) #endif #ifndef SEC_E_KDC_INVALID_REQUEST # define SEC_E_KDC_INVALID_REQUEST ((HRESULT)0x80090340L) #endif #ifndef SEC_E_KDC_UNABLE_TO_REFER # define SEC_E_KDC_UNABLE_TO_REFER ((HRESULT)0x80090341L) #endif #ifndef SEC_E_KDC_UNKNOWN_ETYPE # define SEC_E_KDC_UNKNOWN_ETYPE ((HRESULT)0x80090342L) #endif #ifndef SEC_E_UNSUPPORTED_PREAUTH # define SEC_E_UNSUPPORTED_PREAUTH ((HRESULT)0x80090343L) #endif #ifndef SEC_E_DELEGATION_REQUIRED # define SEC_E_DELEGATION_REQUIRED ((HRESULT)0x80090345L) #endif #ifndef SEC_E_BAD_BINDINGS # define SEC_E_BAD_BINDINGS ((HRESULT)0x80090346L) #endif #ifndef SEC_E_MULTIPLE_ACCOUNTS # define SEC_E_MULTIPLE_ACCOUNTS ((HRESULT)0x80090347L) #endif #ifndef SEC_E_NO_KERB_KEY # define SEC_E_NO_KERB_KEY ((HRESULT)0x80090348L) #endif #ifndef SEC_E_CERT_WRONG_USAGE # define SEC_E_CERT_WRONG_USAGE ((HRESULT)0x80090349L) #endif #ifndef SEC_E_DOWNGRADE_DETECTED # define SEC_E_DOWNGRADE_DETECTED ((HRESULT)0x80090350L) #endif #ifndef SEC_E_SMARTCARD_CERT_REVOKED # define SEC_E_SMARTCARD_CERT_REVOKED ((HRESULT)0x80090351L) #endif #ifndef SEC_E_ISSUING_CA_UNTRUSTED # define SEC_E_ISSUING_CA_UNTRUSTED ((HRESULT)0x80090352L) #endif #ifndef SEC_E_REVOCATION_OFFLINE_C # define SEC_E_REVOCATION_OFFLINE_C ((HRESULT)0x80090353L) #endif #ifndef SEC_E_PKINIT_CLIENT_FAILURE # define SEC_E_PKINIT_CLIENT_FAILURE ((HRESULT)0x80090354L) #endif #ifndef SEC_E_SMARTCARD_CERT_EXPIRED # define SEC_E_SMARTCARD_CERT_EXPIRED ((HRESULT)0x80090355L) #endif #ifndef SEC_E_NO_S4U_PROT_SUPPORT # define SEC_E_NO_S4U_PROT_SUPPORT ((HRESULT)0x80090356L) #endif #ifndef SEC_E_CROSSREALM_DELEGATION_FAILURE # define SEC_E_CROSSREALM_DELEGATION_FAILURE ((HRESULT)0x80090357L) #endif #ifndef SEC_E_REVOCATION_OFFLINE_KDC # define SEC_E_REVOCATION_OFFLINE_KDC ((HRESULT)0x80090358L) #endif #ifndef SEC_E_ISSUING_CA_UNTRUSTED_KDC # define SEC_E_ISSUING_CA_UNTRUSTED_KDC ((HRESULT)0x80090359L) #endif #ifndef SEC_E_KDC_CERT_EXPIRED # define SEC_E_KDC_CERT_EXPIRED ((HRESULT)0x8009035AL) #endif #ifndef SEC_E_KDC_CERT_REVOKED # define SEC_E_KDC_CERT_REVOKED ((HRESULT)0x8009035BL) #endif #ifndef SEC_E_INVALID_PARAMETER # define SEC_E_INVALID_PARAMETER ((HRESULT)0x8009035DL) #endif #ifndef SEC_E_DELEGATION_POLICY # define SEC_E_DELEGATION_POLICY ((HRESULT)0x8009035EL) #endif #ifndef SEC_E_POLICY_NLTM_ONLY # define SEC_E_POLICY_NLTM_ONLY ((HRESULT)0x8009035FL) #endif #ifndef SEC_I_CONTINUE_NEEDED # define SEC_I_CONTINUE_NEEDED ((HRESULT)0x00090312L) #endif #ifndef SEC_I_COMPLETE_NEEDED # define SEC_I_COMPLETE_NEEDED ((HRESULT)0x00090313L) #endif #ifndef SEC_I_COMPLETE_AND_CONTINUE # define SEC_I_COMPLETE_AND_CONTINUE ((HRESULT)0x00090314L) #endif #ifndef SEC_I_LOCAL_LOGON # define SEC_I_LOCAL_LOGON ((HRESULT)0x00090315L) #endif #ifndef SEC_I_CONTEXT_EXPIRED # define SEC_I_CONTEXT_EXPIRED ((HRESULT)0x00090317L) #endif #ifndef SEC_I_INCOMPLETE_CREDENTIALS # define SEC_I_INCOMPLETE_CREDENTIALS ((HRESULT)0x00090320L) #endif #ifndef SEC_I_RENEGOTIATE # define SEC_I_RENEGOTIATE ((HRESULT)0x00090321L) #endif #ifndef SEC_I_NO_LSA_CONTEXT # define SEC_I_NO_LSA_CONTEXT ((HRESULT)0x00090323L) #endif #ifndef SEC_I_SIGNATURE_NEEDED # define SEC_I_SIGNATURE_NEEDED ((HRESULT)0x0009035CL) #endif #ifndef CRYPT_E_REVOKED # define CRYPT_E_REVOKED ((HRESULT)0x80092010L) #endif #ifdef UNICODE # define SECFLAG_WINNT_AUTH_IDENTITY \ (unsigned long)SEC_WINNT_AUTH_IDENTITY_UNICODE #else # define SECFLAG_WINNT_AUTH_IDENTITY \ (unsigned long)SEC_WINNT_AUTH_IDENTITY_ANSI #endif /* * Definitions required from ntsecapi.h are directly provided below this point * to avoid including ntsecapi.h due to a conflict with OpenSSL's safestack.h */ #define KERB_WRAP_NO_ENCRYPT 0x80000001 #endif /* USE_WINDOWS_SSPI */ #endif /* HEADER_CURL_SSPI_H */
YifuLiu/AliOS-Things
components/curl/lib/curl_sspi.h
C
apache-2.0
12,109
/*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2016, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "curl_setup.h" #include <curl/curl.h> #if defined(USE_THREADS_POSIX) # ifdef HAVE_PTHREAD_H # include <pthread.h> # endif #elif defined(USE_THREADS_WIN32) # ifdef HAVE_PROCESS_H # include <process.h> # endif #endif #include "curl_threads.h" #include "curl_memory.h" /* The last #include file should be: */ #include "memdebug.h" #if defined(USE_THREADS_POSIX) struct curl_actual_call { unsigned int (*func)(void *); void *arg; }; static void *curl_thread_create_thunk(void *arg) { struct curl_actual_call * ac = arg; unsigned int (*func)(void *) = ac->func; void *real_arg = ac->arg; free(ac); (*func)(real_arg); return 0; } curl_thread_t Curl_thread_create(unsigned int (*func) (void *), void *arg) { curl_thread_t t = malloc(sizeof(pthread_t)); struct curl_actual_call *ac = malloc(sizeof(struct curl_actual_call)); if(!(ac && t)) goto err; ac->func = func; ac->arg = arg; if(pthread_create(t, NULL, curl_thread_create_thunk, ac) != 0) goto err; return t; err: free(t); free(ac); return curl_thread_t_null; } void Curl_thread_destroy(curl_thread_t hnd) { if(hnd != curl_thread_t_null) { pthread_detach(*hnd); free(hnd); } } int Curl_thread_join(curl_thread_t *hnd) { int ret = (pthread_join(**hnd, NULL) == 0); free(*hnd); *hnd = curl_thread_t_null; return ret; } #elif defined(USE_THREADS_WIN32) /* !checksrc! disable SPACEBEFOREPAREN 1 */ curl_thread_t Curl_thread_create(unsigned int (CURL_STDCALL *func) (void *), void *arg) { #ifdef _WIN32_WCE typedef HANDLE curl_win_thread_handle_t; #elif defined(__MINGW32__) && !defined(__MINGW64_VERSION_MAJOR) typedef unsigned long curl_win_thread_handle_t; #else typedef uintptr_t curl_win_thread_handle_t; #endif curl_thread_t t; curl_win_thread_handle_t thread_handle; #ifdef _WIN32_WCE thread_handle = CreateThread(NULL, 0, func, arg, 0, NULL); #else thread_handle = _beginthreadex(NULL, 0, func, arg, 0, NULL); #endif t = (curl_thread_t)thread_handle; if((t == 0) || (t == LongToHandle(-1L))) { #ifdef _WIN32_WCE DWORD gle = GetLastError(); errno = ((gle == ERROR_ACCESS_DENIED || gle == ERROR_NOT_ENOUGH_MEMORY) ? EACCES : EINVAL); #endif return curl_thread_t_null; } return t; } void Curl_thread_destroy(curl_thread_t hnd) { CloseHandle(hnd); } int Curl_thread_join(curl_thread_t *hnd) { #if !defined(_WIN32_WINNT) || !defined(_WIN32_WINNT_VISTA) || \ (_WIN32_WINNT < _WIN32_WINNT_VISTA) int ret = (WaitForSingleObject(*hnd, INFINITE) == WAIT_OBJECT_0); #else int ret = (WaitForSingleObjectEx(*hnd, INFINITE, FALSE) == WAIT_OBJECT_0); #endif Curl_thread_destroy(*hnd); *hnd = curl_thread_t_null; return ret; } #endif /* USE_THREADS_* */
YifuLiu/AliOS-Things
components/curl/lib/curl_threads.c
C
apache-2.0
3,835
#ifndef HEADER_CURL_THREADS_H #define HEADER_CURL_THREADS_H /*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2016, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "curl_setup.h" #if defined(USE_THREADS_POSIX) # define CURL_STDCALL # define curl_mutex_t pthread_mutex_t # define curl_thread_t pthread_t * # define curl_thread_t_null (pthread_t *)0 # define Curl_mutex_init(m) pthread_mutex_init(m, NULL) # define Curl_mutex_acquire(m) pthread_mutex_lock(m) # define Curl_mutex_release(m) pthread_mutex_unlock(m) # define Curl_mutex_destroy(m) pthread_mutex_destroy(m) #elif defined(USE_THREADS_WIN32) # define CURL_STDCALL __stdcall # define curl_mutex_t CRITICAL_SECTION # define curl_thread_t HANDLE # define curl_thread_t_null (HANDLE)0 # if !defined(_WIN32_WINNT) || !defined(_WIN32_WINNT_VISTA) || \ (_WIN32_WINNT < _WIN32_WINNT_VISTA) || \ (defined(__MINGW32__) && !defined(__MINGW64_VERSION_MAJOR)) # define Curl_mutex_init(m) InitializeCriticalSection(m) # else # define Curl_mutex_init(m) InitializeCriticalSectionEx(m, 0, 1) # endif # define Curl_mutex_acquire(m) EnterCriticalSection(m) # define Curl_mutex_release(m) LeaveCriticalSection(m) # define Curl_mutex_destroy(m) DeleteCriticalSection(m) #endif #if defined(USE_THREADS_POSIX) || defined(USE_THREADS_WIN32) /* !checksrc! disable SPACEBEFOREPAREN 1 */ curl_thread_t Curl_thread_create(unsigned int (CURL_STDCALL *func) (void *), void *arg); void Curl_thread_destroy(curl_thread_t hnd); int Curl_thread_join(curl_thread_t *hnd); #endif /* USE_THREADS_POSIX || USE_THREADS_WIN32 */ #endif /* HEADER_CURL_THREADS_H */
YifuLiu/AliOS-Things
components/curl/lib/curl_threads.h
C
apache-2.0
2,661
#ifndef HEADER_CURL_CURLX_H #define HEADER_CURL_CURLX_H /*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2018, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ /* * Defines protos and includes all header files that provide the curlx_* * functions. The curlx_* functions are not part of the libcurl API, but are * stand-alone functions whose sources can be built and linked by apps if need * be. */ #include <curl/mprintf.h> /* this is still a public header file that provides the curl_mprintf() functions while they still are offered publicly. They will be made library- private one day */ #include "strcase.h" /* "strcase.h" provides the strcasecompare protos */ #include "strtoofft.h" /* "strtoofft.h" provides this function: curlx_strtoofft(), returns a curl_off_t number from a given string. */ #include "nonblock.h" /* "nonblock.h" provides curlx_nonblock() */ #include "warnless.h" /* "warnless.h" provides functions: curlx_ultous() curlx_ultouc() curlx_uztosi() */ /* Now setup curlx_ * names for the functions that are to become curlx_ and be removed from a future libcurl official API: curlx_getenv curlx_mprintf (and its variations) curlx_strcasecompare curlx_strncasecompare */ #define curlx_getenv curl_getenv #define curlx_mvsnprintf curl_mvsnprintf #define curlx_msnprintf curl_msnprintf #define curlx_maprintf curl_maprintf #define curlx_mvaprintf curl_mvaprintf #define curlx_msprintf curl_msprintf #define curlx_mprintf curl_mprintf #define curlx_mfprintf curl_mfprintf #define curlx_mvsprintf curl_mvsprintf #define curlx_mvprintf curl_mvprintf #define curlx_mvfprintf curl_mvfprintf #ifdef ENABLE_CURLX_PRINTF /* If this define is set, we define all "standard" printf() functions to use the curlx_* version instead. It makes the source code transparent and easier to understand/patch. Undefine them first. */ # undef printf # undef fprintf # undef sprintf # undef msnprintf # undef vprintf # undef vfprintf # undef vsprintf # undef mvsnprintf # undef aprintf # undef vaprintf # define printf curlx_mprintf # define fprintf curlx_mfprintf # define sprintf curlx_msprintf # define msnprintf curlx_msnprintf # define vprintf curlx_mvprintf # define vfprintf curlx_mvfprintf # define mvsnprintf curlx_mvsnprintf # define aprintf curlx_maprintf # define vaprintf curlx_mvaprintf #endif /* ENABLE_CURLX_PRINTF */ #endif /* HEADER_CURL_CURLX_H */
YifuLiu/AliOS-Things
components/curl/lib/curlx.h
C
apache-2.0
3,335
/*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2019, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "curl_setup.h" #ifndef CURL_DISABLE_DICT #ifdef HAVE_NETINET_IN_H #include <netinet/in.h> #endif #ifdef HAVE_NETDB_H #include <netdb.h> #endif #ifdef HAVE_ARPA_INET_H #include <arpa/inet.h> #endif #ifdef HAVE_NET_IF_H #include <net/if.h> #endif #ifdef HAVE_SYS_IOCTL_H #include <sys/ioctl.h> #endif #ifdef HAVE_SYS_PARAM_H #include <sys/param.h> #endif #ifdef HAVE_SYS_SELECT_H #include <sys/select.h> #endif #include "urldata.h" #include <curl/curl.h> #include "transfer.h" #include "sendf.h" #include "escape.h" #include "progress.h" #include "dict.h" #include "strcase.h" #include "curl_memory.h" /* The last #include file should be: */ #include "memdebug.h" /* * Forward declarations. */ static CURLcode dict_do(struct connectdata *conn, bool *done); /* * DICT protocol handler. */ const struct Curl_handler Curl_handler_dict = { "DICT", /* scheme */ ZERO_NULL, /* setup_connection */ dict_do, /* do_it */ ZERO_NULL, /* done */ ZERO_NULL, /* do_more */ ZERO_NULL, /* connect_it */ ZERO_NULL, /* connecting */ ZERO_NULL, /* doing */ ZERO_NULL, /* proto_getsock */ ZERO_NULL, /* doing_getsock */ ZERO_NULL, /* domore_getsock */ ZERO_NULL, /* perform_getsock */ ZERO_NULL, /* disconnect */ ZERO_NULL, /* readwrite */ ZERO_NULL, /* connection_check */ PORT_DICT, /* defport */ CURLPROTO_DICT, /* protocol */ PROTOPT_NONE | PROTOPT_NOURLQUERY /* flags */ }; static char *unescape_word(struct Curl_easy *data, const char *inputbuff) { char *newp = NULL; char *dictp; size_t len; CURLcode result = Curl_urldecode(data, inputbuff, 0, &newp, &len, FALSE); if(!newp || result) return NULL; dictp = malloc(len*2 + 1); /* add one for terminating zero */ if(dictp) { char *ptr; char ch; int olen = 0; /* According to RFC2229 section 2.2, these letters need to be escaped with \[letter] */ for(ptr = newp; (ch = *ptr) != 0; ptr++) { if((ch <= 32) || (ch == 127) || (ch == '\'') || (ch == '\"') || (ch == '\\')) { dictp[olen++] = '\\'; } dictp[olen++] = ch; } dictp[olen] = 0; } free(newp); return dictp; } static CURLcode dict_do(struct connectdata *conn, bool *done) { char *word; char *eword; char *ppath; char *database = NULL; char *strategy = NULL; char *nthdef = NULL; /* This is not part of the protocol, but required by RFC 2229 */ CURLcode result = CURLE_OK; struct Curl_easy *data = conn->data; curl_socket_t sockfd = conn->sock[FIRSTSOCKET]; char *path = data->state.up.path; *done = TRUE; /* unconditionally */ if(conn->bits.user_passwd) { /* AUTH is missing */ } if(strncasecompare(path, DICT_MATCH, sizeof(DICT_MATCH)-1) || strncasecompare(path, DICT_MATCH2, sizeof(DICT_MATCH2)-1) || strncasecompare(path, DICT_MATCH3, sizeof(DICT_MATCH3)-1)) { word = strchr(path, ':'); if(word) { word++; database = strchr(word, ':'); if(database) { *database++ = (char)0; strategy = strchr(database, ':'); if(strategy) { *strategy++ = (char)0; nthdef = strchr(strategy, ':'); if(nthdef) { *nthdef = (char)0; } } } } if((word == NULL) || (*word == (char)0)) { infof(data, "lookup word is missing\n"); word = (char *)"default"; } if((database == NULL) || (*database == (char)0)) { database = (char *)"!"; } if((strategy == NULL) || (*strategy == (char)0)) { strategy = (char *)"."; } eword = unescape_word(data, word); if(!eword) return CURLE_OUT_OF_MEMORY; result = Curl_sendf(sockfd, conn, "CLIENT " LIBCURL_NAME " " LIBCURL_VERSION "\r\n" "MATCH " "%s " /* database */ "%s " /* strategy */ "%s\r\n" /* word */ "QUIT\r\n", database, strategy, eword ); free(eword); if(result) { failf(data, "Failed sending DICT request"); return result; } Curl_setup_transfer(data, FIRSTSOCKET, -1, FALSE, -1); /* no upload */ } else if(strncasecompare(path, DICT_DEFINE, sizeof(DICT_DEFINE)-1) || strncasecompare(path, DICT_DEFINE2, sizeof(DICT_DEFINE2)-1) || strncasecompare(path, DICT_DEFINE3, sizeof(DICT_DEFINE3)-1)) { word = strchr(path, ':'); if(word) { word++; database = strchr(word, ':'); if(database) { *database++ = (char)0; nthdef = strchr(database, ':'); if(nthdef) { *nthdef = (char)0; } } } if((word == NULL) || (*word == (char)0)) { infof(data, "lookup word is missing\n"); word = (char *)"default"; } if((database == NULL) || (*database == (char)0)) { database = (char *)"!"; } eword = unescape_word(data, word); if(!eword) return CURLE_OUT_OF_MEMORY; result = Curl_sendf(sockfd, conn, "CLIENT " LIBCURL_NAME " " LIBCURL_VERSION "\r\n" "DEFINE " "%s " /* database */ "%s\r\n" /* word */ "QUIT\r\n", database, eword); free(eword); if(result) { failf(data, "Failed sending DICT request"); return result; } Curl_setup_transfer(data, FIRSTSOCKET, -1, FALSE, -1); } else { ppath = strchr(path, '/'); if(ppath) { int i; ppath++; for(i = 0; ppath[i]; i++) { if(ppath[i] == ':') ppath[i] = ' '; } result = Curl_sendf(sockfd, conn, "CLIENT " LIBCURL_NAME " " LIBCURL_VERSION "\r\n" "%s\r\n" "QUIT\r\n", ppath); if(result) { failf(data, "Failed sending DICT request"); return result; } Curl_setup_transfer(data, FIRSTSOCKET, -1, FALSE, -1); } } return CURLE_OK; } #endif /*CURL_DISABLE_DICT*/
YifuLiu/AliOS-Things
components/curl/lib/dict.c
C
apache-2.0
7,723
#ifndef HEADER_CURL_DICT_H #define HEADER_CURL_DICT_H /*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2009, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #ifndef CURL_DISABLE_DICT extern const struct Curl_handler Curl_handler_dict; #endif #endif /* HEADER_CURL_DICT_H */
YifuLiu/AliOS-Things
components/curl/lib/dict.h
C
apache-2.0
1,199
/*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 2018 - 2019, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "curl_setup.h" #ifndef CURL_DISABLE_DOH #include "urldata.h" #include "curl_addrinfo.h" #include "doh.h" #include "sendf.h" #include "multiif.h" #include "url.h" #include "share.h" #include "curl_base64.h" #include "connect.h" #include "strdup.h" /* The last 3 #include files should be in this order */ #include "curl_printf.h" #include "curl_memory.h" #include "memdebug.h" #define DNS_CLASS_IN 0x01 #define DOH_MAX_RESPONSE_SIZE 3000 /* bytes */ #ifndef CURL_DISABLE_VERBOSE_STRINGS static const char * const errors[]={ "", "Bad label", "Out of range", "Label loop", "Too small", "Out of memory", "RDATA length", "Malformat", "Bad RCODE", "Unexpected TYPE", "Unexpected CLASS", "No content", "Bad ID" }; static const char *doh_strerror(DOHcode code) { if((code >= DOH_OK) && (code <= DOH_DNS_BAD_ID)) return errors[code]; return "bad error code"; } #endif #ifdef DEBUGBUILD #define UNITTEST #else #define UNITTEST static #endif UNITTEST DOHcode doh_encode(const char *host, DNStype dnstype, unsigned char *dnsp, /* buffer */ size_t len, /* buffer size */ size_t *olen) /* output length */ { size_t hostlen = strlen(host); unsigned char *orig = dnsp; const char *hostp = host; if(len < (12 + hostlen + 4)) return DOH_TOO_SMALL_BUFFER; *dnsp++ = 0; /* 16 bit id */ *dnsp++ = 0; *dnsp++ = 0x01; /* |QR| Opcode |AA|TC|RD| Set the RD bit */ *dnsp++ = '\0'; /* |RA| Z | RCODE | */ *dnsp++ = '\0'; *dnsp++ = 1; /* QDCOUNT (number of entries in the question section) */ *dnsp++ = '\0'; *dnsp++ = '\0'; /* ANCOUNT */ *dnsp++ = '\0'; *dnsp++ = '\0'; /* NSCOUNT */ *dnsp++ = '\0'; *dnsp++ = '\0'; /* ARCOUNT */ /* store a QNAME */ do { char *dot = strchr(hostp, '.'); size_t labellen; bool found = false; if(dot) { found = true; labellen = dot - hostp; } else labellen = strlen(hostp); if(labellen > 63) { /* too long label, error out */ *olen = 0; return DOH_DNS_BAD_LABEL; } *dnsp++ = (unsigned char)labellen; memcpy(dnsp, hostp, labellen); dnsp += labellen; hostp += labellen + 1; if(!found) { *dnsp++ = 0; /* terminating zero */ break; } } while(1); *dnsp++ = '\0'; /* upper 8 bit TYPE */ *dnsp++ = (unsigned char)dnstype; *dnsp++ = '\0'; /* upper 8 bit CLASS */ *dnsp++ = DNS_CLASS_IN; /* IN - "the Internet" */ *olen = dnsp - orig; return DOH_OK; } static size_t doh_write_cb(void *contents, size_t size, size_t nmemb, void *userp) { size_t realsize = size * nmemb; struct dohresponse *mem = (struct dohresponse *)userp; if((mem->size + realsize) > DOH_MAX_RESPONSE_SIZE) /* suspiciously much for us */ return 0; mem->memory = Curl_saferealloc(mem->memory, mem->size + realsize); if(!mem->memory) /* out of memory! */ return 0; memcpy(&(mem->memory[mem->size]), contents, realsize); mem->size += realsize; return realsize; } /* called from multi.c when this DOH transfer is complete */ static int Curl_doh_done(struct Curl_easy *doh, CURLcode result) { struct Curl_easy *data = doh->set.dohfor; /* so one of the DOH request done for the 'data' transfer is now complete! */ data->req.doh.pending--; infof(data, "a DOH request is completed, %u to go\n", data->req.doh.pending); if(result) infof(data, "DOH request %s\n", curl_easy_strerror(result)); if(!data->req.doh.pending) { /* DOH completed */ curl_slist_free_all(data->req.doh.headers); data->req.doh.headers = NULL; Curl_expire(data, 0, EXPIRE_RUN_NOW); } return 0; } #define ERROR_CHECK_SETOPT(x,y) \ do { \ result = curl_easy_setopt(doh, x, y); \ if(result) \ goto error; \ } WHILE_FALSE static CURLcode dohprobe(struct Curl_easy *data, struct dnsprobe *p, DNStype dnstype, const char *host, const char *url, CURLM *multi, struct curl_slist *headers) { struct Curl_easy *doh = NULL; char *nurl = NULL; CURLcode result = CURLE_OK; timediff_t timeout_ms; DOHcode d = doh_encode(host, dnstype, p->dohbuffer, sizeof(p->dohbuffer), &p->dohlen); if(d) { failf(data, "Failed to encode DOH packet [%d]\n", d); return CURLE_OUT_OF_MEMORY; } p->dnstype = dnstype; p->serverdoh.memory = NULL; /* the memory will be grown as needed by realloc in the doh_write_cb function */ p->serverdoh.size = 0; /* Note: this is code for sending the DoH request with GET but there's still no logic that actually enables this. We should either add that ability or yank out the GET code. Discuss! */ if(data->set.doh_get) { char *b64; size_t b64len; result = Curl_base64url_encode(data, (char *)p->dohbuffer, p->dohlen, &b64, &b64len); if(result) goto error; nurl = aprintf("%s?dns=%s", url, b64); free(b64); if(!nurl) { result = CURLE_OUT_OF_MEMORY; goto error; } url = nurl; } timeout_ms = Curl_timeleft(data, NULL, TRUE); /* Curl_open() is the internal version of curl_easy_init() */ result = Curl_open(&doh); if(!result) { /* pass in the struct pointer via a local variable to please coverity and the gcc typecheck helpers */ struct dohresponse *resp = &p->serverdoh; ERROR_CHECK_SETOPT(CURLOPT_URL, url); ERROR_CHECK_SETOPT(CURLOPT_WRITEFUNCTION, doh_write_cb); ERROR_CHECK_SETOPT(CURLOPT_WRITEDATA, resp); if(!data->set.doh_get) { ERROR_CHECK_SETOPT(CURLOPT_POSTFIELDS, p->dohbuffer); ERROR_CHECK_SETOPT(CURLOPT_POSTFIELDSIZE, (long)p->dohlen); } ERROR_CHECK_SETOPT(CURLOPT_HTTPHEADER, headers); #ifdef USE_NGHTTP2 ERROR_CHECK_SETOPT(CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_2TLS); #endif #ifndef CURLDEBUG /* enforce HTTPS if not debug */ ERROR_CHECK_SETOPT(CURLOPT_PROTOCOLS, CURLPROTO_HTTPS); #endif ERROR_CHECK_SETOPT(CURLOPT_TIMEOUT_MS, (long)timeout_ms); if(data->set.verbose) ERROR_CHECK_SETOPT(CURLOPT_VERBOSE, 1L); if(data->set.no_signal) ERROR_CHECK_SETOPT(CURLOPT_NOSIGNAL, 1L); /* Inherit *some* SSL options from the user's transfer. This is a best-guess as to which options are needed for compatibility. #3661 */ if(data->set.ssl.falsestart) ERROR_CHECK_SETOPT(CURLOPT_SSL_FALSESTART, 1L); if(data->set.ssl.primary.verifyhost) ERROR_CHECK_SETOPT(CURLOPT_SSL_VERIFYHOST, 2L); if(data->set.proxy_ssl.primary.verifyhost) ERROR_CHECK_SETOPT(CURLOPT_PROXY_SSL_VERIFYHOST, 2L); if(data->set.ssl.primary.verifypeer) ERROR_CHECK_SETOPT(CURLOPT_SSL_VERIFYPEER, 1L); if(data->set.proxy_ssl.primary.verifypeer) ERROR_CHECK_SETOPT(CURLOPT_PROXY_SSL_VERIFYPEER, 1L); if(data->set.ssl.primary.verifystatus) ERROR_CHECK_SETOPT(CURLOPT_SSL_VERIFYSTATUS, 1L); if(data->set.str[STRING_SSL_CAFILE_ORIG]) { ERROR_CHECK_SETOPT(CURLOPT_CAINFO, data->set.str[STRING_SSL_CAFILE_ORIG]); } if(data->set.str[STRING_SSL_CAFILE_PROXY]) { ERROR_CHECK_SETOPT(CURLOPT_PROXY_CAINFO, data->set.str[STRING_SSL_CAFILE_PROXY]); } if(data->set.str[STRING_SSL_CAPATH_ORIG]) { ERROR_CHECK_SETOPT(CURLOPT_CAPATH, data->set.str[STRING_SSL_CAPATH_ORIG]); } if(data->set.str[STRING_SSL_CAPATH_PROXY]) { ERROR_CHECK_SETOPT(CURLOPT_PROXY_CAPATH, data->set.str[STRING_SSL_CAPATH_PROXY]); } if(data->set.str[STRING_SSL_CRLFILE_ORIG]) { ERROR_CHECK_SETOPT(CURLOPT_CRLFILE, data->set.str[STRING_SSL_CRLFILE_ORIG]); } if(data->set.str[STRING_SSL_CRLFILE_PROXY]) { ERROR_CHECK_SETOPT(CURLOPT_PROXY_CRLFILE, data->set.str[STRING_SSL_CRLFILE_PROXY]); } if(data->set.ssl.certinfo) ERROR_CHECK_SETOPT(CURLOPT_CERTINFO, 1L); if(data->set.str[STRING_SSL_RANDOM_FILE]) { ERROR_CHECK_SETOPT(CURLOPT_RANDOM_FILE, data->set.str[STRING_SSL_RANDOM_FILE]); } if(data->set.str[STRING_SSL_EGDSOCKET]) { ERROR_CHECK_SETOPT(CURLOPT_EGDSOCKET, data->set.str[STRING_SSL_EGDSOCKET]); } if(data->set.ssl.no_revoke) ERROR_CHECK_SETOPT(CURLOPT_SSL_OPTIONS, CURLSSLOPT_NO_REVOKE); if(data->set.proxy_ssl.no_revoke) ERROR_CHECK_SETOPT(CURLOPT_PROXY_SSL_OPTIONS, CURLSSLOPT_NO_REVOKE); if(data->set.ssl.fsslctx) ERROR_CHECK_SETOPT(CURLOPT_SSL_CTX_FUNCTION, data->set.ssl.fsslctx); if(data->set.ssl.fsslctxp) ERROR_CHECK_SETOPT(CURLOPT_SSL_CTX_DATA, data->set.ssl.fsslctxp); doh->set.fmultidone = Curl_doh_done; doh->set.dohfor = data; /* identify for which transfer this is done */ p->easy = doh; /* add this transfer to the multi handle */ if(curl_multi_add_handle(multi, doh)) goto error; } else goto error; free(nurl); return CURLE_OK; error: free(nurl); Curl_close(doh); return result; } /* * Curl_doh() resolves a name using DOH. It resolves a name and returns a * 'Curl_addrinfo *' with the address information. */ Curl_addrinfo *Curl_doh(struct connectdata *conn, const char *hostname, int port, int *waitp) { struct Curl_easy *data = conn->data; CURLcode result = CURLE_OK; *waitp = TRUE; /* this never returns synchronously */ (void)conn; (void)hostname; (void)port; /* start clean, consider allocating this struct on demand */ memset(&data->req.doh, 0, sizeof(struct dohdata)); data->req.doh.host = hostname; data->req.doh.port = port; data->req.doh.headers = curl_slist_append(NULL, "Content-Type: application/dns-message"); if(!data->req.doh.headers) goto error; if(conn->ip_version != CURL_IPRESOLVE_V6) { /* create IPv4 DOH request */ result = dohprobe(data, &data->req.doh.probe[0], DNS_TYPE_A, hostname, data->set.str[STRING_DOH], data->multi, data->req.doh.headers); if(result) goto error; data->req.doh.pending++; } if(conn->ip_version != CURL_IPRESOLVE_V4) { /* create IPv6 DOH request */ result = dohprobe(data, &data->req.doh.probe[1], DNS_TYPE_AAAA, hostname, data->set.str[STRING_DOH], data->multi, data->req.doh.headers); if(result) goto error; data->req.doh.pending++; } return NULL; error: curl_slist_free_all(data->req.doh.headers); data->req.doh.headers = NULL; curl_easy_cleanup(data->req.doh.probe[0].easy); data->req.doh.probe[0].easy = NULL; curl_easy_cleanup(data->req.doh.probe[1].easy); data->req.doh.probe[1].easy = NULL; return NULL; } static DOHcode skipqname(unsigned char *doh, size_t dohlen, unsigned int *indexp) { unsigned char length; do { if(dohlen < (*indexp + 1)) return DOH_DNS_OUT_OF_RANGE; length = doh[*indexp]; if((length & 0xc0) == 0xc0) { /* name pointer, advance over it and be done */ if(dohlen < (*indexp + 2)) return DOH_DNS_OUT_OF_RANGE; *indexp += 2; break; } if(length & 0xc0) return DOH_DNS_BAD_LABEL; if(dohlen < (*indexp + 1 + length)) return DOH_DNS_OUT_OF_RANGE; *indexp += 1 + length; } while(length); return DOH_OK; } static unsigned short get16bit(unsigned char *doh, int index) { return (unsigned short)((doh[index] << 8) | doh[index + 1]); } static unsigned int get32bit(unsigned char *doh, int index) { return (doh[index] << 24) | (doh[index + 1] << 16) | (doh[index + 2] << 8) | doh[index + 3]; } static DOHcode store_a(unsigned char *doh, int index, struct dohentry *d) { /* silently ignore addresses over the limit */ if(d->numaddr < DOH_MAX_ADDR) { struct dohaddr *a = &d->addr[d->numaddr]; a->type = DNS_TYPE_A; memcpy(&a->ip.v4, &doh[index], 4); d->numaddr++; } return DOH_OK; } static DOHcode store_aaaa(unsigned char *doh, int index, struct dohentry *d) { /* silently ignore addresses over the limit */ if(d->numaddr < DOH_MAX_ADDR) { struct dohaddr *a = &d->addr[d->numaddr]; a->type = DNS_TYPE_AAAA; memcpy(&a->ip.v6, &doh[index], 16); d->numaddr++; } return DOH_OK; } static DOHcode cnameappend(struct cnamestore *c, unsigned char *src, size_t len) { if(!c->alloc) { c->allocsize = len + 1; c->alloc = malloc(c->allocsize); if(!c->alloc) return DOH_OUT_OF_MEM; } else if(c->allocsize < (c->allocsize + len + 1)) { char *ptr; c->allocsize += len + 1; ptr = realloc(c->alloc, c->allocsize); if(!ptr) { free(c->alloc); return DOH_OUT_OF_MEM; } c->alloc = ptr; } memcpy(&c->alloc[c->len], src, len); c->len += len; c->alloc[c->len] = 0; /* keep it zero terminated */ return DOH_OK; } static DOHcode store_cname(unsigned char *doh, size_t dohlen, unsigned int index, struct dohentry *d) { struct cnamestore *c; unsigned int loop = 128; /* a valid DNS name can never loop this much */ unsigned char length; if(d->numcname == DOH_MAX_CNAME) return DOH_OK; /* skip! */ c = &d->cname[d->numcname++]; do { if(index >= dohlen) return DOH_DNS_OUT_OF_RANGE; length = doh[index]; if((length & 0xc0) == 0xc0) { int newpos; /* name pointer, get the new offset (14 bits) */ if((index + 1) >= dohlen) return DOH_DNS_OUT_OF_RANGE; /* move to the the new index */ newpos = (length & 0x3f) << 8 | doh[index + 1]; index = newpos; continue; } else if(length & 0xc0) return DOH_DNS_BAD_LABEL; /* bad input */ else index++; if(length) { DOHcode rc; if(c->len) { rc = cnameappend(c, (unsigned char *)".", 1); if(rc) return rc; } if((index + length) > dohlen) return DOH_DNS_BAD_LABEL; rc = cnameappend(c, &doh[index], length); if(rc) return rc; index += length; } } while(length && --loop); if(!loop) return DOH_DNS_LABEL_LOOP; return DOH_OK; } static DOHcode rdata(unsigned char *doh, size_t dohlen, unsigned short rdlength, unsigned short type, int index, struct dohentry *d) { /* RDATA - A (TYPE 1): 4 bytes - AAAA (TYPE 28): 16 bytes - NS (TYPE 2): N bytes */ DOHcode rc; switch(type) { case DNS_TYPE_A: if(rdlength != 4) return DOH_DNS_RDATA_LEN; rc = store_a(doh, index, d); if(rc) return rc; break; case DNS_TYPE_AAAA: if(rdlength != 16) return DOH_DNS_RDATA_LEN; rc = store_aaaa(doh, index, d); if(rc) return rc; break; case DNS_TYPE_CNAME: rc = store_cname(doh, dohlen, index, d); if(rc) return rc; break; default: /* unsupported type, just skip it */ break; } return DOH_OK; } static void init_dohentry(struct dohentry *de) { memset(de, 0, sizeof(*de)); de->ttl = INT_MAX; } UNITTEST DOHcode doh_decode(unsigned char *doh, size_t dohlen, DNStype dnstype, struct dohentry *d) { unsigned char rcode; unsigned short qdcount; unsigned short ancount; unsigned short type = 0; unsigned short rdlength; unsigned short nscount; unsigned short arcount; unsigned int index = 12; DOHcode rc; if(dohlen < 12) return DOH_TOO_SMALL_BUFFER; /* too small */ if(!doh || doh[0] || doh[1]) return DOH_DNS_BAD_ID; /* bad ID */ rcode = doh[3] & 0x0f; if(rcode) return DOH_DNS_BAD_RCODE; /* bad rcode */ qdcount = get16bit(doh, 4); while(qdcount) { rc = skipqname(doh, dohlen, &index); if(rc) return rc; /* bad qname */ if(dohlen < (index + 4)) return DOH_DNS_OUT_OF_RANGE; index += 4; /* skip question's type and class */ qdcount--; } ancount = get16bit(doh, 6); while(ancount) { unsigned short class; unsigned int ttl; rc = skipqname(doh, dohlen, &index); if(rc) return rc; /* bad qname */ if(dohlen < (index + 2)) return DOH_DNS_OUT_OF_RANGE; type = get16bit(doh, index); if((type != DNS_TYPE_CNAME) && (type != dnstype)) /* Not the same type as was asked for nor CNAME */ return DOH_DNS_UNEXPECTED_TYPE; index += 2; if(dohlen < (index + 2)) return DOH_DNS_OUT_OF_RANGE; class = get16bit(doh, index); if(DNS_CLASS_IN != class) return DOH_DNS_UNEXPECTED_CLASS; /* unsupported */ index += 2; if(dohlen < (index + 4)) return DOH_DNS_OUT_OF_RANGE; ttl = get32bit(doh, index); if(ttl < d->ttl) d->ttl = ttl; index += 4; if(dohlen < (index + 2)) return DOH_DNS_OUT_OF_RANGE; rdlength = get16bit(doh, index); index += 2; if(dohlen < (index + rdlength)) return DOH_DNS_OUT_OF_RANGE; rc = rdata(doh, dohlen, rdlength, type, index, d); if(rc) return rc; /* bad rdata */ index += rdlength; ancount--; } nscount = get16bit(doh, 8); while(nscount) { rc = skipqname(doh, dohlen, &index); if(rc) return rc; /* bad qname */ if(dohlen < (index + 8)) return DOH_DNS_OUT_OF_RANGE; index += 2 + 2 + 4; /* type, class and ttl */ if(dohlen < (index + 2)) return DOH_DNS_OUT_OF_RANGE; rdlength = get16bit(doh, index); index += 2; if(dohlen < (index + rdlength)) return DOH_DNS_OUT_OF_RANGE; index += rdlength; nscount--; } arcount = get16bit(doh, 10); while(arcount) { rc = skipqname(doh, dohlen, &index); if(rc) return rc; /* bad qname */ if(dohlen < (index + 8)) return DOH_DNS_OUT_OF_RANGE; index += 2 + 2 + 4; /* type, class and ttl */ if(dohlen < (index + 2)) return DOH_DNS_OUT_OF_RANGE; rdlength = get16bit(doh, index); index += 2; if(dohlen < (index + rdlength)) return DOH_DNS_OUT_OF_RANGE; index += rdlength; arcount--; } if(index != dohlen) return DOH_DNS_MALFORMAT; /* something is wrong */ if((type != DNS_TYPE_NS) && !d->numcname && !d->numaddr) /* nothing stored! */ return DOH_NO_CONTENT; return DOH_OK; /* ok */ } #ifndef CURL_DISABLE_VERBOSE_STRINGS static void showdoh(struct Curl_easy *data, struct dohentry *d) { int i; infof(data, "TTL: %u seconds\n", d->ttl); for(i = 0; i < d->numaddr; i++) { struct dohaddr *a = &d->addr[i]; if(a->type == DNS_TYPE_A) { infof(data, "DOH A: %u.%u.%u.%u\n", a->ip.v4[0], a->ip.v4[1], a->ip.v4[2], a->ip.v4[3]); } else if(a->type == DNS_TYPE_AAAA) { int j; char buffer[128]; char *ptr; size_t len; msnprintf(buffer, 128, "DOH AAAA: "); ptr = &buffer[10]; len = 118; for(j = 0; j < 16; j += 2) { size_t l; msnprintf(ptr, len, "%s%02x%02x", j?":":"", d->addr[i].ip.v6[j], d->addr[i].ip.v6[j + 1]); l = strlen(ptr); len -= l; ptr += l; } infof(data, "%s\n", buffer); } } for(i = 0; i < d->numcname; i++) { infof(data, "CNAME: %s\n", d->cname[i].alloc); } } #else #define showdoh(x,y) #endif /* * doh2ai() * * This function returns a pointer to the first element of a newly allocated * Curl_addrinfo struct linked list filled with the data from a set of DOH * lookups. Curl_addrinfo is meant to work like the addrinfo struct does for * a IPv6 stack, but usable also for IPv4, all hosts and environments. * * The memory allocated by this function *MUST* be free'd later on calling * Curl_freeaddrinfo(). For each successful call to this function there * must be an associated call later to Curl_freeaddrinfo(). */ static Curl_addrinfo * doh2ai(const struct dohentry *de, const char *hostname, int port) { Curl_addrinfo *ai; Curl_addrinfo *prevai = NULL; Curl_addrinfo *firstai = NULL; struct sockaddr_in *addr; #ifdef ENABLE_IPV6 struct sockaddr_in6 *addr6; #endif CURLcode result = CURLE_OK; int i; if(!de) /* no input == no output! */ return NULL; for(i = 0; i < de->numaddr; i++) { size_t ss_size; CURL_SA_FAMILY_T addrtype; if(de->addr[i].type == DNS_TYPE_AAAA) { #ifndef ENABLE_IPV6 /* we can't handle IPv6 addresses */ continue; #else ss_size = sizeof(struct sockaddr_in6); addrtype = AF_INET6; #endif } else { ss_size = sizeof(struct sockaddr_in); addrtype = AF_INET; } ai = calloc(1, sizeof(Curl_addrinfo)); if(!ai) { result = CURLE_OUT_OF_MEMORY; break; } ai->ai_canonname = strdup(hostname); if(!ai->ai_canonname) { result = CURLE_OUT_OF_MEMORY; free(ai); break; } ai->ai_addr = calloc(1, ss_size); if(!ai->ai_addr) { result = CURLE_OUT_OF_MEMORY; free(ai->ai_canonname); free(ai); break; } if(!firstai) /* store the pointer we want to return from this function */ firstai = ai; if(prevai) /* make the previous entry point to this */ prevai->ai_next = ai; ai->ai_family = addrtype; /* we return all names as STREAM, so when using this address for TFTP the type must be ignored and conn->socktype be used instead! */ ai->ai_socktype = SOCK_STREAM; ai->ai_addrlen = (curl_socklen_t)ss_size; /* leave the rest of the struct filled with zero */ switch(ai->ai_family) { case AF_INET: addr = (void *)ai->ai_addr; /* storage area for this info */ DEBUGASSERT(sizeof(struct in_addr) == sizeof(de->addr[i].ip.v4)); memcpy(&addr->sin_addr, &de->addr[i].ip.v4, sizeof(struct in_addr)); addr->sin_family = (CURL_SA_FAMILY_T)addrtype; addr->sin_port = htons((unsigned short)port); break; #ifdef ENABLE_IPV6 case AF_INET6: addr6 = (void *)ai->ai_addr; /* storage area for this info */ DEBUGASSERT(sizeof(struct in6_addr) == sizeof(de->addr[i].ip.v6)); memcpy(&addr6->sin6_addr, &de->addr[i].ip.v6, sizeof(struct in6_addr)); addr6->sin6_family = (CURL_SA_FAMILY_T)addrtype; addr6->sin6_port = htons((unsigned short)port); break; #endif } prevai = ai; } if(result) { Curl_freeaddrinfo(firstai); firstai = NULL; } return firstai; } #ifndef CURL_DISABLE_VERBOSE_STRINGS static const char *type2name(DNStype dnstype) { return (dnstype == DNS_TYPE_A)?"A":"AAAA"; } #endif UNITTEST void de_cleanup(struct dohentry *d) { int i = 0; for(i = 0; i < d->numcname; i++) { free(d->cname[i].alloc); } } CURLcode Curl_doh_is_resolved(struct connectdata *conn, struct Curl_dns_entry **dnsp) { struct Curl_easy *data = conn->data; *dnsp = NULL; /* defaults to no response */ if(!data->req.doh.probe[0].easy && !data->req.doh.probe[1].easy) { failf(data, "Could not DOH-resolve: %s", conn->async.hostname); return conn->bits.proxy?CURLE_COULDNT_RESOLVE_PROXY: CURLE_COULDNT_RESOLVE_HOST; } else if(!data->req.doh.pending) { DOHcode rc; DOHcode rc2; struct dohentry de; /* remove DOH handles from multi handle and close them */ curl_multi_remove_handle(data->multi, data->req.doh.probe[0].easy); Curl_close(data->req.doh.probe[0].easy); curl_multi_remove_handle(data->multi, data->req.doh.probe[1].easy); Curl_close(data->req.doh.probe[1].easy); /* parse the responses, create the struct and return it! */ init_dohentry(&de); rc = doh_decode(data->req.doh.probe[0].serverdoh.memory, data->req.doh.probe[0].serverdoh.size, data->req.doh.probe[0].dnstype, &de); free(data->req.doh.probe[0].serverdoh.memory); if(rc) { infof(data, "DOH: %s type %s for %s\n", doh_strerror(rc), type2name(data->req.doh.probe[0].dnstype), data->req.doh.host); } rc2 = doh_decode(data->req.doh.probe[1].serverdoh.memory, data->req.doh.probe[1].serverdoh.size, data->req.doh.probe[1].dnstype, &de); free(data->req.doh.probe[1].serverdoh.memory); if(rc2) { infof(data, "DOH: %s type %s for %s\n", doh_strerror(rc2), type2name(data->req.doh.probe[1].dnstype), data->req.doh.host); } if(!rc || !rc2) { struct Curl_dns_entry *dns; struct Curl_addrinfo *ai; infof(data, "DOH Host name: %s\n", data->req.doh.host); showdoh(data, &de); ai = doh2ai(&de, data->req.doh.host, data->req.doh.port); if(!ai) { de_cleanup(&de); return CURLE_OUT_OF_MEMORY; } if(data->share) Curl_share_lock(data, CURL_LOCK_DATA_DNS, CURL_LOCK_ACCESS_SINGLE); /* we got a response, store it in the cache */ dns = Curl_cache_addr(data, ai, data->req.doh.host, data->req.doh.port); if(data->share) Curl_share_unlock(data, CURL_LOCK_DATA_DNS); de_cleanup(&de); if(!dns) /* returned failure, bail out nicely */ Curl_freeaddrinfo(ai); else { conn->async.dns = dns; *dnsp = dns; return CURLE_OK; } } de_cleanup(&de); return CURLE_COULDNT_RESOLVE_HOST; } return CURLE_OK; } #endif /* CURL_DISABLE_DOH */
YifuLiu/AliOS-Things
components/curl/lib/doh.c
C
apache-2.0
26,856
#ifndef HEADER_CURL_DOH_H #define HEADER_CURL_DOH_H /*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 2018 - 2019, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "urldata.h" #include "curl_addrinfo.h" #ifndef CURL_DISABLE_DOH /* * Curl_doh() resolve a name using DoH (DNS-over-HTTPS). It resolves a name * and returns a 'Curl_addrinfo *' with the address information. */ Curl_addrinfo *Curl_doh(struct connectdata *conn, const char *hostname, int port, int *waitp); CURLcode Curl_doh_is_resolved(struct connectdata *conn, struct Curl_dns_entry **dns); int Curl_doh_getsock(struct connectdata *conn, curl_socket_t *socks, int numsocks); typedef enum { DOH_OK, DOH_DNS_BAD_LABEL, /* 1 */ DOH_DNS_OUT_OF_RANGE, /* 2 */ DOH_DNS_LABEL_LOOP, /* 3 */ DOH_TOO_SMALL_BUFFER, /* 4 */ DOH_OUT_OF_MEM, /* 5 */ DOH_DNS_RDATA_LEN, /* 6 */ DOH_DNS_MALFORMAT, /* 7 */ DOH_DNS_BAD_RCODE, /* 8 - no such name */ DOH_DNS_UNEXPECTED_TYPE, /* 9 */ DOH_DNS_UNEXPECTED_CLASS, /* 10 */ DOH_NO_CONTENT, /* 11 */ DOH_DNS_BAD_ID /* 12 */ } DOHcode; typedef enum { DNS_TYPE_A = 1, DNS_TYPE_NS = 2, DNS_TYPE_CNAME = 5, DNS_TYPE_AAAA = 28 } DNStype; #define DOH_MAX_ADDR 24 #define DOH_MAX_CNAME 4 struct cnamestore { size_t len; /* length of cname */ char *alloc; /* allocated pointer */ size_t allocsize; /* allocated size */ }; struct dohaddr { int type; union { unsigned char v4[4]; /* network byte order */ unsigned char v6[16]; } ip; }; struct dohentry { unsigned int ttl; int numaddr; struct dohaddr addr[DOH_MAX_ADDR]; int numcname; struct cnamestore cname[DOH_MAX_CNAME]; }; #ifdef DEBUGBUILD DOHcode doh_encode(const char *host, DNStype dnstype, unsigned char *dnsp, /* buffer */ size_t len, /* buffer size */ size_t *olen); /* output length */ DOHcode doh_decode(unsigned char *doh, size_t dohlen, DNStype dnstype, struct dohentry *d); void de_cleanup(struct dohentry *d); #endif #else /* if DOH is disabled */ #define Curl_doh(a,b,c,d) NULL #define Curl_doh_is_resolved(x,y) CURLE_COULDNT_RESOLVE_HOST #endif #endif /* HEADER_CURL_DOH_H */
YifuLiu/AliOS-Things
components/curl/lib/doh.h
C
apache-2.0
3,340
/*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2017, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "curl_setup.h" #include <curl/curl.h> #include "dotdot.h" #include "curl_memory.h" /* The last #include file should be: */ #include "memdebug.h" /* * "Remove Dot Segments" * https://tools.ietf.org/html/rfc3986#section-5.2.4 */ /* * Curl_dedotdotify() * @unittest: 1395 * * This function gets a zero-terminated path with dot and dotdot sequences * passed in and strips them off according to the rules in RFC 3986 section * 5.2.4. * * The function handles a query part ('?' + stuff) appended but it expects * that fragments ('#' + stuff) have already been cut off. * * RETURNS * * an allocated dedotdotified output string */ char *Curl_dedotdotify(const char *input) { size_t inlen = strlen(input); char *clone; size_t clen = inlen; /* the length of the cloned input */ char *out = malloc(inlen + 1); char *outptr; char *orgclone; char *queryp; if(!out) return NULL; /* out of memory */ *out = 0; /* zero terminates, for inputs like "./" */ /* get a cloned copy of the input */ clone = strdup(input); if(!clone) { free(out); return NULL; } orgclone = clone; outptr = out; if(!*clone) { /* zero length string, return that */ free(out); return clone; } /* * To handle query-parts properly, we must find it and remove it during the * dotdot-operation and then append it again at the end to the output * string. */ queryp = strchr(clone, '?'); if(queryp) *queryp = 0; do { /* A. If the input buffer begins with a prefix of "../" or "./", then remove that prefix from the input buffer; otherwise, */ if(!strncmp("./", clone, 2)) { clone += 2; clen -= 2; } else if(!strncmp("../", clone, 3)) { clone += 3; clen -= 3; } /* B. if the input buffer begins with a prefix of "/./" or "/.", where "." is a complete path segment, then replace that prefix with "/" in the input buffer; otherwise, */ else if(!strncmp("/./", clone, 3)) { clone += 2; clen -= 2; } else if(!strcmp("/.", clone)) { clone[1]='/'; clone++; clen -= 1; } /* C. if the input buffer begins with a prefix of "/../" or "/..", where ".." is a complete path segment, then replace that prefix with "/" in the input buffer and remove the last segment and its preceding "/" (if any) from the output buffer; otherwise, */ else if(!strncmp("/../", clone, 4)) { clone += 3; clen -= 3; /* remove the last segment from the output buffer */ while(outptr > out) { outptr--; if(*outptr == '/') break; } *outptr = 0; /* zero-terminate where it stops */ } else if(!strcmp("/..", clone)) { clone[2]='/'; clone += 2; clen -= 2; /* remove the last segment from the output buffer */ while(outptr > out) { outptr--; if(*outptr == '/') break; } *outptr = 0; /* zero-terminate where it stops */ } /* D. if the input buffer consists only of "." or "..", then remove that from the input buffer; otherwise, */ else if(!strcmp(".", clone) || !strcmp("..", clone)) { *clone = 0; *out = 0; } else { /* E. move the first path segment in the input buffer to the end of the output buffer, including the initial "/" character (if any) and any subsequent characters up to, but not including, the next "/" character or the end of the input buffer. */ do { *outptr++ = *clone++; clen--; } while(*clone && (*clone != '/')); *outptr = 0; } } while(*clone); if(queryp) { size_t qlen; /* There was a query part, append that to the output. The 'clone' string may now have been altered so we copy from the original input string from the correct index. */ size_t oindex = queryp - orgclone; qlen = strlen(&input[oindex]); memcpy(outptr, &input[oindex], qlen + 1); /* include the end zero byte */ } free(orgclone); return out; }
YifuLiu/AliOS-Things
components/curl/lib/dotdot.c
C
apache-2.0
5,154
#ifndef HEADER_CURL_DOTDOT_H #define HEADER_CURL_DOTDOT_H /*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2014, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ char *Curl_dedotdotify(const char *input); #endif /* HEADER_CURL_DOTDOT_H */
YifuLiu/AliOS-Things
components/curl/lib/dotdot.h
C
apache-2.0
1,161
/*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2019, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "curl_setup.h" /* * See comment in curl_memory.h for the explanation of this sanity check. */ #ifdef CURLX_NO_MEMORY_CALLBACKS #error "libcurl shall not ever be built with CURLX_NO_MEMORY_CALLBACKS defined" #endif #ifdef HAVE_NETINET_IN_H #include <netinet/in.h> #endif #ifdef HAVE_NETDB_H #ifdef USE_LWIPSOCK #include <lwip/netdb.h> #else #include <netdb.h> #endif #endif #ifdef HAVE_ARPA_INET_H #include <arpa/inet.h> #endif #ifdef HAVE_NET_IF_H #include <net/if.h> #endif #ifdef HAVE_SYS_IOCTL_H #include <sys/ioctl.h> #endif #ifdef HAVE_SYS_PARAM_H #include <sys/param.h> #endif #include "urldata.h" #include <curl/curl.h> #include "transfer.h" #include "vtls/vtls.h" #include "url.h" #include "getinfo.h" #include "hostip.h" #include "share.h" #include "strdup.h" #include "progress.h" #include "easyif.h" #include "multiif.h" #include "select.h" #include "sendf.h" /* for failf function prototype */ #include "connect.h" /* for Curl_getconnectinfo */ #include "slist.h" #include "mime.h" #include "amigaos.h" #include "non-ascii.h" #include "warnless.h" #include "multiif.h" #include "sigpipe.h" #include "ssh.h" #include "setopt.h" #include "http_digest.h" #include "system_win32.h" /* The last 3 #include files should be in this order */ #include "curl_printf.h" #include "curl_memory.h" #include "memdebug.h" void Curl_version_init(void); /* true globals -- for curl_global_init() and curl_global_cleanup() */ static unsigned int initialized; static long init_flags; /* * strdup (and other memory functions) is redefined in complicated * ways, but at this point it must be defined as the system-supplied strdup * so the callback pointer is initialized correctly. */ #if defined(_WIN32_WCE) #define system_strdup _strdup #elif !defined(HAVE_STRDUP) #define system_strdup curlx_strdup #else #define system_strdup strdup #endif #if defined(_MSC_VER) && defined(_DLL) && !defined(__POCC__) # pragma warning(disable:4232) /* MSVC extension, dllimport identity */ #endif #ifndef __SYMBIAN32__ /* * If a memory-using function (like curl_getenv) is used before * curl_global_init() is called, we need to have these pointers set already. */ curl_malloc_callback Curl_cmalloc = (curl_malloc_callback)malloc; curl_free_callback Curl_cfree = (curl_free_callback)free; curl_realloc_callback Curl_crealloc = (curl_realloc_callback)realloc; curl_strdup_callback Curl_cstrdup = (curl_strdup_callback)system_strdup; curl_calloc_callback Curl_ccalloc = (curl_calloc_callback)calloc; #if defined(WIN32) && defined(UNICODE) curl_wcsdup_callback Curl_cwcsdup = (curl_wcsdup_callback)_wcsdup; #endif #else /* * Symbian OS doesn't support initialization to code in writable static data. * Initialization will occur in the curl_global_init() call. */ curl_malloc_callback Curl_cmalloc; curl_free_callback Curl_cfree; curl_realloc_callback Curl_crealloc; curl_strdup_callback Curl_cstrdup; curl_calloc_callback Curl_ccalloc; #endif #if defined(_MSC_VER) && defined(_DLL) && !defined(__POCC__) # pragma warning(default:4232) /* MSVC extension, dllimport identity */ #endif /** * curl_global_init() globally initializes curl given a bitwise set of the * different features of what to initialize. */ static CURLcode global_init(long flags, bool memoryfuncs) { if(initialized++) return CURLE_OK; if(memoryfuncs) { /* Setup the default memory functions here (again) */ Curl_cmalloc = (curl_malloc_callback)malloc; Curl_cfree = (curl_free_callback)free; Curl_crealloc = (curl_realloc_callback)realloc; Curl_cstrdup = (curl_strdup_callback)system_strdup; Curl_ccalloc = (curl_calloc_callback)calloc; #if defined(WIN32) && defined(UNICODE) Curl_cwcsdup = (curl_wcsdup_callback)_wcsdup; #endif } if(!Curl_ssl_init()) { DEBUGF(fprintf(stderr, "Error: Curl_ssl_init failed\n")); return CURLE_FAILED_INIT; } #ifdef WIN32 if(Curl_win32_init(flags)) { DEBUGF(fprintf(stderr, "Error: win32_init failed\n")); return CURLE_FAILED_INIT; } #endif #ifdef __AMIGA__ if(!Curl_amiga_init()) { DEBUGF(fprintf(stderr, "Error: Curl_amiga_init failed\n")); return CURLE_FAILED_INIT; } #endif #ifdef NETWARE if(netware_init()) { DEBUGF(fprintf(stderr, "Warning: LONG namespace not available\n")); } #endif if(Curl_resolver_global_init()) { DEBUGF(fprintf(stderr, "Error: resolver_global_init failed\n")); return CURLE_FAILED_INIT; } (void)Curl_ipv6works(); #if defined(USE_LIBSSH2) && defined(HAVE_LIBSSH2_INIT) if(libssh2_init(0)) { DEBUGF(fprintf(stderr, "Error: libssh2_init failed\n")); return CURLE_FAILED_INIT; } #endif #if defined(USE_LIBSSH) if(ssh_init()) { DEBUGF(fprintf(stderr, "Error: libssh_init failed\n")); return CURLE_FAILED_INIT; } #endif if(flags & CURL_GLOBAL_ACK_EINTR) Curl_ack_eintr = 1; init_flags = flags; Curl_version_init(); return CURLE_OK; } /** * curl_global_init() globally initializes curl given a bitwise set of the * different features of what to initialize. */ CURLcode curl_global_init(long flags) { return global_init(flags, TRUE); } /* * curl_global_init_mem() globally initializes curl and also registers the * user provided callback routines. */ CURLcode curl_global_init_mem(long flags, curl_malloc_callback m, curl_free_callback f, curl_realloc_callback r, curl_strdup_callback s, curl_calloc_callback c) { /* Invalid input, return immediately */ if(!m || !f || !r || !s || !c) return CURLE_FAILED_INIT; if(initialized) { /* Already initialized, don't do it again, but bump the variable anyway to work like curl_global_init() and require the same amount of cleanup calls. */ initialized++; return CURLE_OK; } /* set memory functions before global_init() in case it wants memory functions */ Curl_cmalloc = m; Curl_cfree = f; Curl_cstrdup = s; Curl_crealloc = r; Curl_ccalloc = c; /* Call the actual init function, but without setting */ return global_init(flags, FALSE); } /** * curl_global_cleanup() globally cleanups curl, uses the value of * "init_flags" to determine what needs to be cleaned up and what doesn't. */ void curl_global_cleanup(void) { if(!initialized) return; if(--initialized) return; Curl_ssl_cleanup(); Curl_resolver_global_cleanup(); #ifdef WIN32 Curl_win32_cleanup(init_flags); #endif Curl_amiga_cleanup(); #if defined(USE_LIBSSH2) && defined(HAVE_LIBSSH2_EXIT) (void)libssh2_exit(); #endif #if defined(USE_LIBSSH) (void)ssh_finalize(); #endif init_flags = 0; } /* * curl_easy_init() is the external interface to alloc, setup and init an * easy handle that is returned. If anything goes wrong, NULL is returned. */ struct Curl_easy *curl_easy_init(void) { CURLcode result; struct Curl_easy *data; /* Make sure we inited the global SSL stuff */ if(!initialized) { result = curl_global_init(CURL_GLOBAL_DEFAULT); if(result) { /* something in the global init failed, return nothing */ DEBUGF(fprintf(stderr, "Error: curl_global_init failed\n")); return NULL; } } /* We use curl_open() with undefined URL so far */ result = Curl_open(&data); if(result) { DEBUGF(fprintf(stderr, "Error: Curl_open failed\n")); return NULL; } return data; } #ifdef CURLDEBUG struct socketmonitor { struct socketmonitor *next; /* the next node in the list or NULL */ struct pollfd socket; /* socket info of what to monitor */ }; struct events { long ms; /* timeout, run the timeout function when reached */ bool msbump; /* set TRUE when timeout is set by callback */ int num_sockets; /* number of nodes in the monitor list */ struct socketmonitor *list; /* list of sockets to monitor */ int running_handles; /* store the returned number */ }; /* events_timer * * Callback that gets called with a new value when the timeout should be * updated. */ static int events_timer(struct Curl_multi *multi, /* multi handle */ long timeout_ms, /* see above */ void *userp) /* private callback pointer */ { struct events *ev = userp; (void)multi; if(timeout_ms == -1) /* timeout removed */ timeout_ms = 0; else if(timeout_ms == 0) /* timeout is already reached! */ timeout_ms = 1; /* trigger asap */ ev->ms = timeout_ms; ev->msbump = TRUE; return 0; } /* poll2cselect * * convert from poll() bit definitions to libcurl's CURL_CSELECT_* ones */ static int poll2cselect(int pollmask) { int omask = 0; if(pollmask & POLLIN) omask |= CURL_CSELECT_IN; if(pollmask & POLLOUT) omask |= CURL_CSELECT_OUT; if(pollmask & POLLERR) omask |= CURL_CSELECT_ERR; return omask; } /* socketcb2poll * * convert from libcurl' CURL_POLL_* bit definitions to poll()'s */ static short socketcb2poll(int pollmask) { short omask = 0; if(pollmask & CURL_POLL_IN) omask |= POLLIN; if(pollmask & CURL_POLL_OUT) omask |= POLLOUT; return omask; } /* events_socket * * Callback that gets called with information about socket activity to * monitor. */ static int events_socket(struct Curl_easy *easy, /* easy handle */ curl_socket_t s, /* socket */ int what, /* see above */ void *userp, /* private callback pointer */ void *socketp) /* private socket pointer */ { struct events *ev = userp; struct socketmonitor *m; struct socketmonitor *prev = NULL; #if defined(CURL_DISABLE_VERBOSE_STRINGS) (void) easy; #endif (void)socketp; m = ev->list; while(m) { if(m->socket.fd == s) { if(what == CURL_POLL_REMOVE) { struct socketmonitor *nxt = m->next; /* remove this node from the list of monitored sockets */ if(prev) prev->next = nxt; else ev->list = nxt; free(m); m = nxt; infof(easy, "socket cb: socket %d REMOVED\n", s); } else { /* The socket 's' is already being monitored, update the activity mask. Convert from libcurl bitmask to the poll one. */ m->socket.events = socketcb2poll(what); infof(easy, "socket cb: socket %d UPDATED as %s%s\n", s, (what&CURL_POLL_IN)?"IN":"", (what&CURL_POLL_OUT)?"OUT":""); } break; } prev = m; m = m->next; /* move to next node */ } if(!m) { if(what == CURL_POLL_REMOVE) { /* this happens a bit too often, libcurl fix perhaps? */ /* fprintf(stderr, "%s: socket %d asked to be REMOVED but not present!\n", __func__, s); */ } else { m = malloc(sizeof(struct socketmonitor)); if(m) { m->next = ev->list; m->socket.fd = s; m->socket.events = socketcb2poll(what); m->socket.revents = 0; ev->list = m; infof(easy, "socket cb: socket %d ADDED as %s%s\n", s, (what&CURL_POLL_IN)?"IN":"", (what&CURL_POLL_OUT)?"OUT":""); } else return CURLE_OUT_OF_MEMORY; } } return 0; } /* * events_setup() * * Do the multi handle setups that only event-based transfers need. */ static void events_setup(struct Curl_multi *multi, struct events *ev) { /* timer callback */ curl_multi_setopt(multi, CURLMOPT_TIMERFUNCTION, events_timer); curl_multi_setopt(multi, CURLMOPT_TIMERDATA, ev); /* socket callback */ curl_multi_setopt(multi, CURLMOPT_SOCKETFUNCTION, events_socket); curl_multi_setopt(multi, CURLMOPT_SOCKETDATA, ev); } /* wait_or_timeout() * * waits for activity on any of the given sockets, or the timeout to trigger. */ static CURLcode wait_or_timeout(struct Curl_multi *multi, struct events *ev) { bool done = FALSE; CURLMcode mcode = CURLM_OK; CURLcode result = CURLE_OK; while(!done) { CURLMsg *msg; struct socketmonitor *m; struct pollfd *f; struct pollfd fds[4]; int numfds = 0; int pollrc; int i; struct curltime before; struct curltime after; /* populate the fds[] array */ for(m = ev->list, f = &fds[0]; m; m = m->next) { f->fd = m->socket.fd; f->events = m->socket.events; f->revents = 0; /* fprintf(stderr, "poll() %d check socket %d\n", numfds, f->fd); */ f++; numfds++; } /* get the time stamp to use to figure out how long poll takes */ before = Curl_now(); /* wait for activity or timeout */ pollrc = Curl_poll(fds, numfds, (int)ev->ms); after = Curl_now(); ev->msbump = FALSE; /* reset here */ if(0 == pollrc) { /* timeout! */ ev->ms = 0; /* fprintf(stderr, "call curl_multi_socket_action(TIMEOUT)\n"); */ mcode = curl_multi_socket_action(multi, CURL_SOCKET_TIMEOUT, 0, &ev->running_handles); } else if(pollrc > 0) { /* loop over the monitored sockets to see which ones had activity */ for(i = 0; i< numfds; i++) { if(fds[i].revents) { /* socket activity, tell libcurl */ int act = poll2cselect(fds[i].revents); /* convert */ infof(multi->easyp, "call curl_multi_socket_action(socket %d)\n", fds[i].fd); mcode = curl_multi_socket_action(multi, fds[i].fd, act, &ev->running_handles); } } if(!ev->msbump) { /* If nothing updated the timeout, we decrease it by the spent time. * If it was updated, it has the new timeout time stored already. */ timediff_t timediff = Curl_timediff(after, before); if(timediff > 0) { if(timediff > ev->ms) ev->ms = 0; else ev->ms -= (long)timediff; } } } else return CURLE_RECV_ERROR; if(mcode) return CURLE_URL_MALFORMAT; /* we don't really care about the "msgs_in_queue" value returned in the second argument */ msg = curl_multi_info_read(multi, &pollrc); if(msg) { result = msg->data.result; done = TRUE; } } return result; } /* easy_events() * * Runs a transfer in a blocking manner using the events-based API */ static CURLcode easy_events(struct Curl_multi *multi) { /* this struct is made static to allow it to be used after this function returns and curl_multi_remove_handle() is called */ static struct events evs = {2, FALSE, 0, NULL, 0}; /* if running event-based, do some further multi inits */ events_setup(multi, &evs); return wait_or_timeout(multi, &evs); } #else /* CURLDEBUG */ /* when not built with debug, this function doesn't exist */ #define easy_events(x) CURLE_NOT_BUILT_IN #endif static CURLcode easy_transfer(struct Curl_multi *multi) { bool done = FALSE; CURLMcode mcode = CURLM_OK; CURLcode result = CURLE_OK; while(!done && !mcode) { int still_running = 0; bool gotsocket = FALSE; mcode = Curl_multi_wait(multi, NULL, 0, 1000, NULL, &gotsocket); if(!mcode) { if(!gotsocket) { long sleep_ms; /* If it returns without any filedescriptor instantly, we need to avoid busy-looping during periods where it has nothing particular to wait for */ curl_multi_timeout(multi, &sleep_ms); if(sleep_ms) { if(sleep_ms > 1000) sleep_ms = 1000; Curl_wait_ms((int)sleep_ms); } } mcode = curl_multi_perform(multi, &still_running); } /* only read 'still_running' if curl_multi_perform() return OK */ if(!mcode && !still_running) { int rc; CURLMsg *msg = curl_multi_info_read(multi, &rc); if(msg) { result = msg->data.result; done = TRUE; } } } /* Make sure to return some kind of error if there was a multi problem */ if(mcode) { result = (mcode == CURLM_OUT_OF_MEMORY) ? CURLE_OUT_OF_MEMORY : /* The other multi errors should never happen, so return something suitably generic */ CURLE_BAD_FUNCTION_ARGUMENT; } return result; } /* * easy_perform() is the external interface that performs a blocking * transfer as previously setup. * * CONCEPT: This function creates a multi handle, adds the easy handle to it, * runs curl_multi_perform() until the transfer is done, then detaches the * easy handle, destroys the multi handle and returns the easy handle's return * code. * * REALITY: it can't just create and destroy the multi handle that easily. It * needs to keep it around since if this easy handle is used again by this * function, the same multi handle must be re-used so that the same pools and * caches can be used. * * DEBUG: if 'events' is set TRUE, this function will use a replacement engine * instead of curl_multi_perform() and use curl_multi_socket_action(). */ static CURLcode easy_perform(struct Curl_easy *data, bool events) { struct Curl_multi *multi; CURLMcode mcode; CURLcode result = CURLE_OK; SIGPIPE_VARIABLE(pipe_st); if(!data) return CURLE_BAD_FUNCTION_ARGUMENT; if(data->set.errorbuffer) /* clear this as early as possible */ data->set.errorbuffer[0] = 0; if(data->multi) { failf(data, "easy handle already used in multi handle"); return CURLE_FAILED_INIT; } if(data->multi_easy) multi = data->multi_easy; else { /* this multi handle will only ever have a single easy handled attached to it, so make it use minimal hashes */ multi = Curl_multi_handle(1, 3); if(!multi) return CURLE_OUT_OF_MEMORY; data->multi_easy = multi; } if(multi->in_callback) return CURLE_RECURSIVE_API_CALL; /* Copy the MAXCONNECTS option to the multi handle */ curl_multi_setopt(multi, CURLMOPT_MAXCONNECTS, data->set.maxconnects); mcode = curl_multi_add_handle(multi, data); if(mcode) { curl_multi_cleanup(multi); if(mcode == CURLM_OUT_OF_MEMORY) return CURLE_OUT_OF_MEMORY; return CURLE_FAILED_INIT; } sigpipe_ignore(data, &pipe_st); /* assign this after curl_multi_add_handle() since that function checks for it and rejects this handle otherwise */ data->multi = multi; /* run the transfer */ result = events ? easy_events(multi) : easy_transfer(multi); /* ignoring the return code isn't nice, but atm we can't really handle a failure here, room for future improvement! */ (void)curl_multi_remove_handle(multi, data); sigpipe_restore(&pipe_st); /* The multi handle is kept alive, owned by the easy handle */ return result; } /* * curl_easy_perform() is the external interface that performs a blocking * transfer as previously setup. */ CURLcode curl_easy_perform(struct Curl_easy *data) { return easy_perform(data, FALSE); } #ifdef CURLDEBUG /* * curl_easy_perform_ev() is the external interface that performs a blocking * transfer using the event-based API internally. */ CURLcode curl_easy_perform_ev(struct Curl_easy *data) { return easy_perform(data, TRUE); } #endif /* * curl_easy_cleanup() is the external interface to cleaning/freeing the given * easy handle. */ void curl_easy_cleanup(struct Curl_easy *data) { SIGPIPE_VARIABLE(pipe_st); if(!data) return; sigpipe_ignore(data, &pipe_st); Curl_close(data); sigpipe_restore(&pipe_st); } /* * curl_easy_getinfo() is an external interface that allows an app to retrieve * information from a performed transfer and similar. */ #undef curl_easy_getinfo CURLcode curl_easy_getinfo(struct Curl_easy *data, CURLINFO info, ...) { va_list arg; void *paramp; CURLcode result; va_start(arg, info); paramp = va_arg(arg, void *); result = Curl_getinfo(data, info, paramp); va_end(arg); return result; } static CURLcode dupset(struct Curl_easy *dst, struct Curl_easy *src) { CURLcode result = CURLE_OK; enum dupstring i; /* Copy src->set into dst->set first, then deal with the strings afterwards */ dst->set = src->set; Curl_mime_initpart(&dst->set.mimepost, dst); /* clear all string pointers first */ memset(dst->set.str, 0, STRING_LAST * sizeof(char *)); /* duplicate all strings */ for(i = (enum dupstring)0; i< STRING_LASTZEROTERMINATED; i++) { result = Curl_setstropt(&dst->set.str[i], src->set.str[i]); if(result) return result; } /* duplicate memory areas pointed to */ i = STRING_COPYPOSTFIELDS; if(src->set.postfieldsize && src->set.str[i]) { /* postfieldsize is curl_off_t, Curl_memdup() takes a size_t ... */ dst->set.str[i] = Curl_memdup(src->set.str[i], curlx_sotouz(src->set.postfieldsize)); if(!dst->set.str[i]) return CURLE_OUT_OF_MEMORY; /* point to the new copy */ dst->set.postfields = dst->set.str[i]; } /* Duplicate mime data. */ result = Curl_mime_duppart(&dst->set.mimepost, &src->set.mimepost); if(src->set.resolve) dst->change.resolve = dst->set.resolve; return result; } /* * curl_easy_duphandle() is an external interface to allow duplication of a * given input easy handle. The returned handle will be a new working handle * with all options set exactly as the input source handle. */ struct Curl_easy *curl_easy_duphandle(struct Curl_easy *data) { struct Curl_easy *outcurl = calloc(1, sizeof(struct Curl_easy)); if(NULL == outcurl) goto fail; /* * We setup a few buffers we need. We should probably make them * get setup on-demand in the code, as that would probably decrease * the likeliness of us forgetting to init a buffer here in the future. */ outcurl->set.buffer_size = data->set.buffer_size; outcurl->state.buffer = malloc(outcurl->set.buffer_size + 1); if(!outcurl->state.buffer) goto fail; outcurl->state.headerbuff = malloc(HEADERSIZE); if(!outcurl->state.headerbuff) goto fail; outcurl->state.headersize = HEADERSIZE; /* copy all userdefined values */ if(dupset(outcurl, data)) goto fail; /* the connection cache is setup on demand */ outcurl->state.conn_cache = NULL; outcurl->state.lastconnect = NULL; outcurl->progress.flags = data->progress.flags; outcurl->progress.callback = data->progress.callback; if(data->cookies) { /* If cookies are enabled in the parent handle, we enable them in the clone as well! */ outcurl->cookies = Curl_cookie_init(data, data->cookies->filename, outcurl->cookies, data->set.cookiesession); if(!outcurl->cookies) goto fail; } /* duplicate all values in 'change' */ if(data->change.cookielist) { outcurl->change.cookielist = Curl_slist_duplicate(data->change.cookielist); if(!outcurl->change.cookielist) goto fail; } if(data->change.url) { outcurl->change.url = strdup(data->change.url); if(!outcurl->change.url) goto fail; outcurl->change.url_alloc = TRUE; } if(data->change.referer) { outcurl->change.referer = strdup(data->change.referer); if(!outcurl->change.referer) goto fail; outcurl->change.referer_alloc = TRUE; } /* Reinitialize an SSL engine for the new handle * note: the engine name has already been copied by dupset */ if(outcurl->set.str[STRING_SSL_ENGINE]) { if(Curl_ssl_set_engine(outcurl, outcurl->set.str[STRING_SSL_ENGINE])) goto fail; } /* Clone the resolver handle, if present, for the new handle */ if(Curl_resolver_duphandle(outcurl, &outcurl->state.resolver, data->state.resolver)) goto fail; Curl_convert_setup(outcurl); Curl_initinfo(outcurl); outcurl->magic = CURLEASY_MAGIC_NUMBER; /* we reach this point and thus we are OK */ return outcurl; fail: if(outcurl) { curl_slist_free_all(outcurl->change.cookielist); outcurl->change.cookielist = NULL; Curl_safefree(outcurl->state.buffer); Curl_safefree(outcurl->state.headerbuff); Curl_safefree(outcurl->change.url); Curl_safefree(outcurl->change.referer); Curl_freeset(outcurl); free(outcurl); } return NULL; } /* * curl_easy_reset() is an external interface that allows an app to re- * initialize a session handle to the default values. */ void curl_easy_reset(struct Curl_easy *data) { Curl_free_request_state(data); /* zero out UserDefined data: */ Curl_freeset(data); memset(&data->set, 0, sizeof(struct UserDefined)); (void)Curl_init_userdefined(data); /* zero out Progress data: */ memset(&data->progress, 0, sizeof(struct Progress)); /* zero out PureInfo data: */ Curl_initinfo(data); data->progress.flags |= PGRS_HIDE; data->state.current_speed = -1; /* init to negative == impossible */ /* zero out authentication data: */ memset(&data->state.authhost, 0, sizeof(struct auth)); memset(&data->state.authproxy, 0, sizeof(struct auth)); #if !defined(CURL_DISABLE_HTTP) && !defined(CURL_DISABLE_CRYPTO_AUTH) Curl_http_auth_cleanup_digest(data); #endif } /* * curl_easy_pause() allows an application to pause or unpause a specific * transfer and direction. This function sets the full new state for the * current connection this easy handle operates on. * * NOTE: if you have the receiving paused and you call this function to remove * the pausing, you may get your write callback called at this point. * * Action is a bitmask consisting of CURLPAUSE_* bits in curl/curl.h * * NOTE: This is one of few API functions that are allowed to be called from * within a callback. */ CURLcode curl_easy_pause(struct Curl_easy *data, int action) { struct SingleRequest *k = &data->req; CURLcode result = CURLE_OK; /* first switch off both pause bits */ int newstate = k->keepon &~ (KEEP_RECV_PAUSE| KEEP_SEND_PAUSE); /* set the new desired pause bits */ newstate |= ((action & CURLPAUSE_RECV)?KEEP_RECV_PAUSE:0) | ((action & CURLPAUSE_SEND)?KEEP_SEND_PAUSE:0); /* put it back in the keepon */ k->keepon = newstate; if(!(newstate & KEEP_RECV_PAUSE) && data->state.tempcount) { /* there are buffers for sending that can be delivered as the receive pausing is lifted! */ unsigned int i; unsigned int count = data->state.tempcount; struct tempbuf writebuf[3]; /* there can only be three */ struct connectdata *conn = data->conn; struct Curl_easy *saved_data = NULL; /* copy the structs to allow for immediate re-pausing */ for(i = 0; i < data->state.tempcount; i++) { writebuf[i] = data->state.tempwrite[i]; data->state.tempwrite[i].buf = NULL; } data->state.tempcount = 0; /* set the connection's current owner */ if(conn->data != data) { saved_data = conn->data; conn->data = data; } for(i = 0; i < count; i++) { /* even if one function returns error, this loops through and frees all buffers */ if(!result) result = Curl_client_write(conn, writebuf[i].type, writebuf[i].buf, writebuf[i].len); free(writebuf[i].buf); } /* recover previous owner of the connection */ if(saved_data) conn->data = saved_data; if(result) return result; } /* if there's no error and we're not pausing both directions, we want to have this handle checked soon */ if(!result && ((newstate&(KEEP_RECV_PAUSE|KEEP_SEND_PAUSE)) != (KEEP_RECV_PAUSE|KEEP_SEND_PAUSE)) ) Curl_expire(data, 0, EXPIRE_RUN_NOW); /* get this handle going again */ /* This transfer may have been moved in or out of the bundle, update the corresponding socket callback, if used */ Curl_updatesocket(data); return result; } static CURLcode easy_connection(struct Curl_easy *data, curl_socket_t *sfd, struct connectdata **connp) { if(data == NULL) return CURLE_BAD_FUNCTION_ARGUMENT; /* only allow these to be called on handles with CURLOPT_CONNECT_ONLY */ if(!data->set.connect_only) { failf(data, "CONNECT_ONLY is required!"); return CURLE_UNSUPPORTED_PROTOCOL; } *sfd = Curl_getconnectinfo(data, connp); if(*sfd == CURL_SOCKET_BAD) { failf(data, "Failed to get recent socket"); return CURLE_UNSUPPORTED_PROTOCOL; } return CURLE_OK; } /* * Receives data from the connected socket. Use after successful * curl_easy_perform() with CURLOPT_CONNECT_ONLY option. * Returns CURLE_OK on success, error code on error. */ CURLcode curl_easy_recv(struct Curl_easy *data, void *buffer, size_t buflen, size_t *n) { curl_socket_t sfd; CURLcode result; ssize_t n1; struct connectdata *c; if(Curl_is_in_callback(data)) return CURLE_RECURSIVE_API_CALL; result = easy_connection(data, &sfd, &c); if(result) return result; *n = 0; result = Curl_read(c, sfd, buffer, buflen, &n1); if(result) return result; *n = (size_t)n1; return CURLE_OK; } /* * Sends data over the connected socket. Use after successful * curl_easy_perform() with CURLOPT_CONNECT_ONLY option. */ CURLcode curl_easy_send(struct Curl_easy *data, const void *buffer, size_t buflen, size_t *n) { curl_socket_t sfd; CURLcode result; ssize_t n1; struct connectdata *c = NULL; if(Curl_is_in_callback(data)) return CURLE_RECURSIVE_API_CALL; result = easy_connection(data, &sfd, &c); if(result) return result; *n = 0; result = Curl_write(c, sfd, buffer, buflen, &n1); if(n1 == -1) return CURLE_SEND_ERROR; /* detect EAGAIN */ if(!result && !n1) return CURLE_AGAIN; *n = (size_t)n1; return result; } /* * Performs connection upkeep for the given session handle. */ CURLcode curl_easy_upkeep(struct Curl_easy *data) { /* Verify that we got an easy handle we can work with. */ if(!GOOD_EASY_HANDLE(data)) return CURLE_BAD_FUNCTION_ARGUMENT; if(data->multi_easy) { /* Use the common function to keep connections alive. */ return Curl_upkeep(&data->multi_easy->conn_cache, data); } else { /* No connections, so just return success */ return CURLE_OK; } }
YifuLiu/AliOS-Things
components/curl/lib/easy.c
C
apache-2.0
31,491
#ifndef HEADER_CURL_EASYIF_H #define HEADER_CURL_EASYIF_H /*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2016, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ /* * Prototypes for library-wide functions provided by easy.c */ #ifdef CURLDEBUG CURL_EXTERN CURLcode curl_easy_perform_ev(struct Curl_easy *easy); #endif #endif /* HEADER_CURL_EASYIF_H */
YifuLiu/AliOS-Things
components/curl/lib/easyif.h
C
apache-2.0
1,278
/*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2018, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ /* Escape and unescape URL encoding in strings. The functions return a new * allocated string or NULL if an error occurred. */ #include "curl_setup.h" #include <curl/curl.h> #include "urldata.h" #include "warnless.h" #include "non-ascii.h" #include "escape.h" #include "strdup.h" /* The last 3 #include files should be in this order */ #include "curl_printf.h" #include "curl_memory.h" #include "memdebug.h" /* Portable character check (remember EBCDIC). Do not use isalnum() because its behavior is altered by the current locale. See https://tools.ietf.org/html/rfc3986#section-2.3 */ bool Curl_isunreserved(unsigned char in) { switch(in) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g': case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n': case 'o': case 'p': case 'q': case 'r': case 's': case 't': case 'u': case 'v': case 'w': case 'x': case 'y': case 'z': case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G': case 'H': case 'I': case 'J': case 'K': case 'L': case 'M': case 'N': case 'O': case 'P': case 'Q': case 'R': case 'S': case 'T': case 'U': case 'V': case 'W': case 'X': case 'Y': case 'Z': case '-': case '.': case '_': case '~': return TRUE; default: break; } return FALSE; } /* for ABI-compatibility with previous versions */ char *curl_escape(const char *string, int inlength) { return curl_easy_escape(NULL, string, inlength); } /* for ABI-compatibility with previous versions */ char *curl_unescape(const char *string, int length) { return curl_easy_unescape(NULL, string, length, NULL); } char *curl_easy_escape(struct Curl_easy *data, const char *string, int inlength) { size_t alloc; char *ns; char *testing_ptr = NULL; size_t newlen; size_t strindex = 0; size_t length; CURLcode result; if(inlength < 0) return NULL; alloc = (inlength?(size_t)inlength:strlen(string)) + 1; newlen = alloc; ns = malloc(alloc); if(!ns) return NULL; length = alloc-1; while(length--) { unsigned char in = *string; /* we need to treat the characters unsigned */ if(Curl_isunreserved(in)) /* just copy this */ ns[strindex++] = in; else { /* encode it */ newlen += 2; /* the size grows with two, since this'll become a %XX */ if(newlen > alloc) { alloc *= 2; testing_ptr = Curl_saferealloc(ns, alloc); if(!testing_ptr) return NULL; ns = testing_ptr; } result = Curl_convert_to_network(data, (char *)&in, 1); if(result) { /* Curl_convert_to_network calls failf if unsuccessful */ free(ns); return NULL; } msnprintf(&ns[strindex], 4, "%%%02X", in); strindex += 3; } string++; } ns[strindex] = 0; /* terminate it */ return ns; } /* * Curl_urldecode() URL decodes the given string. * * Optionally detects control characters (byte codes lower than 32) in the * data and rejects such data. * * Returns a pointer to a malloced string in *ostring with length given in * *olen. If length == 0, the length is assumed to be strlen(string). * * 'data' can be set to NULL but then this function can't convert network * data to host for non-ascii. */ CURLcode Curl_urldecode(struct Curl_easy *data, const char *string, size_t length, char **ostring, size_t *olen, bool reject_ctrl) { size_t alloc = (length?length:strlen(string)) + 1; char *ns = malloc(alloc); size_t strindex = 0; unsigned long hex; CURLcode result = CURLE_OK; if(!ns) return CURLE_OUT_OF_MEMORY; while(--alloc > 0) { unsigned char in = *string; if(('%' == in) && (alloc > 2) && ISXDIGIT(string[1]) && ISXDIGIT(string[2])) { /* this is two hexadecimal digits following a '%' */ char hexstr[3]; char *ptr; hexstr[0] = string[1]; hexstr[1] = string[2]; hexstr[2] = 0; hex = strtoul(hexstr, &ptr, 16); in = curlx_ultouc(hex); /* this long is never bigger than 255 anyway */ if(data) { result = Curl_convert_from_network(data, (char *)&in, 1); if(result) { /* Curl_convert_from_network calls failf if unsuccessful */ free(ns); return result; } } string += 2; alloc -= 2; } if(reject_ctrl && (in < 0x20)) { free(ns); return CURLE_URL_MALFORMAT; } ns[strindex++] = in; string++; } ns[strindex] = 0; /* terminate it */ if(olen) /* store output size */ *olen = strindex; /* store output string */ *ostring = ns; return CURLE_OK; } /* * Unescapes the given URL escaped string of given length. Returns a * pointer to a malloced string with length given in *olen. * If length == 0, the length is assumed to be strlen(string). * If olen == NULL, no output length is stored. */ char *curl_easy_unescape(struct Curl_easy *data, const char *string, int length, int *olen) { char *str = NULL; if(length >= 0) { size_t inputlen = length; size_t outputlen; CURLcode res = Curl_urldecode(data, string, inputlen, &str, &outputlen, FALSE); if(res) return NULL; if(olen) { if(outputlen <= (size_t) INT_MAX) *olen = curlx_uztosi(outputlen); else /* too large to return in an int, fail! */ Curl_safefree(str); } } return str; } /* For operating systems/environments that use different malloc/free systems for the app and for this library, we provide a free that uses the library's memory system */ void curl_free(void *p) { free(p); }
YifuLiu/AliOS-Things
components/curl/lib/escape.c
C
apache-2.0
6,923
#ifndef HEADER_CURL_ESCAPE_H #define HEADER_CURL_ESCAPE_H /*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2018, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ /* Escape and unescape URL encoding in strings. The functions return a new * allocated string or NULL if an error occurred. */ bool Curl_isunreserved(unsigned char in); CURLcode Curl_urldecode(struct Curl_easy *data, const char *string, size_t length, char **ostring, size_t *olen, bool reject_crlf); #endif /* HEADER_CURL_ESCAPE_H */
YifuLiu/AliOS-Things
components/curl/lib/escape.h
C
apache-2.0
1,495
/*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2019, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "curl_setup.h" #ifndef CURL_DISABLE_FILE #ifdef HAVE_NETINET_IN_H #include <netinet/in.h> #endif #ifdef HAVE_NETDB_H #include <netdb.h> #endif #ifdef HAVE_ARPA_INET_H #include <arpa/inet.h> #endif #ifdef HAVE_NET_IF_H #include <net/if.h> #endif #ifdef HAVE_SYS_IOCTL_H #include <sys/ioctl.h> #endif #ifdef HAVE_SYS_PARAM_H #include <sys/param.h> #endif #ifdef HAVE_FCNTL_H #include <fcntl.h> #endif #include "strtoofft.h" #include "urldata.h" #include <curl/curl.h> #include "progress.h" #include "sendf.h" #include "escape.h" #include "file.h" #include "speedcheck.h" #include "getinfo.h" #include "transfer.h" #include "url.h" #include "parsedate.h" /* for the week day and month names */ #include "warnless.h" #include "curl_range.h" /* The last 3 #include files should be in this order */ #include "curl_printf.h" #include "curl_memory.h" #include "memdebug.h" #if defined(WIN32) || defined(MSDOS) || defined(__EMX__) || \ defined(__SYMBIAN32__) #define DOS_FILESYSTEM 1 #endif #ifdef OPEN_NEEDS_ARG3 # define open_readonly(p,f) open((p),(f),(0)) #else # define open_readonly(p,f) open((p),(f)) #endif /* * Forward declarations. */ static CURLcode file_do(struct connectdata *, bool *done); static CURLcode file_done(struct connectdata *conn, CURLcode status, bool premature); static CURLcode file_connect(struct connectdata *conn, bool *done); static CURLcode file_disconnect(struct connectdata *conn, bool dead_connection); static CURLcode file_setup_connection(struct connectdata *conn); /* * FILE scheme handler. */ const struct Curl_handler Curl_handler_file = { "FILE", /* scheme */ file_setup_connection, /* setup_connection */ file_do, /* do_it */ file_done, /* done */ ZERO_NULL, /* do_more */ file_connect, /* connect_it */ ZERO_NULL, /* connecting */ ZERO_NULL, /* doing */ ZERO_NULL, /* proto_getsock */ ZERO_NULL, /* doing_getsock */ ZERO_NULL, /* domore_getsock */ ZERO_NULL, /* perform_getsock */ file_disconnect, /* disconnect */ ZERO_NULL, /* readwrite */ ZERO_NULL, /* connection_check */ 0, /* defport */ CURLPROTO_FILE, /* protocol */ PROTOPT_NONETWORK | PROTOPT_NOURLQUERY /* flags */ }; static CURLcode file_setup_connection(struct connectdata *conn) { /* allocate the FILE specific struct */ conn->data->req.protop = calloc(1, sizeof(struct FILEPROTO)); if(!conn->data->req.protop) return CURLE_OUT_OF_MEMORY; return CURLE_OK; } /* * file_connect() gets called from Curl_protocol_connect() to allow us to * do protocol-specific actions at connect-time. We emulate a * connect-then-transfer protocol and "connect" to the file here */ static CURLcode file_connect(struct connectdata *conn, bool *done) { struct Curl_easy *data = conn->data; char *real_path; struct FILEPROTO *file = data->req.protop; int fd; #ifdef DOS_FILESYSTEM size_t i; char *actual_path; #endif size_t real_path_len; CURLcode result = Curl_urldecode(data, data->state.up.path, 0, &real_path, &real_path_len, FALSE); if(result) return result; #ifdef DOS_FILESYSTEM /* If the first character is a slash, and there's something that looks like a drive at the beginning of the path, skip the slash. If we remove the initial slash in all cases, paths without drive letters end up relative to the current directory which isn't how browsers work. Some browsers accept | instead of : as the drive letter separator, so we do too. On other platforms, we need the slash to indicate an absolute pathname. On Windows, absolute paths start with a drive letter. */ actual_path = real_path; if((actual_path[0] == '/') && actual_path[1] && (actual_path[2] == ':' || actual_path[2] == '|')) { actual_path[2] = ':'; actual_path++; real_path_len--; } /* change path separators from '/' to '\\' for DOS, Windows and OS/2 */ for(i = 0; i < real_path_len; ++i) if(actual_path[i] == '/') actual_path[i] = '\\'; else if(!actual_path[i]) { /* binary zero */ Curl_safefree(real_path); return CURLE_URL_MALFORMAT; } fd = open_readonly(actual_path, O_RDONLY|O_BINARY); file->path = actual_path; #else if(memchr(real_path, 0, real_path_len)) { /* binary zeroes indicate foul play */ Curl_safefree(real_path); return CURLE_URL_MALFORMAT; } fd = open_readonly(real_path, O_RDONLY); file->path = real_path; #endif file->freepath = real_path; /* free this when done */ file->fd = fd; if(!data->set.upload && (fd == -1)) { failf(data, "Couldn't open file %s", data->state.up.path); file_done(conn, CURLE_FILE_COULDNT_READ_FILE, FALSE); return CURLE_FILE_COULDNT_READ_FILE; } *done = TRUE; return CURLE_OK; } static CURLcode file_done(struct connectdata *conn, CURLcode status, bool premature) { struct FILEPROTO *file = conn->data->req.protop; (void)status; /* not used */ (void)premature; /* not used */ if(file) { Curl_safefree(file->freepath); file->path = NULL; if(file->fd != -1) close(file->fd); file->fd = -1; } return CURLE_OK; } static CURLcode file_disconnect(struct connectdata *conn, bool dead_connection) { struct FILEPROTO *file = conn->data->req.protop; (void)dead_connection; /* not used */ if(file) { Curl_safefree(file->freepath); file->path = NULL; if(file->fd != -1) close(file->fd); file->fd = -1; } return CURLE_OK; } #ifdef DOS_FILESYSTEM #define DIRSEP '\\' #else #define DIRSEP '/' #endif static CURLcode file_upload(struct connectdata *conn) { struct FILEPROTO *file = conn->data->req.protop; const char *dir = strchr(file->path, DIRSEP); int fd; int mode; CURLcode result = CURLE_OK; struct Curl_easy *data = conn->data; char *buf = data->state.buffer; curl_off_t bytecount = 0; struct_stat file_stat; const char *buf2; /* * Since FILE: doesn't do the full init, we need to provide some extra * assignments here. */ conn->data->req.upload_fromhere = buf; if(!dir) return CURLE_FILE_COULDNT_READ_FILE; /* fix: better error code */ if(!dir[1]) return CURLE_FILE_COULDNT_READ_FILE; /* fix: better error code */ #ifdef O_BINARY #define MODE_DEFAULT O_WRONLY|O_CREAT|O_BINARY #else #define MODE_DEFAULT O_WRONLY|O_CREAT #endif if(data->state.resume_from) mode = MODE_DEFAULT|O_APPEND; else mode = MODE_DEFAULT|O_TRUNC; fd = open(file->path, mode, conn->data->set.new_file_perms); if(fd < 0) { failf(data, "Can't open %s for writing", file->path); return CURLE_WRITE_ERROR; } if(-1 != data->state.infilesize) /* known size of data to "upload" */ Curl_pgrsSetUploadSize(data, data->state.infilesize); /* treat the negative resume offset value as the case of "-" */ if(data->state.resume_from < 0) { if(fstat(fd, &file_stat)) { close(fd); failf(data, "Can't get the size of %s", file->path); return CURLE_WRITE_ERROR; } data->state.resume_from = (curl_off_t)file_stat.st_size; } while(!result) { size_t nread; size_t nwrite; size_t readcount; result = Curl_fillreadbuffer(conn, data->set.buffer_size, &readcount); if(result) break; if(!readcount) break; nread = readcount; /*skip bytes before resume point*/ if(data->state.resume_from) { if((curl_off_t)nread <= data->state.resume_from) { data->state.resume_from -= nread; nread = 0; buf2 = buf; } else { buf2 = buf + data->state.resume_from; nread -= (size_t)data->state.resume_from; data->state.resume_from = 0; } } else buf2 = buf; /* write the data to the target */ nwrite = write(fd, buf2, nread); if(nwrite != nread) { result = CURLE_SEND_ERROR; break; } bytecount += nread; Curl_pgrsSetUploadCounter(data, bytecount); if(Curl_pgrsUpdate(conn)) result = CURLE_ABORTED_BY_CALLBACK; else result = Curl_speedcheck(data, Curl_now()); } if(!result && Curl_pgrsUpdate(conn)) result = CURLE_ABORTED_BY_CALLBACK; close(fd); return result; } /* * file_do() is the protocol-specific function for the do-phase, separated * from the connect-phase above. Other protocols merely setup the transfer in * the do-phase, to have it done in the main transfer loop but since some * platforms we support don't allow select()ing etc on file handles (as * opposed to sockets) we instead perform the whole do-operation in this * function. */ static CURLcode file_do(struct connectdata *conn, bool *done) { /* This implementation ignores the host name in conformance with RFC 1738. Only local files (reachable via the standard file system) are supported. This means that files on remotely mounted directories (via NFS, Samba, NT sharing) can be accessed through a file:// URL */ CURLcode result = CURLE_OK; struct_stat statbuf; /* struct_stat instead of struct stat just to allow the Windows version to have a different struct without having to redefine the simple word 'stat' */ curl_off_t expected_size = 0; bool size_known; bool fstated = FALSE; struct Curl_easy *data = conn->data; char *buf = data->state.buffer; curl_off_t bytecount = 0; int fd; struct FILEPROTO *file; *done = TRUE; /* unconditionally */ Curl_pgrsStartNow(data); if(data->set.upload) return file_upload(conn); file = conn->data->req.protop; /* get the fd from the connection phase */ fd = file->fd; /* VMS: This only works reliable for STREAMLF files */ if(-1 != fstat(fd, &statbuf)) { /* we could stat it, then read out the size */ expected_size = statbuf.st_size; /* and store the modification time */ data->info.filetime = statbuf.st_mtime; fstated = TRUE; } if(fstated && !data->state.range && data->set.timecondition) { if(!Curl_meets_timecondition(data, data->info.filetime)) { *done = TRUE; return CURLE_OK; } } if(fstated) { time_t filetime; struct tm buffer; const struct tm *tm = &buffer; char header[80]; msnprintf(header, sizeof(header), "Content-Length: %" CURL_FORMAT_CURL_OFF_T "\r\n", expected_size); result = Curl_client_write(conn, CLIENTWRITE_HEADER, header, 0); if(result) return result; result = Curl_client_write(conn, CLIENTWRITE_HEADER, (char *)"Accept-ranges: bytes\r\n", 0); if(result) return result; filetime = (time_t)statbuf.st_mtime; result = Curl_gmtime(filetime, &buffer); if(result) return result; /* format: "Tue, 15 Nov 1994 12:45:26 GMT" */ msnprintf(header, sizeof(header), "Last-Modified: %s, %02d %s %4d %02d:%02d:%02d GMT\r\n%s", Curl_wkday[tm->tm_wday?tm->tm_wday-1:6], tm->tm_mday, Curl_month[tm->tm_mon], tm->tm_year + 1900, tm->tm_hour, tm->tm_min, tm->tm_sec, data->set.opt_no_body ? "": "\r\n"); result = Curl_client_write(conn, CLIENTWRITE_HEADER, header, 0); if(result) return result; /* set the file size to make it available post transfer */ Curl_pgrsSetDownloadSize(data, expected_size); if(data->set.opt_no_body) return result; } /* Check whether file range has been specified */ result = Curl_range(conn); if(result) return result; /* Adjust the start offset in case we want to get the N last bytes * of the stream if the filesize could be determined */ if(data->state.resume_from < 0) { if(!fstated) { failf(data, "Can't get the size of file."); return CURLE_READ_ERROR; } data->state.resume_from += (curl_off_t)statbuf.st_size; } if(data->state.resume_from <= expected_size) expected_size -= data->state.resume_from; else { failf(data, "failed to resume file:// transfer"); return CURLE_BAD_DOWNLOAD_RESUME; } /* A high water mark has been specified so we obey... */ if(data->req.maxdownload > 0) expected_size = data->req.maxdownload; if(!fstated || (expected_size == 0)) size_known = FALSE; else size_known = TRUE; /* The following is a shortcut implementation of file reading this is both more efficient than the former call to download() and it avoids problems with select() and recv() on file descriptors in Winsock */ if(fstated) Curl_pgrsSetDownloadSize(data, expected_size); if(data->state.resume_from) { if(data->state.resume_from != lseek(fd, data->state.resume_from, SEEK_SET)) return CURLE_BAD_DOWNLOAD_RESUME; } Curl_pgrsTime(data, TIMER_STARTTRANSFER); while(!result) { ssize_t nread; /* Don't fill a whole buffer if we want less than all data */ size_t bytestoread; if(size_known) { bytestoread = (expected_size < data->set.buffer_size) ? curlx_sotouz(expected_size) : (size_t)data->set.buffer_size; } else bytestoread = data->set.buffer_size-1; nread = read(fd, buf, bytestoread); if(nread > 0) buf[nread] = 0; if(nread <= 0 || (size_known && (expected_size == 0))) break; bytecount += nread; if(size_known) expected_size -= nread; result = Curl_client_write(conn, CLIENTWRITE_BODY, buf, nread); if(result) return result; Curl_pgrsSetDownloadCounter(data, bytecount); if(Curl_pgrsUpdate(conn)) result = CURLE_ABORTED_BY_CALLBACK; else result = Curl_speedcheck(data, Curl_now()); } if(Curl_pgrsUpdate(conn)) result = CURLE_ABORTED_BY_CALLBACK; return result; } #endif
YifuLiu/AliOS-Things
components/curl/lib/file.c
C
apache-2.0
15,397
#ifndef HEADER_CURL_FILE_H #define HEADER_CURL_FILE_H /*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2009, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ /**************************************************************************** * FILE unique setup ***************************************************************************/ struct FILEPROTO { char *path; /* the path we operate on */ char *freepath; /* pointer to the allocated block we must free, this might differ from the 'path' pointer */ int fd; /* open file descriptor to read from! */ }; #ifndef CURL_DISABLE_FILE extern const struct Curl_handler Curl_handler_file; #endif #endif /* HEADER_CURL_FILE_H */
YifuLiu/AliOS-Things
components/curl/lib/file.h
C
apache-2.0
1,630
/*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 2010 - 2019, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "curl_setup.h" #ifndef CURL_DISABLE_FTP #include "strdup.h" #include "fileinfo.h" #include "curl_memory.h" /* The last #include file should be: */ #include "memdebug.h" struct fileinfo *Curl_fileinfo_alloc(void) { return calloc(1, sizeof(struct fileinfo)); } void Curl_fileinfo_cleanup(struct fileinfo *finfo) { if(!finfo) return; Curl_safefree(finfo->info.b_data); free(finfo); } #endif
YifuLiu/AliOS-Things
components/curl/lib/fileinfo.c
C
apache-2.0
1,439
#ifndef HEADER_CURL_FILEINFO_H #define HEADER_CURL_FILEINFO_H /*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 2010 - 2018, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include <curl/curl.h> #include "llist.h" struct fileinfo { struct curl_fileinfo info; struct curl_llist_element list; }; struct fileinfo *Curl_fileinfo_alloc(void); void Curl_fileinfo_cleanup(struct fileinfo *finfo); #endif /* HEADER_CURL_FILEINFO_H */
YifuLiu/AliOS-Things
components/curl/lib/fileinfo.h
C
apache-2.0
1,350
#!/bin/sh # *************************************************************************** # * _ _ ____ _ # * Project ___| | | | _ \| | # * / __| | | | |_) | | # * | (__| |_| | _ <| |___ # * \___|\___/|_| \_\_____| # * # * Copyright (C) 1998 - 2015, Daniel Stenberg, <daniel@haxx.se>, et al. # * # * This software is licensed as described in the file COPYING, which # * you should have received as part of this distribution. The terms # * are also available at https://curl.haxx.se/docs/copyright.html. # * # * You may opt to use, copy, modify, merge, publish, distribute and/or sell # * copies of the Software, and permit persons to whom the Software is # * furnished to do so, under the terms of the COPYING file. # * # * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY # * KIND, either express or implied. # * # *************************************************************************** # This shell script creates a fresh ca-bundle.crt file for use with libcurl. # It extracts all ca certs it finds in the local Firefox database and converts # them all into PEM format. # db=`ls -1d $HOME/.mozilla/firefox/*default*` out=$1 if test -z "$out"; then out="ca-bundle.crt" # use a sensible default fi currentdate=`date` cat >$out <<EOF ## ## Bundle of CA Root Certificates ## ## Converted at: ${currentdate} ## These were converted from the local Firefox directory by the db2pem script. ## EOF certutil -L -h 'Builtin Object Token' -d $db | \ grep ' *[CcGTPpu]*,[CcGTPpu]*,[CcGTPpu]* *$' | \ sed -e 's/ *[CcGTPpu]*,[CcGTPpu]*,[CcGTPpu]* *$//' -e 's/\(.*\)/"\1"/' | \ sort | \ while read nickname; \ do echo $nickname | sed -e "s/Builtin Object Token://g"; \ eval certutil -d $db -L -n "$nickname" -a ; \ done >> $out
YifuLiu/AliOS-Things
components/curl/lib/firefox-db2pem.sh
Shell
apache-2.0
1,890
/*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2019, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "curl_setup.h" #include <curl/curl.h> #include "formdata.h" #if !defined(CURL_DISABLE_HTTP) && !defined(CURL_DISABLE_MIME) #if defined(HAVE_LIBGEN_H) && defined(HAVE_BASENAME) #include <libgen.h> #endif #include "urldata.h" /* for struct Curl_easy */ #include "mime.h" #include "non-ascii.h" #include "vtls/vtls.h" #include "strcase.h" #include "sendf.h" #include "strdup.h" #include "rand.h" #include "warnless.h" /* The last 3 #include files should be in this order */ #include "curl_printf.h" #include "curl_memory.h" #include "memdebug.h" #define HTTPPOST_PTRNAME CURL_HTTPPOST_PTRNAME #define HTTPPOST_FILENAME CURL_HTTPPOST_FILENAME #define HTTPPOST_PTRCONTENTS CURL_HTTPPOST_PTRCONTENTS #define HTTPPOST_READFILE CURL_HTTPPOST_READFILE #define HTTPPOST_PTRBUFFER CURL_HTTPPOST_PTRBUFFER #define HTTPPOST_CALLBACK CURL_HTTPPOST_CALLBACK #define HTTPPOST_BUFFER CURL_HTTPPOST_BUFFER /*************************************************************************** * * AddHttpPost() * * Adds a HttpPost structure to the list, if parent_post is given becomes * a subpost of parent_post instead of a direct list element. * * Returns newly allocated HttpPost on success and NULL if malloc failed. * ***************************************************************************/ static struct curl_httppost * AddHttpPost(char *name, size_t namelength, char *value, curl_off_t contentslength, char *buffer, size_t bufferlength, char *contenttype, long flags, struct curl_slist *contentHeader, char *showfilename, char *userp, struct curl_httppost *parent_post, struct curl_httppost **httppost, struct curl_httppost **last_post) { struct curl_httppost *post; post = calloc(1, sizeof(struct curl_httppost)); if(post) { post->name = name; post->namelength = (long)(name?(namelength?namelength:strlen(name)):0); post->contents = value; post->contentlen = contentslength; post->buffer = buffer; post->bufferlength = (long)bufferlength; post->contenttype = contenttype; post->contentheader = contentHeader; post->showfilename = showfilename; post->userp = userp; post->flags = flags | CURL_HTTPPOST_LARGE; } else return NULL; if(parent_post) { /* now, point our 'more' to the original 'more' */ post->more = parent_post->more; /* then move the original 'more' to point to ourselves */ parent_post->more = post; } else { /* make the previous point to this */ if(*last_post) (*last_post)->next = post; else (*httppost) = post; (*last_post) = post; } return post; } /*************************************************************************** * * AddFormInfo() * * Adds a FormInfo structure to the list presented by parent_form_info. * * Returns newly allocated FormInfo on success and NULL if malloc failed/ * parent_form_info is NULL. * ***************************************************************************/ static FormInfo * AddFormInfo(char *value, char *contenttype, FormInfo *parent_form_info) { FormInfo *form_info; form_info = calloc(1, sizeof(struct FormInfo)); if(form_info) { if(value) form_info->value = value; if(contenttype) form_info->contenttype = contenttype; form_info->flags = HTTPPOST_FILENAME; } else return NULL; if(parent_form_info) { /* now, point our 'more' to the original 'more' */ form_info->more = parent_form_info->more; /* then move the original 'more' to point to ourselves */ parent_form_info->more = form_info; } return form_info; } /*************************************************************************** * * FormAdd() * * Stores a formpost parameter and builds the appropriate linked list. * * Has two principal functionalities: using files and byte arrays as * post parts. Byte arrays are either copied or just the pointer is stored * (as the user requests) while for files only the filename and not the * content is stored. * * While you may have only one byte array for each name, multiple filenames * are allowed (and because of this feature CURLFORM_END is needed after * using CURLFORM_FILE). * * Examples: * * Simple name/value pair with copied contents: * curl_formadd (&post, &last, CURLFORM_COPYNAME, "name", * CURLFORM_COPYCONTENTS, "value", CURLFORM_END); * * name/value pair where only the content pointer is remembered: * curl_formadd (&post, &last, CURLFORM_COPYNAME, "name", * CURLFORM_PTRCONTENTS, ptr, CURLFORM_CONTENTSLENGTH, 10, CURLFORM_END); * (if CURLFORM_CONTENTSLENGTH is missing strlen () is used) * * storing a filename (CONTENTTYPE is optional!): * curl_formadd (&post, &last, CURLFORM_COPYNAME, "name", * CURLFORM_FILE, "filename1", CURLFORM_CONTENTTYPE, "plain/text", * CURLFORM_END); * * storing multiple filenames: * curl_formadd (&post, &last, CURLFORM_COPYNAME, "name", * CURLFORM_FILE, "filename1", CURLFORM_FILE, "filename2", CURLFORM_END); * * Returns: * CURL_FORMADD_OK on success * CURL_FORMADD_MEMORY if the FormInfo allocation fails * CURL_FORMADD_OPTION_TWICE if one option is given twice for one Form * CURL_FORMADD_NULL if a null pointer was given for a char * CURL_FORMADD_MEMORY if the allocation of a FormInfo struct failed * CURL_FORMADD_UNKNOWN_OPTION if an unknown option was used * CURL_FORMADD_INCOMPLETE if the some FormInfo is not complete (or error) * CURL_FORMADD_MEMORY if a HttpPost struct cannot be allocated * CURL_FORMADD_MEMORY if some allocation for string copying failed. * CURL_FORMADD_ILLEGAL_ARRAY if an illegal option is used in an array * ***************************************************************************/ static CURLFORMcode FormAdd(struct curl_httppost **httppost, struct curl_httppost **last_post, va_list params) { FormInfo *first_form, *current_form, *form = NULL; CURLFORMcode return_value = CURL_FORMADD_OK; const char *prevtype = NULL; struct curl_httppost *post = NULL; CURLformoption option; struct curl_forms *forms = NULL; char *array_value = NULL; /* value read from an array */ /* This is a state variable, that if TRUE means that we're parsing an array that we got passed to us. If FALSE we're parsing the input va_list arguments. */ bool array_state = FALSE; /* * We need to allocate the first struct to fill in. */ first_form = calloc(1, sizeof(struct FormInfo)); if(!first_form) return CURL_FORMADD_MEMORY; current_form = first_form; /* * Loop through all the options set. Break if we have an error to report. */ while(return_value == CURL_FORMADD_OK) { /* first see if we have more parts of the array param */ if(array_state && forms) { /* get the upcoming option from the given array */ option = forms->option; array_value = (char *)forms->value; forms++; /* advance this to next entry */ if(CURLFORM_END == option) { /* end of array state */ array_state = FALSE; continue; } } else { /* This is not array-state, get next option */ option = va_arg(params, CURLformoption); if(CURLFORM_END == option) break; } switch(option) { case CURLFORM_ARRAY: if(array_state) /* we don't support an array from within an array */ return_value = CURL_FORMADD_ILLEGAL_ARRAY; else { forms = va_arg(params, struct curl_forms *); if(forms) array_state = TRUE; else return_value = CURL_FORMADD_NULL; } break; /* * Set the Name property. */ case CURLFORM_PTRNAME: #ifdef CURL_DOES_CONVERSIONS /* Treat CURLFORM_PTR like CURLFORM_COPYNAME so that libcurl will copy * the data in all cases so that we'll have safe memory for the eventual * conversion. */ #else current_form->flags |= HTTPPOST_PTRNAME; /* fall through */ #endif /* FALLTHROUGH */ case CURLFORM_COPYNAME: if(current_form->name) return_value = CURL_FORMADD_OPTION_TWICE; else { char *name = array_state? array_value:va_arg(params, char *); if(name) current_form->name = name; /* store for the moment */ else return_value = CURL_FORMADD_NULL; } break; case CURLFORM_NAMELENGTH: if(current_form->namelength) return_value = CURL_FORMADD_OPTION_TWICE; else current_form->namelength = array_state?(size_t)array_value:(size_t)va_arg(params, long); break; /* * Set the contents property. */ case CURLFORM_PTRCONTENTS: current_form->flags |= HTTPPOST_PTRCONTENTS; /* FALLTHROUGH */ case CURLFORM_COPYCONTENTS: if(current_form->value) return_value = CURL_FORMADD_OPTION_TWICE; else { char *value = array_state?array_value:va_arg(params, char *); if(value) current_form->value = value; /* store for the moment */ else return_value = CURL_FORMADD_NULL; } break; case CURLFORM_CONTENTSLENGTH: current_form->contentslength = array_state?(size_t)array_value:(size_t)va_arg(params, long); break; case CURLFORM_CONTENTLEN: current_form->flags |= CURL_HTTPPOST_LARGE; current_form->contentslength = array_state?(curl_off_t)(size_t)array_value:va_arg(params, curl_off_t); break; /* Get contents from a given file name */ case CURLFORM_FILECONTENT: if(current_form->flags & (HTTPPOST_PTRCONTENTS|HTTPPOST_READFILE)) return_value = CURL_FORMADD_OPTION_TWICE; else { const char *filename = array_state? array_value:va_arg(params, char *); if(filename) { current_form->value = strdup(filename); if(!current_form->value) return_value = CURL_FORMADD_MEMORY; else { current_form->flags |= HTTPPOST_READFILE; current_form->value_alloc = TRUE; } } else return_value = CURL_FORMADD_NULL; } break; /* We upload a file */ case CURLFORM_FILE: { const char *filename = array_state?array_value: va_arg(params, char *); if(current_form->value) { if(current_form->flags & HTTPPOST_FILENAME) { if(filename) { char *fname = strdup(filename); if(!fname) return_value = CURL_FORMADD_MEMORY; else { form = AddFormInfo(fname, NULL, current_form); if(!form) { free(fname); return_value = CURL_FORMADD_MEMORY; } else { form->value_alloc = TRUE; current_form = form; form = NULL; } } } else return_value = CURL_FORMADD_NULL; } else return_value = CURL_FORMADD_OPTION_TWICE; } else { if(filename) { current_form->value = strdup(filename); if(!current_form->value) return_value = CURL_FORMADD_MEMORY; else { current_form->flags |= HTTPPOST_FILENAME; current_form->value_alloc = TRUE; } } else return_value = CURL_FORMADD_NULL; } break; } case CURLFORM_BUFFERPTR: current_form->flags |= HTTPPOST_PTRBUFFER|HTTPPOST_BUFFER; if(current_form->buffer) return_value = CURL_FORMADD_OPTION_TWICE; else { char *buffer = array_state?array_value:va_arg(params, char *); if(buffer) { current_form->buffer = buffer; /* store for the moment */ current_form->value = buffer; /* make it non-NULL to be accepted as fine */ } else return_value = CURL_FORMADD_NULL; } break; case CURLFORM_BUFFERLENGTH: if(current_form->bufferlength) return_value = CURL_FORMADD_OPTION_TWICE; else current_form->bufferlength = array_state?(size_t)array_value:(size_t)va_arg(params, long); break; case CURLFORM_STREAM: current_form->flags |= HTTPPOST_CALLBACK; if(current_form->userp) return_value = CURL_FORMADD_OPTION_TWICE; else { char *userp = array_state?array_value:va_arg(params, char *); if(userp) { current_form->userp = userp; current_form->value = userp; /* this isn't strictly true but we derive a value from this later on and we need this non-NULL to be accepted as a fine form part */ } else return_value = CURL_FORMADD_NULL; } break; case CURLFORM_CONTENTTYPE: { const char *contenttype = array_state?array_value:va_arg(params, char *); if(current_form->contenttype) { if(current_form->flags & HTTPPOST_FILENAME) { if(contenttype) { char *type = strdup(contenttype); if(!type) return_value = CURL_FORMADD_MEMORY; else { form = AddFormInfo(NULL, type, current_form); if(!form) { free(type); return_value = CURL_FORMADD_MEMORY; } else { form->contenttype_alloc = TRUE; current_form = form; form = NULL; } } } else return_value = CURL_FORMADD_NULL; } else return_value = CURL_FORMADD_OPTION_TWICE; } else { if(contenttype) { current_form->contenttype = strdup(contenttype); if(!current_form->contenttype) return_value = CURL_FORMADD_MEMORY; else current_form->contenttype_alloc = TRUE; } else return_value = CURL_FORMADD_NULL; } break; } case CURLFORM_CONTENTHEADER: { /* this "cast increases required alignment of target type" but we consider it OK anyway */ struct curl_slist *list = array_state? (struct curl_slist *)(void *)array_value: va_arg(params, struct curl_slist *); if(current_form->contentheader) return_value = CURL_FORMADD_OPTION_TWICE; else current_form->contentheader = list; break; } case CURLFORM_FILENAME: case CURLFORM_BUFFER: { const char *filename = array_state?array_value: va_arg(params, char *); if(current_form->showfilename) return_value = CURL_FORMADD_OPTION_TWICE; else { current_form->showfilename = strdup(filename); if(!current_form->showfilename) return_value = CURL_FORMADD_MEMORY; else current_form->showfilename_alloc = TRUE; } break; } default: return_value = CURL_FORMADD_UNKNOWN_OPTION; break; } } if(CURL_FORMADD_OK != return_value) { /* On error, free allocated fields for all nodes of the FormInfo linked list without deallocating nodes. List nodes are deallocated later on */ FormInfo *ptr; for(ptr = first_form; ptr != NULL; ptr = ptr->more) { if(ptr->name_alloc) { Curl_safefree(ptr->name); ptr->name_alloc = FALSE; } if(ptr->value_alloc) { Curl_safefree(ptr->value); ptr->value_alloc = FALSE; } if(ptr->contenttype_alloc) { Curl_safefree(ptr->contenttype); ptr->contenttype_alloc = FALSE; } if(ptr->showfilename_alloc) { Curl_safefree(ptr->showfilename); ptr->showfilename_alloc = FALSE; } } } if(CURL_FORMADD_OK == return_value) { /* go through the list, check for completeness and if everything is * alright add the HttpPost item otherwise set return_value accordingly */ post = NULL; for(form = first_form; form != NULL; form = form->more) { if(((!form->name || !form->value) && !post) || ( (form->contentslength) && (form->flags & HTTPPOST_FILENAME) ) || ( (form->flags & HTTPPOST_FILENAME) && (form->flags & HTTPPOST_PTRCONTENTS) ) || ( (!form->buffer) && (form->flags & HTTPPOST_BUFFER) && (form->flags & HTTPPOST_PTRBUFFER) ) || ( (form->flags & HTTPPOST_READFILE) && (form->flags & HTTPPOST_PTRCONTENTS) ) ) { return_value = CURL_FORMADD_INCOMPLETE; break; } if(((form->flags & HTTPPOST_FILENAME) || (form->flags & HTTPPOST_BUFFER)) && !form->contenttype) { char *f = (form->flags & HTTPPOST_BUFFER)? form->showfilename : form->value; char const *type; type = Curl_mime_contenttype(f); if(!type) type = prevtype; if(!type) type = FILE_CONTENTTYPE_DEFAULT; /* our contenttype is missing */ form->contenttype = strdup(type); if(!form->contenttype) { return_value = CURL_FORMADD_MEMORY; break; } form->contenttype_alloc = TRUE; } if(form->name && form->namelength) { /* Name should not contain nul bytes. */ size_t i; for(i = 0; i < form->namelength; i++) if(!form->name[i]) { return_value = CURL_FORMADD_NULL; break; } if(return_value != CURL_FORMADD_OK) break; } if(!(form->flags & HTTPPOST_PTRNAME) && (form == first_form) ) { /* Note that there's small risk that form->name is NULL here if the app passed in a bad combo, so we better check for that first. */ if(form->name) { /* copy name (without strdup; possibly not nul-terminated) */ form->name = Curl_memdup(form->name, form->namelength? form->namelength: strlen(form->name) + 1); } if(!form->name) { return_value = CURL_FORMADD_MEMORY; break; } form->name_alloc = TRUE; } if(!(form->flags & (HTTPPOST_FILENAME | HTTPPOST_READFILE | HTTPPOST_PTRCONTENTS | HTTPPOST_PTRBUFFER | HTTPPOST_CALLBACK)) && form->value) { /* copy value (without strdup; possibly contains null characters) */ size_t clen = (size_t) form->contentslength; if(!clen) clen = strlen(form->value) + 1; form->value = Curl_memdup(form->value, clen); if(!form->value) { return_value = CURL_FORMADD_MEMORY; break; } form->value_alloc = TRUE; } post = AddHttpPost(form->name, form->namelength, form->value, form->contentslength, form->buffer, form->bufferlength, form->contenttype, form->flags, form->contentheader, form->showfilename, form->userp, post, httppost, last_post); if(!post) { return_value = CURL_FORMADD_MEMORY; break; } if(form->contenttype) prevtype = form->contenttype; } if(CURL_FORMADD_OK != return_value) { /* On error, free allocated fields for nodes of the FormInfo linked list which are not already owned by the httppost linked list without deallocating nodes. List nodes are deallocated later on */ FormInfo *ptr; for(ptr = form; ptr != NULL; ptr = ptr->more) { if(ptr->name_alloc) { Curl_safefree(ptr->name); ptr->name_alloc = FALSE; } if(ptr->value_alloc) { Curl_safefree(ptr->value); ptr->value_alloc = FALSE; } if(ptr->contenttype_alloc) { Curl_safefree(ptr->contenttype); ptr->contenttype_alloc = FALSE; } if(ptr->showfilename_alloc) { Curl_safefree(ptr->showfilename); ptr->showfilename_alloc = FALSE; } } } } /* Always deallocate FormInfo linked list nodes without touching node fields given that these have either been deallocated or are owned now by the httppost linked list */ while(first_form) { FormInfo *ptr = first_form->more; free(first_form); first_form = ptr; } return return_value; } /* * curl_formadd() is a public API to add a section to the multipart formpost. * * @unittest: 1308 */ CURLFORMcode curl_formadd(struct curl_httppost **httppost, struct curl_httppost **last_post, ...) { va_list arg; CURLFORMcode result; va_start(arg, last_post); result = FormAdd(httppost, last_post, arg); va_end(arg); return result; } /* * curl_formget() * Serialize a curl_httppost struct. * Returns 0 on success. * * @unittest: 1308 */ int curl_formget(struct curl_httppost *form, void *arg, curl_formget_callback append) { CURLcode result; curl_mimepart toppart; Curl_mime_initpart(&toppart, NULL); /* default form is empty */ result = Curl_getformdata(NULL, &toppart, form, NULL); if(!result) result = Curl_mime_prepare_headers(&toppart, "multipart/form-data", NULL, MIMESTRATEGY_FORM); while(!result) { char buffer[8192]; size_t nread = Curl_mime_read(buffer, 1, sizeof(buffer), &toppart); if(!nread) break; switch(nread) { default: if(append(arg, buffer, nread) != nread) result = CURLE_READ_ERROR; break; case CURL_READFUNC_ABORT: case CURL_READFUNC_PAUSE: break; } } Curl_mime_cleanpart(&toppart); return (int) result; } /* * curl_formfree() is an external function to free up a whole form post * chain */ void curl_formfree(struct curl_httppost *form) { struct curl_httppost *next; if(!form) /* no form to free, just get out of this */ return; do { next = form->next; /* the following form line */ /* recurse to sub-contents */ curl_formfree(form->more); if(!(form->flags & HTTPPOST_PTRNAME)) free(form->name); /* free the name */ if(!(form->flags & (HTTPPOST_PTRCONTENTS|HTTPPOST_BUFFER|HTTPPOST_CALLBACK)) ) free(form->contents); /* free the contents */ free(form->contenttype); /* free the content type */ free(form->showfilename); /* free the faked file name */ free(form); /* free the struct */ form = next; } while(form); /* continue */ } /* Set mime part name, taking care of non nul-terminated name string. */ static CURLcode setname(curl_mimepart *part, const char *name, size_t len) { char *zname; CURLcode res; if(!name || !len) return curl_mime_name(part, name); zname = malloc(len + 1); if(!zname) return CURLE_OUT_OF_MEMORY; memcpy(zname, name, len); zname[len] = '\0'; res = curl_mime_name(part, zname); free(zname); return res; } /* * Curl_getformdata() converts a linked list of "meta data" into a mime * structure. The input list is in 'post', while the output is stored in * mime part at '*finalform'. * * This function will not do a failf() for the potential memory failures but * should for all other errors it spots. Just note that this function MAY get * a NULL pointer in the 'data' argument. */ CURLcode Curl_getformdata(struct Curl_easy *data, curl_mimepart *finalform, struct curl_httppost *post, curl_read_callback fread_func) { CURLcode result = CURLE_OK; curl_mime *form = NULL; curl_mimepart *part; struct curl_httppost *file; Curl_mime_cleanpart(finalform); /* default form is empty */ if(!post) return result; /* no input => no output! */ form = curl_mime_init(data); if(!form) result = CURLE_OUT_OF_MEMORY; if(!result) result = curl_mime_subparts(finalform, form); /* Process each top part. */ for(; !result && post; post = post->next) { /* If we have more than a file here, create a mime subpart and fill it. */ curl_mime *multipart = form; if(post->more) { part = curl_mime_addpart(form); if(!part) result = CURLE_OUT_OF_MEMORY; if(!result) result = setname(part, post->name, post->namelength); if(!result) { multipart = curl_mime_init(data); if(!multipart) result = CURLE_OUT_OF_MEMORY; } if(!result) result = curl_mime_subparts(part, multipart); } /* Generate all the part contents. */ for(file = post; !result && file; file = file->more) { /* Create the part. */ part = curl_mime_addpart(multipart); if(!part) result = CURLE_OUT_OF_MEMORY; /* Set the headers. */ if(!result) result = curl_mime_headers(part, file->contentheader, 0); /* Set the content type. */ if(!result && file->contenttype) result = curl_mime_type(part, file->contenttype); /* Set field name. */ if(!result && !post->more) result = setname(part, post->name, post->namelength); /* Process contents. */ if(!result) { curl_off_t clen = post->contentslength; if(post->flags & CURL_HTTPPOST_LARGE) clen = post->contentlen; if(!clen) clen = -1; if(post->flags & (HTTPPOST_FILENAME | HTTPPOST_READFILE)) { if(!strcmp(file->contents, "-")) { /* There are a few cases where the code below won't work; in particular, freopen(stdin) by the caller is not guaranteed to result as expected. This feature has been kept for backward compatibility: use of "-" pseudo file name should be avoided. */ result = curl_mime_data_cb(part, (curl_off_t) -1, (curl_read_callback) fread, CURLX_FUNCTION_CAST(curl_seek_callback, fseek), NULL, (void *) stdin); } else result = curl_mime_filedata(part, file->contents); if(!result && (post->flags & HTTPPOST_READFILE)) result = curl_mime_filename(part, NULL); } else if(post->flags & HTTPPOST_BUFFER) result = curl_mime_data(part, post->buffer, post->bufferlength? post->bufferlength: -1); else if(post->flags & HTTPPOST_CALLBACK) /* the contents should be read with the callback and the size is set with the contentslength */ result = curl_mime_data_cb(part, clen, fread_func, NULL, NULL, post->userp); else { result = curl_mime_data(part, post->contents, (ssize_t) clen); #ifdef CURL_DOES_CONVERSIONS /* Convert textual contents now. */ if(!result && data && part->datasize) result = Curl_convert_to_network(data, part->data, part->datasize); #endif } } /* Set fake file name. */ if(!result && post->showfilename) if(post->more || (post->flags & (HTTPPOST_FILENAME | HTTPPOST_BUFFER | HTTPPOST_CALLBACK))) result = curl_mime_filename(part, post->showfilename); } } if(result) Curl_mime_cleanpart(finalform); return result; } #else /* if disabled */ CURLFORMcode curl_formadd(struct curl_httppost **httppost, struct curl_httppost **last_post, ...) { (void)httppost; (void)last_post; return CURL_FORMADD_DISABLED; } int curl_formget(struct curl_httppost *form, void *arg, curl_formget_callback append) { (void) form; (void) arg; (void) append; return CURL_FORMADD_DISABLED; } void curl_formfree(struct curl_httppost *form) { (void)form; /* does nothing HTTP is disabled */ } #endif /* if disabled */
YifuLiu/AliOS-Things
components/curl/lib/formdata.c
C
apache-2.0
29,889
#ifndef HEADER_CURL_FORMDATA_H #define HEADER_CURL_FORMDATA_H /*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2019, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "curl_setup.h" #ifndef CURL_DISABLE_MIME /* used by FormAdd for temporary storage */ typedef struct FormInfo { char *name; bool name_alloc; size_t namelength; char *value; bool value_alloc; curl_off_t contentslength; char *contenttype; bool contenttype_alloc; long flags; char *buffer; /* pointer to existing buffer used for file upload */ size_t bufferlength; char *showfilename; /* The file name to show. If not set, the actual file name will be used */ bool showfilename_alloc; char *userp; /* pointer for the read callback */ struct curl_slist *contentheader; struct FormInfo *more; } FormInfo; CURLcode Curl_getformdata(struct Curl_easy *data, curl_mimepart *, struct curl_httppost *post, curl_read_callback fread_func); #else /* disabled */ #define Curl_getformdata(a,b,c,d) CURLE_NOT_BUILT_IN #endif #endif /* HEADER_CURL_FORMDATA_H */
YifuLiu/AliOS-Things
components/curl/lib/formdata.h
C
apache-2.0
2,093
/*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2019, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "curl_setup.h" #ifndef CURL_DISABLE_FTP #ifdef HAVE_NETINET_IN_H #include <netinet/in.h> #endif #ifdef HAVE_ARPA_INET_H #include <arpa/inet.h> #endif #ifdef HAVE_UTSNAME_H #include <sys/utsname.h> #endif #ifdef HAVE_NETDB_H #include <netdb.h> #endif #ifdef __VMS #include <in.h> #include <inet.h> #endif #if (defined(NETWARE) && defined(__NOVELL_LIBC__)) #undef in_addr_t #define in_addr_t unsigned long #endif #include <curl/curl.h> #include "urldata.h" #include "sendf.h" #include "if2ip.h" #include "hostip.h" #include "progress.h" #include "transfer.h" #include "escape.h" #include "http.h" /* for HTTP proxy tunnel stuff */ #include "socks.h" #include "ftp.h" #include "fileinfo.h" #include "ftplistparser.h" #include "curl_range.h" #include "curl_sec.h" #include "strtoofft.h" #include "strcase.h" #include "vtls/vtls.h" #include "connect.h" #include "strerror.h" #include "inet_ntop.h" #include "inet_pton.h" #include "select.h" #include "parsedate.h" /* for the week day and month names */ #include "sockaddr.h" /* required for Curl_sockaddr_storage */ #include "multiif.h" #include "url.h" #include "strcase.h" #include "speedcheck.h" #include "warnless.h" #include "http_proxy.h" #include "non-ascii.h" /* The last 3 #include files should be in this order */ #include "curl_printf.h" #include "curl_memory.h" #include "memdebug.h" #ifndef NI_MAXHOST #define NI_MAXHOST 1025 #endif #ifndef INET_ADDRSTRLEN #define INET_ADDRSTRLEN 16 #endif #ifdef CURL_DISABLE_VERBOSE_STRINGS #define ftp_pasv_verbose(a,b,c,d) Curl_nop_stmt #endif /* Local API functions */ #ifndef DEBUGBUILD static void _state(struct connectdata *conn, ftpstate newstate); #define state(x,y) _state(x,y) #else static void _state(struct connectdata *conn, ftpstate newstate, int lineno); #define state(x,y) _state(x,y,__LINE__) #endif static CURLcode ftp_sendquote(struct connectdata *conn, struct curl_slist *quote); static CURLcode ftp_quit(struct connectdata *conn); static CURLcode ftp_parse_url_path(struct connectdata *conn); static CURLcode ftp_regular_transfer(struct connectdata *conn, bool *done); #ifndef CURL_DISABLE_VERBOSE_STRINGS static void ftp_pasv_verbose(struct connectdata *conn, Curl_addrinfo *ai, char *newhost, /* ascii version */ int port); #endif static CURLcode ftp_state_prepare_transfer(struct connectdata *conn); static CURLcode ftp_state_mdtm(struct connectdata *conn); static CURLcode ftp_state_quote(struct connectdata *conn, bool init, ftpstate instate); static CURLcode ftp_nb_type(struct connectdata *conn, bool ascii, ftpstate newstate); static int ftp_need_type(struct connectdata *conn, bool ascii); static CURLcode ftp_do(struct connectdata *conn, bool *done); static CURLcode ftp_done(struct connectdata *conn, CURLcode, bool premature); static CURLcode ftp_connect(struct connectdata *conn, bool *done); static CURLcode ftp_disconnect(struct connectdata *conn, bool dead_connection); static CURLcode ftp_do_more(struct connectdata *conn, int *completed); static CURLcode ftp_multi_statemach(struct connectdata *conn, bool *done); static int ftp_getsock(struct connectdata *conn, curl_socket_t *socks, int numsocks); static int ftp_domore_getsock(struct connectdata *conn, curl_socket_t *socks, int numsocks); static CURLcode ftp_doing(struct connectdata *conn, bool *dophase_done); static CURLcode ftp_setup_connection(struct connectdata * conn); static CURLcode init_wc_data(struct connectdata *conn); static CURLcode wc_statemach(struct connectdata *conn); static void wc_data_dtor(void *ptr); static CURLcode ftp_state_retr(struct connectdata *conn, curl_off_t filesize); static CURLcode ftp_readresp(curl_socket_t sockfd, struct pingpong *pp, int *ftpcode, size_t *size); static CURLcode ftp_dophase_done(struct connectdata *conn, bool connected); /* easy-to-use macro: */ #define PPSENDF(x,y,z) result = Curl_pp_sendf(x,y,z); \ if(result) \ return result /* * FTP protocol handler. */ const struct Curl_handler Curl_handler_ftp = { "FTP", /* scheme */ ftp_setup_connection, /* setup_connection */ ftp_do, /* do_it */ ftp_done, /* done */ ftp_do_more, /* do_more */ ftp_connect, /* connect_it */ ftp_multi_statemach, /* connecting */ ftp_doing, /* doing */ ftp_getsock, /* proto_getsock */ ftp_getsock, /* doing_getsock */ ftp_domore_getsock, /* domore_getsock */ ZERO_NULL, /* perform_getsock */ ftp_disconnect, /* disconnect */ ZERO_NULL, /* readwrite */ ZERO_NULL, /* connection_check */ PORT_FTP, /* defport */ CURLPROTO_FTP, /* protocol */ PROTOPT_DUAL | PROTOPT_CLOSEACTION | PROTOPT_NEEDSPWD | PROTOPT_NOURLQUERY | PROTOPT_PROXY_AS_HTTP | PROTOPT_WILDCARD /* flags */ }; #ifdef USE_SSL /* * FTPS protocol handler. */ const struct Curl_handler Curl_handler_ftps = { "FTPS", /* scheme */ ftp_setup_connection, /* setup_connection */ ftp_do, /* do_it */ ftp_done, /* done */ ftp_do_more, /* do_more */ ftp_connect, /* connect_it */ ftp_multi_statemach, /* connecting */ ftp_doing, /* doing */ ftp_getsock, /* proto_getsock */ ftp_getsock, /* doing_getsock */ ftp_domore_getsock, /* domore_getsock */ ZERO_NULL, /* perform_getsock */ ftp_disconnect, /* disconnect */ ZERO_NULL, /* readwrite */ ZERO_NULL, /* connection_check */ PORT_FTPS, /* defport */ CURLPROTO_FTPS, /* protocol */ PROTOPT_SSL | PROTOPT_DUAL | PROTOPT_CLOSEACTION | PROTOPT_NEEDSPWD | PROTOPT_NOURLQUERY | PROTOPT_WILDCARD /* flags */ }; #endif static void close_secondarysocket(struct connectdata *conn) { if(CURL_SOCKET_BAD != conn->sock[SECONDARYSOCKET]) { Curl_closesocket(conn, conn->sock[SECONDARYSOCKET]); conn->sock[SECONDARYSOCKET] = CURL_SOCKET_BAD; } conn->bits.tcpconnect[SECONDARYSOCKET] = FALSE; } /* * NOTE: back in the old days, we added code in the FTP code that made NOBODY * requests on files respond with headers passed to the client/stdout that * looked like HTTP ones. * * This approach is not very elegant, it causes confusion and is error-prone. * It is subject for removal at the next (or at least a future) soname bump. * Until then you can test the effects of the removal by undefining the * following define named CURL_FTP_HTTPSTYLE_HEAD. */ #define CURL_FTP_HTTPSTYLE_HEAD 1 static void freedirs(struct ftp_conn *ftpc) { if(ftpc->dirs) { int i; for(i = 0; i < ftpc->dirdepth; i++) { free(ftpc->dirs[i]); ftpc->dirs[i] = NULL; } free(ftpc->dirs); ftpc->dirs = NULL; ftpc->dirdepth = 0; } Curl_safefree(ftpc->file); /* no longer of any use */ Curl_safefree(ftpc->newhost); } /* Returns non-zero if the given string contains CR (\r) or LF (\n), which are not allowed within RFC 959 <string>. Note: The input string is in the client's encoding which might not be ASCII, so escape sequences \r & \n must be used instead of hex values 0x0d & 0x0a. */ static bool isBadFtpString(const char *string) { return ((NULL != strchr(string, '\r')) || (NULL != strchr(string, '\n'))) ? TRUE : FALSE; } /*********************************************************************** * * AcceptServerConnect() * * After connection request is received from the server this function is * called to accept the connection and close the listening socket * */ static CURLcode AcceptServerConnect(struct connectdata *conn) { struct Curl_easy *data = conn->data; curl_socket_t sock = conn->sock[SECONDARYSOCKET]; curl_socket_t s = CURL_SOCKET_BAD; #ifdef ENABLE_IPV6 struct Curl_sockaddr_storage add; #else struct sockaddr_in add; #endif curl_socklen_t size = (curl_socklen_t) sizeof(add); if(0 == getsockname(sock, (struct sockaddr *) &add, &size)) { size = sizeof(add); s = accept(sock, (struct sockaddr *) &add, &size); } Curl_closesocket(conn, sock); /* close the first socket */ if(CURL_SOCKET_BAD == s) { failf(data, "Error accept()ing server connect"); return CURLE_FTP_PORT_FAILED; } infof(data, "Connection accepted from server\n"); /* when this happens within the DO state it is important that we mark us as not needing DO_MORE anymore */ conn->bits.do_more = FALSE; conn->sock[SECONDARYSOCKET] = s; (void)curlx_nonblock(s, TRUE); /* enable non-blocking */ conn->sock_accepted[SECONDARYSOCKET] = TRUE; if(data->set.fsockopt) { int error = 0; /* activate callback for setting socket options */ Curl_set_in_callback(data, true); error = data->set.fsockopt(data->set.sockopt_client, s, CURLSOCKTYPE_ACCEPT); Curl_set_in_callback(data, false); if(error) { close_secondarysocket(conn); return CURLE_ABORTED_BY_CALLBACK; } } return CURLE_OK; } /* * ftp_timeleft_accept() returns the amount of milliseconds left allowed for * waiting server to connect. If the value is negative, the timeout time has * already elapsed. * * The start time is stored in progress.t_acceptdata - as set with * Curl_pgrsTime(..., TIMER_STARTACCEPT); * */ static timediff_t ftp_timeleft_accept(struct Curl_easy *data) { timediff_t timeout_ms = DEFAULT_ACCEPT_TIMEOUT; timediff_t other; struct curltime now; if(data->set.accepttimeout > 0) timeout_ms = data->set.accepttimeout; now = Curl_now(); /* check if the generic timeout possibly is set shorter */ other = Curl_timeleft(data, &now, FALSE); if(other && (other < timeout_ms)) /* note that this also works fine for when other happens to be negative due to it already having elapsed */ timeout_ms = other; else { /* subtract elapsed time */ timeout_ms -= Curl_timediff(now, data->progress.t_acceptdata); if(!timeout_ms) /* avoid returning 0 as that means no timeout! */ return -1; } return timeout_ms; } /*********************************************************************** * * ReceivedServerConnect() * * After allowing server to connect to us from data port, this function * checks both data connection for connection establishment and ctrl * connection for a negative response regarding a failure in connecting * */ static CURLcode ReceivedServerConnect(struct connectdata *conn, bool *received) { struct Curl_easy *data = conn->data; curl_socket_t ctrl_sock = conn->sock[FIRSTSOCKET]; curl_socket_t data_sock = conn->sock[SECONDARYSOCKET]; struct ftp_conn *ftpc = &conn->proto.ftpc; struct pingpong *pp = &ftpc->pp; int result; time_t timeout_ms; ssize_t nread; int ftpcode; *received = FALSE; timeout_ms = ftp_timeleft_accept(data); infof(data, "Checking for server connect\n"); if(timeout_ms < 0) { /* if a timeout was already reached, bail out */ failf(data, "Accept timeout occurred while waiting server connect"); return CURLE_FTP_ACCEPT_TIMEOUT; } /* First check whether there is a cached response from server */ if(pp->cache_size && pp->cache && pp->cache[0] > '3') { /* Data connection could not be established, let's return */ infof(data, "There is negative response in cache while serv connect\n"); Curl_GetFTPResponse(&nread, conn, &ftpcode); return CURLE_FTP_ACCEPT_FAILED; } result = Curl_socket_check(ctrl_sock, data_sock, CURL_SOCKET_BAD, 0); /* see if the connection request is already here */ switch(result) { case -1: /* error */ /* let's die here */ failf(data, "Error while waiting for server connect"); return CURLE_FTP_ACCEPT_FAILED; case 0: /* Server connect is not received yet */ break; /* loop */ default: if(result & CURL_CSELECT_IN2) { infof(data, "Ready to accept data connection from server\n"); *received = TRUE; } else if(result & CURL_CSELECT_IN) { infof(data, "Ctrl conn has data while waiting for data conn\n"); Curl_GetFTPResponse(&nread, conn, &ftpcode); if(ftpcode/100 > 3) return CURLE_FTP_ACCEPT_FAILED; return CURLE_WEIRD_SERVER_REPLY; } break; } /* switch() */ return CURLE_OK; } /*********************************************************************** * * InitiateTransfer() * * After connection from server is accepted this function is called to * setup transfer parameters and initiate the data transfer. * */ static CURLcode InitiateTransfer(struct connectdata *conn) { struct Curl_easy *data = conn->data; CURLcode result = CURLE_OK; if(conn->bits.ftp_use_data_ssl) { /* since we only have a plaintext TCP connection here, we must now * do the TLS stuff */ infof(data, "Doing the SSL/TLS handshake on the data stream\n"); result = Curl_ssl_connect(conn, SECONDARYSOCKET); if(result) return result; } if(conn->proto.ftpc.state_saved == FTP_STOR) { /* When we know we're uploading a specified file, we can get the file size prior to the actual upload. */ Curl_pgrsSetUploadSize(data, data->state.infilesize); /* set the SO_SNDBUF for the secondary socket for those who need it */ Curl_sndbufset(conn->sock[SECONDARYSOCKET]); Curl_setup_transfer(data, -1, -1, FALSE, SECONDARYSOCKET); } else { /* FTP download: */ Curl_setup_transfer(data, SECONDARYSOCKET, conn->proto.ftpc.retr_size_saved, FALSE, -1); } conn->proto.ftpc.pp.pending_resp = TRUE; /* expect server response */ state(conn, FTP_STOP); return CURLE_OK; } /*********************************************************************** * * AllowServerConnect() * * When we've issue the PORT command, we have told the server to connect to * us. This function checks whether data connection is established if so it is * accepted. * */ static CURLcode AllowServerConnect(struct connectdata *conn, bool *connected) { struct Curl_easy *data = conn->data; time_t timeout_ms; CURLcode result = CURLE_OK; *connected = FALSE; infof(data, "Preparing for accepting server on data port\n"); /* Save the time we start accepting server connect */ Curl_pgrsTime(data, TIMER_STARTACCEPT); timeout_ms = ftp_timeleft_accept(data); if(timeout_ms < 0) { /* if a timeout was already reached, bail out */ failf(data, "Accept timeout occurred while waiting server connect"); return CURLE_FTP_ACCEPT_TIMEOUT; } /* see if the connection request is already here */ result = ReceivedServerConnect(conn, connected); if(result) return result; if(*connected) { result = AcceptServerConnect(conn); if(result) return result; result = InitiateTransfer(conn); if(result) return result; } else { /* Add timeout to multi handle and break out of the loop */ if(!result && *connected == FALSE) { Curl_expire(data, data->set.accepttimeout > 0 ? data->set.accepttimeout: DEFAULT_ACCEPT_TIMEOUT, 0); } } return result; } /* macro to check for a three-digit ftp status code at the start of the given string */ #define STATUSCODE(line) (ISDIGIT(line[0]) && ISDIGIT(line[1]) && \ ISDIGIT(line[2])) /* macro to check for the last line in an FTP server response */ #define LASTLINE(line) (STATUSCODE(line) && (' ' == line[3])) static bool ftp_endofresp(struct connectdata *conn, char *line, size_t len, int *code) { (void)conn; if((len > 3) && LASTLINE(line)) { *code = curlx_sltosi(strtol(line, NULL, 10)); return TRUE; } return FALSE; } static CURLcode ftp_readresp(curl_socket_t sockfd, struct pingpong *pp, int *ftpcode, /* return the ftp-code if done */ size_t *size) /* size of the response */ { struct connectdata *conn = pp->conn; struct Curl_easy *data = conn->data; #ifdef HAVE_GSSAPI char * const buf = data->state.buffer; #endif CURLcode result = CURLE_OK; int code; result = Curl_pp_readresp(sockfd, pp, &code, size); #if defined(HAVE_GSSAPI) /* handle the security-oriented responses 6xx ***/ switch(code) { case 631: code = Curl_sec_read_msg(conn, buf, PROT_SAFE); break; case 632: code = Curl_sec_read_msg(conn, buf, PROT_PRIVATE); break; case 633: code = Curl_sec_read_msg(conn, buf, PROT_CONFIDENTIAL); break; default: /* normal ftp stuff we pass through! */ break; } #endif /* store the latest code for later retrieval */ data->info.httpcode = code; if(ftpcode) *ftpcode = code; if(421 == code) { /* 421 means "Service not available, closing control connection." and FTP * servers use it to signal that idle session timeout has been exceeded. * If we ignored the response, it could end up hanging in some cases. * * This response code can come at any point so having it treated * generically is a good idea. */ infof(data, "We got a 421 - timeout!\n"); state(conn, FTP_STOP); return CURLE_OPERATION_TIMEDOUT; } return result; } /* --- parse FTP server responses --- */ /* * Curl_GetFTPResponse() is a BLOCKING function to read the full response * from a server after a command. * */ CURLcode Curl_GetFTPResponse(ssize_t *nreadp, /* return number of bytes read */ struct connectdata *conn, int *ftpcode) /* return the ftp-code */ { /* * We cannot read just one byte per read() and then go back to select() as * the OpenSSL read() doesn't grok that properly. * * Alas, read as much as possible, split up into lines, use the ending * line in a response or continue reading. */ curl_socket_t sockfd = conn->sock[FIRSTSOCKET]; struct Curl_easy *data = conn->data; CURLcode result = CURLE_OK; struct ftp_conn *ftpc = &conn->proto.ftpc; struct pingpong *pp = &ftpc->pp; size_t nread; int cache_skip = 0; int value_to_be_ignored = 0; if(ftpcode) *ftpcode = 0; /* 0 for errors */ else /* make the pointer point to something for the rest of this function */ ftpcode = &value_to_be_ignored; *nreadp = 0; while(!*ftpcode && !result) { /* check and reset timeout value every lap */ time_t timeout = Curl_pp_state_timeout(pp, FALSE); time_t interval_ms; if(timeout <= 0) { failf(data, "FTP response timeout"); return CURLE_OPERATION_TIMEDOUT; /* already too little time */ } interval_ms = 1000; /* use 1 second timeout intervals */ if(timeout < interval_ms) interval_ms = timeout; /* * Since this function is blocking, we need to wait here for input on the * connection and only then we call the response reading function. We do * timeout at least every second to make the timeout check run. * * A caution here is that the ftp_readresp() function has a cache that may * contain pieces of a response from the previous invoke and we need to * make sure we don't just wait for input while there is unhandled data in * that cache. But also, if the cache is there, we call ftp_readresp() and * the cache wasn't good enough to continue we must not just busy-loop * around this function. * */ if(pp->cache && (cache_skip < 2)) { /* * There's a cache left since before. We then skipping the wait for * socket action, unless this is the same cache like the previous round * as then the cache was deemed not enough to act on and we then need to * wait for more data anyway. */ } else if(!Curl_conn_data_pending(conn, FIRSTSOCKET)) { switch(SOCKET_READABLE(sockfd, interval_ms)) { case -1: /* select() error, stop reading */ failf(data, "FTP response aborted due to select/poll error: %d", SOCKERRNO); return CURLE_RECV_ERROR; case 0: /* timeout */ if(Curl_pgrsUpdate(conn)) return CURLE_ABORTED_BY_CALLBACK; continue; /* just continue in our loop for the timeout duration */ default: /* for clarity */ break; } } result = ftp_readresp(sockfd, pp, ftpcode, &nread); if(result) break; if(!nread && pp->cache) /* bump cache skip counter as on repeated skips we must wait for more data */ cache_skip++; else /* when we got data or there is no cache left, we reset the cache skip counter */ cache_skip = 0; *nreadp += nread; } /* while there's buffer left and loop is requested */ pp->pending_resp = FALSE; return result; } #if defined(DEBUGBUILD) && !defined(CURL_DISABLE_VERBOSE_STRINGS) /* for debug purposes */ static const char * const ftp_state_names[]={ "STOP", "WAIT220", "AUTH", "USER", "PASS", "ACCT", "PBSZ", "PROT", "CCC", "PWD", "SYST", "NAMEFMT", "QUOTE", "RETR_PREQUOTE", "STOR_PREQUOTE", "POSTQUOTE", "CWD", "MKD", "MDTM", "TYPE", "LIST_TYPE", "RETR_TYPE", "STOR_TYPE", "SIZE", "RETR_SIZE", "STOR_SIZE", "REST", "RETR_REST", "PORT", "PRET", "PASV", "LIST", "RETR", "STOR", "QUIT" }; #endif /* This is the ONLY way to change FTP state! */ static void _state(struct connectdata *conn, ftpstate newstate #ifdef DEBUGBUILD , int lineno #endif ) { struct ftp_conn *ftpc = &conn->proto.ftpc; #if defined(DEBUGBUILD) #if defined(CURL_DISABLE_VERBOSE_STRINGS) (void) lineno; #else if(ftpc->state != newstate) infof(conn->data, "FTP %p (line %d) state change from %s to %s\n", (void *)ftpc, lineno, ftp_state_names[ftpc->state], ftp_state_names[newstate]); #endif #endif ftpc->state = newstate; } static CURLcode ftp_state_user(struct connectdata *conn) { CURLcode result; struct FTP *ftp = conn->data->req.protop; /* send USER */ PPSENDF(&conn->proto.ftpc.pp, "USER %s", ftp->user?ftp->user:""); state(conn, FTP_USER); conn->data->state.ftp_trying_alternative = FALSE; return CURLE_OK; } static CURLcode ftp_state_pwd(struct connectdata *conn) { CURLcode result; /* send PWD to discover our entry point */ PPSENDF(&conn->proto.ftpc.pp, "%s", "PWD"); state(conn, FTP_PWD); return CURLE_OK; } /* For the FTP "protocol connect" and "doing" phases only */ static int ftp_getsock(struct connectdata *conn, curl_socket_t *socks, int numsocks) { return Curl_pp_getsock(&conn->proto.ftpc.pp, socks, numsocks); } /* For the FTP "DO_MORE" phase only */ static int ftp_domore_getsock(struct connectdata *conn, curl_socket_t *socks, int numsocks) { struct ftp_conn *ftpc = &conn->proto.ftpc; if(!numsocks) return GETSOCK_BLANK; /* When in DO_MORE state, we could be either waiting for us to connect to a * remote site, or we could wait for that site to connect to us. Or just * handle ordinary commands. */ if(FTP_STOP == ftpc->state) { int bits = GETSOCK_READSOCK(0); /* if stopped and still in this state, then we're also waiting for a connect on the secondary connection */ socks[0] = conn->sock[FIRSTSOCKET]; if(!conn->data->set.ftp_use_port) { int s; int i; /* PORT is used to tell the server to connect to us, and during that we don't do happy eyeballs, but we do if we connect to the server */ for(s = 1, i = 0; i<2; i++) { if(conn->tempsock[i] != CURL_SOCKET_BAD) { socks[s] = conn->tempsock[i]; bits |= GETSOCK_WRITESOCK(s++); } } } else { socks[1] = conn->sock[SECONDARYSOCKET]; bits |= GETSOCK_WRITESOCK(1) | GETSOCK_READSOCK(1); } return bits; } return Curl_pp_getsock(&conn->proto.ftpc.pp, socks, numsocks); } /* This is called after the FTP_QUOTE state is passed. ftp_state_cwd() sends the range of CWD commands to the server to change to the correct directory. It may also need to send MKD commands to create missing ones, if that option is enabled. */ static CURLcode ftp_state_cwd(struct connectdata *conn) { CURLcode result = CURLE_OK; struct ftp_conn *ftpc = &conn->proto.ftpc; if(ftpc->cwddone) /* already done and fine */ result = ftp_state_mdtm(conn); else { ftpc->count2 = 0; /* count2 counts failed CWDs */ /* count3 is set to allow a MKD to fail once. In the case when first CWD fails and then MKD fails (due to another session raced it to create the dir) this then allows for a second try to CWD to it */ ftpc->count3 = (conn->data->set.ftp_create_missing_dirs == 2)?1:0; if((conn->data->set.ftp_filemethod == FTPFILE_NOCWD) && !ftpc->cwdcount) /* No CWD necessary */ result = ftp_state_mdtm(conn); else if(conn->bits.reuse && ftpc->entrypath) { /* This is a re-used connection. Since we change directory to where the transfer is taking place, we must first get back to the original dir where we ended up after login: */ ftpc->cwdcount = 0; /* we count this as the first path, then we add one for all upcoming ones in the ftp->dirs[] array */ PPSENDF(&conn->proto.ftpc.pp, "CWD %s", ftpc->entrypath); state(conn, FTP_CWD); } else { if(ftpc->dirdepth) { ftpc->cwdcount = 1; /* issue the first CWD, the rest is sent when the CWD responses are received... */ PPSENDF(&conn->proto.ftpc.pp, "CWD %s", ftpc->dirs[ftpc->cwdcount -1]); state(conn, FTP_CWD); } else { /* No CWD necessary */ result = ftp_state_mdtm(conn); } } } return result; } typedef enum { EPRT, PORT, DONE } ftpport; static CURLcode ftp_state_use_port(struct connectdata *conn, ftpport fcmd) /* start with this */ { CURLcode result = CURLE_OK; struct ftp_conn *ftpc = &conn->proto.ftpc; struct Curl_easy *data = conn->data; curl_socket_t portsock = CURL_SOCKET_BAD; char myhost[256] = ""; struct Curl_sockaddr_storage ss; Curl_addrinfo *res, *ai; curl_socklen_t sslen; char hbuf[NI_MAXHOST]; struct sockaddr *sa = (struct sockaddr *)&ss; struct sockaddr_in * const sa4 = (void *)sa; #ifdef ENABLE_IPV6 struct sockaddr_in6 * const sa6 = (void *)sa; #endif char tmp[1024]; static const char mode[][5] = { "EPRT", "PORT" }; int rc; int error; char *host = NULL; char *string_ftpport = data->set.str[STRING_FTPPORT]; struct Curl_dns_entry *h = NULL; unsigned short port_min = 0; unsigned short port_max = 0; unsigned short port; bool possibly_non_local = TRUE; char buffer[STRERROR_LEN]; char *addr = NULL; /* Step 1, figure out what is requested, * accepted format : * (ipv4|ipv6|domain|interface)?(:port(-range)?)? */ if(data->set.str[STRING_FTPPORT] && (strlen(data->set.str[STRING_FTPPORT]) > 1)) { #ifdef ENABLE_IPV6 size_t addrlen = INET6_ADDRSTRLEN > strlen(string_ftpport) ? INET6_ADDRSTRLEN : strlen(string_ftpport); #else size_t addrlen = INET_ADDRSTRLEN > strlen(string_ftpport) ? INET_ADDRSTRLEN : strlen(string_ftpport); #endif char *ip_start = string_ftpport; char *ip_end = NULL; char *port_start = NULL; char *port_sep = NULL; addr = calloc(addrlen + 1, 1); if(!addr) return CURLE_OUT_OF_MEMORY; #ifdef ENABLE_IPV6 if(*string_ftpport == '[') { /* [ipv6]:port(-range) */ ip_start = string_ftpport + 1; ip_end = strchr(string_ftpport, ']'); if(ip_end) strncpy(addr, ip_start, ip_end - ip_start); } else #endif if(*string_ftpport == ':') { /* :port */ ip_end = string_ftpport; } else { ip_end = strchr(string_ftpport, ':'); if(ip_end) { /* either ipv6 or (ipv4|domain|interface):port(-range) */ #ifdef ENABLE_IPV6 if(Curl_inet_pton(AF_INET6, string_ftpport, sa6) == 1) { /* ipv6 */ port_min = port_max = 0; strcpy(addr, string_ftpport); ip_end = NULL; /* this got no port ! */ } else #endif /* (ipv4|domain|interface):port(-range) */ strncpy(addr, string_ftpport, ip_end - ip_start); } else /* ipv4|interface */ strcpy(addr, string_ftpport); } /* parse the port */ if(ip_end != NULL) { port_start = strchr(ip_end, ':'); if(port_start) { port_min = curlx_ultous(strtoul(port_start + 1, NULL, 10)); port_sep = strchr(port_start, '-'); if(port_sep) { port_max = curlx_ultous(strtoul(port_sep + 1, NULL, 10)); } else port_max = port_min; } } /* correct errors like: * :1234-1230 * :-4711, in this case port_min is (unsigned)-1, * therefore port_min > port_max for all cases * but port_max = (unsigned)-1 */ if(port_min > port_max) port_min = port_max = 0; if(*addr != '\0') { /* attempt to get the address of the given interface name */ switch(Curl_if2ip(conn->ip_addr->ai_family, Curl_ipv6_scope(conn->ip_addr->ai_addr), conn->scope_id, addr, hbuf, sizeof(hbuf))) { case IF2IP_NOT_FOUND: /* not an interface, use the given string as host name instead */ host = addr; break; case IF2IP_AF_NOT_SUPPORTED: return CURLE_FTP_PORT_FAILED; case IF2IP_FOUND: host = hbuf; /* use the hbuf for host name */ } } else /* there was only a port(-range) given, default the host */ host = NULL; } /* data->set.ftpport */ if(!host) { /* not an interface and not a host name, get default by extracting the IP from the control connection */ sslen = sizeof(ss); if(getsockname(conn->sock[FIRSTSOCKET], sa, &sslen)) { failf(data, "getsockname() failed: %s", Curl_strerror(SOCKERRNO, buffer, sizeof(buffer))); free(addr); return CURLE_FTP_PORT_FAILED; } switch(sa->sa_family) { #ifdef ENABLE_IPV6 case AF_INET6: Curl_inet_ntop(sa->sa_family, &sa6->sin6_addr, hbuf, sizeof(hbuf)); break; #endif default: Curl_inet_ntop(sa->sa_family, &sa4->sin_addr, hbuf, sizeof(hbuf)); break; } host = hbuf; /* use this host name */ possibly_non_local = FALSE; /* we know it is local now */ } /* resolv ip/host to ip */ rc = Curl_resolv(conn, host, 0, FALSE, &h); if(rc == CURLRESOLV_PENDING) (void)Curl_resolver_wait_resolv(conn, &h); if(h) { res = h->addr; /* when we return from this function, we can forget about this entry to we can unlock it now already */ Curl_resolv_unlock(data, h); } /* (h) */ else res = NULL; /* failure! */ if(res == NULL) { failf(data, "failed to resolve the address provided to PORT: %s", host); free(addr); return CURLE_FTP_PORT_FAILED; } free(addr); host = NULL; /* step 2, create a socket for the requested address */ portsock = CURL_SOCKET_BAD; error = 0; for(ai = res; ai; ai = ai->ai_next) { result = Curl_socket(conn, ai, NULL, &portsock); if(result) { error = SOCKERRNO; continue; } break; } if(!ai) { failf(data, "socket failure: %s", Curl_strerror(error, buffer, sizeof(buffer))); return CURLE_FTP_PORT_FAILED; } /* step 3, bind to a suitable local address */ memcpy(sa, ai->ai_addr, ai->ai_addrlen); sslen = ai->ai_addrlen; for(port = port_min; port <= port_max;) { if(sa->sa_family == AF_INET) sa4->sin_port = htons(port); #ifdef ENABLE_IPV6 else sa6->sin6_port = htons(port); #endif /* Try binding the given address. */ if(bind(portsock, sa, sslen) ) { /* It failed. */ error = SOCKERRNO; if(possibly_non_local && (error == EADDRNOTAVAIL)) { /* The requested bind address is not local. Use the address used for * the control connection instead and restart the port loop */ infof(data, "bind(port=%hu) on non-local address failed: %s\n", port, Curl_strerror(error, buffer, sizeof(buffer))); sslen = sizeof(ss); if(getsockname(conn->sock[FIRSTSOCKET], sa, &sslen)) { failf(data, "getsockname() failed: %s", Curl_strerror(SOCKERRNO, buffer, sizeof(buffer))); Curl_closesocket(conn, portsock); return CURLE_FTP_PORT_FAILED; } port = port_min; possibly_non_local = FALSE; /* don't try this again */ continue; } if(error != EADDRINUSE && error != EACCES) { failf(data, "bind(port=%hu) failed: %s", port, Curl_strerror(error, buffer, sizeof(buffer))); Curl_closesocket(conn, portsock); return CURLE_FTP_PORT_FAILED; } } else break; port++; } /* maybe all ports were in use already*/ if(port > port_max) { failf(data, "bind() failed, we ran out of ports!"); Curl_closesocket(conn, portsock); return CURLE_FTP_PORT_FAILED; } /* get the name again after the bind() so that we can extract the port number it uses now */ sslen = sizeof(ss); if(getsockname(portsock, (struct sockaddr *)sa, &sslen)) { failf(data, "getsockname() failed: %s", Curl_strerror(SOCKERRNO, buffer, sizeof(buffer))); Curl_closesocket(conn, portsock); return CURLE_FTP_PORT_FAILED; } /* step 4, listen on the socket */ if(listen(portsock, 1)) { failf(data, "socket failure: %s", Curl_strerror(SOCKERRNO, buffer, sizeof(buffer))); Curl_closesocket(conn, portsock); return CURLE_FTP_PORT_FAILED; } /* step 5, send the proper FTP command */ /* get a plain printable version of the numerical address to work with below */ Curl_printable_address(ai, myhost, sizeof(myhost)); #ifdef ENABLE_IPV6 if(!conn->bits.ftp_use_eprt && conn->bits.ipv6) /* EPRT is disabled but we are connected to a IPv6 host, so we ignore the request and enable EPRT again! */ conn->bits.ftp_use_eprt = TRUE; #endif for(; fcmd != DONE; fcmd++) { if(!conn->bits.ftp_use_eprt && (EPRT == fcmd)) /* if disabled, goto next */ continue; if((PORT == fcmd) && sa->sa_family != AF_INET) /* PORT is IPv4 only */ continue; switch(sa->sa_family) { case AF_INET: port = ntohs(sa4->sin_port); break; #ifdef ENABLE_IPV6 case AF_INET6: port = ntohs(sa6->sin6_port); break; #endif default: continue; /* might as well skip this */ } if(EPRT == fcmd) { /* * Two fine examples from RFC2428; * * EPRT |1|132.235.1.2|6275| * * EPRT |2|1080::8:800:200C:417A|5282| */ result = Curl_pp_sendf(&ftpc->pp, "%s |%d|%s|%hu|", mode[fcmd], sa->sa_family == AF_INET?1:2, myhost, port); if(result) { failf(data, "Failure sending EPRT command: %s", curl_easy_strerror(result)); Curl_closesocket(conn, portsock); /* don't retry using PORT */ ftpc->count1 = PORT; /* bail out */ state(conn, FTP_STOP); return result; } break; } if(PORT == fcmd) { char *source = myhost; char *dest = tmp; /* translate x.x.x.x to x,x,x,x */ while(source && *source) { if(*source == '.') *dest = ','; else *dest = *source; dest++; source++; } *dest = 0; msnprintf(dest, 20, ",%d,%d", (int)(port>>8), (int)(port&0xff)); result = Curl_pp_sendf(&ftpc->pp, "%s %s", mode[fcmd], tmp); if(result) { failf(data, "Failure sending PORT command: %s", curl_easy_strerror(result)); Curl_closesocket(conn, portsock); /* bail out */ state(conn, FTP_STOP); return result; } break; } } /* store which command was sent */ ftpc->count1 = fcmd; close_secondarysocket(conn); /* we set the secondary socket variable to this for now, it is only so that the cleanup function will close it in case we fail before the true secondary stuff is made */ conn->sock[SECONDARYSOCKET] = portsock; /* this tcpconnect assignment below is a hackish work-around to make the multi interface with active FTP work - as it will not wait for a (passive) connect in Curl_is_connected(). The *proper* fix is to make sure that the active connection from the server is done in a non-blocking way. Currently, it is still BLOCKING. */ conn->bits.tcpconnect[SECONDARYSOCKET] = TRUE; state(conn, FTP_PORT); return result; } static CURLcode ftp_state_use_pasv(struct connectdata *conn) { struct ftp_conn *ftpc = &conn->proto.ftpc; CURLcode result = CURLE_OK; /* Here's the excecutive summary on what to do: PASV is RFC959, expect: 227 Entering Passive Mode (a1,a2,a3,a4,p1,p2) LPSV is RFC1639, expect: 228 Entering Long Passive Mode (4,4,a1,a2,a3,a4,2,p1,p2) EPSV is RFC2428, expect: 229 Entering Extended Passive Mode (|||port|) */ static const char mode[][5] = { "EPSV", "PASV" }; int modeoff; #ifdef PF_INET6 if(!conn->bits.ftp_use_epsv && conn->bits.ipv6) /* EPSV is disabled but we are connected to a IPv6 host, so we ignore the request and enable EPSV again! */ conn->bits.ftp_use_epsv = TRUE; #endif modeoff = conn->bits.ftp_use_epsv?0:1; PPSENDF(&ftpc->pp, "%s", mode[modeoff]); ftpc->count1 = modeoff; state(conn, FTP_PASV); infof(conn->data, "Connect data stream passively\n"); return result; } /* * ftp_state_prepare_transfer() starts PORT, PASV or PRET etc. * * REST is the last command in the chain of commands when a "head"-like * request is made. Thus, if an actual transfer is to be made this is where we * take off for real. */ static CURLcode ftp_state_prepare_transfer(struct connectdata *conn) { CURLcode result = CURLE_OK; struct FTP *ftp = conn->data->req.protop; struct Curl_easy *data = conn->data; if(ftp->transfer != FTPTRANSFER_BODY) { /* doesn't transfer any data */ /* still possibly do PRE QUOTE jobs */ state(conn, FTP_RETR_PREQUOTE); result = ftp_state_quote(conn, TRUE, FTP_RETR_PREQUOTE); } else if(data->set.ftp_use_port) { /* We have chosen to use the PORT (or similar) command */ result = ftp_state_use_port(conn, EPRT); } else { /* We have chosen (this is default) to use the PASV (or similar) command */ if(data->set.ftp_use_pret) { /* The user has requested that we send a PRET command to prepare the server for the upcoming PASV */ if(!conn->proto.ftpc.file) { PPSENDF(&conn->proto.ftpc.pp, "PRET %s", data->set.str[STRING_CUSTOMREQUEST]? data->set.str[STRING_CUSTOMREQUEST]: (data->set.ftp_list_only?"NLST":"LIST")); } else if(data->set.upload) { PPSENDF(&conn->proto.ftpc.pp, "PRET STOR %s", conn->proto.ftpc.file); } else { PPSENDF(&conn->proto.ftpc.pp, "PRET RETR %s", conn->proto.ftpc.file); } state(conn, FTP_PRET); } else { result = ftp_state_use_pasv(conn); } } return result; } static CURLcode ftp_state_rest(struct connectdata *conn) { CURLcode result = CURLE_OK; struct FTP *ftp = conn->data->req.protop; struct ftp_conn *ftpc = &conn->proto.ftpc; if((ftp->transfer != FTPTRANSFER_BODY) && ftpc->file) { /* if a "head"-like request is being made (on a file) */ /* Determine if server can respond to REST command and therefore whether it supports range */ PPSENDF(&conn->proto.ftpc.pp, "REST %d", 0); state(conn, FTP_REST); } else result = ftp_state_prepare_transfer(conn); return result; } static CURLcode ftp_state_size(struct connectdata *conn) { CURLcode result = CURLE_OK; struct FTP *ftp = conn->data->req.protop; struct ftp_conn *ftpc = &conn->proto.ftpc; if((ftp->transfer == FTPTRANSFER_INFO) && ftpc->file) { /* if a "head"-like request is being made (on a file) */ /* we know ftpc->file is a valid pointer to a file name */ PPSENDF(&ftpc->pp, "SIZE %s", ftpc->file); state(conn, FTP_SIZE); } else result = ftp_state_rest(conn); return result; } static CURLcode ftp_state_list(struct connectdata *conn) { CURLcode result = CURLE_OK; struct Curl_easy *data = conn->data; struct FTP *ftp = data->req.protop; /* If this output is to be machine-parsed, the NLST command might be better to use, since the LIST command output is not specified or standard in any way. It has turned out that the NLST list output is not the same on all servers either... */ /* if FTPFILE_NOCWD was specified, we are currently in the user's home directory, so we should add the path as argument for the LIST / NLST / or custom command. Whether the server will support this, is uncertain. The other ftp_filemethods will CWD into dir/dir/ first and then just do LIST (in that case: nothing to do here) */ char *cmd, *lstArg, *slashPos; const char *inpath = ftp->path; lstArg = NULL; if((data->set.ftp_filemethod == FTPFILE_NOCWD) && inpath && inpath[0] && strchr(inpath, '/')) { size_t n = strlen(inpath); /* Check if path does not end with /, as then we cut off the file part */ if(inpath[n - 1] != '/') { /* chop off the file part if format is dir/dir/file */ slashPos = strrchr(inpath, '/'); n = slashPos - inpath; } result = Curl_urldecode(data, inpath, n, &lstArg, NULL, TRUE); if(result) return result; } cmd = aprintf("%s%s%s", data->set.str[STRING_CUSTOMREQUEST]? data->set.str[STRING_CUSTOMREQUEST]: (data->set.ftp_list_only?"NLST":"LIST"), lstArg? " ": "", lstArg? lstArg: ""); if(!cmd) { free(lstArg); return CURLE_OUT_OF_MEMORY; } result = Curl_pp_sendf(&conn->proto.ftpc.pp, "%s", cmd); free(lstArg); free(cmd); if(result) return result; state(conn, FTP_LIST); return result; } static CURLcode ftp_state_retr_prequote(struct connectdata *conn) { CURLcode result = CURLE_OK; /* We've sent the TYPE, now we must send the list of prequote strings */ result = ftp_state_quote(conn, TRUE, FTP_RETR_PREQUOTE); return result; } static CURLcode ftp_state_stor_prequote(struct connectdata *conn) { CURLcode result = CURLE_OK; /* We've sent the TYPE, now we must send the list of prequote strings */ result = ftp_state_quote(conn, TRUE, FTP_STOR_PREQUOTE); return result; } static CURLcode ftp_state_type(struct connectdata *conn) { CURLcode result = CURLE_OK; struct FTP *ftp = conn->data->req.protop; struct Curl_easy *data = conn->data; struct ftp_conn *ftpc = &conn->proto.ftpc; /* If we have selected NOBODY and HEADER, it means that we only want file information. Which in FTP can't be much more than the file size and date. */ if(data->set.opt_no_body && ftpc->file && ftp_need_type(conn, data->set.prefer_ascii)) { /* The SIZE command is _not_ RFC 959 specified, and therefore many servers may not support it! It is however the only way we have to get a file's size! */ ftp->transfer = FTPTRANSFER_INFO; /* this means no actual transfer will be made */ /* Some servers return different sizes for different modes, and thus we must set the proper type before we check the size */ result = ftp_nb_type(conn, data->set.prefer_ascii, FTP_TYPE); if(result) return result; } else result = ftp_state_size(conn); return result; } /* This is called after the CWD commands have been done in the beginning of the DO phase */ static CURLcode ftp_state_mdtm(struct connectdata *conn) { CURLcode result = CURLE_OK; struct Curl_easy *data = conn->data; struct ftp_conn *ftpc = &conn->proto.ftpc; /* Requested time of file or time-depended transfer? */ if((data->set.get_filetime || data->set.timecondition) && ftpc->file) { /* we have requested to get the modified-time of the file, this is a white spot as the MDTM is not mentioned in RFC959 */ PPSENDF(&ftpc->pp, "MDTM %s", ftpc->file); state(conn, FTP_MDTM); } else result = ftp_state_type(conn); return result; } /* This is called after the TYPE and possible quote commands have been sent */ static CURLcode ftp_state_ul_setup(struct connectdata *conn, bool sizechecked) { CURLcode result = CURLE_OK; struct FTP *ftp = conn->data->req.protop; struct Curl_easy *data = conn->data; struct ftp_conn *ftpc = &conn->proto.ftpc; if((data->state.resume_from && !sizechecked) || ((data->state.resume_from > 0) && sizechecked)) { /* we're about to continue the uploading of a file */ /* 1. get already existing file's size. We use the SIZE command for this which may not exist in the server! The SIZE command is not in RFC959. */ /* 2. This used to set REST. But since we can do append, we don't another ftp command. We just skip the source file offset and then we APPEND the rest on the file instead */ /* 3. pass file-size number of bytes in the source file */ /* 4. lower the infilesize counter */ /* => transfer as usual */ int seekerr = CURL_SEEKFUNC_OK; if(data->state.resume_from < 0) { /* Got no given size to start from, figure it out */ PPSENDF(&ftpc->pp, "SIZE %s", ftpc->file); state(conn, FTP_STOR_SIZE); return result; } /* enable append */ data->set.ftp_append = TRUE; /* Let's read off the proper amount of bytes from the input. */ if(conn->seek_func) { Curl_set_in_callback(data, true); seekerr = conn->seek_func(conn->seek_client, data->state.resume_from, SEEK_SET); Curl_set_in_callback(data, false); } if(seekerr != CURL_SEEKFUNC_OK) { curl_off_t passed = 0; if(seekerr != CURL_SEEKFUNC_CANTSEEK) { failf(data, "Could not seek stream"); return CURLE_FTP_COULDNT_USE_REST; } /* seekerr == CURL_SEEKFUNC_CANTSEEK (can't seek to offset) */ do { size_t readthisamountnow = (data->state.resume_from - passed > data->set.buffer_size) ? (size_t)data->set.buffer_size : curlx_sotouz(data->state.resume_from - passed); size_t actuallyread = data->state.fread_func(data->state.buffer, 1, readthisamountnow, data->state.in); passed += actuallyread; if((actuallyread == 0) || (actuallyread > readthisamountnow)) { /* this checks for greater-than only to make sure that the CURL_READFUNC_ABORT return code still aborts */ failf(data, "Failed to read data"); return CURLE_FTP_COULDNT_USE_REST; } } while(passed < data->state.resume_from); } /* now, decrease the size of the read */ if(data->state.infilesize>0) { data->state.infilesize -= data->state.resume_from; if(data->state.infilesize <= 0) { infof(data, "File already completely uploaded\n"); /* no data to transfer */ Curl_setup_transfer(data, -1, -1, FALSE, -1); /* Set ->transfer so that we won't get any error in * ftp_done() because we didn't transfer anything! */ ftp->transfer = FTPTRANSFER_NONE; state(conn, FTP_STOP); return CURLE_OK; } } /* we've passed, proceed as normal */ } /* resume_from */ PPSENDF(&ftpc->pp, data->set.ftp_append?"APPE %s":"STOR %s", ftpc->file); state(conn, FTP_STOR); return result; } static CURLcode ftp_state_quote(struct connectdata *conn, bool init, ftpstate instate) { CURLcode result = CURLE_OK; struct Curl_easy *data = conn->data; struct FTP *ftp = data->req.protop; struct ftp_conn *ftpc = &conn->proto.ftpc; bool quote = FALSE; struct curl_slist *item; switch(instate) { case FTP_QUOTE: default: item = data->set.quote; break; case FTP_RETR_PREQUOTE: case FTP_STOR_PREQUOTE: item = data->set.prequote; break; case FTP_POSTQUOTE: item = data->set.postquote; break; } /* * This state uses: * 'count1' to iterate over the commands to send * 'count2' to store whether to allow commands to fail */ if(init) ftpc->count1 = 0; else ftpc->count1++; if(item) { int i = 0; /* Skip count1 items in the linked list */ while((i< ftpc->count1) && item) { item = item->next; i++; } if(item) { char *cmd = item->data; if(cmd[0] == '*') { cmd++; ftpc->count2 = 1; /* the sent command is allowed to fail */ } else ftpc->count2 = 0; /* failure means cancel operation */ PPSENDF(&ftpc->pp, "%s", cmd); state(conn, instate); quote = TRUE; } } if(!quote) { /* No more quote to send, continue to ... */ switch(instate) { case FTP_QUOTE: default: result = ftp_state_cwd(conn); break; case FTP_RETR_PREQUOTE: if(ftp->transfer != FTPTRANSFER_BODY) state(conn, FTP_STOP); else { if(ftpc->known_filesize != -1) { Curl_pgrsSetDownloadSize(data, ftpc->known_filesize); result = ftp_state_retr(conn, ftpc->known_filesize); } else { if(data->set.ignorecl) { /* This code is to support download of growing files. It prevents the state machine from requesting the file size from the server. With an unknown file size the download continues until the server terminates it, otherwise the client stops if the received byte count exceeds the reported file size. Set option CURLOPT_IGNORE_CONTENT_LENGTH to 1 to enable this behavior.*/ PPSENDF(&ftpc->pp, "RETR %s", ftpc->file); state(conn, FTP_RETR); } else { PPSENDF(&ftpc->pp, "SIZE %s", ftpc->file); state(conn, FTP_RETR_SIZE); } } } break; case FTP_STOR_PREQUOTE: result = ftp_state_ul_setup(conn, FALSE); break; case FTP_POSTQUOTE: break; } } return result; } /* called from ftp_state_pasv_resp to switch to PASV in case of EPSV problems */ static CURLcode ftp_epsv_disable(struct connectdata *conn) { CURLcode result = CURLE_OK; if(conn->bits.ipv6 && !(conn->bits.tunnel_proxy || conn->bits.socksproxy)) { /* We can't disable EPSV when doing IPv6, so this is instead a fail */ failf(conn->data, "Failed EPSV attempt, exiting\n"); return CURLE_WEIRD_SERVER_REPLY; } infof(conn->data, "Failed EPSV attempt. Disabling EPSV\n"); /* disable it for next transfer */ conn->bits.ftp_use_epsv = FALSE; conn->data->state.errorbuf = FALSE; /* allow error message to get rewritten */ PPSENDF(&conn->proto.ftpc.pp, "%s", "PASV"); conn->proto.ftpc.count1++; /* remain in/go to the FTP_PASV state */ state(conn, FTP_PASV); return result; } static char *control_address(struct connectdata *conn) { /* Returns the control connection IP address. If a proxy tunnel is used, returns the original host name instead, because the effective control connection address is the proxy address, not the ftp host. */ if(conn->bits.tunnel_proxy || conn->bits.socksproxy) return conn->host.name; return conn->ip_addr_str; } static CURLcode ftp_state_pasv_resp(struct connectdata *conn, int ftpcode) { struct ftp_conn *ftpc = &conn->proto.ftpc; CURLcode result; struct Curl_easy *data = conn->data; struct Curl_dns_entry *addr = NULL; int rc; unsigned short connectport; /* the local port connect() should use! */ char *str = &data->state.buffer[4]; /* start on the first letter */ /* if we come here again, make sure the former name is cleared */ Curl_safefree(ftpc->newhost); if((ftpc->count1 == 0) && (ftpcode == 229)) { /* positive EPSV response */ char *ptr = strchr(str, '('); if(ptr) { unsigned int num; char separator[4]; ptr++; if(5 == sscanf(ptr, "%c%c%c%u%c", &separator[0], &separator[1], &separator[2], &num, &separator[3])) { const char sep1 = separator[0]; int i; /* The four separators should be identical, or else this is an oddly formatted reply and we bail out immediately. */ for(i = 1; i<4; i++) { if(separator[i] != sep1) { ptr = NULL; /* set to NULL to signal error */ break; } } if(num > 0xffff) { failf(data, "Illegal port number in EPSV reply"); return CURLE_FTP_WEIRD_PASV_REPLY; } if(ptr) { ftpc->newport = (unsigned short)(num & 0xffff); ftpc->newhost = strdup(control_address(conn)); if(!ftpc->newhost) return CURLE_OUT_OF_MEMORY; } } else ptr = NULL; } if(!ptr) { failf(data, "Weirdly formatted EPSV reply"); return CURLE_FTP_WEIRD_PASV_REPLY; } } else if((ftpc->count1 == 1) && (ftpcode == 227)) { /* positive PASV response */ unsigned int ip[4]; unsigned int port[2]; /* * Scan for a sequence of six comma-separated numbers and use them as * IP+port indicators. * * Found reply-strings include: * "227 Entering Passive Mode (127,0,0,1,4,51)" * "227 Data transfer will passively listen to 127,0,0,1,4,51" * "227 Entering passive mode. 127,0,0,1,4,51" */ while(*str) { if(6 == sscanf(str, "%u,%u,%u,%u,%u,%u", &ip[0], &ip[1], &ip[2], &ip[3], &port[0], &port[1])) break; str++; } if(!*str || (ip[0] > 255) || (ip[1] > 255) || (ip[2] > 255) || (ip[3] > 255) || (port[0] > 255) || (port[1] > 255) ) { failf(data, "Couldn't interpret the 227-response"); return CURLE_FTP_WEIRD_227_FORMAT; } /* we got OK from server */ if(data->set.ftp_skip_ip) { /* told to ignore the remotely given IP but instead use the host we used for the control connection */ infof(data, "Skip %u.%u.%u.%u for data connection, re-use %s instead\n", ip[0], ip[1], ip[2], ip[3], conn->host.name); ftpc->newhost = strdup(control_address(conn)); } else ftpc->newhost = aprintf("%u.%u.%u.%u", ip[0], ip[1], ip[2], ip[3]); if(!ftpc->newhost) return CURLE_OUT_OF_MEMORY; ftpc->newport = (unsigned short)(((port[0]<<8) + port[1]) & 0xffff); } else if(ftpc->count1 == 0) { /* EPSV failed, move on to PASV */ return ftp_epsv_disable(conn); } else { failf(data, "Bad PASV/EPSV response: %03d", ftpcode); return CURLE_FTP_WEIRD_PASV_REPLY; } if(conn->bits.proxy) { /* * This connection uses a proxy and we need to connect to the proxy again * here. We don't want to rely on a former host lookup that might've * expired now, instead we remake the lookup here and now! */ const char * const host_name = conn->bits.socksproxy ? conn->socks_proxy.host.name : conn->http_proxy.host.name; rc = Curl_resolv(conn, host_name, (int)conn->port, FALSE, &addr); if(rc == CURLRESOLV_PENDING) /* BLOCKING, ignores the return code but 'addr' will be NULL in case of failure */ (void)Curl_resolver_wait_resolv(conn, &addr); connectport = (unsigned short)conn->port; /* we connect to the proxy's port */ if(!addr) { failf(data, "Can't resolve proxy host %s:%hu", host_name, connectport); return CURLE_COULDNT_RESOLVE_PROXY; } } else { /* normal, direct, ftp connection */ rc = Curl_resolv(conn, ftpc->newhost, ftpc->newport, FALSE, &addr); if(rc == CURLRESOLV_PENDING) /* BLOCKING */ (void)Curl_resolver_wait_resolv(conn, &addr); connectport = ftpc->newport; /* we connect to the remote port */ if(!addr) { failf(data, "Can't resolve new host %s:%hu", ftpc->newhost, connectport); return CURLE_FTP_CANT_GET_HOST; } } conn->bits.tcpconnect[SECONDARYSOCKET] = FALSE; result = Curl_connecthost(conn, addr); if(result) { Curl_resolv_unlock(data, addr); /* we're done using this address */ if(ftpc->count1 == 0 && ftpcode == 229) return ftp_epsv_disable(conn); return result; } /* * When this is used from the multi interface, this might've returned with * the 'connected' set to FALSE and thus we are now awaiting a non-blocking * connect to connect. */ if(data->set.verbose) /* this just dumps information about this second connection */ ftp_pasv_verbose(conn, addr->addr, ftpc->newhost, connectport); Curl_resolv_unlock(data, addr); /* we're done using this address */ Curl_safefree(conn->secondaryhostname); conn->secondary_port = ftpc->newport; conn->secondaryhostname = strdup(ftpc->newhost); if(!conn->secondaryhostname) return CURLE_OUT_OF_MEMORY; conn->bits.do_more = TRUE; state(conn, FTP_STOP); /* this phase is completed */ return result; } static CURLcode ftp_state_port_resp(struct connectdata *conn, int ftpcode) { struct Curl_easy *data = conn->data; struct ftp_conn *ftpc = &conn->proto.ftpc; ftpport fcmd = (ftpport)ftpc->count1; CURLcode result = CURLE_OK; /* The FTP spec tells a positive response should have code 200. Be more permissive here to tolerate deviant servers. */ if(ftpcode / 100 != 2) { /* the command failed */ if(EPRT == fcmd) { infof(data, "disabling EPRT usage\n"); conn->bits.ftp_use_eprt = FALSE; } fcmd++; if(fcmd == DONE) { failf(data, "Failed to do PORT"); result = CURLE_FTP_PORT_FAILED; } else /* try next */ result = ftp_state_use_port(conn, fcmd); } else { infof(data, "Connect data stream actively\n"); state(conn, FTP_STOP); /* end of DO phase */ result = ftp_dophase_done(conn, FALSE); } return result; } static CURLcode ftp_state_mdtm_resp(struct connectdata *conn, int ftpcode) { CURLcode result = CURLE_OK; struct Curl_easy *data = conn->data; struct FTP *ftp = data->req.protop; struct ftp_conn *ftpc = &conn->proto.ftpc; switch(ftpcode) { case 213: { /* we got a time. Format should be: "YYYYMMDDHHMMSS[.sss]" where the last .sss part is optional and means fractions of a second */ int year, month, day, hour, minute, second; if(6 == sscanf(&data->state.buffer[4], "%04d%02d%02d%02d%02d%02d", &year, &month, &day, &hour, &minute, &second)) { /* we have a time, reformat it */ char timebuf[24]; time_t secs = time(NULL); msnprintf(timebuf, sizeof(timebuf), "%04d%02d%02d %02d:%02d:%02d GMT", year, month, day, hour, minute, second); /* now, convert this into a time() value: */ data->info.filetime = curl_getdate(timebuf, &secs); } #ifdef CURL_FTP_HTTPSTYLE_HEAD /* If we asked for a time of the file and we actually got one as well, we "emulate" a HTTP-style header in our output. */ if(data->set.opt_no_body && ftpc->file && data->set.get_filetime && (data->info.filetime >= 0) ) { char headerbuf[128]; time_t filetime = data->info.filetime; struct tm buffer; const struct tm *tm = &buffer; result = Curl_gmtime(filetime, &buffer); if(result) return result; /* format: "Tue, 15 Nov 1994 12:45:26" */ msnprintf(headerbuf, sizeof(headerbuf), "Last-Modified: %s, %02d %s %4d %02d:%02d:%02d GMT\r\n", Curl_wkday[tm->tm_wday?tm->tm_wday-1:6], tm->tm_mday, Curl_month[tm->tm_mon], tm->tm_year + 1900, tm->tm_hour, tm->tm_min, tm->tm_sec); result = Curl_client_write(conn, CLIENTWRITE_BOTH, headerbuf, 0); if(result) return result; } /* end of a ridiculous amount of conditionals */ #endif } break; default: infof(data, "unsupported MDTM reply format\n"); break; case 550: /* "No such file or directory" */ failf(data, "Given file does not exist"); result = CURLE_FTP_COULDNT_RETR_FILE; break; } if(data->set.timecondition) { if((data->info.filetime > 0) && (data->set.timevalue > 0)) { switch(data->set.timecondition) { case CURL_TIMECOND_IFMODSINCE: default: if(data->info.filetime <= data->set.timevalue) { infof(data, "The requested document is not new enough\n"); ftp->transfer = FTPTRANSFER_NONE; /* mark to not transfer data */ data->info.timecond = TRUE; state(conn, FTP_STOP); return CURLE_OK; } break; case CURL_TIMECOND_IFUNMODSINCE: if(data->info.filetime > data->set.timevalue) { infof(data, "The requested document is not old enough\n"); ftp->transfer = FTPTRANSFER_NONE; /* mark to not transfer data */ data->info.timecond = TRUE; state(conn, FTP_STOP); return CURLE_OK; } break; } /* switch */ } else { infof(data, "Skipping time comparison\n"); } } if(!result) result = ftp_state_type(conn); return result; } static CURLcode ftp_state_type_resp(struct connectdata *conn, int ftpcode, ftpstate instate) { CURLcode result = CURLE_OK; struct Curl_easy *data = conn->data; if(ftpcode/100 != 2) { /* "sasserftpd" and "(u)r(x)bot ftpd" both responds with 226 after a successful 'TYPE I'. While that is not as RFC959 says, it is still a positive response code and we allow that. */ failf(data, "Couldn't set desired mode"); return CURLE_FTP_COULDNT_SET_TYPE; } if(ftpcode != 200) infof(data, "Got a %03d response code instead of the assumed 200\n", ftpcode); if(instate == FTP_TYPE) result = ftp_state_size(conn); else if(instate == FTP_LIST_TYPE) result = ftp_state_list(conn); else if(instate == FTP_RETR_TYPE) result = ftp_state_retr_prequote(conn); else if(instate == FTP_STOR_TYPE) result = ftp_state_stor_prequote(conn); return result; } static CURLcode ftp_state_retr(struct connectdata *conn, curl_off_t filesize) { CURLcode result = CURLE_OK; struct Curl_easy *data = conn->data; struct FTP *ftp = data->req.protop; struct ftp_conn *ftpc = &conn->proto.ftpc; if(data->set.max_filesize && (filesize > data->set.max_filesize)) { failf(data, "Maximum file size exceeded"); return CURLE_FILESIZE_EXCEEDED; } ftp->downloadsize = filesize; if(data->state.resume_from) { /* We always (attempt to) get the size of downloads, so it is done before this even when not doing resumes. */ if(filesize == -1) { infof(data, "ftp server doesn't support SIZE\n"); /* We couldn't get the size and therefore we can't know if there really is a part of the file left to get, although the server will just close the connection when we start the connection so it won't cause us any harm, just not make us exit as nicely. */ } else { /* We got a file size report, so we check that there actually is a part of the file left to get, or else we go home. */ if(data->state.resume_from< 0) { /* We're supposed to download the last abs(from) bytes */ if(filesize < -data->state.resume_from) { failf(data, "Offset (%" CURL_FORMAT_CURL_OFF_T ") was beyond file size (%" CURL_FORMAT_CURL_OFF_T ")", data->state.resume_from, filesize); return CURLE_BAD_DOWNLOAD_RESUME; } /* convert to size to download */ ftp->downloadsize = -data->state.resume_from; /* download from where? */ data->state.resume_from = filesize - ftp->downloadsize; } else { if(filesize < data->state.resume_from) { failf(data, "Offset (%" CURL_FORMAT_CURL_OFF_T ") was beyond file size (%" CURL_FORMAT_CURL_OFF_T ")", data->state.resume_from, filesize); return CURLE_BAD_DOWNLOAD_RESUME; } /* Now store the number of bytes we are expected to download */ ftp->downloadsize = filesize-data->state.resume_from; } } if(ftp->downloadsize == 0) { /* no data to transfer */ Curl_setup_transfer(data, -1, -1, FALSE, -1); infof(data, "File already completely downloaded\n"); /* Set ->transfer so that we won't get any error in ftp_done() * because we didn't transfer the any file */ ftp->transfer = FTPTRANSFER_NONE; state(conn, FTP_STOP); return CURLE_OK; } /* Set resume file transfer offset */ infof(data, "Instructs server to resume from offset %" CURL_FORMAT_CURL_OFF_T "\n", data->state.resume_from); PPSENDF(&ftpc->pp, "REST %" CURL_FORMAT_CURL_OFF_T, data->state.resume_from); state(conn, FTP_RETR_REST); } else { /* no resume */ PPSENDF(&ftpc->pp, "RETR %s", ftpc->file); state(conn, FTP_RETR); } return result; } static CURLcode ftp_state_size_resp(struct connectdata *conn, int ftpcode, ftpstate instate) { CURLcode result = CURLE_OK; struct Curl_easy *data = conn->data; curl_off_t filesize = -1; char *buf = data->state.buffer; /* get the size from the ascii string: */ if(ftpcode == 213) /* ignores parsing errors, which will make the size remain unknown */ (void)curlx_strtoofft(buf + 4, NULL, 0, &filesize); if(instate == FTP_SIZE) { #ifdef CURL_FTP_HTTPSTYLE_HEAD if(-1 != filesize) { char clbuf[128]; msnprintf(clbuf, sizeof(clbuf), "Content-Length: %" CURL_FORMAT_CURL_OFF_T "\r\n", filesize); result = Curl_client_write(conn, CLIENTWRITE_BOTH, clbuf, 0); if(result) return result; } #endif Curl_pgrsSetDownloadSize(data, filesize); result = ftp_state_rest(conn); } else if(instate == FTP_RETR_SIZE) { Curl_pgrsSetDownloadSize(data, filesize); result = ftp_state_retr(conn, filesize); } else if(instate == FTP_STOR_SIZE) { data->state.resume_from = filesize; result = ftp_state_ul_setup(conn, TRUE); } return result; } static CURLcode ftp_state_rest_resp(struct connectdata *conn, int ftpcode, ftpstate instate) { CURLcode result = CURLE_OK; struct ftp_conn *ftpc = &conn->proto.ftpc; switch(instate) { case FTP_REST: default: #ifdef CURL_FTP_HTTPSTYLE_HEAD if(ftpcode == 350) { char buffer[24]= { "Accept-ranges: bytes\r\n" }; result = Curl_client_write(conn, CLIENTWRITE_BOTH, buffer, 0); if(result) return result; } #endif result = ftp_state_prepare_transfer(conn); break; case FTP_RETR_REST: if(ftpcode != 350) { failf(conn->data, "Couldn't use REST"); result = CURLE_FTP_COULDNT_USE_REST; } else { PPSENDF(&ftpc->pp, "RETR %s", ftpc->file); state(conn, FTP_RETR); } break; } return result; } static CURLcode ftp_state_stor_resp(struct connectdata *conn, int ftpcode, ftpstate instate) { CURLcode result = CURLE_OK; struct Curl_easy *data = conn->data; if(ftpcode >= 400) { failf(data, "Failed FTP upload: %0d", ftpcode); state(conn, FTP_STOP); /* oops, we never close the sockets! */ return CURLE_UPLOAD_FAILED; } conn->proto.ftpc.state_saved = instate; /* PORT means we are now awaiting the server to connect to us. */ if(data->set.ftp_use_port) { bool connected; state(conn, FTP_STOP); /* no longer in STOR state */ result = AllowServerConnect(conn, &connected); if(result) return result; if(!connected) { struct ftp_conn *ftpc = &conn->proto.ftpc; infof(data, "Data conn was not available immediately\n"); ftpc->wait_data_conn = TRUE; } return CURLE_OK; } return InitiateTransfer(conn); } /* for LIST and RETR responses */ static CURLcode ftp_state_get_resp(struct connectdata *conn, int ftpcode, ftpstate instate) { CURLcode result = CURLE_OK; struct Curl_easy *data = conn->data; struct FTP *ftp = data->req.protop; if((ftpcode == 150) || (ftpcode == 125)) { /* A; 150 Opening BINARY mode data connection for /etc/passwd (2241 bytes). (ok, the file is being transferred) B: 150 Opening ASCII mode data connection for /bin/ls C: 150 ASCII data connection for /bin/ls (137.167.104.91,37445) (0 bytes). D: 150 Opening ASCII mode data connection for [file] (0.0.0.0,0) (545 bytes) E: 125 Data connection already open; Transfer starting. */ curl_off_t size = -1; /* default unknown size */ /* * It appears that there are FTP-servers that return size 0 for files when * SIZE is used on the file while being in BINARY mode. To work around * that (stupid) behavior, we attempt to parse the RETR response even if * the SIZE returned size zero. * * Debugging help from Salvatore Sorrentino on February 26, 2003. */ if((instate != FTP_LIST) && !data->set.prefer_ascii && (ftp->downloadsize < 1)) { /* * It seems directory listings either don't show the size or very * often uses size 0 anyway. ASCII transfers may very well turn out * that the transferred amount of data is not the same as this line * tells, why using this number in those cases only confuses us. * * Example D above makes this parsing a little tricky */ char *bytes; char *buf = data->state.buffer; bytes = strstr(buf, " bytes"); if(bytes) { long in = (long)(--bytes-buf); /* this is a hint there is size information in there! ;-) */ while(--in) { /* scan for the left parenthesis and break there */ if('(' == *bytes) break; /* skip only digits */ if(!ISDIGIT(*bytes)) { bytes = NULL; break; } /* one more estep backwards */ bytes--; } /* if we have nothing but digits: */ if(bytes++) { /* get the number! */ (void)curlx_strtoofft(bytes, NULL, 0, &size); } } } else if(ftp->downloadsize > -1) size = ftp->downloadsize; if(size > data->req.maxdownload && data->req.maxdownload > 0) size = data->req.size = data->req.maxdownload; else if((instate != FTP_LIST) && (data->set.prefer_ascii)) size = -1; /* kludge for servers that understate ASCII mode file size */ infof(data, "Maxdownload = %" CURL_FORMAT_CURL_OFF_T "\n", data->req.maxdownload); if(instate != FTP_LIST) infof(data, "Getting file with size: %" CURL_FORMAT_CURL_OFF_T "\n", size); /* FTP download: */ conn->proto.ftpc.state_saved = instate; conn->proto.ftpc.retr_size_saved = size; if(data->set.ftp_use_port) { bool connected; result = AllowServerConnect(conn, &connected); if(result) return result; if(!connected) { struct ftp_conn *ftpc = &conn->proto.ftpc; infof(data, "Data conn was not available immediately\n"); state(conn, FTP_STOP); ftpc->wait_data_conn = TRUE; } } else return InitiateTransfer(conn); } else { if((instate == FTP_LIST) && (ftpcode == 450)) { /* simply no matching files in the dir listing */ ftp->transfer = FTPTRANSFER_NONE; /* don't download anything */ state(conn, FTP_STOP); /* this phase is over */ } else { failf(data, "RETR response: %03d", ftpcode); return instate == FTP_RETR && ftpcode == 550? CURLE_REMOTE_FILE_NOT_FOUND: CURLE_FTP_COULDNT_RETR_FILE; } } return result; } /* after USER, PASS and ACCT */ static CURLcode ftp_state_loggedin(struct connectdata *conn) { CURLcode result = CURLE_OK; if(conn->ssl[FIRSTSOCKET].use) { /* PBSZ = PROTECTION BUFFER SIZE. The 'draft-murray-auth-ftp-ssl' (draft 12, page 7) says: Specifically, the PROT command MUST be preceded by a PBSZ command and a PBSZ command MUST be preceded by a successful security data exchange (the TLS negotiation in this case) ... (and on page 8): Thus the PBSZ command must still be issued, but must have a parameter of '0' to indicate that no buffering is taking place and the data connection should not be encapsulated. */ PPSENDF(&conn->proto.ftpc.pp, "PBSZ %d", 0); state(conn, FTP_PBSZ); } else { result = ftp_state_pwd(conn); } return result; } /* for USER and PASS responses */ static CURLcode ftp_state_user_resp(struct connectdata *conn, int ftpcode, ftpstate instate) { CURLcode result = CURLE_OK; struct Curl_easy *data = conn->data; struct FTP *ftp = data->req.protop; struct ftp_conn *ftpc = &conn->proto.ftpc; (void)instate; /* no use for this yet */ /* some need password anyway, and others just return 2xx ignored */ if((ftpcode == 331) && (ftpc->state == FTP_USER)) { /* 331 Password required for ... (the server requires to send the user's password too) */ PPSENDF(&ftpc->pp, "PASS %s", ftp->passwd?ftp->passwd:""); state(conn, FTP_PASS); } else if(ftpcode/100 == 2) { /* 230 User ... logged in. (the user logged in with or without password) */ result = ftp_state_loggedin(conn); } else if(ftpcode == 332) { if(data->set.str[STRING_FTP_ACCOUNT]) { PPSENDF(&ftpc->pp, "ACCT %s", data->set.str[STRING_FTP_ACCOUNT]); state(conn, FTP_ACCT); } else { failf(data, "ACCT requested but none available"); result = CURLE_LOGIN_DENIED; } } else { /* All other response codes, like: 530 User ... access denied (the server denies to log the specified user) */ if(conn->data->set.str[STRING_FTP_ALTERNATIVE_TO_USER] && !conn->data->state.ftp_trying_alternative) { /* Ok, USER failed. Let's try the supplied command. */ PPSENDF(&conn->proto.ftpc.pp, "%s", conn->data->set.str[STRING_FTP_ALTERNATIVE_TO_USER]); conn->data->state.ftp_trying_alternative = TRUE; state(conn, FTP_USER); result = CURLE_OK; } else { failf(data, "Access denied: %03d", ftpcode); result = CURLE_LOGIN_DENIED; } } return result; } /* for ACCT response */ static CURLcode ftp_state_acct_resp(struct connectdata *conn, int ftpcode) { CURLcode result = CURLE_OK; struct Curl_easy *data = conn->data; if(ftpcode != 230) { failf(data, "ACCT rejected by server: %03d", ftpcode); result = CURLE_FTP_WEIRD_PASS_REPLY; /* FIX */ } else result = ftp_state_loggedin(conn); return result; } static CURLcode ftp_statemach_act(struct connectdata *conn) { CURLcode result; curl_socket_t sock = conn->sock[FIRSTSOCKET]; struct Curl_easy *data = conn->data; int ftpcode; struct ftp_conn *ftpc = &conn->proto.ftpc; struct pingpong *pp = &ftpc->pp; static const char ftpauth[][4] = { "SSL", "TLS" }; size_t nread = 0; if(pp->sendleft) return Curl_pp_flushsend(pp); result = ftp_readresp(sock, pp, &ftpcode, &nread); if(result) return result; if(ftpcode) { /* we have now received a full FTP server response */ switch(ftpc->state) { case FTP_WAIT220: if(ftpcode == 230) /* 230 User logged in - already! */ return ftp_state_user_resp(conn, ftpcode, ftpc->state); else if(ftpcode != 220) { failf(data, "Got a %03d ftp-server response when 220 was expected", ftpcode); return CURLE_WEIRD_SERVER_REPLY; } /* We have received a 220 response fine, now we proceed. */ #ifdef HAVE_GSSAPI if(data->set.krb) { /* If not anonymous login, try a secure login. Note that this procedure is still BLOCKING. */ Curl_sec_request_prot(conn, "private"); /* We set private first as default, in case the line below fails to set a valid level */ Curl_sec_request_prot(conn, data->set.str[STRING_KRB_LEVEL]); if(Curl_sec_login(conn)) infof(data, "Logging in with password in cleartext!\n"); else infof(data, "Authentication successful\n"); } #endif if(data->set.use_ssl && (!conn->ssl[FIRSTSOCKET].use || (conn->bits.proxy_ssl_connected[FIRSTSOCKET] && !conn->proxy_ssl[FIRSTSOCKET].use))) { /* We don't have a SSL/TLS connection yet, but FTPS is requested. Try a FTPS connection now */ ftpc->count3 = 0; switch(data->set.ftpsslauth) { case CURLFTPAUTH_DEFAULT: case CURLFTPAUTH_SSL: ftpc->count2 = 1; /* add one to get next */ ftpc->count1 = 0; break; case CURLFTPAUTH_TLS: ftpc->count2 = -1; /* subtract one to get next */ ftpc->count1 = 1; break; default: failf(data, "unsupported parameter to CURLOPT_FTPSSLAUTH: %d", (int)data->set.ftpsslauth); return CURLE_UNKNOWN_OPTION; /* we don't know what to do */ } PPSENDF(&ftpc->pp, "AUTH %s", ftpauth[ftpc->count1]); state(conn, FTP_AUTH); } else { result = ftp_state_user(conn); if(result) return result; } break; case FTP_AUTH: /* we have gotten the response to a previous AUTH command */ /* RFC2228 (page 5) says: * * If the server is willing to accept the named security mechanism, * and does not require any security data, it must respond with * reply code 234/334. */ if((ftpcode == 234) || (ftpcode == 334)) { /* Curl_ssl_connect is BLOCKING */ result = Curl_ssl_connect(conn, FIRSTSOCKET); if(!result) { conn->bits.ftp_use_data_ssl = FALSE; /* clear-text data */ result = ftp_state_user(conn); } } else if(ftpc->count3 < 1) { ftpc->count3++; ftpc->count1 += ftpc->count2; /* get next attempt */ result = Curl_pp_sendf(&ftpc->pp, "AUTH %s", ftpauth[ftpc->count1]); /* remain in this same state */ } else { if(data->set.use_ssl > CURLUSESSL_TRY) /* we failed and CURLUSESSL_CONTROL or CURLUSESSL_ALL is set */ result = CURLE_USE_SSL_FAILED; else /* ignore the failure and continue */ result = ftp_state_user(conn); } if(result) return result; break; case FTP_USER: case FTP_PASS: result = ftp_state_user_resp(conn, ftpcode, ftpc->state); break; case FTP_ACCT: result = ftp_state_acct_resp(conn, ftpcode); break; case FTP_PBSZ: PPSENDF(&ftpc->pp, "PROT %c", data->set.use_ssl == CURLUSESSL_CONTROL ? 'C' : 'P'); state(conn, FTP_PROT); break; case FTP_PROT: if(ftpcode/100 == 2) /* We have enabled SSL for the data connection! */ conn->bits.ftp_use_data_ssl = (data->set.use_ssl != CURLUSESSL_CONTROL) ? TRUE : FALSE; /* FTP servers typically responds with 500 if they decide to reject our 'P' request */ else if(data->set.use_ssl > CURLUSESSL_CONTROL) /* we failed and bails out */ return CURLE_USE_SSL_FAILED; if(data->set.ftp_ccc) { /* CCC - Clear Command Channel */ PPSENDF(&ftpc->pp, "%s", "CCC"); state(conn, FTP_CCC); } else { result = ftp_state_pwd(conn); if(result) return result; } break; case FTP_CCC: if(ftpcode < 500) { /* First shut down the SSL layer (note: this call will block) */ result = Curl_ssl_shutdown(conn, FIRSTSOCKET); if(result) { failf(conn->data, "Failed to clear the command channel (CCC)"); return result; } } /* Then continue as normal */ result = ftp_state_pwd(conn); if(result) return result; break; case FTP_PWD: if(ftpcode == 257) { char *ptr = &data->state.buffer[4]; /* start on the first letter */ const size_t buf_size = data->set.buffer_size; char *dir; bool entry_extracted = FALSE; dir = malloc(nread + 1); if(!dir) return CURLE_OUT_OF_MEMORY; /* Reply format is like 257<space>[rubbish]"<directory-name>"<space><commentary> and the RFC959 says The directory name can contain any character; embedded double-quotes should be escaped by double-quotes (the "quote-doubling" convention). */ /* scan for the first double-quote for non-standard responses */ while(ptr < &data->state.buffer[buf_size] && *ptr != '\n' && *ptr != '\0' && *ptr != '"') ptr++; if('\"' == *ptr) { /* it started good */ char *store; ptr++; for(store = dir; *ptr;) { if('\"' == *ptr) { if('\"' == ptr[1]) { /* "quote-doubling" */ *store = ptr[1]; ptr++; } else { /* end of path */ entry_extracted = TRUE; break; /* get out of this loop */ } } else *store = *ptr; store++; ptr++; } *store = '\0'; /* zero terminate */ } if(entry_extracted) { /* If the path name does not look like an absolute path (i.e.: it does not start with a '/'), we probably need some server-dependent adjustments. For example, this is the case when connecting to an OS400 FTP server: this server supports two name syntaxes, the default one being incompatible with standard paths. In addition, this server switches automatically to the regular path syntax when one is encountered in a command: this results in having an entrypath in the wrong syntax when later used in CWD. The method used here is to check the server OS: we do it only if the path name looks strange to minimize overhead on other systems. */ if(!ftpc->server_os && dir[0] != '/') { result = Curl_pp_sendf(&ftpc->pp, "%s", "SYST"); if(result) { free(dir); return result; } Curl_safefree(ftpc->entrypath); ftpc->entrypath = dir; /* remember this */ infof(data, "Entry path is '%s'\n", ftpc->entrypath); /* also save it where getinfo can access it: */ data->state.most_recent_ftp_entrypath = ftpc->entrypath; state(conn, FTP_SYST); break; } Curl_safefree(ftpc->entrypath); ftpc->entrypath = dir; /* remember this */ infof(data, "Entry path is '%s'\n", ftpc->entrypath); /* also save it where getinfo can access it: */ data->state.most_recent_ftp_entrypath = ftpc->entrypath; } else { /* couldn't get the path */ free(dir); infof(data, "Failed to figure out path\n"); } } state(conn, FTP_STOP); /* we are done with the CONNECT phase! */ DEBUGF(infof(data, "protocol connect phase DONE\n")); break; case FTP_SYST: if(ftpcode == 215) { char *ptr = &data->state.buffer[4]; /* start on the first letter */ char *os; char *store; os = malloc(nread + 1); if(!os) return CURLE_OUT_OF_MEMORY; /* Reply format is like 215<space><OS-name><space><commentary> */ while(*ptr == ' ') ptr++; for(store = os; *ptr && *ptr != ' ';) *store++ = *ptr++; *store = '\0'; /* zero terminate */ /* Check for special servers here. */ if(strcasecompare(os, "OS/400")) { /* Force OS400 name format 1. */ result = Curl_pp_sendf(&ftpc->pp, "%s", "SITE NAMEFMT 1"); if(result) { free(os); return result; } /* remember target server OS */ Curl_safefree(ftpc->server_os); ftpc->server_os = os; state(conn, FTP_NAMEFMT); break; } /* Nothing special for the target server. */ /* remember target server OS */ Curl_safefree(ftpc->server_os); ftpc->server_os = os; } else { /* Cannot identify server OS. Continue anyway and cross fingers. */ } state(conn, FTP_STOP); /* we are done with the CONNECT phase! */ DEBUGF(infof(data, "protocol connect phase DONE\n")); break; case FTP_NAMEFMT: if(ftpcode == 250) { /* Name format change successful: reload initial path. */ ftp_state_pwd(conn); break; } state(conn, FTP_STOP); /* we are done with the CONNECT phase! */ DEBUGF(infof(data, "protocol connect phase DONE\n")); break; case FTP_QUOTE: case FTP_POSTQUOTE: case FTP_RETR_PREQUOTE: case FTP_STOR_PREQUOTE: if((ftpcode >= 400) && !ftpc->count2) { /* failure response code, and not allowed to fail */ failf(conn->data, "QUOT command failed with %03d", ftpcode); return CURLE_QUOTE_ERROR; } result = ftp_state_quote(conn, FALSE, ftpc->state); if(result) return result; break; case FTP_CWD: if(ftpcode/100 != 2) { /* failure to CWD there */ if(conn->data->set.ftp_create_missing_dirs && ftpc->cwdcount && !ftpc->count2) { /* try making it */ ftpc->count2++; /* counter to prevent CWD-MKD loops */ PPSENDF(&ftpc->pp, "MKD %s", ftpc->dirs[ftpc->cwdcount - 1]); state(conn, FTP_MKD); } else { /* return failure */ failf(data, "Server denied you to change to the given directory"); ftpc->cwdfail = TRUE; /* don't remember this path as we failed to enter it */ return CURLE_REMOTE_ACCESS_DENIED; } } else { /* success */ ftpc->count2 = 0; if(++ftpc->cwdcount <= ftpc->dirdepth) { /* send next CWD */ PPSENDF(&ftpc->pp, "CWD %s", ftpc->dirs[ftpc->cwdcount - 1]); } else { result = ftp_state_mdtm(conn); if(result) return result; } } break; case FTP_MKD: if((ftpcode/100 != 2) && !ftpc->count3--) { /* failure to MKD the dir */ failf(data, "Failed to MKD dir: %03d", ftpcode); return CURLE_REMOTE_ACCESS_DENIED; } state(conn, FTP_CWD); /* send CWD */ PPSENDF(&ftpc->pp, "CWD %s", ftpc->dirs[ftpc->cwdcount - 1]); break; case FTP_MDTM: result = ftp_state_mdtm_resp(conn, ftpcode); break; case FTP_TYPE: case FTP_LIST_TYPE: case FTP_RETR_TYPE: case FTP_STOR_TYPE: result = ftp_state_type_resp(conn, ftpcode, ftpc->state); break; case FTP_SIZE: case FTP_RETR_SIZE: case FTP_STOR_SIZE: result = ftp_state_size_resp(conn, ftpcode, ftpc->state); break; case FTP_REST: case FTP_RETR_REST: result = ftp_state_rest_resp(conn, ftpcode, ftpc->state); break; case FTP_PRET: if(ftpcode != 200) { /* there only is this one standard OK return code. */ failf(data, "PRET command not accepted: %03d", ftpcode); return CURLE_FTP_PRET_FAILED; } result = ftp_state_use_pasv(conn); break; case FTP_PASV: result = ftp_state_pasv_resp(conn, ftpcode); break; case FTP_PORT: result = ftp_state_port_resp(conn, ftpcode); break; case FTP_LIST: case FTP_RETR: result = ftp_state_get_resp(conn, ftpcode, ftpc->state); break; case FTP_STOR: result = ftp_state_stor_resp(conn, ftpcode, ftpc->state); break; case FTP_QUIT: /* fallthrough, just stop! */ default: /* internal error */ state(conn, FTP_STOP); break; } } /* if(ftpcode) */ return result; } /* called repeatedly until done from multi.c */ static CURLcode ftp_multi_statemach(struct connectdata *conn, bool *done) { struct ftp_conn *ftpc = &conn->proto.ftpc; CURLcode result = Curl_pp_statemach(&ftpc->pp, FALSE, FALSE); /* Check for the state outside of the Curl_socket_check() return code checks since at times we are in fact already in this state when this function gets called. */ *done = (ftpc->state == FTP_STOP) ? TRUE : FALSE; return result; } static CURLcode ftp_block_statemach(struct connectdata *conn) { struct ftp_conn *ftpc = &conn->proto.ftpc; struct pingpong *pp = &ftpc->pp; CURLcode result = CURLE_OK; while(ftpc->state != FTP_STOP) { result = Curl_pp_statemach(pp, TRUE, TRUE /* disconnecting */); if(result) break; } return result; } /* * ftp_connect() should do everything that is to be considered a part of * the connection phase. * * The variable 'done' points to will be TRUE if the protocol-layer connect * phase is done when this function returns, or FALSE if not. * */ static CURLcode ftp_connect(struct connectdata *conn, bool *done) /* see description above */ { CURLcode result; struct ftp_conn *ftpc = &conn->proto.ftpc; struct pingpong *pp = &ftpc->pp; *done = FALSE; /* default to not done yet */ /* We always support persistent connections on ftp */ connkeep(conn, "FTP default"); pp->response_time = RESP_TIMEOUT; /* set default response time-out */ pp->statemach_act = ftp_statemach_act; pp->endofresp = ftp_endofresp; pp->conn = conn; if(conn->handler->flags & PROTOPT_SSL) { /* BLOCKING */ result = Curl_ssl_connect(conn, FIRSTSOCKET); if(result) return result; } Curl_pp_init(pp); /* init the generic pingpong data */ /* When we connect, we start in the state where we await the 220 response */ state(conn, FTP_WAIT220); result = ftp_multi_statemach(conn, done); return result; } /*********************************************************************** * * ftp_done() * * The DONE function. This does what needs to be done after a single DO has * performed. * * Input argument is already checked for validity. */ static CURLcode ftp_done(struct connectdata *conn, CURLcode status, bool premature) { struct Curl_easy *data = conn->data; struct FTP *ftp = data->req.protop; struct ftp_conn *ftpc = &conn->proto.ftpc; struct pingpong *pp = &ftpc->pp; ssize_t nread; int ftpcode; CURLcode result = CURLE_OK; char *path = NULL; if(!ftp) return CURLE_OK; switch(status) { case CURLE_BAD_DOWNLOAD_RESUME: case CURLE_FTP_WEIRD_PASV_REPLY: case CURLE_FTP_PORT_FAILED: case CURLE_FTP_ACCEPT_FAILED: case CURLE_FTP_ACCEPT_TIMEOUT: case CURLE_FTP_COULDNT_SET_TYPE: case CURLE_FTP_COULDNT_RETR_FILE: case CURLE_PARTIAL_FILE: case CURLE_UPLOAD_FAILED: case CURLE_REMOTE_ACCESS_DENIED: case CURLE_FILESIZE_EXCEEDED: case CURLE_REMOTE_FILE_NOT_FOUND: case CURLE_WRITE_ERROR: /* the connection stays alive fine even though this happened */ /* fall-through */ case CURLE_OK: /* doesn't affect the control connection's status */ if(!premature) break; /* until we cope better with prematurely ended requests, let them * fallback as if in complete failure */ /* FALLTHROUGH */ default: /* by default, an error means the control connection is wedged and should not be used anymore */ ftpc->ctl_valid = FALSE; ftpc->cwdfail = TRUE; /* set this TRUE to prevent us to remember the current path, as this connection is going */ connclose(conn, "FTP ended with bad error code"); result = status; /* use the already set error code */ break; } /* now store a copy of the directory we are in */ free(ftpc->prevpath); if(data->state.wildcardmatch) { if(data->set.chunk_end && ftpc->file) { Curl_set_in_callback(data, true); data->set.chunk_end(data->wildcard.customptr); Curl_set_in_callback(data, false); } ftpc->known_filesize = -1; } if(!result) /* get the "raw" path */ result = Curl_urldecode(data, ftp->path, 0, &path, NULL, TRUE); if(result) { /* We can limp along anyway (and should try to since we may already be in * the error path) */ ftpc->ctl_valid = FALSE; /* mark control connection as bad */ connclose(conn, "FTP: out of memory!"); /* mark for connection closure */ ftpc->prevpath = NULL; /* no path remembering */ } else { size_t flen = ftpc->file?strlen(ftpc->file):0; /* file is "raw" already */ size_t dlen = strlen(path)-flen; if(!ftpc->cwdfail) { ftpc->prevmethod = data->set.ftp_filemethod; if(dlen && (data->set.ftp_filemethod != FTPFILE_NOCWD)) { ftpc->prevpath = path; if(flen) /* if 'path' is not the whole string */ ftpc->prevpath[dlen] = 0; /* terminate */ } else { free(path); /* we never changed dir */ ftpc->prevpath = strdup(""); if(!ftpc->prevpath) return CURLE_OUT_OF_MEMORY; } if(ftpc->prevpath) infof(data, "Remembering we are in dir \"%s\"\n", ftpc->prevpath); } else { ftpc->prevpath = NULL; /* no path */ free(path); } } /* free the dir tree and file parts */ freedirs(ftpc); /* shut down the socket to inform the server we're done */ #ifdef _WIN32_WCE shutdown(conn->sock[SECONDARYSOCKET], 2); /* SD_BOTH */ #endif if(conn->sock[SECONDARYSOCKET] != CURL_SOCKET_BAD) { if(!result && ftpc->dont_check && data->req.maxdownload > 0) { /* partial download completed */ result = Curl_pp_sendf(pp, "%s", "ABOR"); if(result) { failf(data, "Failure sending ABOR command: %s", curl_easy_strerror(result)); ftpc->ctl_valid = FALSE; /* mark control connection as bad */ connclose(conn, "ABOR command failed"); /* connection closure */ } } if(conn->ssl[SECONDARYSOCKET].use) { /* The secondary socket is using SSL so we must close down that part first before we close the socket for real */ Curl_ssl_close(conn, SECONDARYSOCKET); /* Note that we keep "use" set to TRUE since that (next) connection is still requested to use SSL */ } close_secondarysocket(conn); } if(!result && (ftp->transfer == FTPTRANSFER_BODY) && ftpc->ctl_valid && pp->pending_resp && !premature) { /* * Let's see what the server says about the transfer we just performed, * but lower the timeout as sometimes this connection has died while the * data has been transferred. This happens when doing through NATs etc that * abandon old silent connections. */ long old_time = pp->response_time; pp->response_time = 60*1000; /* give it only a minute for now */ pp->response = Curl_now(); /* timeout relative now */ result = Curl_GetFTPResponse(&nread, conn, &ftpcode); pp->response_time = old_time; /* set this back to previous value */ if(!nread && (CURLE_OPERATION_TIMEDOUT == result)) { failf(data, "control connection looks dead"); ftpc->ctl_valid = FALSE; /* mark control connection as bad */ connclose(conn, "Timeout or similar in FTP DONE operation"); /* close */ } if(result) return result; if(ftpc->dont_check && data->req.maxdownload > 0) { /* we have just sent ABOR and there is no reliable way to check if it was * successful or not; we have to close the connection now */ infof(data, "partial download completed, closing connection\n"); connclose(conn, "Partial download with no ability to check"); return result; } if(!ftpc->dont_check) { /* 226 Transfer complete, 250 Requested file action okay, completed. */ if((ftpcode != 226) && (ftpcode != 250)) { failf(data, "server did not report OK, got %d", ftpcode); result = CURLE_PARTIAL_FILE; } } } if(result || premature) /* the response code from the transfer showed an error already so no use checking further */ ; else if(data->set.upload) { if((-1 != data->state.infilesize) && (data->state.infilesize != data->req.writebytecount) && !data->set.crlf && (ftp->transfer == FTPTRANSFER_BODY)) { failf(data, "Uploaded unaligned file size (%" CURL_FORMAT_CURL_OFF_T " out of %" CURL_FORMAT_CURL_OFF_T " bytes)", data->req.bytecount, data->state.infilesize); result = CURLE_PARTIAL_FILE; } } else { if((-1 != data->req.size) && (data->req.size != data->req.bytecount) && #ifdef CURL_DO_LINEEND_CONV /* Most FTP servers don't adjust their file SIZE response for CRLFs, so * we'll check to see if the discrepancy can be explained by the number * of CRLFs we've changed to LFs. */ ((data->req.size + data->state.crlf_conversions) != data->req.bytecount) && #endif /* CURL_DO_LINEEND_CONV */ (data->req.maxdownload != data->req.bytecount)) { failf(data, "Received only partial file: %" CURL_FORMAT_CURL_OFF_T " bytes", data->req.bytecount); result = CURLE_PARTIAL_FILE; } else if(!ftpc->dont_check && !data->req.bytecount && (data->req.size>0)) { failf(data, "No data was received!"); result = CURLE_FTP_COULDNT_RETR_FILE; } } /* clear these for next connection */ ftp->transfer = FTPTRANSFER_BODY; ftpc->dont_check = FALSE; /* Send any post-transfer QUOTE strings? */ if(!status && !result && !premature && data->set.postquote) result = ftp_sendquote(conn, data->set.postquote); Curl_safefree(ftp->pathalloc); return result; } /*********************************************************************** * * ftp_sendquote() * * Where a 'quote' means a list of custom commands to send to the server. * The quote list is passed as an argument. * * BLOCKING */ static CURLcode ftp_sendquote(struct connectdata *conn, struct curl_slist *quote) { struct curl_slist *item; ssize_t nread; int ftpcode; CURLcode result; struct ftp_conn *ftpc = &conn->proto.ftpc; struct pingpong *pp = &ftpc->pp; item = quote; while(item) { if(item->data) { char *cmd = item->data; bool acceptfail = FALSE; /* if a command starts with an asterisk, which a legal FTP command never can, the command will be allowed to fail without it causing any aborts or cancels etc. It will cause libcurl to act as if the command is successful, whatever the server reponds. */ if(cmd[0] == '*') { cmd++; acceptfail = TRUE; } PPSENDF(&conn->proto.ftpc.pp, "%s", cmd); pp->response = Curl_now(); /* timeout relative now */ result = Curl_GetFTPResponse(&nread, conn, &ftpcode); if(result) return result; if(!acceptfail && (ftpcode >= 400)) { failf(conn->data, "QUOT string not accepted: %s", cmd); return CURLE_QUOTE_ERROR; } } item = item->next; } return CURLE_OK; } /*********************************************************************** * * ftp_need_type() * * Returns TRUE if we in the current situation should send TYPE */ static int ftp_need_type(struct connectdata *conn, bool ascii_wanted) { return conn->proto.ftpc.transfertype != (ascii_wanted?'A':'I'); } /*********************************************************************** * * ftp_nb_type() * * Set TYPE. We only deal with ASCII or BINARY so this function * sets one of them. * If the transfer type is not sent, simulate on OK response in newstate */ static CURLcode ftp_nb_type(struct connectdata *conn, bool ascii, ftpstate newstate) { struct ftp_conn *ftpc = &conn->proto.ftpc; CURLcode result; char want = (char)(ascii?'A':'I'); if(ftpc->transfertype == want) { state(conn, newstate); return ftp_state_type_resp(conn, 200, newstate); } PPSENDF(&ftpc->pp, "TYPE %c", want); state(conn, newstate); /* keep track of our current transfer type */ ftpc->transfertype = want; return CURLE_OK; } /*************************************************************************** * * ftp_pasv_verbose() * * This function only outputs some informationals about this second connection * when we've issued a PASV command before and thus we have connected to a * possibly new IP address. * */ #ifndef CURL_DISABLE_VERBOSE_STRINGS static void ftp_pasv_verbose(struct connectdata *conn, Curl_addrinfo *ai, char *newhost, /* ascii version */ int port) { char buf[256]; Curl_printable_address(ai, buf, sizeof(buf)); infof(conn->data, "Connecting to %s (%s) port %d\n", newhost, buf, port); } #endif /* * ftp_do_more() * * This function shall be called when the second FTP (data) connection is * connected. * * 'complete' can return 0 for incomplete, 1 for done and -1 for go back * (which basically is only for when PASV is being sent to retry a failed * EPSV). */ static CURLcode ftp_do_more(struct connectdata *conn, int *completep) { struct Curl_easy *data = conn->data; struct ftp_conn *ftpc = &conn->proto.ftpc; CURLcode result = CURLE_OK; bool connected = FALSE; bool complete = FALSE; /* the ftp struct is inited in ftp_connect() */ struct FTP *ftp = data->req.protop; /* if the second connection isn't done yet, wait for it */ if(!conn->bits.tcpconnect[SECONDARYSOCKET]) { if(Curl_connect_ongoing(conn)) { /* As we're in TUNNEL_CONNECT state now, we know the proxy name and port aren't used so we blank their arguments. */ result = Curl_proxyCONNECT(conn, SECONDARYSOCKET, NULL, 0); return result; } result = Curl_is_connected(conn, SECONDARYSOCKET, &connected); /* Ready to do more? */ if(connected) { DEBUGF(infof(data, "DO-MORE connected phase starts\n")); } else { if(result && (ftpc->count1 == 0)) { *completep = -1; /* go back to DOING please */ /* this is a EPSV connect failing, try PASV instead */ return ftp_epsv_disable(conn); } return result; } } result = Curl_proxy_connect(conn, SECONDARYSOCKET); if(result) return result; if(CONNECT_SECONDARYSOCKET_PROXY_SSL()) return result; if(conn->bits.tunnel_proxy && conn->bits.httpproxy && Curl_connect_ongoing(conn)) return result; if(ftpc->state) { /* already in a state so skip the initial commands. They are only done to kickstart the do_more state */ result = ftp_multi_statemach(conn, &complete); *completep = (int)complete; /* if we got an error or if we don't wait for a data connection return immediately */ if(result || (ftpc->wait_data_conn != TRUE)) return result; if(ftpc->wait_data_conn) /* if we reach the end of the FTP state machine here, *complete will be TRUE but so is ftpc->wait_data_conn, which says we need to wait for the data connection and therefore we're not actually complete */ *completep = 0; } if(ftp->transfer <= FTPTRANSFER_INFO) { /* a transfer is about to take place, or if not a file name was given so we'll do a SIZE on it later and then we need the right TYPE first */ if(ftpc->wait_data_conn == TRUE) { bool serv_conned; result = ReceivedServerConnect(conn, &serv_conned); if(result) return result; /* Failed to accept data connection */ if(serv_conned) { /* It looks data connection is established */ result = AcceptServerConnect(conn); ftpc->wait_data_conn = FALSE; if(!result) result = InitiateTransfer(conn); if(result) return result; *completep = 1; /* this state is now complete when the server has connected back to us */ } } else if(data->set.upload) { result = ftp_nb_type(conn, data->set.prefer_ascii, FTP_STOR_TYPE); if(result) return result; result = ftp_multi_statemach(conn, &complete); if(ftpc->wait_data_conn) /* if we reach the end of the FTP state machine here, *complete will be TRUE but so is ftpc->wait_data_conn, which says we need to wait for the data connection and therefore we're not actually complete */ *completep = 0; else *completep = (int)complete; } else { /* download */ ftp->downloadsize = -1; /* unknown as of yet */ result = Curl_range(conn); if(result == CURLE_OK && data->req.maxdownload >= 0) { /* Don't check for successful transfer */ ftpc->dont_check = TRUE; } if(result) ; else if(data->set.ftp_list_only || !ftpc->file) { /* The specified path ends with a slash, and therefore we think this is a directory that is requested, use LIST. But before that we need to set ASCII transfer mode. */ /* But only if a body transfer was requested. */ if(ftp->transfer == FTPTRANSFER_BODY) { result = ftp_nb_type(conn, TRUE, FTP_LIST_TYPE); if(result) return result; } /* otherwise just fall through */ } else { result = ftp_nb_type(conn, data->set.prefer_ascii, FTP_RETR_TYPE); if(result) return result; } result = ftp_multi_statemach(conn, &complete); *completep = (int)complete; } return result; } if(!result && (ftp->transfer != FTPTRANSFER_BODY)) /* no data to transfer. FIX: it feels like a kludge to have this here too! */ Curl_setup_transfer(data, -1, -1, FALSE, -1); if(!ftpc->wait_data_conn) { /* no waiting for the data connection so this is now complete */ *completep = 1; DEBUGF(infof(data, "DO-MORE phase ends with %d\n", (int)result)); } return result; } /*********************************************************************** * * ftp_perform() * * This is the actual DO function for FTP. Get a file/directory according to * the options previously setup. */ static CURLcode ftp_perform(struct connectdata *conn, bool *connected, /* connect status after PASV / PORT */ bool *dophase_done) { /* this is FTP and no proxy */ CURLcode result = CURLE_OK; DEBUGF(infof(conn->data, "DO phase starts\n")); if(conn->data->set.opt_no_body) { /* requested no body means no transfer... */ struct FTP *ftp = conn->data->req.protop; ftp->transfer = FTPTRANSFER_INFO; } *dophase_done = FALSE; /* not done yet */ /* start the first command in the DO phase */ result = ftp_state_quote(conn, TRUE, FTP_QUOTE); if(result) return result; /* run the state-machine */ result = ftp_multi_statemach(conn, dophase_done); *connected = conn->bits.tcpconnect[SECONDARYSOCKET]; infof(conn->data, "ftp_perform ends with SECONDARY: %d\n", *connected); if(*dophase_done) DEBUGF(infof(conn->data, "DO phase is complete1\n")); return result; } static void wc_data_dtor(void *ptr) { struct ftp_wc *ftpwc = ptr; if(ftpwc && ftpwc->parser) Curl_ftp_parselist_data_free(&ftpwc->parser); free(ftpwc); } static CURLcode init_wc_data(struct connectdata *conn) { char *last_slash; struct FTP *ftp = conn->data->req.protop; char *path = ftp->path; struct WildcardData *wildcard = &(conn->data->wildcard); CURLcode result = CURLE_OK; struct ftp_wc *ftpwc = NULL; last_slash = strrchr(ftp->path, '/'); if(last_slash) { last_slash++; if(last_slash[0] == '\0') { wildcard->state = CURLWC_CLEAN; result = ftp_parse_url_path(conn); return result; } wildcard->pattern = strdup(last_slash); if(!wildcard->pattern) return CURLE_OUT_OF_MEMORY; last_slash[0] = '\0'; /* cut file from path */ } else { /* there is only 'wildcard pattern' or nothing */ if(path[0]) { wildcard->pattern = strdup(path); if(!wildcard->pattern) return CURLE_OUT_OF_MEMORY; path[0] = '\0'; } else { /* only list */ wildcard->state = CURLWC_CLEAN; result = ftp_parse_url_path(conn); return result; } } /* program continues only if URL is not ending with slash, allocate needed resources for wildcard transfer */ /* allocate ftp protocol specific wildcard data */ ftpwc = calloc(1, sizeof(struct ftp_wc)); if(!ftpwc) { result = CURLE_OUT_OF_MEMORY; goto fail; } /* INITIALIZE parselist structure */ ftpwc->parser = Curl_ftp_parselist_data_alloc(); if(!ftpwc->parser) { result = CURLE_OUT_OF_MEMORY; goto fail; } wildcard->protdata = ftpwc; /* put it to the WildcardData tmp pointer */ wildcard->dtor = wc_data_dtor; /* wildcard does not support NOCWD option (assert it?) */ if(conn->data->set.ftp_filemethod == FTPFILE_NOCWD) conn->data->set.ftp_filemethod = FTPFILE_MULTICWD; /* try to parse ftp url */ result = ftp_parse_url_path(conn); if(result) { goto fail; } wildcard->path = strdup(ftp->path); if(!wildcard->path) { result = CURLE_OUT_OF_MEMORY; goto fail; } /* backup old write_function */ ftpwc->backup.write_function = conn->data->set.fwrite_func; /* parsing write function */ conn->data->set.fwrite_func = Curl_ftp_parselist; /* backup old file descriptor */ ftpwc->backup.file_descriptor = conn->data->set.out; /* let the writefunc callback know what curl pointer is working with */ conn->data->set.out = conn; infof(conn->data, "Wildcard - Parsing started\n"); return CURLE_OK; fail: if(ftpwc) { Curl_ftp_parselist_data_free(&ftpwc->parser); free(ftpwc); } Curl_safefree(wildcard->pattern); wildcard->dtor = ZERO_NULL; wildcard->protdata = NULL; return result; } /* This is called recursively */ static CURLcode wc_statemach(struct connectdata *conn) { struct WildcardData * const wildcard = &(conn->data->wildcard); CURLcode result = CURLE_OK; switch(wildcard->state) { case CURLWC_INIT: result = init_wc_data(conn); if(wildcard->state == CURLWC_CLEAN) /* only listing! */ break; wildcard->state = result ? CURLWC_ERROR : CURLWC_MATCHING; break; case CURLWC_MATCHING: { /* In this state is LIST response successfully parsed, so lets restore previous WRITEFUNCTION callback and WRITEDATA pointer */ struct ftp_wc *ftpwc = wildcard->protdata; conn->data->set.fwrite_func = ftpwc->backup.write_function; conn->data->set.out = ftpwc->backup.file_descriptor; ftpwc->backup.write_function = ZERO_NULL; ftpwc->backup.file_descriptor = NULL; wildcard->state = CURLWC_DOWNLOADING; if(Curl_ftp_parselist_geterror(ftpwc->parser)) { /* error found in LIST parsing */ wildcard->state = CURLWC_CLEAN; return wc_statemach(conn); } if(wildcard->filelist.size == 0) { /* no corresponding file */ wildcard->state = CURLWC_CLEAN; return CURLE_REMOTE_FILE_NOT_FOUND; } return wc_statemach(conn); } case CURLWC_DOWNLOADING: { /* filelist has at least one file, lets get first one */ struct ftp_conn *ftpc = &conn->proto.ftpc; struct curl_fileinfo *finfo = wildcard->filelist.head->ptr; struct FTP *ftp = conn->data->req.protop; char *tmp_path = aprintf("%s%s", wildcard->path, finfo->filename); if(!tmp_path) return CURLE_OUT_OF_MEMORY; /* switch default ftp->path and tmp_path */ free(ftp->pathalloc); ftp->pathalloc = ftp->path = tmp_path; infof(conn->data, "Wildcard - START of \"%s\"\n", finfo->filename); if(conn->data->set.chunk_bgn) { long userresponse; Curl_set_in_callback(conn->data, true); userresponse = conn->data->set.chunk_bgn( finfo, wildcard->customptr, (int)wildcard->filelist.size); Curl_set_in_callback(conn->data, false); switch(userresponse) { case CURL_CHUNK_BGN_FUNC_SKIP: infof(conn->data, "Wildcard - \"%s\" skipped by user\n", finfo->filename); wildcard->state = CURLWC_SKIP; return wc_statemach(conn); case CURL_CHUNK_BGN_FUNC_FAIL: return CURLE_CHUNK_FAILED; } } if(finfo->filetype != CURLFILETYPE_FILE) { wildcard->state = CURLWC_SKIP; return wc_statemach(conn); } if(finfo->flags & CURLFINFOFLAG_KNOWN_SIZE) ftpc->known_filesize = finfo->size; result = ftp_parse_url_path(conn); if(result) return result; /* we don't need the Curl_fileinfo of first file anymore */ Curl_llist_remove(&wildcard->filelist, wildcard->filelist.head, NULL); if(wildcard->filelist.size == 0) { /* remains only one file to down. */ wildcard->state = CURLWC_CLEAN; /* after that will be ftp_do called once again and no transfer will be done because of CURLWC_CLEAN state */ return CURLE_OK; } } break; case CURLWC_SKIP: { if(conn->data->set.chunk_end) { Curl_set_in_callback(conn->data, true); conn->data->set.chunk_end(conn->data->wildcard.customptr); Curl_set_in_callback(conn->data, false); } Curl_llist_remove(&wildcard->filelist, wildcard->filelist.head, NULL); wildcard->state = (wildcard->filelist.size == 0) ? CURLWC_CLEAN : CURLWC_DOWNLOADING; return wc_statemach(conn); } case CURLWC_CLEAN: { struct ftp_wc *ftpwc = wildcard->protdata; result = CURLE_OK; if(ftpwc) result = Curl_ftp_parselist_geterror(ftpwc->parser); wildcard->state = result ? CURLWC_ERROR : CURLWC_DONE; } break; case CURLWC_DONE: case CURLWC_ERROR: case CURLWC_CLEAR: if(wildcard->dtor) wildcard->dtor(wildcard->protdata); break; } return result; } /*********************************************************************** * * ftp_do() * * This function is registered as 'curl_do' function. It decodes the path * parts etc as a wrapper to the actual DO function (ftp_perform). * * The input argument is already checked for validity. */ static CURLcode ftp_do(struct connectdata *conn, bool *done) { CURLcode result = CURLE_OK; struct ftp_conn *ftpc = &conn->proto.ftpc; *done = FALSE; /* default to false */ ftpc->wait_data_conn = FALSE; /* default to no such wait */ if(conn->data->state.wildcardmatch) { result = wc_statemach(conn); if(conn->data->wildcard.state == CURLWC_SKIP || conn->data->wildcard.state == CURLWC_DONE) { /* do not call ftp_regular_transfer */ return CURLE_OK; } if(result) /* error, loop or skipping the file */ return result; } else { /* no wildcard FSM needed */ result = ftp_parse_url_path(conn); if(result) return result; } result = ftp_regular_transfer(conn, done); return result; } CURLcode Curl_ftpsend(struct connectdata *conn, const char *cmd) { ssize_t bytes_written; #define SBUF_SIZE 1024 char s[SBUF_SIZE]; size_t write_len; char *sptr = s; CURLcode result = CURLE_OK; #ifdef HAVE_GSSAPI enum protection_level data_sec = conn->data_prot; #endif if(!cmd) return CURLE_BAD_FUNCTION_ARGUMENT; write_len = strlen(cmd); if(!write_len || write_len > (sizeof(s) -3)) return CURLE_BAD_FUNCTION_ARGUMENT; memcpy(&s, cmd, write_len); strcpy(&s[write_len], "\r\n"); /* append a trailing CRLF */ write_len += 2; bytes_written = 0; result = Curl_convert_to_network(conn->data, s, write_len); /* Curl_convert_to_network calls failf if unsuccessful */ if(result) return result; for(;;) { #ifdef HAVE_GSSAPI conn->data_prot = PROT_CMD; #endif result = Curl_write(conn, conn->sock[FIRSTSOCKET], sptr, write_len, &bytes_written); #ifdef HAVE_GSSAPI DEBUGASSERT(data_sec > PROT_NONE && data_sec < PROT_LAST); conn->data_prot = data_sec; #endif if(result) break; if(conn->data->set.verbose) Curl_debug(conn->data, CURLINFO_HEADER_OUT, sptr, (size_t)bytes_written); if(bytes_written != (ssize_t)write_len) { write_len -= bytes_written; sptr += bytes_written; } else break; } return result; } /*********************************************************************** * * ftp_quit() * * This should be called before calling sclose() on an ftp control connection * (not data connections). We should then wait for the response from the * server before returning. The calling code should then try to close the * connection. * */ static CURLcode ftp_quit(struct connectdata *conn) { CURLcode result = CURLE_OK; if(conn->proto.ftpc.ctl_valid) { result = Curl_pp_sendf(&conn->proto.ftpc.pp, "%s", "QUIT"); if(result) { failf(conn->data, "Failure sending QUIT command: %s", curl_easy_strerror(result)); conn->proto.ftpc.ctl_valid = FALSE; /* mark control connection as bad */ connclose(conn, "QUIT command failed"); /* mark for connection closure */ state(conn, FTP_STOP); return result; } state(conn, FTP_QUIT); result = ftp_block_statemach(conn); } return result; } /*********************************************************************** * * ftp_disconnect() * * Disconnect from an FTP server. Cleanup protocol-specific per-connection * resources. BLOCKING. */ static CURLcode ftp_disconnect(struct connectdata *conn, bool dead_connection) { struct ftp_conn *ftpc = &conn->proto.ftpc; struct pingpong *pp = &ftpc->pp; /* We cannot send quit unconditionally. If this connection is stale or bad in any way, sending quit and waiting around here will make the disconnect wait in vain and cause more problems than we need to. ftp_quit() will check the state of ftp->ctl_valid. If it's ok it will try to send the QUIT command, otherwise it will just return. */ if(dead_connection) ftpc->ctl_valid = FALSE; /* The FTP session may or may not have been allocated/setup at this point! */ (void)ftp_quit(conn); /* ignore errors on the QUIT */ if(ftpc->entrypath) { struct Curl_easy *data = conn->data; if(data->state.most_recent_ftp_entrypath == ftpc->entrypath) { data->state.most_recent_ftp_entrypath = NULL; } free(ftpc->entrypath); ftpc->entrypath = NULL; } freedirs(ftpc); free(ftpc->prevpath); ftpc->prevpath = NULL; free(ftpc->server_os); ftpc->server_os = NULL; Curl_pp_disconnect(pp); #ifdef HAVE_GSSAPI Curl_sec_end(conn); #endif return CURLE_OK; } /*********************************************************************** * * ftp_parse_url_path() * * Parse the URL path into separate path components. * */ static CURLcode ftp_parse_url_path(struct connectdata *conn) { struct Curl_easy *data = conn->data; /* the ftp struct is already inited in ftp_connect() */ struct FTP *ftp = data->req.protop; struct ftp_conn *ftpc = &conn->proto.ftpc; const char *slash_pos; /* position of the first '/' char in curpos */ const char *path_to_use = ftp->path; const char *cur_pos; const char *filename = NULL; cur_pos = path_to_use; /* current position in path. point at the begin of next path component */ ftpc->ctl_valid = FALSE; ftpc->cwdfail = FALSE; switch(data->set.ftp_filemethod) { case FTPFILE_NOCWD: /* fastest, but less standard-compliant */ /* The best time to check whether the path is a file or directory is right here. so: the first condition in the if() right here, is there just in case someone decides to set path to NULL one day */ if(path_to_use[0] && (path_to_use[strlen(path_to_use) - 1] != '/') ) filename = path_to_use; /* this is a full file path */ /* else { ftpc->file is not used anywhere other than for operations on a file. In other words, never for directory operations. So we can safely leave filename as NULL here and use it as a argument in dir/file decisions. } */ break; case FTPFILE_SINGLECWD: /* get the last slash */ if(!path_to_use[0]) { /* no dir, no file */ ftpc->dirdepth = 0; break; } slash_pos = strrchr(cur_pos, '/'); if(slash_pos || !*cur_pos) { size_t dirlen = slash_pos-cur_pos; CURLcode result; ftpc->dirs = calloc(1, sizeof(ftpc->dirs[0])); if(!ftpc->dirs) return CURLE_OUT_OF_MEMORY; if(!dirlen) dirlen++; result = Curl_urldecode(conn->data, slash_pos ? cur_pos : "/", slash_pos ? dirlen : 1, &ftpc->dirs[0], NULL, TRUE); if(result) { freedirs(ftpc); return result; } ftpc->dirdepth = 1; /* we consider it to be a single dir */ filename = slash_pos ? slash_pos + 1 : cur_pos; /* rest is file name */ } else filename = cur_pos; /* this is a file name only */ break; default: /* allow pretty much anything */ case FTPFILE_MULTICWD: ftpc->dirdepth = 0; ftpc->diralloc = 5; /* default dir depth to allocate */ ftpc->dirs = calloc(ftpc->diralloc, sizeof(ftpc->dirs[0])); if(!ftpc->dirs) return CURLE_OUT_OF_MEMORY; /* we have a special case for listing the root dir only */ if(!strcmp(path_to_use, "/")) { cur_pos++; /* make it point to the zero byte */ ftpc->dirs[0] = strdup("/"); ftpc->dirdepth++; } else { /* parse the URL path into separate path components */ while((slash_pos = strchr(cur_pos, '/')) != NULL) { /* 1 or 0 pointer offset to indicate absolute directory */ ssize_t absolute_dir = ((cur_pos - ftp->path > 0) && (ftpc->dirdepth == 0))?1:0; /* seek out the next path component */ if(slash_pos-cur_pos) { /* we skip empty path components, like "x//y" since the FTP command CWD requires a parameter and a non-existent parameter a) doesn't work on many servers and b) has no effect on the others. */ size_t len = slash_pos - cur_pos + absolute_dir; CURLcode result = Curl_urldecode(conn->data, cur_pos - absolute_dir, len, &ftpc->dirs[ftpc->dirdepth], NULL, TRUE); if(result) { freedirs(ftpc); return result; } } else { cur_pos = slash_pos + 1; /* jump to the rest of the string */ if(!ftpc->dirdepth) { /* path starts with a slash, add that as a directory */ ftpc->dirs[ftpc->dirdepth] = strdup("/"); if(!ftpc->dirs[ftpc->dirdepth++]) { /* run out of memory ... */ failf(data, "no memory"); freedirs(ftpc); return CURLE_OUT_OF_MEMORY; } } continue; } cur_pos = slash_pos + 1; /* jump to the rest of the string */ if(++ftpc->dirdepth >= ftpc->diralloc) { /* enlarge array */ char **bigger; ftpc->diralloc *= 2; /* double the size each time */ bigger = realloc(ftpc->dirs, ftpc->diralloc * sizeof(ftpc->dirs[0])); if(!bigger) { freedirs(ftpc); return CURLE_OUT_OF_MEMORY; } ftpc->dirs = bigger; } } } filename = cur_pos; /* the rest is the file name */ break; } /* switch */ if(filename && *filename) { CURLcode result = Curl_urldecode(conn->data, filename, 0, &ftpc->file, NULL, TRUE); if(result) { freedirs(ftpc); return result; } } else ftpc->file = NULL; /* instead of point to a zero byte, we make it a NULL pointer */ if(data->set.upload && !ftpc->file && (ftp->transfer == FTPTRANSFER_BODY)) { /* We need a file name when uploading. Return error! */ failf(data, "Uploading to a URL without a file name!"); return CURLE_URL_MALFORMAT; } ftpc->cwddone = FALSE; /* default to not done */ if(ftpc->prevpath) { /* prevpath is "raw" so we convert the input path before we compare the strings */ size_t dlen; char *path; CURLcode result = Curl_urldecode(conn->data, ftp->path, 0, &path, &dlen, TRUE); if(result) { freedirs(ftpc); return result; } dlen -= ftpc->file?strlen(ftpc->file):0; if((dlen == strlen(ftpc->prevpath)) && !strncmp(path, ftpc->prevpath, dlen) && (ftpc->prevmethod == data->set.ftp_filemethod)) { infof(data, "Request has same path as previous transfer\n"); ftpc->cwddone = TRUE; } free(path); } return CURLE_OK; } /* call this when the DO phase has completed */ static CURLcode ftp_dophase_done(struct connectdata *conn, bool connected) { struct FTP *ftp = conn->data->req.protop; struct ftp_conn *ftpc = &conn->proto.ftpc; if(connected) { int completed; CURLcode result = ftp_do_more(conn, &completed); if(result) { close_secondarysocket(conn); return result; } } if(ftp->transfer != FTPTRANSFER_BODY) /* no data to transfer */ Curl_setup_transfer(conn->data, -1, -1, FALSE, -1); else if(!connected) /* since we didn't connect now, we want do_more to get called */ conn->bits.do_more = TRUE; ftpc->ctl_valid = TRUE; /* seems good */ return CURLE_OK; } /* called from multi.c while DOing */ static CURLcode ftp_doing(struct connectdata *conn, bool *dophase_done) { CURLcode result = ftp_multi_statemach(conn, dophase_done); if(result) DEBUGF(infof(conn->data, "DO phase failed\n")); else if(*dophase_done) { result = ftp_dophase_done(conn, FALSE /* not connected */); DEBUGF(infof(conn->data, "DO phase is complete2\n")); } return result; } /*********************************************************************** * * ftp_regular_transfer() * * The input argument is already checked for validity. * * Performs all commands done before a regular transfer between a local and a * remote host. * * ftp->ctl_valid starts out as FALSE, and gets set to TRUE if we reach the * ftp_done() function without finding any major problem. */ static CURLcode ftp_regular_transfer(struct connectdata *conn, bool *dophase_done) { CURLcode result = CURLE_OK; bool connected = FALSE; struct Curl_easy *data = conn->data; struct ftp_conn *ftpc = &conn->proto.ftpc; data->req.size = -1; /* make sure this is unknown at this point */ Curl_pgrsSetUploadCounter(data, 0); Curl_pgrsSetDownloadCounter(data, 0); Curl_pgrsSetUploadSize(data, -1); Curl_pgrsSetDownloadSize(data, -1); ftpc->ctl_valid = TRUE; /* starts good */ result = ftp_perform(conn, &connected, /* have we connected after PASV/PORT */ dophase_done); /* all commands in the DO-phase done? */ if(!result) { if(!*dophase_done) /* the DO phase has not completed yet */ return CURLE_OK; result = ftp_dophase_done(conn, connected); if(result) return result; } else freedirs(ftpc); return result; } static CURLcode ftp_setup_connection(struct connectdata *conn) { struct Curl_easy *data = conn->data; char *type; struct FTP *ftp; conn->data->req.protop = ftp = calloc(sizeof(struct FTP), 1); if(NULL == ftp) return CURLE_OUT_OF_MEMORY; ftp->path = &data->state.up.path[1]; /* don't include the initial slash */ /* FTP URLs support an extension like ";type=<typecode>" that * we'll try to get now! */ type = strstr(ftp->path, ";type="); if(!type) type = strstr(conn->host.rawalloc, ";type="); if(type) { char command; *type = 0; /* it was in the middle of the hostname */ command = Curl_raw_toupper(type[6]); conn->bits.type_set = TRUE; switch(command) { case 'A': /* ASCII mode */ data->set.prefer_ascii = TRUE; break; case 'D': /* directory mode */ data->set.ftp_list_only = TRUE; break; case 'I': /* binary mode */ default: /* switch off ASCII */ data->set.prefer_ascii = FALSE; break; } } /* get some initial data into the ftp struct */ ftp->transfer = FTPTRANSFER_BODY; ftp->downloadsize = 0; /* No need to duplicate user+password, the connectdata struct won't change during a session, but we re-init them here since on subsequent inits since the conn struct may have changed or been replaced. */ ftp->user = conn->user; ftp->passwd = conn->passwd; if(isBadFtpString(ftp->user)) return CURLE_URL_MALFORMAT; if(isBadFtpString(ftp->passwd)) return CURLE_URL_MALFORMAT; conn->proto.ftpc.known_filesize = -1; /* unknown size for now */ return CURLE_OK; } #endif /* CURL_DISABLE_FTP */
YifuLiu/AliOS-Things
components/curl/lib/ftp.c
C
apache-2.0
133,326
#ifndef HEADER_CURL_FTP_H #define HEADER_CURL_FTP_H /*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2019, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "pingpong.h" #ifndef CURL_DISABLE_FTP extern const struct Curl_handler Curl_handler_ftp; #ifdef USE_SSL extern const struct Curl_handler Curl_handler_ftps; #endif CURLcode Curl_ftpsend(struct connectdata *, const char *cmd); CURLcode Curl_GetFTPResponse(ssize_t *nread, struct connectdata *conn, int *ftpcode); #endif /* CURL_DISABLE_FTP */ /**************************************************************************** * FTP unique setup ***************************************************************************/ typedef enum { FTP_STOP, /* do nothing state, stops the state machine */ FTP_WAIT220, /* waiting for the initial 220 response immediately after a connect */ FTP_AUTH, FTP_USER, FTP_PASS, FTP_ACCT, FTP_PBSZ, FTP_PROT, FTP_CCC, FTP_PWD, FTP_SYST, FTP_NAMEFMT, FTP_QUOTE, /* waiting for a response to a command sent in a quote list */ FTP_RETR_PREQUOTE, FTP_STOR_PREQUOTE, FTP_POSTQUOTE, FTP_CWD, /* change dir */ FTP_MKD, /* if the dir didn't exist */ FTP_MDTM, /* to figure out the datestamp */ FTP_TYPE, /* to set type when doing a head-like request */ FTP_LIST_TYPE, /* set type when about to do a dir list */ FTP_RETR_TYPE, /* set type when about to RETR a file */ FTP_STOR_TYPE, /* set type when about to STOR a file */ FTP_SIZE, /* get the remote file's size for head-like request */ FTP_RETR_SIZE, /* get the remote file's size for RETR */ FTP_STOR_SIZE, /* get the size for STOR */ FTP_REST, /* when used to check if the server supports it in head-like */ FTP_RETR_REST, /* when asking for "resume" in for RETR */ FTP_PORT, /* generic state for PORT, LPRT and EPRT, check count1 */ FTP_PRET, /* generic state for PRET RETR, PRET STOR and PRET LIST/NLST */ FTP_PASV, /* generic state for PASV and EPSV, check count1 */ FTP_LIST, /* generic state for LIST, NLST or a custom list command */ FTP_RETR, FTP_STOR, /* generic state for STOR and APPE */ FTP_QUIT, FTP_LAST /* never used */ } ftpstate; struct ftp_parselist_data; /* defined later in ftplistparser.c */ struct ftp_wc { struct ftp_parselist_data *parser; struct { curl_write_callback write_function; FILE *file_descriptor; } backup; }; typedef enum { FTPFILE_MULTICWD = 1, /* as defined by RFC1738 */ FTPFILE_NOCWD = 2, /* use SIZE / RETR / STOR on the full path */ FTPFILE_SINGLECWD = 3 /* make one CWD, then SIZE / RETR / STOR on the file */ } curl_ftpfile; /* This FTP struct is used in the Curl_easy. All FTP data that is connection-oriented must be in FTP_conn to properly deal with the fact that perhaps the Curl_easy is changed between the times the connection is used. */ struct FTP { char *user; /* user name string */ char *passwd; /* password string */ char *path; /* points to the urlpieces struct field */ char *pathalloc; /* if non-NULL a pointer to an allocated path */ /* transfer a file/body or not, done as a typedefed enum just to make debuggers display the full symbol and not just the numerical value */ curl_pp_transfer transfer; curl_off_t downloadsize; }; /* ftp_conn is used for struct connection-oriented data in the connectdata struct */ struct ftp_conn { struct pingpong pp; char *entrypath; /* the PWD reply when we logged on */ char **dirs; /* realloc()ed array for path components */ int dirdepth; /* number of entries used in the 'dirs' array */ int diralloc; /* number of entries allocated for the 'dirs' array */ char *file; /* decoded file */ bool dont_check; /* Set to TRUE to prevent the final (post-transfer) file size and 226/250 status check. It should still read the line, just ignore the result. */ bool ctl_valid; /* Tells Curl_ftp_quit() whether or not to do anything. If the connection has timed out or been closed, this should be FALSE when it gets to Curl_ftp_quit() */ bool cwddone; /* if it has been determined that the proper CWD combo already has been done */ int cwdcount; /* number of CWD commands issued */ bool cwdfail; /* set TRUE if a CWD command fails, as then we must prevent caching the current directory */ bool wait_data_conn; /* this is set TRUE if data connection is waited */ char *prevpath; /* conn->path from the previous transfer */ curl_ftpfile prevmethod; /* ftp method in previous transfer */ char transfertype; /* set by ftp_transfertype for use by Curl_client_write()a and others (A/I or zero) */ int count1; /* general purpose counter for the state machine */ int count2; /* general purpose counter for the state machine */ int count3; /* general purpose counter for the state machine */ ftpstate state; /* always use ftp.c:state() to change state! */ ftpstate state_saved; /* transfer type saved to be reloaded after data connection is established */ curl_off_t retr_size_saved; /* Size of retrieved file saved */ char *server_os; /* The target server operating system. */ curl_off_t known_filesize; /* file size is different from -1, if wildcard LIST parsing was done and wc_statemach set it */ /* newhost is the (allocated) IP addr or host name to connect the data connection to */ char *newhost; /* this is the pair to connect the DATA... */ unsigned short newport; /* connection to */ }; #define DEFAULT_ACCEPT_TIMEOUT 60000 /* milliseconds == one minute */ #endif /* HEADER_CURL_FTP_H */
YifuLiu/AliOS-Things
components/curl/lib/ftp.h
C
apache-2.0
6,817
/*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2018, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ /** * Now implemented: * * 1) Unix version 1 * drwxr-xr-x 1 user01 ftp 512 Jan 29 23:32 prog * 2) Unix version 2 * drwxr-xr-x 1 user01 ftp 512 Jan 29 1997 prog * 3) Unix version 3 * drwxr-xr-x 1 1 1 512 Jan 29 23:32 prog * 4) Unix symlink * lrwxr-xr-x 1 user01 ftp 512 Jan 29 23:32 prog -> prog2000 * 5) DOS style * 01-29-97 11:32PM <DIR> prog */ #include "curl_setup.h" #ifndef CURL_DISABLE_FTP #include <curl/curl.h> #include "urldata.h" #include "fileinfo.h" #include "llist.h" #include "strtoofft.h" #include "ftp.h" #include "ftplistparser.h" #include "curl_fnmatch.h" #include "curl_memory.h" #include "multiif.h" /* The last #include file should be: */ #include "memdebug.h" /* allocs buffer which will contain one line of LIST command response */ #define FTP_BUFFER_ALLOCSIZE 160 typedef enum { PL_UNIX_TOTALSIZE = 0, PL_UNIX_FILETYPE, PL_UNIX_PERMISSION, PL_UNIX_HLINKS, PL_UNIX_USER, PL_UNIX_GROUP, PL_UNIX_SIZE, PL_UNIX_TIME, PL_UNIX_FILENAME, PL_UNIX_SYMLINK } pl_unix_mainstate; typedef union { enum { PL_UNIX_TOTALSIZE_INIT = 0, PL_UNIX_TOTALSIZE_READING } total_dirsize; enum { PL_UNIX_HLINKS_PRESPACE = 0, PL_UNIX_HLINKS_NUMBER } hlinks; enum { PL_UNIX_USER_PRESPACE = 0, PL_UNIX_USER_PARSING } user; enum { PL_UNIX_GROUP_PRESPACE = 0, PL_UNIX_GROUP_NAME } group; enum { PL_UNIX_SIZE_PRESPACE = 0, PL_UNIX_SIZE_NUMBER } size; enum { PL_UNIX_TIME_PREPART1 = 0, PL_UNIX_TIME_PART1, PL_UNIX_TIME_PREPART2, PL_UNIX_TIME_PART2, PL_UNIX_TIME_PREPART3, PL_UNIX_TIME_PART3 } time; enum { PL_UNIX_FILENAME_PRESPACE = 0, PL_UNIX_FILENAME_NAME, PL_UNIX_FILENAME_WINDOWSEOL } filename; enum { PL_UNIX_SYMLINK_PRESPACE = 0, PL_UNIX_SYMLINK_NAME, PL_UNIX_SYMLINK_PRETARGET1, PL_UNIX_SYMLINK_PRETARGET2, PL_UNIX_SYMLINK_PRETARGET3, PL_UNIX_SYMLINK_PRETARGET4, PL_UNIX_SYMLINK_TARGET, PL_UNIX_SYMLINK_WINDOWSEOL } symlink; } pl_unix_substate; typedef enum { PL_WINNT_DATE = 0, PL_WINNT_TIME, PL_WINNT_DIRORSIZE, PL_WINNT_FILENAME } pl_winNT_mainstate; typedef union { enum { PL_WINNT_TIME_PRESPACE = 0, PL_WINNT_TIME_TIME } time; enum { PL_WINNT_DIRORSIZE_PRESPACE = 0, PL_WINNT_DIRORSIZE_CONTENT } dirorsize; enum { PL_WINNT_FILENAME_PRESPACE = 0, PL_WINNT_FILENAME_CONTENT, PL_WINNT_FILENAME_WINEOL } filename; } pl_winNT_substate; /* This struct is used in wildcard downloading - for parsing LIST response */ struct ftp_parselist_data { enum { OS_TYPE_UNKNOWN = 0, OS_TYPE_UNIX, OS_TYPE_WIN_NT } os_type; union { struct { pl_unix_mainstate main; pl_unix_substate sub; } UNIX; struct { pl_winNT_mainstate main; pl_winNT_substate sub; } NT; } state; CURLcode error; struct fileinfo *file_data; unsigned int item_length; size_t item_offset; struct { size_t filename; size_t user; size_t group; size_t time; size_t perm; size_t symlink_target; } offsets; }; struct ftp_parselist_data *Curl_ftp_parselist_data_alloc(void) { return calloc(1, sizeof(struct ftp_parselist_data)); } void Curl_ftp_parselist_data_free(struct ftp_parselist_data **parserp) { struct ftp_parselist_data *parser = *parserp; if(parser) Curl_fileinfo_cleanup(parser->file_data); free(parser); *parserp = NULL; } CURLcode Curl_ftp_parselist_geterror(struct ftp_parselist_data *pl_data) { return pl_data->error; } #define FTP_LP_MALFORMATED_PERM 0x01000000 static int ftp_pl_get_permission(const char *str) { int permissions = 0; /* USER */ if(str[0] == 'r') permissions |= 1 << 8; else if(str[0] != '-') permissions |= FTP_LP_MALFORMATED_PERM; if(str[1] == 'w') permissions |= 1 << 7; else if(str[1] != '-') permissions |= FTP_LP_MALFORMATED_PERM; if(str[2] == 'x') permissions |= 1 << 6; else if(str[2] == 's') { permissions |= 1 << 6; permissions |= 1 << 11; } else if(str[2] == 'S') permissions |= 1 << 11; else if(str[2] != '-') permissions |= FTP_LP_MALFORMATED_PERM; /* GROUP */ if(str[3] == 'r') permissions |= 1 << 5; else if(str[3] != '-') permissions |= FTP_LP_MALFORMATED_PERM; if(str[4] == 'w') permissions |= 1 << 4; else if(str[4] != '-') permissions |= FTP_LP_MALFORMATED_PERM; if(str[5] == 'x') permissions |= 1 << 3; else if(str[5] == 's') { permissions |= 1 << 3; permissions |= 1 << 10; } else if(str[5] == 'S') permissions |= 1 << 10; else if(str[5] != '-') permissions |= FTP_LP_MALFORMATED_PERM; /* others */ if(str[6] == 'r') permissions |= 1 << 2; else if(str[6] != '-') permissions |= FTP_LP_MALFORMATED_PERM; if(str[7] == 'w') permissions |= 1 << 1; else if(str[7] != '-') permissions |= FTP_LP_MALFORMATED_PERM; if(str[8] == 'x') permissions |= 1; else if(str[8] == 't') { permissions |= 1; permissions |= 1 << 9; } else if(str[8] == 'T') permissions |= 1 << 9; else if(str[8] != '-') permissions |= FTP_LP_MALFORMATED_PERM; return permissions; } static CURLcode ftp_pl_insert_finfo(struct connectdata *conn, struct fileinfo *infop) { curl_fnmatch_callback compare; struct WildcardData *wc = &conn->data->wildcard; struct ftp_wc *ftpwc = wc->protdata; struct curl_llist *llist = &wc->filelist; struct ftp_parselist_data *parser = ftpwc->parser; bool add = TRUE; struct curl_fileinfo *finfo = &infop->info; /* move finfo pointers to b_data */ char *str = finfo->b_data; finfo->filename = str + parser->offsets.filename; finfo->strings.group = parser->offsets.group ? str + parser->offsets.group : NULL; finfo->strings.perm = parser->offsets.perm ? str + parser->offsets.perm : NULL; finfo->strings.target = parser->offsets.symlink_target ? str + parser->offsets.symlink_target : NULL; finfo->strings.time = str + parser->offsets.time; finfo->strings.user = parser->offsets.user ? str + parser->offsets.user : NULL; /* get correct fnmatch callback */ compare = conn->data->set.fnmatch; if(!compare) compare = Curl_fnmatch; /* filter pattern-corresponding filenames */ Curl_set_in_callback(conn->data, true); if(compare(conn->data->set.fnmatch_data, wc->pattern, finfo->filename) == 0) { /* discard symlink which is containing multiple " -> " */ if((finfo->filetype == CURLFILETYPE_SYMLINK) && finfo->strings.target && (strstr(finfo->strings.target, " -> "))) { add = FALSE; } } else { add = FALSE; } Curl_set_in_callback(conn->data, false); if(add) { Curl_llist_insert_next(llist, llist->tail, finfo, &infop->list); } else { Curl_fileinfo_cleanup(infop); } ftpwc->parser->file_data = NULL; return CURLE_OK; } size_t Curl_ftp_parselist(char *buffer, size_t size, size_t nmemb, void *connptr) { size_t bufflen = size*nmemb; struct connectdata *conn = (struct connectdata *)connptr; struct ftp_wc *ftpwc = conn->data->wildcard.protdata; struct ftp_parselist_data *parser = ftpwc->parser; struct fileinfo *infop; struct curl_fileinfo *finfo; unsigned long i = 0; CURLcode result; size_t retsize = bufflen; if(parser->error) { /* error in previous call */ /* scenario: * 1. call => OK.. * 2. call => OUT_OF_MEMORY (or other error) * 3. (last) call => is skipped RIGHT HERE and the error is hadled later * in wc_statemach() */ goto fail; } if(parser->os_type == OS_TYPE_UNKNOWN && bufflen > 0) { /* considering info about FILE response format */ parser->os_type = (buffer[0] >= '0' && buffer[0] <= '9') ? OS_TYPE_WIN_NT : OS_TYPE_UNIX; } while(i < bufflen) { /* FSM */ char c = buffer[i]; if(!parser->file_data) { /* tmp file data is not allocated yet */ parser->file_data = Curl_fileinfo_alloc(); if(!parser->file_data) { parser->error = CURLE_OUT_OF_MEMORY; goto fail; } parser->file_data->info.b_data = malloc(FTP_BUFFER_ALLOCSIZE); if(!parser->file_data->info.b_data) { parser->error = CURLE_OUT_OF_MEMORY; goto fail; } parser->file_data->info.b_size = FTP_BUFFER_ALLOCSIZE; parser->item_offset = 0; parser->item_length = 0; } infop = parser->file_data; finfo = &infop->info; finfo->b_data[finfo->b_used++] = c; if(finfo->b_used >= finfo->b_size - 1) { /* if it is important, extend buffer space for file data */ char *tmp = realloc(finfo->b_data, finfo->b_size + FTP_BUFFER_ALLOCSIZE); if(tmp) { finfo->b_size += FTP_BUFFER_ALLOCSIZE; finfo->b_data = tmp; } else { Curl_fileinfo_cleanup(parser->file_data); parser->file_data = NULL; parser->error = CURLE_OUT_OF_MEMORY; goto fail; } } switch(parser->os_type) { case OS_TYPE_UNIX: switch(parser->state.UNIX.main) { case PL_UNIX_TOTALSIZE: switch(parser->state.UNIX.sub.total_dirsize) { case PL_UNIX_TOTALSIZE_INIT: if(c == 't') { parser->state.UNIX.sub.total_dirsize = PL_UNIX_TOTALSIZE_READING; parser->item_length++; } else { parser->state.UNIX.main = PL_UNIX_FILETYPE; /* start FSM again not considering size of directory */ finfo->b_used = 0; continue; } break; case PL_UNIX_TOTALSIZE_READING: parser->item_length++; if(c == '\r') { parser->item_length--; finfo->b_used--; } else if(c == '\n') { finfo->b_data[parser->item_length - 1] = 0; if(strncmp("total ", finfo->b_data, 6) == 0) { char *endptr = finfo->b_data + 6; /* here we can deal with directory size, pass the leading white spaces and then the digits */ while(ISSPACE(*endptr)) endptr++; while(ISDIGIT(*endptr)) endptr++; if(*endptr != 0) { parser->error = CURLE_FTP_BAD_FILE_LIST; goto fail; } parser->state.UNIX.main = PL_UNIX_FILETYPE; finfo->b_used = 0; } else { parser->error = CURLE_FTP_BAD_FILE_LIST; goto fail; } } break; } break; case PL_UNIX_FILETYPE: switch(c) { case '-': finfo->filetype = CURLFILETYPE_FILE; break; case 'd': finfo->filetype = CURLFILETYPE_DIRECTORY; break; case 'l': finfo->filetype = CURLFILETYPE_SYMLINK; break; case 'p': finfo->filetype = CURLFILETYPE_NAMEDPIPE; break; case 's': finfo->filetype = CURLFILETYPE_SOCKET; break; case 'c': finfo->filetype = CURLFILETYPE_DEVICE_CHAR; break; case 'b': finfo->filetype = CURLFILETYPE_DEVICE_BLOCK; break; case 'D': finfo->filetype = CURLFILETYPE_DOOR; break; default: parser->error = CURLE_FTP_BAD_FILE_LIST; goto fail; } parser->state.UNIX.main = PL_UNIX_PERMISSION; parser->item_length = 0; parser->item_offset = 1; break; case PL_UNIX_PERMISSION: parser->item_length++; if(parser->item_length <= 9) { if(!strchr("rwx-tTsS", c)) { parser->error = CURLE_FTP_BAD_FILE_LIST; goto fail; } } else if(parser->item_length == 10) { unsigned int perm; if(c != ' ') { parser->error = CURLE_FTP_BAD_FILE_LIST; goto fail; } finfo->b_data[10] = 0; /* terminate permissions */ perm = ftp_pl_get_permission(finfo->b_data + parser->item_offset); if(perm & FTP_LP_MALFORMATED_PERM) { parser->error = CURLE_FTP_BAD_FILE_LIST; goto fail; } parser->file_data->info.flags |= CURLFINFOFLAG_KNOWN_PERM; parser->file_data->info.perm = perm; parser->offsets.perm = parser->item_offset; parser->item_length = 0; parser->state.UNIX.main = PL_UNIX_HLINKS; parser->state.UNIX.sub.hlinks = PL_UNIX_HLINKS_PRESPACE; } break; case PL_UNIX_HLINKS: switch(parser->state.UNIX.sub.hlinks) { case PL_UNIX_HLINKS_PRESPACE: if(c != ' ') { if(c >= '0' && c <= '9') { parser->item_offset = finfo->b_used - 1; parser->item_length = 1; parser->state.UNIX.sub.hlinks = PL_UNIX_HLINKS_NUMBER; } else { parser->error = CURLE_FTP_BAD_FILE_LIST; goto fail; } } break; case PL_UNIX_HLINKS_NUMBER: parser->item_length ++; if(c == ' ') { char *p; long int hlinks; finfo->b_data[parser->item_offset + parser->item_length - 1] = 0; hlinks = strtol(finfo->b_data + parser->item_offset, &p, 10); if(p[0] == '\0' && hlinks != LONG_MAX && hlinks != LONG_MIN) { parser->file_data->info.flags |= CURLFINFOFLAG_KNOWN_HLINKCOUNT; parser->file_data->info.hardlinks = hlinks; } parser->item_length = 0; parser->item_offset = 0; parser->state.UNIX.main = PL_UNIX_USER; parser->state.UNIX.sub.user = PL_UNIX_USER_PRESPACE; } else if(c < '0' || c > '9') { parser->error = CURLE_FTP_BAD_FILE_LIST; goto fail; } break; } break; case PL_UNIX_USER: switch(parser->state.UNIX.sub.user) { case PL_UNIX_USER_PRESPACE: if(c != ' ') { parser->item_offset = finfo->b_used - 1; parser->item_length = 1; parser->state.UNIX.sub.user = PL_UNIX_USER_PARSING; } break; case PL_UNIX_USER_PARSING: parser->item_length++; if(c == ' ') { finfo->b_data[parser->item_offset + parser->item_length - 1] = 0; parser->offsets.user = parser->item_offset; parser->state.UNIX.main = PL_UNIX_GROUP; parser->state.UNIX.sub.group = PL_UNIX_GROUP_PRESPACE; parser->item_offset = 0; parser->item_length = 0; } break; } break; case PL_UNIX_GROUP: switch(parser->state.UNIX.sub.group) { case PL_UNIX_GROUP_PRESPACE: if(c != ' ') { parser->item_offset = finfo->b_used - 1; parser->item_length = 1; parser->state.UNIX.sub.group = PL_UNIX_GROUP_NAME; } break; case PL_UNIX_GROUP_NAME: parser->item_length++; if(c == ' ') { finfo->b_data[parser->item_offset + parser->item_length - 1] = 0; parser->offsets.group = parser->item_offset; parser->state.UNIX.main = PL_UNIX_SIZE; parser->state.UNIX.sub.size = PL_UNIX_SIZE_PRESPACE; parser->item_offset = 0; parser->item_length = 0; } break; } break; case PL_UNIX_SIZE: switch(parser->state.UNIX.sub.size) { case PL_UNIX_SIZE_PRESPACE: if(c != ' ') { if(c >= '0' && c <= '9') { parser->item_offset = finfo->b_used - 1; parser->item_length = 1; parser->state.UNIX.sub.size = PL_UNIX_SIZE_NUMBER; } else { parser->error = CURLE_FTP_BAD_FILE_LIST; goto fail; } } break; case PL_UNIX_SIZE_NUMBER: parser->item_length++; if(c == ' ') { char *p; curl_off_t fsize; finfo->b_data[parser->item_offset + parser->item_length - 1] = 0; if(!curlx_strtoofft(finfo->b_data + parser->item_offset, &p, 10, &fsize)) { if(p[0] == '\0' && fsize != CURL_OFF_T_MAX && fsize != CURL_OFF_T_MIN) { parser->file_data->info.flags |= CURLFINFOFLAG_KNOWN_SIZE; parser->file_data->info.size = fsize; } parser->item_length = 0; parser->item_offset = 0; parser->state.UNIX.main = PL_UNIX_TIME; parser->state.UNIX.sub.time = PL_UNIX_TIME_PREPART1; } } else if(!ISDIGIT(c)) { parser->error = CURLE_FTP_BAD_FILE_LIST; goto fail; } break; } break; case PL_UNIX_TIME: switch(parser->state.UNIX.sub.time) { case PL_UNIX_TIME_PREPART1: if(c != ' ') { if(ISALNUM(c)) { parser->item_offset = finfo->b_used -1; parser->item_length = 1; parser->state.UNIX.sub.time = PL_UNIX_TIME_PART1; } else { parser->error = CURLE_FTP_BAD_FILE_LIST; goto fail; } } break; case PL_UNIX_TIME_PART1: parser->item_length++; if(c == ' ') { parser->state.UNIX.sub.time = PL_UNIX_TIME_PREPART2; } else if(!ISALNUM(c) && c != '.') { parser->error = CURLE_FTP_BAD_FILE_LIST; goto fail; } break; case PL_UNIX_TIME_PREPART2: parser->item_length++; if(c != ' ') { if(ISALNUM(c)) { parser->state.UNIX.sub.time = PL_UNIX_TIME_PART2; } else { parser->error = CURLE_FTP_BAD_FILE_LIST; goto fail; } } break; case PL_UNIX_TIME_PART2: parser->item_length++; if(c == ' ') { parser->state.UNIX.sub.time = PL_UNIX_TIME_PREPART3; } else if(!ISALNUM(c) && c != '.') { parser->error = CURLE_FTP_BAD_FILE_LIST; goto fail; } break; case PL_UNIX_TIME_PREPART3: parser->item_length++; if(c != ' ') { if(ISALNUM(c)) { parser->state.UNIX.sub.time = PL_UNIX_TIME_PART3; } else { parser->error = CURLE_FTP_BAD_FILE_LIST; goto fail; } } break; case PL_UNIX_TIME_PART3: parser->item_length++; if(c == ' ') { finfo->b_data[parser->item_offset + parser->item_length -1] = 0; parser->offsets.time = parser->item_offset; /* if(ftp_pl_gettime(parser, finfo->b_data + parser->item_offset)) { parser->file_data->flags |= CURLFINFOFLAG_KNOWN_TIME; } */ if(finfo->filetype == CURLFILETYPE_SYMLINK) { parser->state.UNIX.main = PL_UNIX_SYMLINK; parser->state.UNIX.sub.symlink = PL_UNIX_SYMLINK_PRESPACE; } else { parser->state.UNIX.main = PL_UNIX_FILENAME; parser->state.UNIX.sub.filename = PL_UNIX_FILENAME_PRESPACE; } } else if(!ISALNUM(c) && c != '.' && c != ':') { parser->error = CURLE_FTP_BAD_FILE_LIST; goto fail; } break; } break; case PL_UNIX_FILENAME: switch(parser->state.UNIX.sub.filename) { case PL_UNIX_FILENAME_PRESPACE: if(c != ' ') { parser->item_offset = finfo->b_used - 1; parser->item_length = 1; parser->state.UNIX.sub.filename = PL_UNIX_FILENAME_NAME; } break; case PL_UNIX_FILENAME_NAME: parser->item_length++; if(c == '\r') { parser->state.UNIX.sub.filename = PL_UNIX_FILENAME_WINDOWSEOL; } else if(c == '\n') { finfo->b_data[parser->item_offset + parser->item_length - 1] = 0; parser->offsets.filename = parser->item_offset; parser->state.UNIX.main = PL_UNIX_FILETYPE; result = ftp_pl_insert_finfo(conn, infop); if(result) { parser->error = result; goto fail; } } break; case PL_UNIX_FILENAME_WINDOWSEOL: if(c == '\n') { finfo->b_data[parser->item_offset + parser->item_length - 1] = 0; parser->offsets.filename = parser->item_offset; parser->state.UNIX.main = PL_UNIX_FILETYPE; result = ftp_pl_insert_finfo(conn, infop); if(result) { parser->error = result; goto fail; } } else { parser->error = CURLE_FTP_BAD_FILE_LIST; goto fail; } break; } break; case PL_UNIX_SYMLINK: switch(parser->state.UNIX.sub.symlink) { case PL_UNIX_SYMLINK_PRESPACE: if(c != ' ') { parser->item_offset = finfo->b_used - 1; parser->item_length = 1; parser->state.UNIX.sub.symlink = PL_UNIX_SYMLINK_NAME; } break; case PL_UNIX_SYMLINK_NAME: parser->item_length++; if(c == ' ') { parser->state.UNIX.sub.symlink = PL_UNIX_SYMLINK_PRETARGET1; } else if(c == '\r' || c == '\n') { parser->error = CURLE_FTP_BAD_FILE_LIST; goto fail; } break; case PL_UNIX_SYMLINK_PRETARGET1: parser->item_length++; if(c == '-') { parser->state.UNIX.sub.symlink = PL_UNIX_SYMLINK_PRETARGET2; } else if(c == '\r' || c == '\n') { parser->error = CURLE_FTP_BAD_FILE_LIST; goto fail; } else { parser->state.UNIX.sub.symlink = PL_UNIX_SYMLINK_NAME; } break; case PL_UNIX_SYMLINK_PRETARGET2: parser->item_length++; if(c == '>') { parser->state.UNIX.sub.symlink = PL_UNIX_SYMLINK_PRETARGET3; } else if(c == '\r' || c == '\n') { parser->error = CURLE_FTP_BAD_FILE_LIST; goto fail; } else { parser->state.UNIX.sub.symlink = PL_UNIX_SYMLINK_NAME; } break; case PL_UNIX_SYMLINK_PRETARGET3: parser->item_length++; if(c == ' ') { parser->state.UNIX.sub.symlink = PL_UNIX_SYMLINK_PRETARGET4; /* now place where is symlink following */ finfo->b_data[parser->item_offset + parser->item_length - 4] = 0; parser->offsets.filename = parser->item_offset; parser->item_length = 0; parser->item_offset = 0; } else if(c == '\r' || c == '\n') { parser->error = CURLE_FTP_BAD_FILE_LIST; goto fail; } else { parser->state.UNIX.sub.symlink = PL_UNIX_SYMLINK_NAME; } break; case PL_UNIX_SYMLINK_PRETARGET4: if(c != '\r' && c != '\n') { parser->state.UNIX.sub.symlink = PL_UNIX_SYMLINK_TARGET; parser->item_offset = finfo->b_used - 1; parser->item_length = 1; } else { parser->error = CURLE_FTP_BAD_FILE_LIST; goto fail; } break; case PL_UNIX_SYMLINK_TARGET: parser->item_length++; if(c == '\r') { parser->state.UNIX.sub.symlink = PL_UNIX_SYMLINK_WINDOWSEOL; } else if(c == '\n') { finfo->b_data[parser->item_offset + parser->item_length - 1] = 0; parser->offsets.symlink_target = parser->item_offset; result = ftp_pl_insert_finfo(conn, infop); if(result) { parser->error = result; goto fail; } parser->state.UNIX.main = PL_UNIX_FILETYPE; } break; case PL_UNIX_SYMLINK_WINDOWSEOL: if(c == '\n') { finfo->b_data[parser->item_offset + parser->item_length - 1] = 0; parser->offsets.symlink_target = parser->item_offset; result = ftp_pl_insert_finfo(conn, infop); if(result) { parser->error = result; goto fail; } parser->state.UNIX.main = PL_UNIX_FILETYPE; } else { parser->error = CURLE_FTP_BAD_FILE_LIST; goto fail; } break; } break; } break; case OS_TYPE_WIN_NT: switch(parser->state.NT.main) { case PL_WINNT_DATE: parser->item_length++; if(parser->item_length < 9) { if(!strchr("0123456789-", c)) { /* only simple control */ parser->error = CURLE_FTP_BAD_FILE_LIST; goto fail; } } else if(parser->item_length == 9) { if(c == ' ') { parser->state.NT.main = PL_WINNT_TIME; parser->state.NT.sub.time = PL_WINNT_TIME_PRESPACE; } else { parser->error = CURLE_FTP_BAD_FILE_LIST; goto fail; } } else { parser->error = CURLE_FTP_BAD_FILE_LIST; goto fail; } break; case PL_WINNT_TIME: parser->item_length++; switch(parser->state.NT.sub.time) { case PL_WINNT_TIME_PRESPACE: if(!ISSPACE(c)) { parser->state.NT.sub.time = PL_WINNT_TIME_TIME; } break; case PL_WINNT_TIME_TIME: if(c == ' ') { parser->offsets.time = parser->item_offset; finfo->b_data[parser->item_offset + parser->item_length -1] = 0; parser->state.NT.main = PL_WINNT_DIRORSIZE; parser->state.NT.sub.dirorsize = PL_WINNT_DIRORSIZE_PRESPACE; parser->item_length = 0; } else if(!strchr("APM0123456789:", c)) { parser->error = CURLE_FTP_BAD_FILE_LIST; goto fail; } break; } break; case PL_WINNT_DIRORSIZE: switch(parser->state.NT.sub.dirorsize) { case PL_WINNT_DIRORSIZE_PRESPACE: if(c != ' ') { parser->item_offset = finfo->b_used - 1; parser->item_length = 1; parser->state.NT.sub.dirorsize = PL_WINNT_DIRORSIZE_CONTENT; } break; case PL_WINNT_DIRORSIZE_CONTENT: parser->item_length ++; if(c == ' ') { finfo->b_data[parser->item_offset + parser->item_length - 1] = 0; if(strcmp("<DIR>", finfo->b_data + parser->item_offset) == 0) { finfo->filetype = CURLFILETYPE_DIRECTORY; finfo->size = 0; } else { char *endptr; if(curlx_strtoofft(finfo->b_data + parser->item_offset, &endptr, 10, &finfo->size)) { parser->error = CURLE_FTP_BAD_FILE_LIST; goto fail; } /* correct file type */ parser->file_data->info.filetype = CURLFILETYPE_FILE; } parser->file_data->info.flags |= CURLFINFOFLAG_KNOWN_SIZE; parser->item_length = 0; parser->state.NT.main = PL_WINNT_FILENAME; parser->state.NT.sub.filename = PL_WINNT_FILENAME_PRESPACE; } break; } break; case PL_WINNT_FILENAME: switch(parser->state.NT.sub.filename) { case PL_WINNT_FILENAME_PRESPACE: if(c != ' ') { parser->item_offset = finfo->b_used -1; parser->item_length = 1; parser->state.NT.sub.filename = PL_WINNT_FILENAME_CONTENT; } break; case PL_WINNT_FILENAME_CONTENT: parser->item_length++; if(c == '\r') { parser->state.NT.sub.filename = PL_WINNT_FILENAME_WINEOL; finfo->b_data[finfo->b_used - 1] = 0; } else if(c == '\n') { parser->offsets.filename = parser->item_offset; finfo->b_data[finfo->b_used - 1] = 0; parser->offsets.filename = parser->item_offset; result = ftp_pl_insert_finfo(conn, infop); if(result) { parser->error = result; goto fail; } parser->state.NT.main = PL_WINNT_DATE; parser->state.NT.sub.filename = PL_WINNT_FILENAME_PRESPACE; } break; case PL_WINNT_FILENAME_WINEOL: if(c == '\n') { parser->offsets.filename = parser->item_offset; result = ftp_pl_insert_finfo(conn, infop); if(result) { parser->error = result; goto fail; } parser->state.NT.main = PL_WINNT_DATE; parser->state.NT.sub.filename = PL_WINNT_FILENAME_PRESPACE; } else { parser->error = CURLE_FTP_BAD_FILE_LIST; goto fail; } break; } break; } break; default: retsize = bufflen + 1; goto fail; } i++; } return retsize; fail: /* Clean up any allocated memory. */ if(parser->file_data) { Curl_fileinfo_cleanup(parser->file_data); parser->file_data = NULL; } return retsize; } #endif /* CURL_DISABLE_FTP */
YifuLiu/AliOS-Things
components/curl/lib/ftplistparser.c
C
apache-2.0
31,251
#ifndef HEADER_CURL_FTPLISTPARSER_H #define HEADER_CURL_FTPLISTPARSER_H /*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2012, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "curl_setup.h" #ifndef CURL_DISABLE_FTP /* WRITEFUNCTION callback for parsing LIST responses */ size_t Curl_ftp_parselist(char *buffer, size_t size, size_t nmemb, void *connptr); struct ftp_parselist_data; /* defined inside ftplibparser.c */ CURLcode Curl_ftp_parselist_geterror(struct ftp_parselist_data *pl_data); struct ftp_parselist_data *Curl_ftp_parselist_data_alloc(void); void Curl_ftp_parselist_data_free(struct ftp_parselist_data **pl_data); #endif /* CURL_DISABLE_FTP */ #endif /* HEADER_CURL_FTPLISTPARSER_H */
YifuLiu/AliOS-Things
components/curl/lib/ftplistparser.h
C
apache-2.0
1,663
/*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2012, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "curl_setup.h" #include <curl/curl.h> #include "curl_memory.h" #include "memdebug.h" static char *GetEnv(const char *variable) { #if defined(_WIN32_WCE) || defined(CURL_WINDOWS_APP) (void)variable; return NULL; #else #ifdef WIN32 char env[MAX_PATH]; /* MAX_PATH is from windef.h */ char *temp = getenv(variable); env[0] = '\0'; if(temp != NULL) ExpandEnvironmentStringsA(temp, env, sizeof(env)); return (env[0] != '\0')?strdup(env):NULL; #else char *env = getenv(variable); return (env && env[0])?strdup(env):NULL; #endif #endif } char *curl_getenv(const char *v) { return GetEnv(v); }
YifuLiu/AliOS-Things
components/curl/lib/getenv.c
C
apache-2.0
1,650
/*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2019, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "curl_setup.h" #include <curl/curl.h> #include "urldata.h" #include "getinfo.h" #include "vtls/vtls.h" #include "connect.h" /* Curl_getconnectinfo() */ #include "progress.h" /* The last #include files should be: */ #include "curl_memory.h" #include "memdebug.h" /* * Initialize statistical and informational data. * * This function is called in curl_easy_reset, curl_easy_duphandle and at the * beginning of a perform session. It must reset the session-info variables, * in particular all variables in struct PureInfo. */ CURLcode Curl_initinfo(struct Curl_easy *data) { struct Progress *pro = &data->progress; struct PureInfo *info = &data->info; pro->t_nslookup = 0; pro->t_connect = 0; pro->t_appconnect = 0; pro->t_pretransfer = 0; pro->t_starttransfer = 0; pro->timespent = 0; pro->t_redirect = 0; pro->is_t_startransfer_set = false; info->httpcode = 0; info->httpproxycode = 0; info->httpversion = 0; info->filetime = -1; /* -1 is an illegal time and thus means unknown */ info->timecond = FALSE; info->header_size = 0; info->request_size = 0; info->proxyauthavail = 0; info->httpauthavail = 0; info->numconnects = 0; free(info->contenttype); info->contenttype = NULL; free(info->wouldredirect); info->wouldredirect = NULL; info->conn_primary_ip[0] = '\0'; info->conn_local_ip[0] = '\0'; info->conn_primary_port = 0; info->conn_local_port = 0; info->conn_scheme = 0; info->conn_protocol = 0; #ifdef USE_SSL Curl_ssl_free_certinfo(data); #endif return CURLE_OK; } static CURLcode getinfo_char(struct Curl_easy *data, CURLINFO info, const char **param_charp) { switch(info) { case CURLINFO_EFFECTIVE_URL: *param_charp = data->change.url?data->change.url:(char *)""; break; case CURLINFO_CONTENT_TYPE: *param_charp = data->info.contenttype; break; case CURLINFO_PRIVATE: *param_charp = (char *) data->set.private_data; break; case CURLINFO_FTP_ENTRY_PATH: /* Return the entrypath string from the most recent connection. This pointer was copied from the connectdata structure by FTP. The actual string may be free()ed by subsequent libcurl calls so it must be copied to a safer area before the next libcurl call. Callers must never free it themselves. */ *param_charp = data->state.most_recent_ftp_entrypath; break; case CURLINFO_REDIRECT_URL: /* Return the URL this request would have been redirected to if that option had been enabled! */ *param_charp = data->info.wouldredirect; break; case CURLINFO_PRIMARY_IP: /* Return the ip address of the most recent (primary) connection */ *param_charp = data->info.conn_primary_ip; break; case CURLINFO_LOCAL_IP: /* Return the source/local ip address of the most recent (primary) connection */ *param_charp = data->info.conn_local_ip; break; case CURLINFO_RTSP_SESSION_ID: *param_charp = data->set.str[STRING_RTSP_SESSION_ID]; break; case CURLINFO_SCHEME: *param_charp = data->info.conn_scheme; break; default: return CURLE_UNKNOWN_OPTION; } return CURLE_OK; } static CURLcode getinfo_long(struct Curl_easy *data, CURLINFO info, long *param_longp) { curl_socket_t sockfd; union { unsigned long *to_ulong; long *to_long; } lptr; switch(info) { case CURLINFO_RESPONSE_CODE: *param_longp = data->info.httpcode; break; case CURLINFO_HTTP_CONNECTCODE: *param_longp = data->info.httpproxycode; break; case CURLINFO_FILETIME: if(data->info.filetime > LONG_MAX) *param_longp = LONG_MAX; else if(data->info.filetime < LONG_MIN) *param_longp = LONG_MIN; else *param_longp = (long)data->info.filetime; break; case CURLINFO_HEADER_SIZE: *param_longp = (long)data->info.header_size; break; case CURLINFO_REQUEST_SIZE: *param_longp = (long)data->info.request_size; break; case CURLINFO_SSL_VERIFYRESULT: *param_longp = data->set.ssl.certverifyresult; break; case CURLINFO_PROXY_SSL_VERIFYRESULT: *param_longp = data->set.proxy_ssl.certverifyresult; break; case CURLINFO_REDIRECT_COUNT: *param_longp = data->set.followlocation; break; case CURLINFO_HTTPAUTH_AVAIL: lptr.to_long = param_longp; *lptr.to_ulong = data->info.httpauthavail; break; case CURLINFO_PROXYAUTH_AVAIL: lptr.to_long = param_longp; *lptr.to_ulong = data->info.proxyauthavail; break; case CURLINFO_OS_ERRNO: *param_longp = data->state.os_errno; break; case CURLINFO_NUM_CONNECTS: *param_longp = data->info.numconnects; break; case CURLINFO_LASTSOCKET: sockfd = Curl_getconnectinfo(data, NULL); /* note: this is not a good conversion for systems with 64 bit sockets and 32 bit longs */ if(sockfd != CURL_SOCKET_BAD) *param_longp = (long)sockfd; else /* this interface is documented to return -1 in case of badness, which may not be the same as the CURL_SOCKET_BAD value */ *param_longp = -1; break; case CURLINFO_PRIMARY_PORT: /* Return the (remote) port of the most recent (primary) connection */ *param_longp = data->info.conn_primary_port; break; case CURLINFO_LOCAL_PORT: /* Return the local port of the most recent (primary) connection */ *param_longp = data->info.conn_local_port; break; case CURLINFO_CONDITION_UNMET: /* return if the condition prevented the document to get transferred */ *param_longp = data->info.timecond ? 1L : 0L; break; case CURLINFO_RTSP_CLIENT_CSEQ: *param_longp = data->state.rtsp_next_client_CSeq; break; case CURLINFO_RTSP_SERVER_CSEQ: *param_longp = data->state.rtsp_next_server_CSeq; break; case CURLINFO_RTSP_CSEQ_RECV: *param_longp = data->state.rtsp_CSeq_recv; break; case CURLINFO_HTTP_VERSION: switch(data->info.httpversion) { case 10: *param_longp = CURL_HTTP_VERSION_1_0; break; case 11: *param_longp = CURL_HTTP_VERSION_1_1; break; case 20: *param_longp = CURL_HTTP_VERSION_2_0; break; default: *param_longp = CURL_HTTP_VERSION_NONE; break; } break; case CURLINFO_PROTOCOL: *param_longp = data->info.conn_protocol; break; default: return CURLE_UNKNOWN_OPTION; } return CURLE_OK; } #define DOUBLE_SECS(x) (double)(x)/1000000 static CURLcode getinfo_offt(struct Curl_easy *data, CURLINFO info, curl_off_t *param_offt) { switch(info) { case CURLINFO_FILETIME_T: *param_offt = (curl_off_t)data->info.filetime; break; case CURLINFO_SIZE_UPLOAD_T: *param_offt = data->progress.uploaded; break; case CURLINFO_SIZE_DOWNLOAD_T: *param_offt = data->progress.downloaded; break; case CURLINFO_SPEED_DOWNLOAD_T: *param_offt = data->progress.dlspeed; break; case CURLINFO_SPEED_UPLOAD_T: *param_offt = data->progress.ulspeed; break; case CURLINFO_CONTENT_LENGTH_DOWNLOAD_T: *param_offt = (data->progress.flags & PGRS_DL_SIZE_KNOWN)? data->progress.size_dl:-1; break; case CURLINFO_CONTENT_LENGTH_UPLOAD_T: *param_offt = (data->progress.flags & PGRS_UL_SIZE_KNOWN)? data->progress.size_ul:-1; break; case CURLINFO_TOTAL_TIME_T: *param_offt = data->progress.timespent; break; case CURLINFO_NAMELOOKUP_TIME_T: *param_offt = data->progress.t_nslookup; break; case CURLINFO_CONNECT_TIME_T: *param_offt = data->progress.t_connect; break; case CURLINFO_APPCONNECT_TIME_T: *param_offt = data->progress.t_appconnect; break; case CURLINFO_PRETRANSFER_TIME_T: *param_offt = data->progress.t_pretransfer; break; case CURLINFO_STARTTRANSFER_TIME_T: *param_offt = data->progress.t_starttransfer; break; case CURLINFO_REDIRECT_TIME_T: *param_offt = data->progress.t_redirect; break; default: return CURLE_UNKNOWN_OPTION; } return CURLE_OK; } static CURLcode getinfo_double(struct Curl_easy *data, CURLINFO info, double *param_doublep) { switch(info) { case CURLINFO_TOTAL_TIME: *param_doublep = DOUBLE_SECS(data->progress.timespent); break; case CURLINFO_NAMELOOKUP_TIME: *param_doublep = DOUBLE_SECS(data->progress.t_nslookup); break; case CURLINFO_CONNECT_TIME: *param_doublep = DOUBLE_SECS(data->progress.t_connect); break; case CURLINFO_APPCONNECT_TIME: *param_doublep = DOUBLE_SECS(data->progress.t_appconnect); break; case CURLINFO_PRETRANSFER_TIME: *param_doublep = DOUBLE_SECS(data->progress.t_pretransfer); break; case CURLINFO_STARTTRANSFER_TIME: *param_doublep = DOUBLE_SECS(data->progress.t_starttransfer); break; case CURLINFO_SIZE_UPLOAD: *param_doublep = (double)data->progress.uploaded; break; case CURLINFO_SIZE_DOWNLOAD: *param_doublep = (double)data->progress.downloaded; break; case CURLINFO_SPEED_DOWNLOAD: *param_doublep = (double)data->progress.dlspeed; break; case CURLINFO_SPEED_UPLOAD: *param_doublep = (double)data->progress.ulspeed; break; case CURLINFO_CONTENT_LENGTH_DOWNLOAD: *param_doublep = (data->progress.flags & PGRS_DL_SIZE_KNOWN)? (double)data->progress.size_dl:-1; break; case CURLINFO_CONTENT_LENGTH_UPLOAD: *param_doublep = (data->progress.flags & PGRS_UL_SIZE_KNOWN)? (double)data->progress.size_ul:-1; break; case CURLINFO_REDIRECT_TIME: *param_doublep = DOUBLE_SECS(data->progress.t_redirect); break; default: return CURLE_UNKNOWN_OPTION; } return CURLE_OK; } static CURLcode getinfo_slist(struct Curl_easy *data, CURLINFO info, struct curl_slist **param_slistp) { union { struct curl_certinfo *to_certinfo; struct curl_slist *to_slist; } ptr; switch(info) { case CURLINFO_SSL_ENGINES: *param_slistp = Curl_ssl_engines_list(data); break; case CURLINFO_COOKIELIST: *param_slistp = Curl_cookie_list(data); break; case CURLINFO_CERTINFO: /* Return the a pointer to the certinfo struct. Not really an slist pointer but we can pretend it is here */ ptr.to_certinfo = &data->info.certs; *param_slistp = ptr.to_slist; break; case CURLINFO_TLS_SESSION: case CURLINFO_TLS_SSL_PTR: { struct curl_tlssessioninfo **tsip = (struct curl_tlssessioninfo **) param_slistp; struct curl_tlssessioninfo *tsi = &data->tsi; #ifdef USE_SSL struct connectdata *conn = data->conn; #endif *tsip = tsi; tsi->backend = Curl_ssl_backend(); tsi->internals = NULL; #ifdef USE_SSL if(conn && tsi->backend != CURLSSLBACKEND_NONE) { unsigned int i; for(i = 0; i < (sizeof(conn->ssl) / sizeof(conn->ssl[0])); ++i) { if(conn->ssl[i].use) { tsi->internals = Curl_ssl->get_internals(&conn->ssl[i], info); break; } } } #endif } break; default: return CURLE_UNKNOWN_OPTION; } return CURLE_OK; } static CURLcode getinfo_socket(struct Curl_easy *data, CURLINFO info, curl_socket_t *param_socketp) { switch(info) { case CURLINFO_ACTIVESOCKET: *param_socketp = Curl_getconnectinfo(data, NULL); break; default: return CURLE_UNKNOWN_OPTION; } return CURLE_OK; } CURLcode Curl_getinfo(struct Curl_easy *data, CURLINFO info, ...) { va_list arg; long *param_longp = NULL; double *param_doublep = NULL; curl_off_t *param_offt = NULL; const char **param_charp = NULL; struct curl_slist **param_slistp = NULL; curl_socket_t *param_socketp = NULL; int type; CURLcode result = CURLE_UNKNOWN_OPTION; if(!data) return result; va_start(arg, info); type = CURLINFO_TYPEMASK & (int)info; switch(type) { case CURLINFO_STRING: param_charp = va_arg(arg, const char **); if(param_charp) result = getinfo_char(data, info, param_charp); break; case CURLINFO_LONG: param_longp = va_arg(arg, long *); if(param_longp) result = getinfo_long(data, info, param_longp); break; case CURLINFO_DOUBLE: param_doublep = va_arg(arg, double *); if(param_doublep) result = getinfo_double(data, info, param_doublep); break; case CURLINFO_OFF_T: param_offt = va_arg(arg, curl_off_t *); if(param_offt) result = getinfo_offt(data, info, param_offt); break; case CURLINFO_SLIST: param_slistp = va_arg(arg, struct curl_slist **); if(param_slistp) result = getinfo_slist(data, info, param_slistp); break; case CURLINFO_SOCKET: param_socketp = va_arg(arg, curl_socket_t *); if(param_socketp) result = getinfo_socket(data, info, param_socketp); break; default: break; } va_end(arg); return result; }
YifuLiu/AliOS-Things
components/curl/lib/getinfo.c
C
apache-2.0
14,013
#ifndef HEADER_CURL_GETINFO_H #define HEADER_CURL_GETINFO_H /*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2010, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ CURLcode Curl_getinfo(struct Curl_easy *data, CURLINFO info, ...); CURLcode Curl_initinfo(struct Curl_easy *data); #endif /* HEADER_CURL_GETINFO_H */
YifuLiu/AliOS-Things
components/curl/lib/getinfo.h
C
apache-2.0
1,237
/*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2019, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "curl_setup.h" #ifndef CURL_DISABLE_GOPHER #include "urldata.h" #include <curl/curl.h> #include "transfer.h" #include "sendf.h" #include "progress.h" #include "gopher.h" #include "select.h" #include "strdup.h" #include "url.h" #include "escape.h" #include "warnless.h" #include "curl_printf.h" #include "curl_memory.h" /* The last #include file should be: */ #include "memdebug.h" /* * Forward declarations. */ static CURLcode gopher_do(struct connectdata *conn, bool *done); /* * Gopher protocol handler. * This is also a nice simple template to build off for simple * connect-command-download protocols. */ const struct Curl_handler Curl_handler_gopher = { "GOPHER", /* scheme */ ZERO_NULL, /* setup_connection */ gopher_do, /* do_it */ ZERO_NULL, /* done */ ZERO_NULL, /* do_more */ ZERO_NULL, /* connect_it */ ZERO_NULL, /* connecting */ ZERO_NULL, /* doing */ ZERO_NULL, /* proto_getsock */ ZERO_NULL, /* doing_getsock */ ZERO_NULL, /* domore_getsock */ ZERO_NULL, /* perform_getsock */ ZERO_NULL, /* disconnect */ ZERO_NULL, /* readwrite */ ZERO_NULL, /* connection_check */ PORT_GOPHER, /* defport */ CURLPROTO_GOPHER, /* protocol */ PROTOPT_NONE /* flags */ }; static CURLcode gopher_do(struct connectdata *conn, bool *done) { CURLcode result = CURLE_OK; struct Curl_easy *data = conn->data; curl_socket_t sockfd = conn->sock[FIRSTSOCKET]; char *gopherpath; char *path = data->state.up.path; char *query = data->state.up.query; char *sel = NULL; char *sel_org = NULL; ssize_t amount, k; size_t len; *done = TRUE; /* unconditionally */ /* path is guaranteed non-NULL */ DEBUGASSERT(path); if(query) gopherpath = aprintf("%s?%s", path, query); else gopherpath = strdup(path); if(!gopherpath) return CURLE_OUT_OF_MEMORY; /* Create selector. Degenerate cases: / and /1 => convert to "" */ if(strlen(gopherpath) <= 2) { sel = (char *)""; len = strlen(sel); free(gopherpath); } else { char *newp; /* Otherwise, drop / and the first character (i.e., item type) ... */ newp = gopherpath; newp += 2; /* ... and finally unescape */ result = Curl_urldecode(data, newp, 0, &sel, &len, FALSE); free(gopherpath); if(result) return result; sel_org = sel; } /* We use Curl_write instead of Curl_sendf to make sure the entire buffer is sent, which could be sizeable with long selectors. */ k = curlx_uztosz(len); for(;;) { result = Curl_write(conn, sockfd, sel, k, &amount); if(!result) { /* Which may not have written it all! */ result = Curl_client_write(conn, CLIENTWRITE_HEADER, sel, amount); if(result) break; k -= amount; sel += amount; if(k < 1) break; /* but it did write it all */ } else break; /* Don't busyloop. The entire loop thing is a work-around as it causes a BLOCKING behavior which is a NO-NO. This function should rather be split up in a do and a doing piece where the pieces that aren't possible to send now will be sent in the doing function repeatedly until the entire request is sent. Wait a while for the socket to be writable. Note that this doesn't acknowledge the timeout. */ if(SOCKET_WRITABLE(sockfd, 100) < 0) { result = CURLE_SEND_ERROR; break; } } free(sel_org); if(!result) /* We can use Curl_sendf to send the terminal \r\n relatively safely and save allocing another string/doing another _write loop. */ result = Curl_sendf(sockfd, conn, "\r\n"); if(result) { failf(data, "Failed sending Gopher request"); return result; } result = Curl_client_write(conn, CLIENTWRITE_HEADER, (char *)"\r\n", 2); if(result) return result; Curl_setup_transfer(data, FIRSTSOCKET, -1, FALSE, -1); return CURLE_OK; } #endif /*CURL_DISABLE_GOPHER*/
YifuLiu/AliOS-Things
components/curl/lib/gopher.c
C
apache-2.0
5,432
#ifndef HEADER_CURL_GOPHER_H #define HEADER_CURL_GOPHER_H /*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2009, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #ifndef CURL_DISABLE_GOPHER extern const struct Curl_handler Curl_handler_gopher; #endif #endif /* HEADER_CURL_GOPHER_H */
YifuLiu/AliOS-Things
components/curl/lib/gopher.h
C
apache-2.0
1,209
/*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2018, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "curl_setup.h" #include <curl/curl.h> #include "hash.h" #include "llist.h" #include "curl_memory.h" /* The last #include file should be: */ #include "memdebug.h" static void hash_element_dtor(void *user, void *element) { struct curl_hash *h = (struct curl_hash *) user; struct curl_hash_element *e = (struct curl_hash_element *) element; if(e->ptr) { h->dtor(e->ptr); e->ptr = NULL; } e->key_len = 0; free(e); } /* Initializes a hash structure. * Return 1 on error, 0 is fine. * * @unittest: 1602 * @unittest: 1603 */ int Curl_hash_init(struct curl_hash *h, int slots, hash_function hfunc, comp_function comparator, curl_hash_dtor dtor) { if(!slots || !hfunc || !comparator ||!dtor) { return 1; /* failure */ } h->hash_func = hfunc; h->comp_func = comparator; h->dtor = dtor; h->size = 0; h->slots = slots; h->table = malloc(slots * sizeof(struct curl_llist)); if(h->table) { int i; for(i = 0; i < slots; ++i) Curl_llist_init(&h->table[i], (curl_llist_dtor) hash_element_dtor); return 0; /* fine */ } h->slots = 0; return 1; /* failure */ } static struct curl_hash_element * mk_hash_element(const void *key, size_t key_len, const void *p) { /* allocate the struct plus memory after it to store the key */ struct curl_hash_element *he = malloc(sizeof(struct curl_hash_element) + key_len); if(he) { /* copy the key */ memcpy(he->key, key, key_len); he->key_len = key_len; he->ptr = (void *) p; } return he; } #define FETCH_LIST(x,y,z) &x->table[x->hash_func(y, z, x->slots)] /* Insert the data in the hash. If there already was a match in the hash, * that data is replaced. * * @unittest: 1305 * @unittest: 1602 * @unittest: 1603 */ void * Curl_hash_add(struct curl_hash *h, void *key, size_t key_len, void *p) { struct curl_hash_element *he; struct curl_llist_element *le; struct curl_llist *l = FETCH_LIST(h, key, key_len); for(le = l->head; le; le = le->next) { he = (struct curl_hash_element *) le->ptr; if(h->comp_func(he->key, he->key_len, key, key_len)) { Curl_llist_remove(l, le, (void *)h); --h->size; break; } } he = mk_hash_element(key, key_len, p); if(he) { Curl_llist_insert_next(l, l->tail, he, &he->list); ++h->size; return p; /* return the new entry */ } return NULL; /* failure */ } /* Remove the identified hash entry. * Returns non-zero on failure. * * @unittest: 1603 */ int Curl_hash_delete(struct curl_hash *h, void *key, size_t key_len) { struct curl_llist_element *le; struct curl_llist *l = FETCH_LIST(h, key, key_len); for(le = l->head; le; le = le->next) { struct curl_hash_element *he = le->ptr; if(h->comp_func(he->key, he->key_len, key, key_len)) { Curl_llist_remove(l, le, (void *) h); --h->size; return 0; } } return 1; } /* Retrieves a hash element. * * @unittest: 1603 */ void * Curl_hash_pick(struct curl_hash *h, void *key, size_t key_len) { struct curl_llist_element *le; struct curl_llist *l; if(h) { l = FETCH_LIST(h, key, key_len); for(le = l->head; le; le = le->next) { struct curl_hash_element *he = le->ptr; if(h->comp_func(he->key, he->key_len, key, key_len)) { return he->ptr; } } } return NULL; } #if defined(DEBUGBUILD) && defined(AGGRESIVE_TEST) void Curl_hash_apply(curl_hash *h, void *user, void (*cb)(void *user, void *ptr)) { struct curl_llist_element *le; int i; for(i = 0; i < h->slots; ++i) { for(le = (h->table[i])->head; le; le = le->next) { curl_hash_element *el = le->ptr; cb(user, el->ptr); } } } #endif /* Destroys all the entries in the given hash and resets its attributes, * prepping the given hash for [static|dynamic] deallocation. * * @unittest: 1305 * @unittest: 1602 * @unittest: 1603 */ void Curl_hash_destroy(struct curl_hash *h) { int i; for(i = 0; i < h->slots; ++i) { Curl_llist_destroy(&h->table[i], (void *) h); } Curl_safefree(h->table); h->size = 0; h->slots = 0; } /* Removes all the entries in the given hash. * * @unittest: 1602 */ void Curl_hash_clean(struct curl_hash *h) { Curl_hash_clean_with_criterium(h, NULL, NULL); } /* Cleans all entries that pass the comp function criteria. */ void Curl_hash_clean_with_criterium(struct curl_hash *h, void *user, int (*comp)(void *, void *)) { struct curl_llist_element *le; struct curl_llist_element *lnext; struct curl_llist *list; int i; if(!h) return; for(i = 0; i < h->slots; ++i) { list = &h->table[i]; le = list->head; /* get first list entry */ while(le) { struct curl_hash_element *he = le->ptr; lnext = le->next; /* ask the callback function if we shall remove this entry or not */ if(comp == NULL || comp(user, he->ptr)) { Curl_llist_remove(list, le, (void *) h); --h->size; /* one less entry in the hash now */ } le = lnext; } } } size_t Curl_hash_str(void *key, size_t key_length, size_t slots_num) { const char *key_str = (const char *) key; const char *end = key_str + key_length; size_t h = 5381; while(key_str < end) { h += h << 5; h ^= *key_str++; } return (h % slots_num); } size_t Curl_str_key_compare(void *k1, size_t key1_len, void *k2, size_t key2_len) { if((key1_len == key2_len) && !memcmp(k1, k2, key1_len)) return 1; return 0; } void Curl_hash_start_iterate(struct curl_hash *hash, struct curl_hash_iterator *iter) { iter->hash = hash; iter->slot_index = 0; iter->current_element = NULL; } struct curl_hash_element * Curl_hash_next_element(struct curl_hash_iterator *iter) { struct curl_hash *h = iter->hash; /* Get the next element in the current list, if any */ if(iter->current_element) iter->current_element = iter->current_element->next; /* If we have reached the end of the list, find the next one */ if(!iter->current_element) { int i; for(i = iter->slot_index; i < h->slots; i++) { if(h->table[i].head) { iter->current_element = h->table[i].head; iter->slot_index = i + 1; break; } } } if(iter->current_element) { struct curl_hash_element *he = iter->current_element->ptr; return he; } iter->current_element = NULL; return NULL; } #if 0 /* useful function for debugging hashes and their contents */ void Curl_hash_print(struct curl_hash *h, void (*func)(void *)) { struct curl_hash_iterator iter; struct curl_hash_element *he; int last_index = -1; if(!h) return; fprintf(stderr, "=Hash dump=\n"); Curl_hash_start_iterate(h, &iter); he = Curl_hash_next_element(&iter); while(he) { if(iter.slot_index != last_index) { fprintf(stderr, "index %d:", iter.slot_index); if(last_index >= 0) { fprintf(stderr, "\n"); } last_index = iter.slot_index; } if(func) func(he->ptr); else fprintf(stderr, " [%p]", (void *)he->ptr); he = Curl_hash_next_element(&iter); } fprintf(stderr, "\n"); } #endif
YifuLiu/AliOS-Things
components/curl/lib/hash.c
C
apache-2.0
8,386
#ifndef HEADER_CURL_HASH_H #define HEADER_CURL_HASH_H /*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2017, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "curl_setup.h" #include <stddef.h> #include "llist.h" /* Hash function prototype */ typedef size_t (*hash_function) (void *key, size_t key_length, size_t slots_num); /* Comparator function prototype. Compares two keys. */ typedef size_t (*comp_function) (void *key1, size_t key1_len, void *key2, size_t key2_len); typedef void (*curl_hash_dtor)(void *); struct curl_hash { struct curl_llist *table; /* Hash function to be used for this hash table */ hash_function hash_func; /* Comparator function to compare keys */ comp_function comp_func; curl_hash_dtor dtor; int slots; size_t size; }; struct curl_hash_element { struct curl_llist_element list; void *ptr; size_t key_len; char key[1]; /* allocated memory following the struct */ }; struct curl_hash_iterator { struct curl_hash *hash; int slot_index; struct curl_llist_element *current_element; }; int Curl_hash_init(struct curl_hash *h, int slots, hash_function hfunc, comp_function comparator, curl_hash_dtor dtor); void *Curl_hash_add(struct curl_hash *h, void *key, size_t key_len, void *p); int Curl_hash_delete(struct curl_hash *h, void *key, size_t key_len); void *Curl_hash_pick(struct curl_hash *, void *key, size_t key_len); void Curl_hash_apply(struct curl_hash *h, void *user, void (*cb)(void *user, void *ptr)); int Curl_hash_count(struct curl_hash *h); void Curl_hash_destroy(struct curl_hash *h); void Curl_hash_clean(struct curl_hash *h); void Curl_hash_clean_with_criterium(struct curl_hash *h, void *user, int (*comp)(void *, void *)); size_t Curl_hash_str(void *key, size_t key_length, size_t slots_num); size_t Curl_str_key_compare(void *k1, size_t key1_len, void *k2, size_t key2_len); void Curl_hash_start_iterate(struct curl_hash *hash, struct curl_hash_iterator *iter); struct curl_hash_element * Curl_hash_next_element(struct curl_hash_iterator *iter); void Curl_hash_print(struct curl_hash *h, void (*func)(void *)); #endif /* HEADER_CURL_HASH_H */
YifuLiu/AliOS-Things
components/curl/lib/hash.h
C
apache-2.0
3,448
/*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2018, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * * RFC2104 Keyed-Hashing for Message Authentication * ***************************************************************************/ #include "curl_setup.h" #ifndef CURL_DISABLE_CRYPTO_AUTH #include <curl/curl.h> #include "curl_hmac.h" #include "curl_memory.h" /* The last #include file should be: */ #include "memdebug.h" /* * Generic HMAC algorithm. * * This module computes HMAC digests based on any hash function. Parameters * and computing procedures are set-up dynamically at HMAC computation * context initialisation. */ static const unsigned char hmac_ipad = 0x36; static const unsigned char hmac_opad = 0x5C; HMAC_context * Curl_HMAC_init(const HMAC_params * hashparams, const unsigned char *key, unsigned int keylen) { size_t i; HMAC_context *ctxt; unsigned char *hkey; unsigned char b; /* Create HMAC context. */ i = sizeof(*ctxt) + 2 * hashparams->hmac_ctxtsize + hashparams->hmac_resultlen; ctxt = malloc(i); if(!ctxt) return ctxt; ctxt->hmac_hash = hashparams; ctxt->hmac_hashctxt1 = (void *) (ctxt + 1); ctxt->hmac_hashctxt2 = (void *) ((char *) ctxt->hmac_hashctxt1 + hashparams->hmac_ctxtsize); /* If the key is too long, replace it by its hash digest. */ if(keylen > hashparams->hmac_maxkeylen) { (*hashparams->hmac_hinit)(ctxt->hmac_hashctxt1); (*hashparams->hmac_hupdate)(ctxt->hmac_hashctxt1, key, keylen); hkey = (unsigned char *) ctxt->hmac_hashctxt2 + hashparams->hmac_ctxtsize; (*hashparams->hmac_hfinal)(hkey, ctxt->hmac_hashctxt1); key = hkey; keylen = hashparams->hmac_resultlen; } /* Prime the two hash contexts with the modified key. */ (*hashparams->hmac_hinit)(ctxt->hmac_hashctxt1); (*hashparams->hmac_hinit)(ctxt->hmac_hashctxt2); for(i = 0; i < keylen; i++) { b = (unsigned char)(*key ^ hmac_ipad); (*hashparams->hmac_hupdate)(ctxt->hmac_hashctxt1, &b, 1); b = (unsigned char)(*key++ ^ hmac_opad); (*hashparams->hmac_hupdate)(ctxt->hmac_hashctxt2, &b, 1); } for(; i < hashparams->hmac_maxkeylen; i++) { (*hashparams->hmac_hupdate)(ctxt->hmac_hashctxt1, &hmac_ipad, 1); (*hashparams->hmac_hupdate)(ctxt->hmac_hashctxt2, &hmac_opad, 1); } /* Done, return pointer to HMAC context. */ return ctxt; } int Curl_HMAC_update(HMAC_context * ctxt, const unsigned char *data, unsigned int len) { /* Update first hash calculation. */ (*ctxt->hmac_hash->hmac_hupdate)(ctxt->hmac_hashctxt1, data, len); return 0; } int Curl_HMAC_final(HMAC_context *ctxt, unsigned char *result) { const HMAC_params * hashparams = ctxt->hmac_hash; /* Do not get result if called with a null parameter: only release storage. */ if(!result) result = (unsigned char *) ctxt->hmac_hashctxt2 + ctxt->hmac_hash->hmac_ctxtsize; (*hashparams->hmac_hfinal)(result, ctxt->hmac_hashctxt1); (*hashparams->hmac_hupdate)(ctxt->hmac_hashctxt2, result, hashparams->hmac_resultlen); (*hashparams->hmac_hfinal)(result, ctxt->hmac_hashctxt2); free((char *) ctxt); return 0; } #endif /* CURL_DISABLE_CRYPTO_AUTH */
YifuLiu/AliOS-Things
components/curl/lib/hmac.c
C
apache-2.0
4,098
/*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2019, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "curl_setup.h" /*********************************************************************** * Only for builds using asynchronous name resolves **********************************************************************/ #ifdef CURLRES_ASYNCH #ifdef HAVE_NETINET_IN_H #include <netinet/in.h> #endif #ifdef HAVE_NETDB_H #include <netdb.h> #endif #ifdef HAVE_ARPA_INET_H #include <arpa/inet.h> #endif #ifdef __VMS #include <in.h> #include <inet.h> #endif #ifdef HAVE_PROCESS_H #include <process.h> #endif #include "urldata.h" #include "sendf.h" #include "hostip.h" #include "hash.h" #include "share.h" #include "strerror.h" #include "url.h" #include "curl_memory.h" /* The last #include file should be: */ #include "memdebug.h" /* * Curl_addrinfo_callback() gets called by ares, gethostbyname_thread() * or getaddrinfo_thread() when we got the name resolved (or not!). * * If the status argument is CURL_ASYNC_SUCCESS, this function takes * ownership of the Curl_addrinfo passed, storing the resolved data * in the DNS cache. * * The storage operation locks and unlocks the DNS cache. */ CURLcode Curl_addrinfo_callback(struct connectdata *conn, int status, struct Curl_addrinfo *ai) { struct Curl_dns_entry *dns = NULL; CURLcode result = CURLE_OK; conn->async.status = status; if(CURL_ASYNC_SUCCESS == status) { if(ai) { struct Curl_easy *data = conn->data; if(data->share) Curl_share_lock(data, CURL_LOCK_DATA_DNS, CURL_LOCK_ACCESS_SINGLE); dns = Curl_cache_addr(data, ai, conn->async.hostname, conn->async.port); if(data->share) Curl_share_unlock(data, CURL_LOCK_DATA_DNS); if(!dns) { /* failed to store, cleanup and return error */ Curl_freeaddrinfo(ai); result = CURLE_OUT_OF_MEMORY; } } else { result = CURLE_OUT_OF_MEMORY; } } conn->async.dns = dns; /* Set async.done TRUE last in this function since it may be used multi- threaded and once this is TRUE the other thread may read fields from the async struct */ conn->async.done = TRUE; /* IPv4: The input hostent struct will be freed by ares when we return from this function */ return result; } /* * Curl_getaddrinfo() is the generic low-level name resolve API within this * source file. There are several versions of this function - for different * name resolve layers (selected at build-time). They all take this same set * of arguments */ Curl_addrinfo *Curl_getaddrinfo(struct connectdata *conn, const char *hostname, int port, int *waitp) { return Curl_resolver_getaddrinfo(conn, hostname, port, waitp); } #endif /* CURLRES_ASYNCH */
YifuLiu/AliOS-Things
components/curl/lib/hostasyn.c
C
apache-2.0
3,901
/*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2018, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "curl_setup.h" #if defined(USE_OPENSSL) \ || defined(USE_GSKIT) \ || defined(USE_SCHANNEL) /* these backends use functions from this file */ #ifdef HAVE_NETINET_IN_H #include <netinet/in.h> #endif #ifdef HAVE_NETINET_IN6_H #include <netinet/in6.h> #endif #include "hostcheck.h" #include "strcase.h" #include "inet_pton.h" #include "curl_memory.h" /* The last #include file should be: */ #include "memdebug.h" /* * Match a hostname against a wildcard pattern. * E.g. * "foo.host.com" matches "*.host.com". * * We use the matching rule described in RFC6125, section 6.4.3. * https://tools.ietf.org/html/rfc6125#section-6.4.3 * * In addition: ignore trailing dots in the host names and wildcards, so that * the names are used normalized. This is what the browsers do. * * Do not allow wildcard matching on IP numbers. There are apparently * certificates being used with an IP address in the CN field, thus making no * apparent distinction between a name and an IP. We need to detect the use of * an IP address and not wildcard match on such names. * * NOTE: hostmatch() gets called with copied buffers so that it can modify the * contents at will. */ static int hostmatch(char *hostname, char *pattern) { const char *pattern_label_end, *pattern_wildcard, *hostname_label_end; int wildcard_enabled; size_t prefixlen, suffixlen; struct in_addr ignored; #ifdef ENABLE_IPV6 struct sockaddr_in6 si6; #endif /* normalize pattern and hostname by stripping off trailing dots */ size_t len = strlen(hostname); if(hostname[len-1]=='.') hostname[len-1] = 0; len = strlen(pattern); if(pattern[len-1]=='.') pattern[len-1] = 0; pattern_wildcard = strchr(pattern, '*'); if(pattern_wildcard == NULL) return strcasecompare(pattern, hostname) ? CURL_HOST_MATCH : CURL_HOST_NOMATCH; /* detect IP address as hostname and fail the match if so */ if(Curl_inet_pton(AF_INET, hostname, &ignored) > 0) return CURL_HOST_NOMATCH; #ifdef ENABLE_IPV6 if(Curl_inet_pton(AF_INET6, hostname, &si6.sin6_addr) > 0) return CURL_HOST_NOMATCH; #endif /* We require at least 2 dots in pattern to avoid too wide wildcard match. */ wildcard_enabled = 1; pattern_label_end = strchr(pattern, '.'); if(pattern_label_end == NULL || strchr(pattern_label_end + 1, '.') == NULL || pattern_wildcard > pattern_label_end || strncasecompare(pattern, "xn--", 4)) { wildcard_enabled = 0; } if(!wildcard_enabled) return strcasecompare(pattern, hostname) ? CURL_HOST_MATCH : CURL_HOST_NOMATCH; hostname_label_end = strchr(hostname, '.'); if(hostname_label_end == NULL || !strcasecompare(pattern_label_end, hostname_label_end)) return CURL_HOST_NOMATCH; /* The wildcard must match at least one character, so the left-most label of the hostname is at least as large as the left-most label of the pattern. */ if(hostname_label_end - hostname < pattern_label_end - pattern) return CURL_HOST_NOMATCH; prefixlen = pattern_wildcard - pattern; suffixlen = pattern_label_end - (pattern_wildcard + 1); return strncasecompare(pattern, hostname, prefixlen) && strncasecompare(pattern_wildcard + 1, hostname_label_end - suffixlen, suffixlen) ? CURL_HOST_MATCH : CURL_HOST_NOMATCH; } int Curl_cert_hostcheck(const char *match_pattern, const char *hostname) { int res = 0; if(!match_pattern || !*match_pattern || !hostname || !*hostname) /* sanity check */ ; else { char *matchp = strdup(match_pattern); if(matchp) { char *hostp = strdup(hostname); if(hostp) { if(hostmatch(hostp, matchp) == CURL_HOST_MATCH) res = 1; free(hostp); } free(matchp); } } return res; } #endif /* OPENSSL, GSKIT or schannel+wince */
YifuLiu/AliOS-Things
components/curl/lib/hostcheck.c
C
apache-2.0
4,920
#ifndef HEADER_CURL_HOSTCHECK_H #define HEADER_CURL_HOSTCHECK_H /*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2012, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include <curl/curl.h> #define CURL_HOST_NOMATCH 0 #define CURL_HOST_MATCH 1 int Curl_cert_hostcheck(const char *match_pattern, const char *hostname); #endif /* HEADER_CURL_HOSTCHECK_H */
YifuLiu/AliOS-Things
components/curl/lib/hostcheck.h
C
apache-2.0
1,283
/*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2019, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "curl_setup.h" #ifdef HAVE_NETINET_IN_H #include <netinet/in.h> #endif #ifdef HAVE_NETINET_IN6_H #include <netinet/in6.h> #endif #ifdef HAVE_NETDB_H #ifdef USE_LWIPSOCK #include <lwip/sockets.h> #else #include <netdb.h> #endif #endif #ifdef HAVE_ARPA_INET_H #include <arpa/inet.h> #endif #ifdef __VMS #include <in.h> #include <inet.h> #endif #ifdef HAVE_SETJMP_H #include <setjmp.h> #endif #ifdef HAVE_SIGNAL_H #include <signal.h> #endif #ifdef HAVE_PROCESS_H #include <process.h> #endif #include "urldata.h" #include "sendf.h" #include "hostip.h" #include "hash.h" #include "rand.h" #include "share.h" #include "strerror.h" #include "url.h" #include "inet_ntop.h" #include "multiif.h" #include "doh.h" #include "warnless.h" /* The last 3 #include files should be in this order */ #include "curl_printf.h" #include "curl_memory.h" #include "memdebug.h" #if defined(CURLRES_SYNCH) && \ defined(HAVE_ALARM) && defined(SIGALRM) && defined(HAVE_SIGSETJMP) /* alarm-based timeouts can only be used with all the dependencies satisfied */ #define USE_ALARM_TIMEOUT #endif #define MAX_HOSTCACHE_LEN (255 + 7) /* max FQDN + colon + port number + zero */ /* * hostip.c explained * ================== * * The main COMPILE-TIME DEFINES to keep in mind when reading the host*.c * source file are these: * * CURLRES_IPV6 - this host has getaddrinfo() and family, and thus we use * that. The host may not be able to resolve IPv6, but we don't really have to * take that into account. Hosts that aren't IPv6-enabled have CURLRES_IPV4 * defined. * * CURLRES_ARES - is defined if libcurl is built to use c-ares for * asynchronous name resolves. This can be Windows or *nix. * * CURLRES_THREADED - is defined if libcurl is built to run under (native) * Windows, and then the name resolve will be done in a new thread, and the * supported API will be the same as for ares-builds. * * If any of the two previous are defined, CURLRES_ASYNCH is defined too. If * libcurl is not built to use an asynchronous resolver, CURLRES_SYNCH is * defined. * * The host*.c sources files are split up like this: * * hostip.c - method-independent resolver functions and utility functions * hostasyn.c - functions for asynchronous name resolves * hostsyn.c - functions for synchronous name resolves * hostip4.c - IPv4 specific functions * hostip6.c - IPv6 specific functions * * The two asynchronous name resolver backends are implemented in: * asyn-ares.c - functions for ares-using name resolves * asyn-thread.c - functions for threaded name resolves * The hostip.h is the united header file for all this. It defines the * CURLRES_* defines based on the config*.h and curl_setup.h defines. */ static void freednsentry(void *freethis); /* * Return # of addresses in a Curl_addrinfo struct */ int Curl_num_addresses(const Curl_addrinfo *addr) { int i = 0; while(addr) { addr = addr->ai_next; i++; } return i; } /* * Curl_printable_address() returns a printable version of the 1st address * given in the 'ai' argument. The result will be stored in the buf that is * bufsize bytes big. * * If the conversion fails, it returns NULL. */ const char * Curl_printable_address(const Curl_addrinfo *ai, char *buf, size_t bufsize) { const struct sockaddr_in *sa4; const struct in_addr *ipaddr4; #ifdef ENABLE_IPV6 const struct sockaddr_in6 *sa6; const struct in6_addr *ipaddr6; #endif switch(ai->ai_family) { case AF_INET: sa4 = (const void *)ai->ai_addr; ipaddr4 = &sa4->sin_addr; return Curl_inet_ntop(ai->ai_family, (const void *)ipaddr4, buf, bufsize); #ifdef ENABLE_IPV6 case AF_INET6: sa6 = (const void *)ai->ai_addr; ipaddr6 = &sa6->sin6_addr; return Curl_inet_ntop(ai->ai_family, (const void *)ipaddr6, buf, bufsize); #endif default: break; } return NULL; } /* * Create a hostcache id string for the provided host + port, to be used by * the DNS caching. Without alloc. */ static void create_hostcache_id(const char *name, int port, char *ptr, size_t buflen) { size_t len = strlen(name); if(len > (buflen - 7)) len = buflen - 7; /* store and lower case the name */ while(len--) *ptr++ = (char)TOLOWER(*name++); msnprintf(ptr, 7, ":%u", port); } struct hostcache_prune_data { long cache_timeout; time_t now; }; /* * This function is set as a callback to be called for every entry in the DNS * cache when we want to prune old unused entries. * * Returning non-zero means remove the entry, return 0 to keep it in the * cache. */ static int hostcache_timestamp_remove(void *datap, void *hc) { struct hostcache_prune_data *data = (struct hostcache_prune_data *) datap; struct Curl_dns_entry *c = (struct Curl_dns_entry *) hc; return (0 != c->timestamp) && (data->now - c->timestamp >= data->cache_timeout); } /* * Prune the DNS cache. This assumes that a lock has already been taken. */ static void hostcache_prune(struct curl_hash *hostcache, long cache_timeout, time_t now) { struct hostcache_prune_data user; user.cache_timeout = cache_timeout; user.now = now; Curl_hash_clean_with_criterium(hostcache, (void *) &user, hostcache_timestamp_remove); } /* * Library-wide function for pruning the DNS cache. This function takes and * returns the appropriate locks. */ void Curl_hostcache_prune(struct Curl_easy *data) { time_t now; if((data->set.dns_cache_timeout == -1) || !data->dns.hostcache) /* cache forever means never prune, and NULL hostcache means we can't do it */ return; if(data->share) Curl_share_lock(data, CURL_LOCK_DATA_DNS, CURL_LOCK_ACCESS_SINGLE); time(&now); /* Remove outdated and unused entries from the hostcache */ hostcache_prune(data->dns.hostcache, data->set.dns_cache_timeout, now); if(data->share) Curl_share_unlock(data, CURL_LOCK_DATA_DNS); } #ifdef HAVE_SIGSETJMP /* Beware this is a global and unique instance. This is used to store the return address that we can jump back to from inside a signal handler. This is not thread-safe stuff. */ sigjmp_buf curl_jmpenv; #endif /* lookup address, returns entry if found and not stale */ static struct Curl_dns_entry * fetch_addr(struct connectdata *conn, const char *hostname, int port) { struct Curl_dns_entry *dns = NULL; size_t entry_len; struct Curl_easy *data = conn->data; char entry_id[MAX_HOSTCACHE_LEN]; /* Create an entry id, based upon the hostname and port */ create_hostcache_id(hostname, port, entry_id, sizeof(entry_id)); entry_len = strlen(entry_id); /* See if its already in our dns cache */ dns = Curl_hash_pick(data->dns.hostcache, entry_id, entry_len + 1); /* No entry found in cache, check if we might have a wildcard entry */ if(!dns && data->change.wildcard_resolve) { create_hostcache_id("*", port, entry_id, sizeof(entry_id)); entry_len = strlen(entry_id); /* See if it's already in our dns cache */ dns = Curl_hash_pick(data->dns.hostcache, entry_id, entry_len + 1); } if(dns && (data->set.dns_cache_timeout != -1)) { /* See whether the returned entry is stale. Done before we release lock */ struct hostcache_prune_data user; time(&user.now); user.cache_timeout = data->set.dns_cache_timeout; if(hostcache_timestamp_remove(&user, dns)) { infof(data, "Hostname in DNS cache was stale, zapped\n"); dns = NULL; /* the memory deallocation is being handled by the hash */ Curl_hash_delete(data->dns.hostcache, entry_id, entry_len + 1); } } return dns; } /* * Curl_fetch_addr() fetches a 'Curl_dns_entry' already in the DNS cache. * * Curl_resolv() checks initially and multi_runsingle() checks each time * it discovers the handle in the state WAITRESOLVE whether the hostname * has already been resolved and the address has already been stored in * the DNS cache. This short circuits waiting for a lot of pending * lookups for the same hostname requested by different handles. * * Returns the Curl_dns_entry entry pointer or NULL if not in the cache. * * The returned data *MUST* be "unlocked" with Curl_resolv_unlock() after * use, or we'll leak memory! */ struct Curl_dns_entry * Curl_fetch_addr(struct connectdata *conn, const char *hostname, int port) { struct Curl_easy *data = conn->data; struct Curl_dns_entry *dns = NULL; if(data->share) Curl_share_lock(data, CURL_LOCK_DATA_DNS, CURL_LOCK_ACCESS_SINGLE); dns = fetch_addr(conn, hostname, port); if(dns) dns->inuse++; /* we use it! */ if(data->share) Curl_share_unlock(data, CURL_LOCK_DATA_DNS); return dns; } #ifndef CURL_DISABLE_SHUFFLE_DNS UNITTEST CURLcode Curl_shuffle_addr(struct Curl_easy *data, Curl_addrinfo **addr); /* * Curl_shuffle_addr() shuffles the order of addresses in a 'Curl_addrinfo' * struct by re-linking its linked list. * * The addr argument should be the address of a pointer to the head node of a * `Curl_addrinfo` list and it will be modified to point to the new head after * shuffling. * * Not declared static only to make it easy to use in a unit test! * * @unittest: 1608 */ UNITTEST CURLcode Curl_shuffle_addr(struct Curl_easy *data, Curl_addrinfo **addr) { CURLcode result = CURLE_OK; const int num_addrs = Curl_num_addresses(*addr); if(num_addrs > 1) { Curl_addrinfo **nodes; infof(data, "Shuffling %i addresses", num_addrs); nodes = malloc(num_addrs*sizeof(*nodes)); if(nodes) { int i; unsigned int *rnd; const size_t rnd_size = num_addrs * sizeof(*rnd); /* build a plain array of Curl_addrinfo pointers */ nodes[0] = *addr; for(i = 1; i < num_addrs; i++) { nodes[i] = nodes[i-1]->ai_next; } rnd = malloc(rnd_size); if(rnd) { /* Fisher-Yates shuffle */ if(Curl_rand(data, (unsigned char *)rnd, rnd_size) == CURLE_OK) { Curl_addrinfo *swap_tmp; for(i = num_addrs - 1; i > 0; i--) { swap_tmp = nodes[rnd[i] % (i + 1)]; nodes[rnd[i] % (i + 1)] = nodes[i]; nodes[i] = swap_tmp; } /* relink list in the new order */ for(i = 1; i < num_addrs; i++) { nodes[i-1]->ai_next = nodes[i]; } nodes[num_addrs-1]->ai_next = NULL; *addr = nodes[0]; } free(rnd); } else result = CURLE_OUT_OF_MEMORY; free(nodes); } else result = CURLE_OUT_OF_MEMORY; } return result; } #endif /* * Curl_cache_addr() stores a 'Curl_addrinfo' struct in the DNS cache. * * When calling Curl_resolv() has resulted in a response with a returned * address, we call this function to store the information in the dns * cache etc * * Returns the Curl_dns_entry entry pointer or NULL if the storage failed. */ struct Curl_dns_entry * Curl_cache_addr(struct Curl_easy *data, Curl_addrinfo *addr, const char *hostname, int port) { char entry_id[MAX_HOSTCACHE_LEN]; size_t entry_len; struct Curl_dns_entry *dns; struct Curl_dns_entry *dns2; #ifndef CURL_DISABLE_SHUFFLE_DNS /* shuffle addresses if requested */ if(data->set.dns_shuffle_addresses) { CURLcode result = Curl_shuffle_addr(data, &addr); if(result) return NULL; } #endif /* Create a new cache entry */ dns = calloc(1, sizeof(struct Curl_dns_entry)); if(!dns) { return NULL; } /* Create an entry id, based upon the hostname and port */ create_hostcache_id(hostname, port, entry_id, sizeof(entry_id)); entry_len = strlen(entry_id); dns->inuse = 1; /* the cache has the first reference */ dns->addr = addr; /* this is the address(es) */ time(&dns->timestamp); if(dns->timestamp == 0) dns->timestamp = 1; /* zero indicates CURLOPT_RESOLVE entry */ /* Store the resolved data in our DNS cache. */ dns2 = Curl_hash_add(data->dns.hostcache, entry_id, entry_len + 1, (void *)dns); if(!dns2) { free(dns); return NULL; } dns = dns2; dns->inuse++; /* mark entry as in-use */ return dns; } /* * Curl_resolv() is the main name resolve function within libcurl. It resolves * a name and returns a pointer to the entry in the 'entry' argument (if one * is provided). This function might return immediately if we're using asynch * resolves. See the return codes. * * The cache entry we return will get its 'inuse' counter increased when this * function is used. You MUST call Curl_resolv_unlock() later (when you're * done using this struct) to decrease the counter again. * * In debug mode, we specifically test for an interface name "LocalHost" * and resolve "localhost" instead as a means to permit test cases * to connect to a local test server with any host name. * * Return codes: * * CURLRESOLV_ERROR (-1) = error, no pointer * CURLRESOLV_RESOLVED (0) = OK, pointer provided * CURLRESOLV_PENDING (1) = waiting for response, no pointer */ int Curl_resolv(struct connectdata *conn, const char *hostname, int port, bool allowDOH, struct Curl_dns_entry **entry) { struct Curl_dns_entry *dns = NULL; struct Curl_easy *data = conn->data; CURLcode result; int rc = CURLRESOLV_ERROR; /* default to failure */ *entry = NULL; if(data->share) Curl_share_lock(data, CURL_LOCK_DATA_DNS, CURL_LOCK_ACCESS_SINGLE); dns = fetch_addr(conn, hostname, port); if(dns) { infof(data, "Hostname %s was found in DNS cache\n", hostname); dns->inuse++; /* we use it! */ rc = CURLRESOLV_RESOLVED; } if(data->share) Curl_share_unlock(data, CURL_LOCK_DATA_DNS); if(!dns) { /* The entry was not in the cache. Resolve it to IP address */ Curl_addrinfo *addr; int respwait = 0; /* Check what IP specifics the app has requested and if we can provide it. * If not, bail out. */ if(!Curl_ipvalid(conn)) return CURLRESOLV_ERROR; /* notify the resolver start callback */ if(data->set.resolver_start) { int st; Curl_set_in_callback(data, true); st = data->set.resolver_start(data->state.resolver, NULL, data->set.resolver_start_client); Curl_set_in_callback(data, false); if(st) return CURLRESOLV_ERROR; } if(allowDOH && data->set.doh) { addr = Curl_doh(conn, hostname, port, &respwait); } else { /* If Curl_getaddrinfo() returns NULL, 'respwait' might be set to a non-zero value indicating that we need to wait for the response to the resolve call */ addr = Curl_getaddrinfo(conn, #ifdef DEBUGBUILD (data->set.str[STRING_DEVICE] && !strcmp(data->set.str[STRING_DEVICE], "LocalHost"))?"localhost": #endif hostname, port, &respwait); } if(!addr) { if(respwait) { /* the response to our resolve call will come asynchronously at a later time, good or bad */ /* First, check that we haven't received the info by now */ result = Curl_resolv_check(conn, &dns); if(result) /* error detected */ return CURLRESOLV_ERROR; if(dns) rc = CURLRESOLV_RESOLVED; /* pointer provided */ else rc = CURLRESOLV_PENDING; /* no info yet */ } } else { if(data->share) Curl_share_lock(data, CURL_LOCK_DATA_DNS, CURL_LOCK_ACCESS_SINGLE); /* we got a response, store it in the cache */ dns = Curl_cache_addr(data, addr, hostname, port); if(data->share) Curl_share_unlock(data, CURL_LOCK_DATA_DNS); if(!dns) /* returned failure, bail out nicely */ Curl_freeaddrinfo(addr); else rc = CURLRESOLV_RESOLVED; } } *entry = dns; return rc; } #ifdef USE_ALARM_TIMEOUT /* * This signal handler jumps back into the main libcurl code and continues * execution. This effectively causes the remainder of the application to run * within a signal handler which is nonportable and could lead to problems. */ static RETSIGTYPE alarmfunc(int sig) { /* this is for "-ansi -Wall -pedantic" to stop complaining! (rabe) */ (void)sig; siglongjmp(curl_jmpenv, 1); } #endif /* USE_ALARM_TIMEOUT */ /* * Curl_resolv_timeout() is the same as Curl_resolv() but specifies a * timeout. This function might return immediately if we're using asynch * resolves. See the return codes. * * The cache entry we return will get its 'inuse' counter increased when this * function is used. You MUST call Curl_resolv_unlock() later (when you're * done using this struct) to decrease the counter again. * * If built with a synchronous resolver and use of signals is not * disabled by the application, then a nonzero timeout will cause a * timeout after the specified number of milliseconds. Otherwise, timeout * is ignored. * * Return codes: * * CURLRESOLV_TIMEDOUT(-2) = warning, time too short or previous alarm expired * CURLRESOLV_ERROR (-1) = error, no pointer * CURLRESOLV_RESOLVED (0) = OK, pointer provided * CURLRESOLV_PENDING (1) = waiting for response, no pointer */ int Curl_resolv_timeout(struct connectdata *conn, const char *hostname, int port, struct Curl_dns_entry **entry, time_t timeoutms) { #ifdef USE_ALARM_TIMEOUT #ifdef HAVE_SIGACTION struct sigaction keep_sigact; /* store the old struct here */ volatile bool keep_copysig = FALSE; /* whether old sigact has been saved */ struct sigaction sigact; #else #ifdef HAVE_SIGNAL void (*keep_sigact)(int); /* store the old handler here */ #endif /* HAVE_SIGNAL */ #endif /* HAVE_SIGACTION */ volatile long timeout; volatile unsigned int prev_alarm = 0; struct Curl_easy *data = conn->data; #endif /* USE_ALARM_TIMEOUT */ int rc; *entry = NULL; if(timeoutms < 0) /* got an already expired timeout */ return CURLRESOLV_TIMEDOUT; #ifdef USE_ALARM_TIMEOUT if(data->set.no_signal) /* Ignore the timeout when signals are disabled */ timeout = 0; else timeout = (timeoutms > LONG_MAX) ? LONG_MAX : (long)timeoutms; if(!timeout) /* USE_ALARM_TIMEOUT defined, but no timeout actually requested */ return Curl_resolv(conn, hostname, port, TRUE, entry); if(timeout < 1000) { /* The alarm() function only provides integer second resolution, so if we want to wait less than one second we must bail out already now. */ failf(data, "remaining timeout of %ld too small to resolve via SIGALRM method", timeout); return CURLRESOLV_TIMEDOUT; } /* This allows us to time-out from the name resolver, as the timeout will generate a signal and we will siglongjmp() from that here. This technique has problems (see alarmfunc). This should be the last thing we do before calling Curl_resolv(), as otherwise we'd have to worry about variables that get modified before we invoke Curl_resolv() (and thus use "volatile"). */ if(sigsetjmp(curl_jmpenv, 1)) { /* this is coming from a siglongjmp() after an alarm signal */ failf(data, "name lookup timed out"); rc = CURLRESOLV_ERROR; goto clean_up; } else { /************************************************************* * Set signal handler to catch SIGALRM * Store the old value to be able to set it back later! *************************************************************/ #ifdef HAVE_SIGACTION sigaction(SIGALRM, NULL, &sigact); keep_sigact = sigact; keep_copysig = TRUE; /* yes, we have a copy */ sigact.sa_handler = alarmfunc; #ifdef SA_RESTART /* HPUX doesn't have SA_RESTART but defaults to that behaviour! */ sigact.sa_flags &= ~SA_RESTART; #endif /* now set the new struct */ sigaction(SIGALRM, &sigact, NULL); #else /* HAVE_SIGACTION */ /* no sigaction(), revert to the much lamer signal() */ #ifdef HAVE_SIGNAL keep_sigact = signal(SIGALRM, alarmfunc); #endif #endif /* HAVE_SIGACTION */ /* alarm() makes a signal get sent when the timeout fires off, and that will abort system calls */ prev_alarm = alarm(curlx_sltoui(timeout/1000L)); } #else #ifndef CURLRES_ASYNCH if(timeoutms) infof(conn->data, "timeout on name lookup is not supported\n"); #else (void)timeoutms; /* timeoutms not used with an async resolver */ #endif #endif /* USE_ALARM_TIMEOUT */ /* Perform the actual name resolution. This might be interrupted by an * alarm if it takes too long. */ rc = Curl_resolv(conn, hostname, port, TRUE, entry); #ifdef USE_ALARM_TIMEOUT clean_up: if(!prev_alarm) /* deactivate a possibly active alarm before uninstalling the handler */ alarm(0); #ifdef HAVE_SIGACTION if(keep_copysig) { /* we got a struct as it looked before, now put that one back nice and clean */ sigaction(SIGALRM, &keep_sigact, NULL); /* put it back */ } #else #ifdef HAVE_SIGNAL /* restore the previous SIGALRM handler */ signal(SIGALRM, keep_sigact); #endif #endif /* HAVE_SIGACTION */ /* switch back the alarm() to either zero or to what it was before minus the time we spent until now! */ if(prev_alarm) { /* there was an alarm() set before us, now put it back */ timediff_t elapsed_secs = Curl_timediff(Curl_now(), conn->created) / 1000; /* the alarm period is counted in even number of seconds */ unsigned long alarm_set = prev_alarm - elapsed_secs; if(!alarm_set || ((alarm_set >= 0x80000000) && (prev_alarm < 0x80000000)) ) { /* if the alarm time-left reached zero or turned "negative" (counted with unsigned values), we should fire off a SIGALRM here, but we won't, and zero would be to switch it off so we never set it to less than 1! */ alarm(1); rc = CURLRESOLV_TIMEDOUT; failf(data, "Previous alarm fired off!"); } else alarm((unsigned int)alarm_set); } #endif /* USE_ALARM_TIMEOUT */ return rc; } /* * Curl_resolv_unlock() unlocks the given cached DNS entry. When this has been * made, the struct may be destroyed due to pruning. It is important that only * one unlock is made for each Curl_resolv() call. * * May be called with 'data' == NULL for global cache. */ void Curl_resolv_unlock(struct Curl_easy *data, struct Curl_dns_entry *dns) { if(data && data->share) Curl_share_lock(data, CURL_LOCK_DATA_DNS, CURL_LOCK_ACCESS_SINGLE); freednsentry(dns); if(data && data->share) Curl_share_unlock(data, CURL_LOCK_DATA_DNS); } /* * File-internal: release cache dns entry reference, free if inuse drops to 0 */ static void freednsentry(void *freethis) { struct Curl_dns_entry *dns = (struct Curl_dns_entry *) freethis; DEBUGASSERT(dns && (dns->inuse>0)); dns->inuse--; if(dns->inuse == 0) { Curl_freeaddrinfo(dns->addr); free(dns); } } /* * Curl_mk_dnscache() inits a new DNS cache and returns success/failure. */ int Curl_mk_dnscache(struct curl_hash *hash) { return Curl_hash_init(hash, 7, Curl_hash_str, Curl_str_key_compare, freednsentry); } /* * Curl_hostcache_clean() * * This _can_ be called with 'data' == NULL but then of course no locking * can be done! */ void Curl_hostcache_clean(struct Curl_easy *data, struct curl_hash *hash) { if(data && data->share) Curl_share_lock(data, CURL_LOCK_DATA_DNS, CURL_LOCK_ACCESS_SINGLE); Curl_hash_clean(hash); if(data && data->share) Curl_share_unlock(data, CURL_LOCK_DATA_DNS); } CURLcode Curl_loadhostpairs(struct Curl_easy *data) { struct curl_slist *hostp; char hostname[256]; int port = 0; /* Default is no wildcard found */ data->change.wildcard_resolve = false; for(hostp = data->change.resolve; hostp; hostp = hostp->next) { char entry_id[MAX_HOSTCACHE_LEN]; if(!hostp->data) continue; if(hostp->data[0] == '-') { size_t entry_len; if(2 != sscanf(hostp->data + 1, "%255[^:]:%d", hostname, &port)) { infof(data, "Couldn't parse CURLOPT_RESOLVE removal entry '%s'!\n", hostp->data); continue; } /* Create an entry id, based upon the hostname and port */ create_hostcache_id(hostname, port, entry_id, sizeof(entry_id)); entry_len = strlen(entry_id); if(data->share) Curl_share_lock(data, CURL_LOCK_DATA_DNS, CURL_LOCK_ACCESS_SINGLE); /* delete entry, ignore if it didn't exist */ Curl_hash_delete(data->dns.hostcache, entry_id, entry_len + 1); if(data->share) Curl_share_unlock(data, CURL_LOCK_DATA_DNS); } else { struct Curl_dns_entry *dns; Curl_addrinfo *head = NULL, *tail = NULL; size_t entry_len; char address[64]; #if !defined(CURL_DISABLE_VERBOSE_STRINGS) char *addresses = NULL; #endif char *addr_begin; char *addr_end; char *port_ptr; char *end_ptr; char *host_end; unsigned long tmp_port; bool error = true; host_end = strchr(hostp->data, ':'); if(!host_end || ((host_end - hostp->data) >= (ptrdiff_t)sizeof(hostname))) goto err; memcpy(hostname, hostp->data, host_end - hostp->data); hostname[host_end - hostp->data] = '\0'; port_ptr = host_end + 1; tmp_port = strtoul(port_ptr, &end_ptr, 10); if(tmp_port > USHRT_MAX || end_ptr == port_ptr || *end_ptr != ':') goto err; port = (int)tmp_port; #if !defined(CURL_DISABLE_VERBOSE_STRINGS) addresses = end_ptr + 1; #endif while(*end_ptr) { size_t alen; Curl_addrinfo *ai; addr_begin = end_ptr + 1; addr_end = strchr(addr_begin, ','); if(!addr_end) addr_end = addr_begin + strlen(addr_begin); end_ptr = addr_end; /* allow IP(v6) address within [brackets] */ if(*addr_begin == '[') { if(addr_end == addr_begin || *(addr_end - 1) != ']') goto err; ++addr_begin; --addr_end; } alen = addr_end - addr_begin; if(!alen) continue; if(alen >= sizeof(address)) goto err; memcpy(address, addr_begin, alen); address[alen] = '\0'; #ifndef ENABLE_IPV6 if(strchr(address, ':')) { infof(data, "Ignoring resolve address '%s', missing IPv6 support.\n", address); continue; } #endif ai = Curl_str2addr(address, port); if(!ai) { infof(data, "Resolve address '%s' found illegal!\n", address); goto err; } if(tail) { tail->ai_next = ai; tail = tail->ai_next; } else { head = tail = ai; } } if(!head) goto err; error = false; err: if(error) { infof(data, "Couldn't parse CURLOPT_RESOLVE entry '%s'!\n", hostp->data); Curl_freeaddrinfo(head); continue; } /* Create an entry id, based upon the hostname and port */ create_hostcache_id(hostname, port, entry_id, sizeof(entry_id)); entry_len = strlen(entry_id); if(data->share) Curl_share_lock(data, CURL_LOCK_DATA_DNS, CURL_LOCK_ACCESS_SINGLE); /* See if its already in our dns cache */ dns = Curl_hash_pick(data->dns.hostcache, entry_id, entry_len + 1); if(dns) { infof(data, "RESOLVE %s:%d is - old addresses discarded!\n", hostname, port); /* delete old entry entry, there are two reasons for this 1. old entry may have different addresses. 2. even if entry with correct addresses is already in the cache, but if it is close to expire, then by the time next http request is made, it can get expired and pruned because old entry is not necessarily marked as added by CURLOPT_RESOLVE. */ Curl_hash_delete(data->dns.hostcache, entry_id, entry_len + 1); } /* put this new host in the cache */ dns = Curl_cache_addr(data, head, hostname, port); if(dns) { dns->timestamp = 0; /* mark as added by CURLOPT_RESOLVE */ /* release the returned reference; the cache itself will keep the * entry alive: */ dns->inuse--; } if(data->share) Curl_share_unlock(data, CURL_LOCK_DATA_DNS); if(!dns) { Curl_freeaddrinfo(head); return CURLE_OUT_OF_MEMORY; } infof(data, "Added %s:%d:%s to DNS cache\n", hostname, port, addresses); /* Wildcard hostname */ if(hostname[0] == '*' && hostname[1] == '\0') { infof(data, "RESOLVE %s:%d is wildcard, enabling wildcard checks\n", hostname, port); data->change.wildcard_resolve = true; } } } data->change.resolve = NULL; /* dealt with now */ return CURLE_OK; } CURLcode Curl_resolv_check(struct connectdata *conn, struct Curl_dns_entry **dns) { if(conn->data->set.doh) return Curl_doh_is_resolved(conn, dns); return Curl_resolver_is_resolved(conn, dns); } int Curl_resolv_getsock(struct connectdata *conn, curl_socket_t *socks, int numsocks) { #ifdef CURLRES_ASYNCH if(conn->data->set.doh) /* nothing to wait for during DOH resolve, those handles have their own sockets */ return GETSOCK_BLANK; return Curl_resolver_getsock(conn, socks, numsocks); #else (void)conn; (void)socks; (void)numsocks; return GETSOCK_BLANK; #endif } /* Call this function after Curl_connect() has returned async=TRUE and then a successful name resolve has been received. Note: this function disconnects and frees the conn data in case of resolve failure */ CURLcode Curl_once_resolved(struct connectdata *conn, bool *protocol_done) { CURLcode result; if(conn->async.dns) { conn->dns_entry = conn->async.dns; conn->async.dns = NULL; } result = Curl_setup_conn(conn, protocol_done); if(result) /* We're not allowed to return failure with memory left allocated in the connectdata struct, free those here */ Curl_disconnect(conn->data, conn, TRUE); /* close the connection */ return result; }
YifuLiu/AliOS-Things
components/curl/lib/hostip.c
C
apache-2.0
31,883
#ifndef HEADER_CURL_HOSTIP_H #define HEADER_CURL_HOSTIP_H /*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2019, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "curl_setup.h" #include "hash.h" #include "curl_addrinfo.h" #include "asyn.h" #ifdef HAVE_SETJMP_H #include <setjmp.h> #endif #ifdef NETWARE #undef in_addr_t #define in_addr_t unsigned long #endif /* Allocate enough memory to hold the full name information structs and * everything. OSF1 is known to require at least 8872 bytes. The buffer * required for storing all possible aliases and IP numbers is according to * Stevens' Unix Network Programming 2nd edition, p. 304: 8192 bytes! */ #define CURL_HOSTENT_SIZE 9000 #define CURL_TIMEOUT_RESOLVE 300 /* when using asynch methods, we allow this many seconds for a name resolve */ #define CURL_ASYNC_SUCCESS CURLE_OK struct addrinfo; struct hostent; struct Curl_easy; struct connectdata; /* * Curl_global_host_cache_init() initializes and sets up a global DNS cache. * Global DNS cache is general badness. Do not use. This will be removed in * a future version. Use the share interface instead! * * Returns a struct curl_hash pointer on success, NULL on failure. */ struct curl_hash *Curl_global_host_cache_init(void); void Curl_global_host_cache_dtor(void); struct Curl_dns_entry { Curl_addrinfo *addr; /* timestamp == 0 -- CURLOPT_RESOLVE entry, doesn't timeout */ time_t timestamp; /* use-counter, use Curl_resolv_unlock to release reference */ long inuse; }; /* * Curl_resolv() returns an entry with the info for the specified host * and port. * * The returned data *MUST* be "unlocked" with Curl_resolv_unlock() after * use, or we'll leak memory! */ /* return codes */ #define CURLRESOLV_TIMEDOUT -2 #define CURLRESOLV_ERROR -1 #define CURLRESOLV_RESOLVED 0 #define CURLRESOLV_PENDING 1 int Curl_resolv(struct connectdata *conn, const char *hostname, int port, bool allowDOH, struct Curl_dns_entry **dnsentry); int Curl_resolv_timeout(struct connectdata *conn, const char *hostname, int port, struct Curl_dns_entry **dnsentry, time_t timeoutms); #ifdef CURLRES_IPV6 /* * Curl_ipv6works() returns TRUE if IPv6 seems to work. */ bool Curl_ipv6works(void); #else #define Curl_ipv6works() FALSE #endif /* * Curl_ipvalid() checks what CURL_IPRESOLVE_* requirements that might've * been set and returns TRUE if they are OK. */ bool Curl_ipvalid(struct connectdata *conn); /* * Curl_getaddrinfo() is the generic low-level name resolve API within this * source file. There are several versions of this function - for different * name resolve layers (selected at build-time). They all take this same set * of arguments */ Curl_addrinfo *Curl_getaddrinfo(struct connectdata *conn, const char *hostname, int port, int *waitp); /* unlock a previously resolved dns entry */ void Curl_resolv_unlock(struct Curl_easy *data, struct Curl_dns_entry *dns); /* for debugging purposes only: */ void Curl_scan_cache_used(void *user, void *ptr); /* init a new dns cache and return success */ int Curl_mk_dnscache(struct curl_hash *hash); /* prune old entries from the DNS cache */ void Curl_hostcache_prune(struct Curl_easy *data); /* Return # of addresses in a Curl_addrinfo struct */ int Curl_num_addresses(const Curl_addrinfo *addr); #if defined(CURLDEBUG) && defined(HAVE_GETNAMEINFO) int curl_dogetnameinfo(GETNAMEINFO_QUAL_ARG1 GETNAMEINFO_TYPE_ARG1 sa, GETNAMEINFO_TYPE_ARG2 salen, char *host, GETNAMEINFO_TYPE_ARG46 hostlen, char *serv, GETNAMEINFO_TYPE_ARG46 servlen, GETNAMEINFO_TYPE_ARG7 flags, int line, const char *source); #endif /* IPv4 threadsafe resolve function used for synch and asynch builds */ Curl_addrinfo *Curl_ipv4_resolve_r(const char *hostname, int port); CURLcode Curl_once_resolved(struct connectdata *conn, bool *protocol_connect); /* * Curl_addrinfo_callback() is used when we build with any asynch specialty. * Handles end of async request processing. Inserts ai into hostcache when * status is CURL_ASYNC_SUCCESS. Twiddles fields in conn to indicate async * request completed whether successful or failed. */ CURLcode Curl_addrinfo_callback(struct connectdata *conn, int status, Curl_addrinfo *ai); /* * Curl_printable_address() returns a printable version of the 1st address * given in the 'ip' argument. The result will be stored in the buf that is * bufsize bytes big. */ const char *Curl_printable_address(const Curl_addrinfo *ip, char *buf, size_t bufsize); /* * Curl_fetch_addr() fetches a 'Curl_dns_entry' already in the DNS cache. * * Returns the Curl_dns_entry entry pointer or NULL if not in the cache. * * The returned data *MUST* be "unlocked" with Curl_resolv_unlock() after * use, or we'll leak memory! */ struct Curl_dns_entry * Curl_fetch_addr(struct connectdata *conn, const char *hostname, int port); /* * Curl_cache_addr() stores a 'Curl_addrinfo' struct in the DNS cache. * * Returns the Curl_dns_entry entry pointer or NULL if the storage failed. */ struct Curl_dns_entry * Curl_cache_addr(struct Curl_easy *data, Curl_addrinfo *addr, const char *hostname, int port); #ifndef INADDR_NONE #define CURL_INADDR_NONE (in_addr_t) ~0 #else #define CURL_INADDR_NONE INADDR_NONE #endif #ifdef HAVE_SIGSETJMP /* Forward-declaration of variable defined in hostip.c. Beware this * is a global and unique instance. This is used to store the return * address that we can jump back to from inside a signal handler. * This is not thread-safe stuff. */ extern sigjmp_buf curl_jmpenv; #endif /* * Function provided by the resolver backend to set DNS servers to use. */ CURLcode Curl_set_dns_servers(struct Curl_easy *data, char *servers); /* * Function provided by the resolver backend to set * outgoing interface to use for DNS requests */ CURLcode Curl_set_dns_interface(struct Curl_easy *data, const char *interf); /* * Function provided by the resolver backend to set * local IPv4 address to use as source address for DNS requests */ CURLcode Curl_set_dns_local_ip4(struct Curl_easy *data, const char *local_ip4); /* * Function provided by the resolver backend to set * local IPv6 address to use as source address for DNS requests */ CURLcode Curl_set_dns_local_ip6(struct Curl_easy *data, const char *local_ip6); /* * Clean off entries from the cache */ void Curl_hostcache_clean(struct Curl_easy *data, struct curl_hash *hash); /* * Destroy the hostcache of this handle. */ void Curl_hostcache_destroy(struct Curl_easy *data); /* * Populate the cache with specified entries from CURLOPT_RESOLVE. */ CURLcode Curl_loadhostpairs(struct Curl_easy *data); CURLcode Curl_resolv_check(struct connectdata *conn, struct Curl_dns_entry **dns); int Curl_resolv_getsock(struct connectdata *conn, curl_socket_t *socks, int numsocks); #endif /* HEADER_CURL_HOSTIP_H */
YifuLiu/AliOS-Things
components/curl/lib/hostip.h
C
apache-2.0
8,446
/*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2018, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "curl_setup.h" /*********************************************************************** * Only for plain IPv4 builds **********************************************************************/ #ifdef CURLRES_IPV4 /* plain IPv4 code coming up */ #ifdef HAVE_NETINET_IN_H #include <netinet/in.h> #endif #ifdef HAVE_NETDB_H #include <netdb.h> #endif #ifdef HAVE_ARPA_INET_H #include <arpa/inet.h> #endif #ifdef __VMS #include <in.h> #include <inet.h> #endif #ifdef HAVE_PROCESS_H #include <process.h> #endif #include "urldata.h" #include "sendf.h" #include "hostip.h" #include "hash.h" #include "share.h" #include "strerror.h" #include "url.h" #include "inet_pton.h" /* The last 3 #include files should be in this order */ #include "curl_printf.h" #include "curl_memory.h" #include "memdebug.h" /* * Curl_ipvalid() checks what CURL_IPRESOLVE_* requirements that might've * been set and returns TRUE if they are OK. */ bool Curl_ipvalid(struct connectdata *conn) { if(conn->ip_version == CURL_IPRESOLVE_V6) /* An IPv6 address was requested and we can't get/use one */ return FALSE; return TRUE; /* OK, proceed */ } #ifdef CURLRES_SYNCH /* * Curl_getaddrinfo() - the IPv4 synchronous version. * * The original code to this function was from the Dancer source code, written * by Bjorn Reese, it has since been patched and modified considerably. * * gethostbyname_r() is the thread-safe version of the gethostbyname() * function. When we build for plain IPv4, we attempt to use this * function. There are _three_ different gethostbyname_r() versions, and we * detect which one this platform supports in the configure script and set up * the HAVE_GETHOSTBYNAME_R_3, HAVE_GETHOSTBYNAME_R_5 or * HAVE_GETHOSTBYNAME_R_6 defines accordingly. Note that HAVE_GETADDRBYNAME * has the corresponding rules. This is primarily on *nix. Note that some unix * flavours have thread-safe versions of the plain gethostbyname() etc. * */ Curl_addrinfo *Curl_getaddrinfo(struct connectdata *conn, const char *hostname, int port, int *waitp) { Curl_addrinfo *ai = NULL; #ifdef CURL_DISABLE_VERBOSE_STRINGS (void)conn; #endif *waitp = 0; /* synchronous response only */ ai = Curl_ipv4_resolve_r(hostname, port); if(!ai) infof(conn->data, "Curl_ipv4_resolve_r failed for %s\n", hostname); return ai; } #endif /* CURLRES_SYNCH */ #endif /* CURLRES_IPV4 */ #if defined(CURLRES_IPV4) && !defined(CURLRES_ARES) /* * Curl_ipv4_resolve_r() - ipv4 threadsafe resolver function. * * This is used for both synchronous and asynchronous resolver builds, * implying that only threadsafe code and function calls may be used. * */ Curl_addrinfo *Curl_ipv4_resolve_r(const char *hostname, int port) { #if !defined(HAVE_GETADDRINFO_THREADSAFE) && defined(HAVE_GETHOSTBYNAME_R_3) int res; #endif Curl_addrinfo *ai = NULL; struct hostent *h = NULL; struct in_addr in; struct hostent *buf = NULL; if(Curl_inet_pton(AF_INET, hostname, &in) > 0) /* This is a dotted IP address 123.123.123.123-style */ return Curl_ip2addr(AF_INET, &in, hostname, port); #if defined(HAVE_GETADDRINFO_THREADSAFE) else { struct addrinfo hints; char sbuf[12]; char *sbufptr = NULL; memset(&hints, 0, sizeof(hints)); hints.ai_family = PF_INET; hints.ai_socktype = SOCK_STREAM; if(port) { msnprintf(sbuf, sizeof(sbuf), "%d", port); sbufptr = sbuf; } (void)Curl_getaddrinfo_ex(hostname, sbufptr, &hints, &ai); #elif defined(HAVE_GETHOSTBYNAME_R) /* * gethostbyname_r() is the preferred resolve function for many platforms. * Since there are three different versions of it, the following code is * somewhat #ifdef-ridden. */ else { int h_errnop; buf = calloc(1, CURL_HOSTENT_SIZE); if(!buf) return NULL; /* major failure */ /* * The clearing of the buffer is a workaround for a gethostbyname_r bug in * qnx nto and it is also _required_ for some of these functions on some * platforms. */ #if defined(HAVE_GETHOSTBYNAME_R_5) /* Solaris, IRIX and more */ h = gethostbyname_r(hostname, (struct hostent *)buf, (char *)buf + sizeof(struct hostent), CURL_HOSTENT_SIZE - sizeof(struct hostent), &h_errnop); /* If the buffer is too small, it returns NULL and sets errno to * ERANGE. The errno is thread safe if this is compiled with * -D_REENTRANT as then the 'errno' variable is a macro defined to get * used properly for threads. */ if(h) { ; } else #elif defined(HAVE_GETHOSTBYNAME_R_6) /* Linux */ (void)gethostbyname_r(hostname, (struct hostent *)buf, (char *)buf + sizeof(struct hostent), CURL_HOSTENT_SIZE - sizeof(struct hostent), &h, /* DIFFERENCE */ &h_errnop); /* Redhat 8, using glibc 2.2.93 changed the behavior. Now all of a * sudden this function returns EAGAIN if the given buffer size is too * small. Previous versions are known to return ERANGE for the same * problem. * * This wouldn't be such a big problem if older versions wouldn't * sometimes return EAGAIN on a common failure case. Alas, we can't * assume that EAGAIN *or* ERANGE means ERANGE for any given version of * glibc. * * For now, we do that and thus we may call the function repeatedly and * fail for older glibc versions that return EAGAIN, until we run out of * buffer size (step_size grows beyond CURL_HOSTENT_SIZE). * * If anyone has a better fix, please tell us! * * ------------------------------------------------------------------- * * On October 23rd 2003, Dan C dug up more details on the mysteries of * gethostbyname_r() in glibc: * * In glibc 2.2.5 the interface is different (this has also been * discovered in glibc 2.1.1-6 as shipped by Redhat 6). What I can't * explain, is that tests performed on glibc 2.2.4-34 and 2.2.4-32 * (shipped/upgraded by Redhat 7.2) don't show this behavior! * * In this "buggy" version, the return code is -1 on error and 'errno' * is set to the ERANGE or EAGAIN code. Note that 'errno' is not a * thread-safe variable. */ if(!h) /* failure */ #elif defined(HAVE_GETHOSTBYNAME_R_3) /* AIX, Digital Unix/Tru64, HPUX 10, more? */ /* For AIX 4.3 or later, we don't use gethostbyname_r() at all, because of * the plain fact that it does not return unique full buffers on each * call, but instead several of the pointers in the hostent structs will * point to the same actual data! This have the unfortunate down-side that * our caching system breaks down horribly. Luckily for us though, AIX 4.3 * and more recent versions have a "completely thread-safe"[*] libc where * all the data is stored in thread-specific memory areas making calls to * the plain old gethostbyname() work fine even for multi-threaded * programs. * * This AIX 4.3 or later detection is all made in the configure script. * * Troels Walsted Hansen helped us work this out on March 3rd, 2003. * * [*] = much later we've found out that it isn't at all "completely * thread-safe", but at least the gethostbyname() function is. */ if(CURL_HOSTENT_SIZE >= (sizeof(struct hostent) + sizeof(struct hostent_data))) { /* August 22nd, 2000: Albert Chin-A-Young brought an updated version * that should work! September 20: Richard Prescott worked on the buffer * size dilemma. */ res = gethostbyname_r(hostname, (struct hostent *)buf, (struct hostent_data *)((char *)buf + sizeof(struct hostent))); h_errnop = SOCKERRNO; /* we don't deal with this, but set it anyway */ } else res = -1; /* failure, too smallish buffer size */ if(!res) { /* success */ h = buf; /* result expected in h */ /* This is the worst kind of the different gethostbyname_r() interfaces. * Since we don't know how big buffer this particular lookup required, * we can't realloc down the huge alloc without doing closer analysis of * the returned data. Thus, we always use CURL_HOSTENT_SIZE for every * name lookup. Fixing this would require an extra malloc() and then * calling Curl_addrinfo_copy() that subsequent realloc()s down the new * memory area to the actually used amount. */ } else #endif /* HAVE_...BYNAME_R_5 || HAVE_...BYNAME_R_6 || HAVE_...BYNAME_R_3 */ { h = NULL; /* set return code to NULL */ free(buf); } #else /* HAVE_GETADDRINFO_THREADSAFE || HAVE_GETHOSTBYNAME_R */ /* * Here is code for platforms that don't have a thread safe * getaddrinfo() nor gethostbyname_r() function or for which * gethostbyname() is the preferred one. */ else { h = gethostbyname((void *)hostname); #endif /* HAVE_GETADDRINFO_THREADSAFE || HAVE_GETHOSTBYNAME_R */ } if(h) { ai = Curl_he2ai(h, port); if(buf) /* used a *_r() function */ free(buf); } return ai; } #endif /* defined(CURLRES_IPV4) && !defined(CURLRES_ARES) */
YifuLiu/AliOS-Things
components/curl/lib/hostip4.c
C
apache-2.0
10,607
/*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2019, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "curl_setup.h" /*********************************************************************** * Only for IPv6-enabled builds **********************************************************************/ #ifdef CURLRES_IPV6 #ifdef HAVE_NETINET_IN_H #include <netinet/in.h> #endif #ifdef HAVE_NETDB_H #include <netdb.h> #endif #ifdef HAVE_ARPA_INET_H #include <arpa/inet.h> #endif #ifdef __VMS #include <in.h> #include <inet.h> #endif #ifdef HAVE_PROCESS_H #include <process.h> #endif #include "urldata.h" #include "sendf.h" #include "hostip.h" #include "hash.h" #include "share.h" #include "strerror.h" #include "url.h" #include "inet_pton.h" #include "connect.h" /* The last 3 #include files should be in this order */ #include "curl_printf.h" #include "curl_memory.h" #include "memdebug.h" /* * Curl_ipv6works() returns TRUE if IPv6 seems to work. */ bool Curl_ipv6works(void) { /* the nature of most system is that IPv6 status doesn't come and go during a program's lifetime so we only probe the first time and then we have the info kept for fast re-use */ static int ipv6_works = -1; if(-1 == ipv6_works) { /* probe to see if we have a working IPv6 stack */ curl_socket_t s = socket(PF_INET6, SOCK_DGRAM, 0); if(s == CURL_SOCKET_BAD) /* an IPv6 address was requested but we can't get/use one */ ipv6_works = 0; else { ipv6_works = 1; Curl_closesocket(NULL, s); } } return (ipv6_works>0)?TRUE:FALSE; } /* * Curl_ipvalid() checks what CURL_IPRESOLVE_* requirements that might've * been set and returns TRUE if they are OK. */ bool Curl_ipvalid(struct connectdata *conn) { if(conn->ip_version == CURL_IPRESOLVE_V6) return Curl_ipv6works(); return TRUE; } #if defined(CURLRES_SYNCH) #ifdef DEBUG_ADDRINFO static void dump_addrinfo(struct connectdata *conn, const Curl_addrinfo *ai) { printf("dump_addrinfo:\n"); for(; ai; ai = ai->ai_next) { char buf[INET6_ADDRSTRLEN]; printf(" fam %2d, CNAME %s, ", ai->ai_family, ai->ai_canonname ? ai->ai_canonname : "<none>"); if(Curl_printable_address(ai, buf, sizeof(buf))) printf("%s\n", buf); else { char buffer[STRERROR_LEN]; printf("failed; %s\n", Curl_strerror(SOCKERRNO, buffer, sizeof(buffer))); } } } #else #define dump_addrinfo(x,y) Curl_nop_stmt #endif /* * Curl_getaddrinfo() when built IPv6-enabled (non-threading and * non-ares version). * * Returns name information about the given hostname and port number. If * successful, the 'addrinfo' is returned and the forth argument will point to * memory we need to free after use. That memory *MUST* be freed with * Curl_freeaddrinfo(), nothing else. */ Curl_addrinfo *Curl_getaddrinfo(struct connectdata *conn, const char *hostname, int port, int *waitp) { struct addrinfo hints; Curl_addrinfo *res; int error; char sbuf[12]; char *sbufptr = NULL; #ifndef USE_RESOLVE_ON_IPS char addrbuf[128]; #endif int pf; #if !defined(CURL_DISABLE_VERBOSE_STRINGS) struct Curl_easy *data = conn->data; #endif *waitp = 0; /* synchronous response only */ /* Check if a limited name resolve has been requested */ switch(conn->ip_version) { case CURL_IPRESOLVE_V4: pf = PF_INET; break; case CURL_IPRESOLVE_V6: pf = PF_INET6; break; default: pf = PF_UNSPEC; break; } if((pf != PF_INET) && !Curl_ipv6works()) /* The stack seems to be a non-IPv6 one */ pf = PF_INET; memset(&hints, 0, sizeof(hints)); hints.ai_family = pf; hints.ai_socktype = conn->socktype; #ifndef USE_RESOLVE_ON_IPS /* * The AI_NUMERICHOST must not be set to get synthesized IPv6 address from * an IPv4 address on iOS and Mac OS X. */ if((1 == Curl_inet_pton(AF_INET, hostname, addrbuf)) || (1 == Curl_inet_pton(AF_INET6, hostname, addrbuf))) { /* the given address is numerical only, prevent a reverse lookup */ hints.ai_flags = AI_NUMERICHOST; } #endif if(port) { msnprintf(sbuf, sizeof(sbuf), "%d", port); sbufptr = sbuf; } error = Curl_getaddrinfo_ex(hostname, sbufptr, &hints, &res); if(error) { infof(data, "getaddrinfo(3) failed for %s:%d\n", hostname, port); return NULL; } if(port) { Curl_addrinfo_set_port(res, port); } dump_addrinfo(conn, res); return res; } #endif /* CURLRES_SYNCH */ #endif /* CURLRES_IPV6 */
YifuLiu/AliOS-Things
components/curl/lib/hostip6.c
C
apache-2.0
5,506
/*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2015, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "curl_setup.h" /*********************************************************************** * Only for builds using synchronous name resolves **********************************************************************/ #ifdef CURLRES_SYNCH #ifdef HAVE_NETINET_IN_H #include <netinet/in.h> #endif #ifdef HAVE_NETDB_H #ifdef USE_LWIPSOCK #include <lwip/netdb.h> #else #include <netdb.h> #endif #endif #ifdef HAVE_ARPA_INET_H #include <arpa/inet.h> #endif #ifdef __VMS #include <in.h> #include <inet.h> #endif #ifdef HAVE_PROCESS_H #include <process.h> #endif #include "urldata.h" #include "sendf.h" #include "hostip.h" #include "hash.h" #include "share.h" #include "strerror.h" #include "url.h" #include "curl_memory.h" /* The last #include file should be: */ #include "memdebug.h" /* * Function provided by the resolver backend to set DNS servers to use. */ CURLcode Curl_set_dns_servers(struct Curl_easy *data, char *servers) { (void)data; (void)servers; return CURLE_NOT_BUILT_IN; } /* * Function provided by the resolver backend to set * outgoing interface to use for DNS requests */ CURLcode Curl_set_dns_interface(struct Curl_easy *data, const char *interf) { (void)data; (void)interf; return CURLE_NOT_BUILT_IN; } /* * Function provided by the resolver backend to set * local IPv4 address to use as source address for DNS requests */ CURLcode Curl_set_dns_local_ip4(struct Curl_easy *data, const char *local_ip4) { (void)data; (void)local_ip4; return CURLE_NOT_BUILT_IN; } /* * Function provided by the resolver backend to set * local IPv6 address to use as source address for DNS requests */ CURLcode Curl_set_dns_local_ip6(struct Curl_easy *data, const char *local_ip6) { (void)data; (void)local_ip6; return CURLE_NOT_BUILT_IN; } #endif /* truly sync */
YifuLiu/AliOS-Things
components/curl/lib/hostsyn.c
C
apache-2.0
2,961
/*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2019, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "curl_setup.h" #ifndef CURL_DISABLE_HTTP #ifdef HAVE_NETINET_IN_H #include <netinet/in.h> #endif #ifdef HAVE_NETDB_H #ifdef USE_LWIPSOCK #include <lwip/netdb.h> #else #include <netdb.h> #endif #endif #ifdef HAVE_ARPA_INET_H #include <arpa/inet.h> #endif #ifdef HAVE_NET_IF_H #include <net/if.h> #endif #ifdef HAVE_SYS_IOCTL_H #include <sys/ioctl.h> #endif #ifdef HAVE_SYS_PARAM_H #include <sys/param.h> #endif #include "urldata.h" #include <curl/curl.h> #include "transfer.h" #include "sendf.h" #include "formdata.h" #include "mime.h" #include "progress.h" #include "curl_base64.h" #include "cookie.h" #include "vauth/vauth.h" #include "vtls/vtls.h" #include "http_digest.h" #include "http_ntlm.h" #include "curl_ntlm_wb.h" #include "http_negotiate.h" #include "url.h" #include "share.h" #include "hostip.h" #include "http.h" #include "select.h" #include "parsedate.h" /* for the week day and month names */ #include "strtoofft.h" #include "multiif.h" #include "strcase.h" #include "content_encoding.h" #include "http_proxy.h" #include "warnless.h" #include "non-ascii.h" #include "http2.h" #include "connect.h" #include "strdup.h" #include "altsvc.h" /* The last 3 #include files should be in this order */ #include "curl_printf.h" #include "curl_memory.h" #include "memdebug.h" /* * Forward declarations. */ static int http_getsock_do(struct connectdata *conn, curl_socket_t *socks, int numsocks); static int http_should_fail(struct connectdata *conn); #ifndef CURL_DISABLE_PROXY static CURLcode add_haproxy_protocol_header(struct connectdata *conn); #endif #ifdef USE_SSL static CURLcode https_connecting(struct connectdata *conn, bool *done); static int https_getsock(struct connectdata *conn, curl_socket_t *socks, int numsocks); #else #define https_connecting(x,y) CURLE_COULDNT_CONNECT #endif static CURLcode http_setup_conn(struct connectdata *conn); /* * HTTP handler interface. */ const struct Curl_handler Curl_handler_http = { "HTTP", /* scheme */ http_setup_conn, /* setup_connection */ Curl_http, /* do_it */ Curl_http_done, /* done */ ZERO_NULL, /* do_more */ Curl_http_connect, /* connect_it */ ZERO_NULL, /* connecting */ ZERO_NULL, /* doing */ ZERO_NULL, /* proto_getsock */ http_getsock_do, /* doing_getsock */ ZERO_NULL, /* domore_getsock */ ZERO_NULL, /* perform_getsock */ ZERO_NULL, /* disconnect */ ZERO_NULL, /* readwrite */ ZERO_NULL, /* connection_check */ PORT_HTTP, /* defport */ CURLPROTO_HTTP, /* protocol */ PROTOPT_CREDSPERREQUEST /* flags */ }; #ifdef USE_SSL /* * HTTPS handler interface. */ const struct Curl_handler Curl_handler_https = { "HTTPS", /* scheme */ http_setup_conn, /* setup_connection */ Curl_http, /* do_it */ Curl_http_done, /* done */ ZERO_NULL, /* do_more */ Curl_http_connect, /* connect_it */ https_connecting, /* connecting */ ZERO_NULL, /* doing */ https_getsock, /* proto_getsock */ http_getsock_do, /* doing_getsock */ ZERO_NULL, /* domore_getsock */ ZERO_NULL, /* perform_getsock */ ZERO_NULL, /* disconnect */ ZERO_NULL, /* readwrite */ ZERO_NULL, /* connection_check */ PORT_HTTPS, /* defport */ CURLPROTO_HTTPS, /* protocol */ PROTOPT_SSL | PROTOPT_CREDSPERREQUEST | PROTOPT_ALPN_NPN /* flags */ }; #endif static CURLcode http_setup_conn(struct connectdata *conn) { /* allocate the HTTP-specific struct for the Curl_easy, only to survive during this request */ struct HTTP *http; struct Curl_easy *data = conn->data; DEBUGASSERT(data->req.protop == NULL); http = calloc(1, sizeof(struct HTTP)); if(!http) return CURLE_OUT_OF_MEMORY; Curl_mime_initpart(&http->form, conn->data); data->req.protop = http; if(!CONN_INUSE(conn)) /* if not already multi-using, setup connection details */ Curl_http2_setup_conn(conn); Curl_http2_setup_req(data); return CURLE_OK; } #ifndef CURL_DISABLE_PROXY /* * checkProxyHeaders() checks the linked list of custom proxy headers * if proxy headers are not available, then it will lookup into http header * link list * * It takes a connectdata struct as input instead of the Curl_easy simply to * know if this is a proxy request or not, as it then might check a different * header list. Provide the header prefix without colon!. */ char *Curl_checkProxyheaders(const struct connectdata *conn, const char *thisheader) { struct curl_slist *head; size_t thislen = strlen(thisheader); struct Curl_easy *data = conn->data; for(head = (conn->bits.proxy && data->set.sep_headers) ? data->set.proxyheaders : data->set.headers; head; head = head->next) { if(strncasecompare(head->data, thisheader, thislen) && Curl_headersep(head->data[thislen])) return head->data; } return NULL; } #else /* disabled */ #define Curl_checkProxyheaders(x,y) NULL #endif /* * Strip off leading and trailing whitespace from the value in the * given HTTP header line and return a strdupped copy. Returns NULL in * case of allocation failure. Returns an empty string if the header value * consists entirely of whitespace. */ char *Curl_copy_header_value(const char *header) { const char *start; const char *end; char *value; size_t len; /* Find the end of the header name */ while(*header && (*header != ':')) ++header; if(*header) /* Skip over colon */ ++header; /* Find the first non-space letter */ start = header; while(*start && ISSPACE(*start)) start++; /* data is in the host encoding so use '\r' and '\n' instead of 0x0d and 0x0a */ end = strchr(start, '\r'); if(!end) end = strchr(start, '\n'); if(!end) end = strchr(start, '\0'); if(!end) return NULL; /* skip all trailing space letters */ while((end > start) && ISSPACE(*end)) end--; /* get length of the type */ len = end - start + 1; value = malloc(len + 1); if(!value) return NULL; memcpy(value, start, len); value[len] = 0; /* zero terminate */ return value; } #ifndef CURL_DISABLE_HTTP_AUTH /* * http_output_basic() sets up an Authorization: header (or the proxy version) * for HTTP Basic authentication. * * Returns CURLcode. */ static CURLcode http_output_basic(struct connectdata *conn, bool proxy) { size_t size = 0; char *authorization = NULL; struct Curl_easy *data = conn->data; char **userp; const char *user; const char *pwd; CURLcode result; char *out; if(proxy) { userp = &conn->allocptr.proxyuserpwd; user = conn->http_proxy.user; pwd = conn->http_proxy.passwd; } else { userp = &conn->allocptr.userpwd; user = conn->user; pwd = conn->passwd; } out = aprintf("%s:%s", user, pwd); if(!out) return CURLE_OUT_OF_MEMORY; result = Curl_base64_encode(data, out, strlen(out), &authorization, &size); if(result) goto fail; if(!authorization) { result = CURLE_REMOTE_ACCESS_DENIED; goto fail; } free(*userp); *userp = aprintf("%sAuthorization: Basic %s\r\n", proxy ? "Proxy-" : "", authorization); free(authorization); if(!*userp) { result = CURLE_OUT_OF_MEMORY; goto fail; } fail: free(out); return result; } /* * http_output_bearer() sets up an Authorization: header * for HTTP Bearer authentication. * * Returns CURLcode. */ static CURLcode http_output_bearer(struct connectdata *conn) { char **userp; CURLcode result = CURLE_OK; userp = &conn->allocptr.userpwd; free(*userp); *userp = aprintf("Authorization: Bearer %s\r\n", conn->oauth_bearer); if(!*userp) { result = CURLE_OUT_OF_MEMORY; goto fail; } fail: return result; } #endif /* pickoneauth() selects the most favourable authentication method from the * ones available and the ones we want. * * return TRUE if one was picked */ static bool pickoneauth(struct auth *pick, unsigned long mask) { bool picked; /* only deal with authentication we want */ unsigned long avail = pick->avail & pick->want & mask; picked = TRUE; /* The order of these checks is highly relevant, as this will be the order of preference in case of the existence of multiple accepted types. */ if(avail & CURLAUTH_NEGOTIATE) pick->picked = CURLAUTH_NEGOTIATE; else if(avail & CURLAUTH_BEARER) pick->picked = CURLAUTH_BEARER; else if(avail & CURLAUTH_DIGEST) pick->picked = CURLAUTH_DIGEST; else if(avail & CURLAUTH_NTLM) pick->picked = CURLAUTH_NTLM; else if(avail & CURLAUTH_NTLM_WB) pick->picked = CURLAUTH_NTLM_WB; else if(avail & CURLAUTH_BASIC) pick->picked = CURLAUTH_BASIC; else { pick->picked = CURLAUTH_PICKNONE; /* we select to use nothing */ picked = FALSE; } pick->avail = CURLAUTH_NONE; /* clear it here */ return picked; } /* * Curl_http_perhapsrewind() * * If we are doing POST or PUT { * If we have more data to send { * If we are doing NTLM { * Keep sending since we must not disconnect * } * else { * If there is more than just a little data left to send, close * the current connection by force. * } * } * If we have sent any data { * If we don't have track of all the data { * call app to tell it to rewind * } * else { * rewind internally so that the operation can restart fine * } * } * } */ static CURLcode http_perhapsrewind(struct connectdata *conn) { struct Curl_easy *data = conn->data; struct HTTP *http = data->req.protop; curl_off_t bytessent; curl_off_t expectsend = -1; /* default is unknown */ if(!http) /* If this is still NULL, we have not reach very far and we can safely skip this rewinding stuff */ return CURLE_OK; switch(data->set.httpreq) { case HTTPREQ_GET: case HTTPREQ_HEAD: return CURLE_OK; default: break; } bytessent = data->req.writebytecount; if(conn->bits.authneg) { /* This is a state where we are known to be negotiating and we don't send any data then. */ expectsend = 0; } else if(!conn->bits.protoconnstart) { /* HTTP CONNECT in progress: there is no body */ expectsend = 0; } else { /* figure out how much data we are expected to send */ switch(data->set.httpreq) { case HTTPREQ_POST: if(data->state.infilesize != -1) expectsend = data->state.infilesize; break; case HTTPREQ_PUT: if(data->state.infilesize != -1) expectsend = data->state.infilesize; break; case HTTPREQ_POST_FORM: case HTTPREQ_POST_MIME: expectsend = http->postsize; break; default: break; } } conn->bits.rewindaftersend = FALSE; /* default */ if((expectsend == -1) || (expectsend > bytessent)) { #if defined(USE_NTLM) /* There is still data left to send */ if((data->state.authproxy.picked == CURLAUTH_NTLM) || (data->state.authhost.picked == CURLAUTH_NTLM) || (data->state.authproxy.picked == CURLAUTH_NTLM_WB) || (data->state.authhost.picked == CURLAUTH_NTLM_WB)) { if(((expectsend - bytessent) < 2000) || (conn->http_ntlm_state != NTLMSTATE_NONE) || (conn->proxy_ntlm_state != NTLMSTATE_NONE)) { /* The NTLM-negotiation has started *OR* there is just a little (<2K) data left to send, keep on sending. */ /* rewind data when completely done sending! */ if(!conn->bits.authneg && (conn->writesockfd != CURL_SOCKET_BAD)) { conn->bits.rewindaftersend = TRUE; infof(data, "Rewind stream after send\n"); } return CURLE_OK; } if(conn->bits.close) /* this is already marked to get closed */ return CURLE_OK; infof(data, "NTLM send, close instead of sending %" CURL_FORMAT_CURL_OFF_T " bytes\n", (curl_off_t)(expectsend - bytessent)); } #endif #if defined(USE_SPNEGO) /* There is still data left to send */ if((data->state.authproxy.picked == CURLAUTH_NEGOTIATE) || (data->state.authhost.picked == CURLAUTH_NEGOTIATE)) { if(((expectsend - bytessent) < 2000) || (conn->http_negotiate_state != GSS_AUTHNONE) || (conn->proxy_negotiate_state != GSS_AUTHNONE)) { /* The NEGOTIATE-negotiation has started *OR* there is just a little (<2K) data left to send, keep on sending. */ /* rewind data when completely done sending! */ if(!conn->bits.authneg && (conn->writesockfd != CURL_SOCKET_BAD)) { conn->bits.rewindaftersend = TRUE; infof(data, "Rewind stream after send\n"); } return CURLE_OK; } if(conn->bits.close) /* this is already marked to get closed */ return CURLE_OK; infof(data, "NEGOTIATE send, close instead of sending %" CURL_FORMAT_CURL_OFF_T " bytes\n", (curl_off_t)(expectsend - bytessent)); } #endif /* This is not NEGOTIATE/NTLM or many bytes left to send: close */ streamclose(conn, "Mid-auth HTTP and much data left to send"); data->req.size = 0; /* don't download any more than 0 bytes */ /* There still is data left to send, but this connection is marked for closure so we can safely do the rewind right now */ } if(bytessent) /* we rewind now at once since if we already sent something */ return Curl_readrewind(conn); return CURLE_OK; } /* * Curl_http_auth_act() gets called when all HTTP headers have been received * and it checks what authentication methods that are available and decides * which one (if any) to use. It will set 'newurl' if an auth method was * picked. */ CURLcode Curl_http_auth_act(struct connectdata *conn) { struct Curl_easy *data = conn->data; bool pickhost = FALSE; bool pickproxy = FALSE; CURLcode result = CURLE_OK; unsigned long authmask = ~0ul; if(!conn->oauth_bearer) authmask &= (unsigned long)~CURLAUTH_BEARER; if(100 <= data->req.httpcode && 199 >= data->req.httpcode) /* this is a transient response code, ignore */ return CURLE_OK; if(data->state.authproblem) return data->set.http_fail_on_error?CURLE_HTTP_RETURNED_ERROR:CURLE_OK; if((conn->bits.user_passwd || conn->oauth_bearer) && ((data->req.httpcode == 401) || (conn->bits.authneg && data->req.httpcode < 300))) { pickhost = pickoneauth(&data->state.authhost, authmask); if(!pickhost) data->state.authproblem = TRUE; if(data->state.authhost.picked == CURLAUTH_NTLM && conn->httpversion > 11) { infof(data, "Forcing HTTP/1.1 for NTLM"); connclose(conn, "Force HTTP/1.1 connection"); conn->data->set.httpversion = CURL_HTTP_VERSION_1_1; } } if(conn->bits.proxy_user_passwd && ((data->req.httpcode == 407) || (conn->bits.authneg && data->req.httpcode < 300))) { pickproxy = pickoneauth(&data->state.authproxy, authmask & ~CURLAUTH_BEARER); if(!pickproxy) data->state.authproblem = TRUE; } if(pickhost || pickproxy) { if((data->set.httpreq != HTTPREQ_GET) && (data->set.httpreq != HTTPREQ_HEAD) && !conn->bits.rewindaftersend) { result = http_perhapsrewind(conn); if(result) return result; } /* In case this is GSS auth, the newurl field is already allocated so we must make sure to free it before allocating a new one. As figured out in bug #2284386 */ Curl_safefree(data->req.newurl); data->req.newurl = strdup(data->change.url); /* clone URL */ if(!data->req.newurl) return CURLE_OUT_OF_MEMORY; } else if((data->req.httpcode < 300) && (!data->state.authhost.done) && conn->bits.authneg) { /* no (known) authentication available, authentication is not "done" yet and no authentication seems to be required and we didn't try HEAD or GET */ if((data->set.httpreq != HTTPREQ_GET) && (data->set.httpreq != HTTPREQ_HEAD)) { data->req.newurl = strdup(data->change.url); /* clone URL */ if(!data->req.newurl) return CURLE_OUT_OF_MEMORY; data->state.authhost.done = TRUE; } } if(http_should_fail(conn)) { failf(data, "The requested URL returned error: %d", data->req.httpcode); result = CURLE_HTTP_RETURNED_ERROR; } return result; } #ifndef CURL_DISABLE_HTTP_AUTH /* * Output the correct authentication header depending on the auth type * and whether or not it is to a proxy. */ static CURLcode output_auth_headers(struct connectdata *conn, struct auth *authstatus, const char *request, const char *path, bool proxy) { const char *auth = NULL; CURLcode result = CURLE_OK; #if !defined(CURL_DISABLE_VERBOSE_STRINGS) || defined(USE_SPNEGO) struct Curl_easy *data = conn->data; #endif #ifdef CURL_DISABLE_CRYPTO_AUTH (void)request; (void)path; #endif #ifdef USE_SPNEGO if((authstatus->picked == CURLAUTH_NEGOTIATE)) { auth = "Negotiate"; result = Curl_output_negotiate(conn, proxy); if(result) return result; } else #endif #ifdef USE_NTLM if(authstatus->picked == CURLAUTH_NTLM) { auth = "NTLM"; result = Curl_output_ntlm(conn, proxy); if(result) return result; } else #endif #if defined(USE_NTLM) && defined(NTLM_WB_ENABLED) if(authstatus->picked == CURLAUTH_NTLM_WB) { auth = "NTLM_WB"; result = Curl_output_ntlm_wb(conn, proxy); if(result) return result; } else #endif #ifndef CURL_DISABLE_CRYPTO_AUTH if(authstatus->picked == CURLAUTH_DIGEST) { auth = "Digest"; result = Curl_output_digest(conn, proxy, (const unsigned char *)request, (const unsigned char *)path); if(result) return result; } else #endif if(authstatus->picked == CURLAUTH_BASIC) { /* Basic */ if((proxy && conn->bits.proxy_user_passwd && !Curl_checkProxyheaders(conn, "Proxy-authorization")) || (!proxy && conn->bits.user_passwd && !Curl_checkheaders(conn, "Authorization"))) { auth = "Basic"; result = http_output_basic(conn, proxy); if(result) return result; } /* NOTE: this function should set 'done' TRUE, as the other auth functions work that way */ authstatus->done = TRUE; } if(authstatus->picked == CURLAUTH_BEARER) { /* Bearer */ if((!proxy && conn->oauth_bearer && !Curl_checkheaders(conn, "Authorization:"))) { auth = "Bearer"; result = http_output_bearer(conn); if(result) return result; } /* NOTE: this function should set 'done' TRUE, as the other auth functions work that way */ authstatus->done = TRUE; } if(auth) { infof(data, "%s auth using %s with user '%s'\n", proxy ? "Proxy" : "Server", auth, proxy ? (conn->http_proxy.user ? conn->http_proxy.user : "") : (conn->user ? conn->user : "")); authstatus->multipass = (!authstatus->done) ? TRUE : FALSE; } else authstatus->multipass = FALSE; return CURLE_OK; } /** * Curl_http_output_auth() setups the authentication headers for the * host/proxy and the correct authentication * method. conn->data->state.authdone is set to TRUE when authentication is * done. * * @param conn all information about the current connection * @param request pointer to the request keyword * @param path pointer to the requested path; should include query part * @param proxytunnel boolean if this is the request setting up a "proxy * tunnel" * * @returns CURLcode */ CURLcode Curl_http_output_auth(struct connectdata *conn, const char *request, const char *path, bool proxytunnel) /* TRUE if this is the request setting up the proxy tunnel */ { CURLcode result = CURLE_OK; struct Curl_easy *data = conn->data; struct auth *authhost; struct auth *authproxy; DEBUGASSERT(data); authhost = &data->state.authhost; authproxy = &data->state.authproxy; if((conn->bits.httpproxy && conn->bits.proxy_user_passwd) || conn->bits.user_passwd || conn->oauth_bearer) /* continue please */; else { authhost->done = TRUE; authproxy->done = TRUE; return CURLE_OK; /* no authentication with no user or password */ } if(authhost->want && !authhost->picked) /* The app has selected one or more methods, but none has been picked so far by a server round-trip. Then we set the picked one to the want one, and if this is one single bit it'll be used instantly. */ authhost->picked = authhost->want; if(authproxy->want && !authproxy->picked) /* The app has selected one or more methods, but none has been picked so far by a proxy round-trip. Then we set the picked one to the want one, and if this is one single bit it'll be used instantly. */ authproxy->picked = authproxy->want; #ifndef CURL_DISABLE_PROXY /* Send proxy authentication header if needed */ if(conn->bits.httpproxy && (conn->bits.tunnel_proxy == (bit)proxytunnel)) { result = output_auth_headers(conn, authproxy, request, path, TRUE); if(result) return result; } else #else (void)proxytunnel; #endif /* CURL_DISABLE_PROXY */ /* we have no proxy so let's pretend we're done authenticating with it */ authproxy->done = TRUE; /* To prevent the user+password to get sent to other than the original host due to a location-follow, we do some weirdo checks here */ if(!data->state.this_is_a_follow || conn->bits.netrc || !data->state.first_host || data->set.allow_auth_to_other_hosts || strcasecompare(data->state.first_host, conn->host.name)) { result = output_auth_headers(conn, authhost, request, path, FALSE); } else authhost->done = TRUE; return result; } #else /* when disabled */ CURLcode Curl_http_output_auth(struct connectdata *conn, const char *request, const char *path, bool proxytunnel) { (void)conn; (void)request; (void)path; (void)proxytunnel; return CURLE_OK; } #endif /* * Curl_http_input_auth() deals with Proxy-Authenticate: and WWW-Authenticate: * headers. They are dealt with both in the transfer.c main loop and in the * proxy CONNECT loop. */ CURLcode Curl_http_input_auth(struct connectdata *conn, bool proxy, const char *auth) /* the first non-space */ { /* * This resource requires authentication */ struct Curl_easy *data = conn->data; #ifdef USE_SPNEGO curlnegotiate *negstate = proxy ? &conn->proxy_negotiate_state : &conn->http_negotiate_state; #endif unsigned long *availp; struct auth *authp; if(proxy) { availp = &data->info.proxyauthavail; authp = &data->state.authproxy; } else { availp = &data->info.httpauthavail; authp = &data->state.authhost; } /* * Here we check if we want the specific single authentication (using ==) and * if we do, we initiate usage of it. * * If the provided authentication is wanted as one out of several accepted * types (using &), we OR this authentication type to the authavail * variable. * * Note: * * ->picked is first set to the 'want' value (one or more bits) before the * request is sent, and then it is again set _after_ all response 401/407 * headers have been received but then only to a single preferred method * (bit). */ while(*auth) { #ifdef USE_SPNEGO if(checkprefix("Negotiate", auth)) { if((authp->avail & CURLAUTH_NEGOTIATE) || Curl_auth_is_spnego_supported()) { *availp |= CURLAUTH_NEGOTIATE; authp->avail |= CURLAUTH_NEGOTIATE; if(authp->picked == CURLAUTH_NEGOTIATE) { CURLcode result = Curl_input_negotiate(conn, proxy, auth); if(!result) { DEBUGASSERT(!data->req.newurl); data->req.newurl = strdup(data->change.url); if(!data->req.newurl) return CURLE_OUT_OF_MEMORY; data->state.authproblem = FALSE; /* we received a GSS auth token and we dealt with it fine */ *negstate = GSS_AUTHRECV; } else data->state.authproblem = TRUE; } } } else #endif #ifdef USE_NTLM /* NTLM support requires the SSL crypto libs */ if(checkprefix("NTLM", auth)) { if((authp->avail & CURLAUTH_NTLM) || (authp->avail & CURLAUTH_NTLM_WB) || Curl_auth_is_ntlm_supported()) { *availp |= CURLAUTH_NTLM; authp->avail |= CURLAUTH_NTLM; if(authp->picked == CURLAUTH_NTLM || authp->picked == CURLAUTH_NTLM_WB) { /* NTLM authentication is picked and activated */ CURLcode result = Curl_input_ntlm(conn, proxy, auth); if(!result) { data->state.authproblem = FALSE; #ifdef NTLM_WB_ENABLED if(authp->picked == CURLAUTH_NTLM_WB) { *availp &= ~CURLAUTH_NTLM; authp->avail &= ~CURLAUTH_NTLM; *availp |= CURLAUTH_NTLM_WB; authp->avail |= CURLAUTH_NTLM_WB; result = Curl_input_ntlm_wb(conn, proxy, auth); if(result) { infof(data, "Authentication problem. Ignoring this.\n"); data->state.authproblem = TRUE; } } #endif } else { infof(data, "Authentication problem. Ignoring this.\n"); data->state.authproblem = TRUE; } } } } else #endif #ifndef CURL_DISABLE_CRYPTO_AUTH if(checkprefix("Digest", auth)) { if((authp->avail & CURLAUTH_DIGEST) != 0) infof(data, "Ignoring duplicate digest auth header.\n"); else if(Curl_auth_is_digest_supported()) { CURLcode result; *availp |= CURLAUTH_DIGEST; authp->avail |= CURLAUTH_DIGEST; /* We call this function on input Digest headers even if Digest * authentication isn't activated yet, as we need to store the * incoming data from this header in case we are going to use * Digest */ result = Curl_input_digest(conn, proxy, auth); if(result) { infof(data, "Authentication problem. Ignoring this.\n"); data->state.authproblem = TRUE; } } } else #endif if(checkprefix("Basic", auth)) { *availp |= CURLAUTH_BASIC; authp->avail |= CURLAUTH_BASIC; if(authp->picked == CURLAUTH_BASIC) { /* We asked for Basic authentication but got a 40X back anyway, which basically means our name+password isn't valid. */ authp->avail = CURLAUTH_NONE; infof(data, "Authentication problem. Ignoring this.\n"); data->state.authproblem = TRUE; } } else if(checkprefix("Bearer", auth)) { *availp |= CURLAUTH_BEARER; authp->avail |= CURLAUTH_BEARER; if(authp->picked == CURLAUTH_BEARER) { /* We asked for Bearer authentication but got a 40X back anyway, which basically means our token isn't valid. */ authp->avail = CURLAUTH_NONE; infof(data, "Authentication problem. Ignoring this.\n"); data->state.authproblem = TRUE; } } /* there may be multiple methods on one line, so keep reading */ while(*auth && *auth != ',') /* read up to the next comma */ auth++; if(*auth == ',') /* if we're on a comma, skip it */ auth++; while(*auth && ISSPACE(*auth)) auth++; } return CURLE_OK; } /** * http_should_fail() determines whether an HTTP response has gotten us * into an error state or not. * * @param conn all information about the current connection * * @retval 0 communications should continue * * @retval 1 communications should not continue */ static int http_should_fail(struct connectdata *conn) { struct Curl_easy *data; int httpcode; DEBUGASSERT(conn); data = conn->data; DEBUGASSERT(data); httpcode = data->req.httpcode; /* ** If we haven't been asked to fail on error, ** don't fail. */ if(!data->set.http_fail_on_error) return 0; /* ** Any code < 400 is never terminal. */ if(httpcode < 400) return 0; /* ** Any code >= 400 that's not 401 or 407 is always ** a terminal error */ if((httpcode != 401) && (httpcode != 407)) return 1; /* ** All we have left to deal with is 401 and 407 */ DEBUGASSERT((httpcode == 401) || (httpcode == 407)); /* ** Examine the current authentication state to see if this ** is an error. The idea is for this function to get ** called after processing all the headers in a response ** message. So, if we've been to asked to authenticate a ** particular stage, and we've done it, we're OK. But, if ** we're already completely authenticated, it's not OK to ** get another 401 or 407. ** ** It is possible for authentication to go stale such that ** the client needs to reauthenticate. Once that info is ** available, use it here. */ /* ** Either we're not authenticating, or we're supposed to ** be authenticating something else. This is an error. */ if((httpcode == 401) && !conn->bits.user_passwd) return TRUE; if((httpcode == 407) && !conn->bits.proxy_user_passwd) return TRUE; return data->state.authproblem; } /* * readmoredata() is a "fread() emulation" to provide POST and/or request * data. It is used when a huge POST is to be made and the entire chunk wasn't * sent in the first send(). This function will then be called from the * transfer.c loop when more data is to be sent to the peer. * * Returns the amount of bytes it filled the buffer with. */ static size_t readmoredata(char *buffer, size_t size, size_t nitems, void *userp) { struct connectdata *conn = (struct connectdata *)userp; struct HTTP *http = conn->data->req.protop; size_t fullsize = size * nitems; if(!http->postsize) /* nothing to return */ return 0; /* make sure that a HTTP request is never sent away chunked! */ conn->data->req.forbidchunk = (http->sending == HTTPSEND_REQUEST)?TRUE:FALSE; if(http->postsize <= (curl_off_t)fullsize) { memcpy(buffer, http->postdata, (size_t)http->postsize); fullsize = (size_t)http->postsize; if(http->backup.postsize) { /* move backup data into focus and continue on that */ http->postdata = http->backup.postdata; http->postsize = http->backup.postsize; conn->data->state.fread_func = http->backup.fread_func; conn->data->state.in = http->backup.fread_in; http->sending++; /* move one step up */ http->backup.postsize = 0; } else http->postsize = 0; return fullsize; } memcpy(buffer, http->postdata, fullsize); http->postdata += fullsize; http->postsize -= fullsize; return fullsize; } /* ------------------------------------------------------------------------- */ /* add_buffer functions */ /* * Curl_add_buffer_init() sets up and returns a fine buffer struct */ Curl_send_buffer *Curl_add_buffer_init(void) { return calloc(1, sizeof(Curl_send_buffer)); } /* * Curl_add_buffer_free() frees all associated resources. */ void Curl_add_buffer_free(Curl_send_buffer **inp) { Curl_send_buffer *in = *inp; if(in) /* deal with NULL input */ free(in->buffer); free(in); *inp = NULL; } /* * Curl_add_buffer_send() sends a header buffer and frees all associated * memory. Body data may be appended to the header data if desired. * * Returns CURLcode */ CURLcode Curl_add_buffer_send(Curl_send_buffer **inp, struct connectdata *conn, /* add the number of sent bytes to this counter */ curl_off_t *bytes_written, /* how much of the buffer contains body data */ size_t included_body_bytes, int socketindex) { ssize_t amount; CURLcode result; char *ptr; size_t size; struct Curl_easy *data = conn->data; struct HTTP *http = data->req.protop; size_t sendsize; curl_socket_t sockfd; size_t headersize; Curl_send_buffer *in = *inp; DEBUGASSERT(socketindex <= SECONDARYSOCKET); sockfd = conn->sock[socketindex]; /* The looping below is required since we use non-blocking sockets, but due to the circumstances we will just loop and try again and again etc */ ptr = in->buffer; size = in->size_used; headersize = size - included_body_bytes; /* the initial part that isn't body is header */ DEBUGASSERT(size > included_body_bytes); result = Curl_convert_to_network(data, ptr, headersize); /* Curl_convert_to_network calls failf if unsuccessful */ if(result) { /* conversion failed, free memory and return to the caller */ Curl_add_buffer_free(inp); return result; } if((conn->handler->flags & PROTOPT_SSL || conn->http_proxy.proxytype == CURLPROXY_HTTPS) && conn->httpversion != 20) { /* We never send more than CURL_MAX_WRITE_SIZE bytes in one single chunk when we speak HTTPS, as if only a fraction of it is sent now, this data needs to fit into the normal read-callback buffer later on and that buffer is using this size. */ sendsize = CURLMIN(size, CURL_MAX_WRITE_SIZE); /* OpenSSL is very picky and we must send the SAME buffer pointer to the library when we attempt to re-send this buffer. Sending the same data is not enough, we must use the exact same address. For this reason, we must copy the data to the uploadbuffer first, since that is the buffer we will be using if this send is retried later. */ result = Curl_get_upload_buffer(data); if(result) { /* malloc failed, free memory and return to the caller */ Curl_add_buffer_free(&in); return result; } memcpy(data->state.ulbuf, ptr, sendsize); ptr = data->state.ulbuf; } else sendsize = size; result = Curl_write(conn, sockfd, ptr, sendsize, &amount); if(!result) { /* * Note that we may not send the entire chunk at once, and we have a set * number of data bytes at the end of the big buffer (out of which we may * only send away a part). */ /* how much of the header that was sent */ size_t headlen = (size_t)amount>headersize ? headersize : (size_t)amount; size_t bodylen = amount - headlen; if(data->set.verbose) { /* this data _may_ contain binary stuff */ Curl_debug(data, CURLINFO_HEADER_OUT, ptr, headlen); if(bodylen) { /* there was body data sent beyond the initial header part, pass that on to the debug callback too */ Curl_debug(data, CURLINFO_DATA_OUT, ptr + headlen, bodylen); } } /* 'amount' can never be a very large value here so typecasting it so a signed 31 bit value should not cause problems even if ssize_t is 64bit */ *bytes_written += (long)amount; if(http) { /* if we sent a piece of the body here, up the byte counter for it accordingly */ data->req.writebytecount += bodylen; Curl_pgrsSetUploadCounter(data, data->req.writebytecount); if((size_t)amount != size) { /* The whole request could not be sent in one system call. We must queue it up and send it later when we get the chance. We must not loop here and wait until it might work again. */ size -= amount; ptr = in->buffer + amount; /* backup the currently set pointers */ http->backup.fread_func = data->state.fread_func; http->backup.fread_in = data->state.in; http->backup.postdata = http->postdata; http->backup.postsize = http->postsize; /* set the new pointers for the request-sending */ data->state.fread_func = (curl_read_callback)readmoredata; data->state.in = (void *)conn; http->postdata = ptr; http->postsize = (curl_off_t)size; http->send_buffer = in; http->sending = HTTPSEND_REQUEST; return CURLE_OK; } http->sending = HTTPSEND_BODY; /* the full buffer was sent, clean up and return */ } else { if((size_t)amount != size) /* We have no continue-send mechanism now, fail. This can only happen when this function is used from the CONNECT sending function. We currently (stupidly) assume that the whole request is always sent away in the first single chunk. This needs FIXing. */ return CURLE_SEND_ERROR; } } Curl_add_buffer_free(&in); return result; } /* * add_bufferf() add the formatted input to the buffer. */ CURLcode Curl_add_bufferf(Curl_send_buffer **inp, const char *fmt, ...) { char *s; va_list ap; Curl_send_buffer *in = *inp; va_start(ap, fmt); s = vaprintf(fmt, ap); /* this allocs a new string to append */ va_end(ap); if(s) { CURLcode result = Curl_add_buffer(inp, s, strlen(s)); free(s); return result; } /* If we failed, we cleanup the whole buffer and return error */ free(in->buffer); free(in); *inp = NULL; return CURLE_OUT_OF_MEMORY; } /* * Curl_add_buffer() appends a memory chunk to the existing buffer */ CURLcode Curl_add_buffer(Curl_send_buffer **inp, const void *inptr, size_t size) { char *new_rb; Curl_send_buffer *in = *inp; if(~size < in->size_used) { /* If resulting used size of send buffer would wrap size_t, cleanup the whole buffer and return error. Otherwise the required buffer size will fit into a single allocatable memory chunk */ Curl_safefree(in->buffer); free(in); *inp = NULL; return CURLE_OUT_OF_MEMORY; } if(!in->buffer || ((in->size_used + size) > (in->size_max - 1))) { /* If current buffer size isn't enough to hold the result, use a buffer size that doubles the required size. If this new size would wrap size_t, then just use the largest possible one */ size_t new_size; if((size > (size_t)-1 / 2) || (in->size_used > (size_t)-1 / 2) || (~(size * 2) < (in->size_used * 2))) new_size = (size_t)-1; else new_size = (in->size_used + size) * 2; if(in->buffer) /* we have a buffer, enlarge the existing one */ new_rb = Curl_saferealloc(in->buffer, new_size); else /* create a new buffer */ new_rb = malloc(new_size); if(!new_rb) { /* If we failed, we cleanup the whole buffer and return error */ free(in); *inp = NULL; return CURLE_OUT_OF_MEMORY; } in->buffer = new_rb; in->size_max = new_size; } memcpy(&in->buffer[in->size_used], inptr, size); in->size_used += size; return CURLE_OK; } /* end of the add_buffer functions */ /* ------------------------------------------------------------------------- */ /* * Curl_compareheader() * * Returns TRUE if 'headerline' contains the 'header' with given 'content'. * Pass headers WITH the colon. */ bool Curl_compareheader(const char *headerline, /* line to check */ const char *header, /* header keyword _with_ colon */ const char *content) /* content string to find */ { /* RFC2616, section 4.2 says: "Each header field consists of a name followed * by a colon (":") and the field value. Field names are case-insensitive. * The field value MAY be preceded by any amount of LWS, though a single SP * is preferred." */ size_t hlen = strlen(header); size_t clen; size_t len; const char *start; const char *end; if(!strncasecompare(headerline, header, hlen)) return FALSE; /* doesn't start with header */ /* pass the header */ start = &headerline[hlen]; /* pass all white spaces */ while(*start && ISSPACE(*start)) start++; /* find the end of the header line */ end = strchr(start, '\r'); /* lines end with CRLF */ if(!end) { /* in case there's a non-standard compliant line here */ end = strchr(start, '\n'); if(!end) /* hm, there's no line ending here, use the zero byte! */ end = strchr(start, '\0'); } len = end-start; /* length of the content part of the input line */ clen = strlen(content); /* length of the word to find */ /* find the content string in the rest of the line */ for(; len >= clen; len--, start++) { if(strncasecompare(start, content, clen)) return TRUE; /* match! */ } return FALSE; /* no match */ } /* * Curl_http_connect() performs HTTP stuff to do at connect-time, called from * the generic Curl_connect(). */ CURLcode Curl_http_connect(struct connectdata *conn, bool *done) { CURLcode result; /* We default to persistent connections. We set this already in this connect function to make the re-use checks properly be able to check this bit. */ connkeep(conn, "HTTP default"); /* the CONNECT procedure might not have been completed */ result = Curl_proxy_connect(conn, FIRSTSOCKET); if(result) return result; if(conn->bits.proxy_connect_closed) /* this is not an error, just part of the connection negotiation */ return CURLE_OK; if(CONNECT_FIRSTSOCKET_PROXY_SSL()) return CURLE_OK; /* wait for HTTPS proxy SSL initialization to complete */ if(Curl_connect_ongoing(conn)) /* nothing else to do except wait right now - we're not done here. */ return CURLE_OK; #ifndef CURL_DISABLE_PROXY if(conn->data->set.haproxyprotocol) { /* add HAProxy PROXY protocol header */ result = add_haproxy_protocol_header(conn); if(result) return result; } #endif if(conn->given->protocol & CURLPROTO_HTTPS) { /* perform SSL initialization */ result = https_connecting(conn, done); if(result) return result; } else *done = TRUE; return CURLE_OK; } /* this returns the socket to wait for in the DO and DOING state for the multi interface and then we're always _sending_ a request and thus we wait for the single socket to become writable only */ static int http_getsock_do(struct connectdata *conn, curl_socket_t *socks, int numsocks) { /* write mode */ (void)numsocks; /* unused, we trust it to be at least 1 */ socks[0] = conn->sock[FIRSTSOCKET]; return GETSOCK_WRITESOCK(0); } #ifndef CURL_DISABLE_PROXY static CURLcode add_haproxy_protocol_header(struct connectdata *conn) { char proxy_header[128]; Curl_send_buffer *req_buffer; CURLcode result; char tcp_version[5]; /* Emit the correct prefix for IPv6 */ if(conn->bits.ipv6) { strcpy(tcp_version, "TCP6"); } else { strcpy(tcp_version, "TCP4"); } msnprintf(proxy_header, sizeof(proxy_header), "PROXY %s %s %s %li %li\r\n", tcp_version, conn->data->info.conn_local_ip, conn->data->info.conn_primary_ip, conn->data->info.conn_local_port, conn->data->info.conn_primary_port); req_buffer = Curl_add_buffer_init(); if(!req_buffer) return CURLE_OUT_OF_MEMORY; result = Curl_add_bufferf(&req_buffer, proxy_header); if(result) return result; result = Curl_add_buffer_send(&req_buffer, conn, &conn->data->info.request_size, 0, FIRSTSOCKET); return result; } #endif #ifdef USE_SSL static CURLcode https_connecting(struct connectdata *conn, bool *done) { CURLcode result; DEBUGASSERT((conn) && (conn->handler->flags & PROTOPT_SSL)); /* perform SSL initialization for this socket */ result = Curl_ssl_connect_nonblocking(conn, FIRSTSOCKET, done); if(result) connclose(conn, "Failed HTTPS connection"); return result; } static int https_getsock(struct connectdata *conn, curl_socket_t *socks, int numsocks) { if(conn->handler->flags & PROTOPT_SSL) return Curl_ssl_getsock(conn, socks, numsocks); return GETSOCK_BLANK; } #endif /* USE_SSL */ /* * Curl_http_done() gets called after a single HTTP request has been * performed. */ CURLcode Curl_http_done(struct connectdata *conn, CURLcode status, bool premature) { struct Curl_easy *data = conn->data; struct HTTP *http = data->req.protop; /* Clear multipass flag. If authentication isn't done yet, then it will get * a chance to be set back to true when we output the next auth header */ data->state.authhost.multipass = FALSE; data->state.authproxy.multipass = FALSE; Curl_unencode_cleanup(conn); /* set the proper values (possibly modified on POST) */ conn->seek_func = data->set.seek_func; /* restore */ conn->seek_client = data->set.seek_client; /* restore */ if(!http) return CURLE_OK; if(http->send_buffer) { Curl_add_buffer_free(&http->send_buffer); } Curl_http2_done(conn, premature); Curl_mime_cleanpart(&http->form); if(status) return status; if(!premature && /* this check is pointless when DONE is called before the entire operation is complete */ !conn->bits.retry && !data->set.connect_only && (data->req.bytecount + data->req.headerbytecount - data->req.deductheadercount) <= 0) { /* If this connection isn't simply closed to be retried, AND nothing was read from the HTTP server (that counts), this can't be right so we return an error here */ failf(data, "Empty reply from server"); return CURLE_GOT_NOTHING; } return CURLE_OK; } /* * Determine if we should use HTTP 1.1 (OR BETTER) for this request. Reasons * to avoid it include: * * - if the user specifically requested HTTP 1.0 * - if the server we are connected to only supports 1.0 * - if any server previously contacted to handle this request only supports * 1.0. */ static bool use_http_1_1plus(const struct Curl_easy *data, const struct connectdata *conn) { if((data->state.httpversion == 10) || (conn->httpversion == 10)) return FALSE; if((data->set.httpversion == CURL_HTTP_VERSION_1_0) && (conn->httpversion <= 10)) return FALSE; return ((data->set.httpversion == CURL_HTTP_VERSION_NONE) || (data->set.httpversion >= CURL_HTTP_VERSION_1_1)); } static const char *get_http_string(const struct Curl_easy *data, const struct connectdata *conn) { #ifdef USE_NGHTTP2 if(conn->proto.httpc.h2) return "2"; #endif if(use_http_1_1plus(data, conn)) return "1.1"; return "1.0"; } /* check and possibly add an Expect: header */ static CURLcode expect100(struct Curl_easy *data, struct connectdata *conn, Curl_send_buffer *req_buffer) { CURLcode result = CURLE_OK; data->state.expect100header = FALSE; /* default to false unless it is set to TRUE below */ if(use_http_1_1plus(data, conn) && (conn->httpversion != 20)) { /* if not doing HTTP 1.0 or version 2, or disabled explicitly, we add an Expect: 100-continue to the headers which actually speeds up post operations (as there is one packet coming back from the web server) */ const char *ptr = Curl_checkheaders(conn, "Expect"); if(ptr) { data->state.expect100header = Curl_compareheader(ptr, "Expect:", "100-continue"); } else { result = Curl_add_bufferf(&req_buffer, "Expect: 100-continue\r\n"); if(!result) data->state.expect100header = TRUE; } } return result; } enum proxy_use { HEADER_SERVER, /* direct to server */ HEADER_PROXY, /* regular request to proxy */ HEADER_CONNECT /* sending CONNECT to a proxy */ }; /* used to compile the provided trailers into one buffer will return an error code if one of the headers is not formatted correctly */ CURLcode Curl_http_compile_trailers(struct curl_slist *trailers, Curl_send_buffer *buffer, struct Curl_easy *handle) { char *ptr = NULL; CURLcode result = CURLE_OK; const char *endofline_native = NULL; const char *endofline_network = NULL; if( #ifdef CURL_DO_LINEEND_CONV (handle->set.prefer_ascii) || #endif (handle->set.crlf)) { /* \n will become \r\n later on */ endofline_native = "\n"; endofline_network = "\x0a"; } else { endofline_native = "\r\n"; endofline_network = "\x0d\x0a"; } while(trailers) { /* only add correctly formatted trailers */ ptr = strchr(trailers->data, ':'); if(ptr && *(ptr + 1) == ' ') { result = Curl_add_bufferf(&buffer, "%s%s", trailers->data, endofline_native); if(result) return result; } else infof(handle, "Malformatted trailing header ! Skipping trailer."); trailers = trailers->next; } result = Curl_add_buffer(&buffer, endofline_network, strlen(endofline_network)); return result; } CURLcode Curl_add_custom_headers(struct connectdata *conn, bool is_connect, Curl_send_buffer *req_buffer) { char *ptr; struct curl_slist *h[2]; struct curl_slist *headers; int numlists = 1; /* by default */ struct Curl_easy *data = conn->data; int i; enum proxy_use proxy; if(is_connect) proxy = HEADER_CONNECT; else proxy = conn->bits.httpproxy && !conn->bits.tunnel_proxy? HEADER_PROXY:HEADER_SERVER; switch(proxy) { case HEADER_SERVER: h[0] = data->set.headers; break; case HEADER_PROXY: h[0] = data->set.headers; if(data->set.sep_headers) { h[1] = data->set.proxyheaders; numlists++; } break; case HEADER_CONNECT: if(data->set.sep_headers) h[0] = data->set.proxyheaders; else h[0] = data->set.headers; break; } /* loop through one or two lists */ for(i = 0; i < numlists; i++) { headers = h[i]; while(headers) { char *semicolonp = NULL; ptr = strchr(headers->data, ':'); if(!ptr) { char *optr; /* no colon, semicolon? */ ptr = strchr(headers->data, ';'); if(ptr) { optr = ptr; ptr++; /* pass the semicolon */ while(*ptr && ISSPACE(*ptr)) ptr++; if(*ptr) { /* this may be used for something else in the future */ optr = NULL; } else { if(*(--ptr) == ';') { /* copy the source */ semicolonp = strdup(headers->data); if(!semicolonp) { Curl_add_buffer_free(&req_buffer); return CURLE_OUT_OF_MEMORY; } /* put a colon where the semicolon is */ semicolonp[ptr - headers->data] = ':'; /* point at the colon */ optr = &semicolonp [ptr - headers->data]; } } ptr = optr; } } if(ptr) { /* we require a colon for this to be a true header */ ptr++; /* pass the colon */ while(*ptr && ISSPACE(*ptr)) ptr++; if(*ptr || semicolonp) { /* only send this if the contents was non-blank or done special */ CURLcode result = CURLE_OK; char *compare = semicolonp ? semicolonp : headers->data; if(conn->allocptr.host && /* a Host: header was sent already, don't pass on any custom Host: header as that will produce *two* in the same request! */ checkprefix("Host:", compare)) ; else if(data->set.httpreq == HTTPREQ_POST_FORM && /* this header (extended by formdata.c) is sent later */ checkprefix("Content-Type:", compare)) ; else if(data->set.httpreq == HTTPREQ_POST_MIME && /* this header is sent later */ checkprefix("Content-Type:", compare)) ; else if(conn->bits.authneg && /* while doing auth neg, don't allow the custom length since we will force length zero then */ checkprefix("Content-Length:", compare)) ; else if(conn->allocptr.te && /* when asking for Transfer-Encoding, don't pass on a custom Connection: */ checkprefix("Connection:", compare)) ; else if((conn->httpversion == 20) && checkprefix("Transfer-Encoding:", compare)) /* HTTP/2 doesn't support chunked requests */ ; else if((checkprefix("Authorization:", compare) || checkprefix("Cookie:", compare)) && /* be careful of sending this potentially sensitive header to other hosts */ (data->state.this_is_a_follow && data->state.first_host && !data->set.allow_auth_to_other_hosts && !strcasecompare(data->state.first_host, conn->host.name))) ; else { result = Curl_add_bufferf(&req_buffer, "%s\r\n", compare); } if(semicolonp) free(semicolonp); if(result) return result; } } headers = headers->next; } } return CURLE_OK; } #ifndef CURL_DISABLE_PARSEDATE CURLcode Curl_add_timecondition(struct Curl_easy *data, Curl_send_buffer *req_buffer) { const struct tm *tm; struct tm keeptime; CURLcode result; char datestr[80]; const char *condp; if(data->set.timecondition == CURL_TIMECOND_NONE) /* no condition was asked for */ return CURLE_OK; result = Curl_gmtime(data->set.timevalue, &keeptime); if(result) { failf(data, "Invalid TIMEVALUE"); return result; } tm = &keeptime; switch(data->set.timecondition) { default: return CURLE_BAD_FUNCTION_ARGUMENT; case CURL_TIMECOND_IFMODSINCE: condp = "If-Modified-Since"; break; case CURL_TIMECOND_IFUNMODSINCE: condp = "If-Unmodified-Since"; break; case CURL_TIMECOND_LASTMOD: condp = "Last-Modified"; break; } /* The If-Modified-Since header family should have their times set in * GMT as RFC2616 defines: "All HTTP date/time stamps MUST be * represented in Greenwich Mean Time (GMT), without exception. For the * purposes of HTTP, GMT is exactly equal to UTC (Coordinated Universal * Time)." (see page 20 of RFC2616). */ /* format: "Tue, 15 Nov 1994 12:45:26 GMT" */ msnprintf(datestr, sizeof(datestr), "%s: %s, %02d %s %4d %02d:%02d:%02d GMT\r\n", condp, Curl_wkday[tm->tm_wday?tm->tm_wday-1:6], tm->tm_mday, Curl_month[tm->tm_mon], tm->tm_year + 1900, tm->tm_hour, tm->tm_min, tm->tm_sec); result = Curl_add_buffer(&req_buffer, datestr, strlen(datestr)); return result; } #else /* disabled */ CURLcode Curl_add_timecondition(struct Curl_easy *data, Curl_send_buffer *req_buffer) { (void)data; (void)req_buffer; return CURLE_OK; } #endif /* * Curl_http() gets called from the generic multi_do() function when a HTTP * request is to be performed. This creates and sends a properly constructed * HTTP request. */ CURLcode Curl_http(struct connectdata *conn, bool *done) { struct Curl_easy *data = conn->data; CURLcode result = CURLE_OK; struct HTTP *http; const char *path = data->state.up.path; const char *query = data->state.up.query; bool paste_ftp_userpwd = FALSE; char ftp_typecode[sizeof("/;type=?")] = ""; const char *host = conn->host.name; const char *te = ""; /* transfer-encoding */ const char *ptr; const char *request; Curl_HttpReq httpreq = data->set.httpreq; #if !defined(CURL_DISABLE_COOKIES) char *addcookies = NULL; #endif curl_off_t included_body = 0; const char *httpstring; Curl_send_buffer *req_buffer; curl_off_t postsize = 0; /* curl_off_t to handle large file sizes */ /* Always consider the DO phase done after this function call, even if there may be parts of the request that is not yet sent, since we can deal with the rest of the request in the PERFORM phase. */ *done = TRUE; if(conn->httpversion < 20) { /* unless the connection is re-used and already http2 */ switch(conn->negnpn) { case CURL_HTTP_VERSION_2: conn->httpversion = 20; /* we know we're on HTTP/2 now */ result = Curl_http2_switched(conn, NULL, 0); if(result) return result; break; case CURL_HTTP_VERSION_1_1: /* continue with HTTP/1.1 when explicitly requested */ break; default: /* Check if user wants to use HTTP/2 with clear TCP*/ #ifdef USE_NGHTTP2 if(conn->data->set.httpversion == CURL_HTTP_VERSION_2_PRIOR_KNOWLEDGE) { if(conn->bits.httpproxy && !conn->bits.tunnel_proxy) { /* We don't support HTTP/2 proxies yet. Also it's debatable whether or not this setting should apply to HTTP/2 proxies. */ infof(data, "Ignoring HTTP/2 prior knowledge due to proxy\n"); break; } DEBUGF(infof(data, "HTTP/2 over clean TCP\n")); conn->httpversion = 20; result = Curl_http2_switched(conn, NULL, 0); if(result) return result; } #endif break; } } else { /* prepare for a http2 request */ result = Curl_http2_setup(conn); if(result) return result; } http = data->req.protop; DEBUGASSERT(http); if(!data->state.this_is_a_follow) { /* Free to avoid leaking memory on multiple requests*/ free(data->state.first_host); data->state.first_host = strdup(conn->host.name); if(!data->state.first_host) return CURLE_OUT_OF_MEMORY; data->state.first_remote_port = conn->remote_port; } if((conn->handler->protocol&(PROTO_FAMILY_HTTP|CURLPROTO_FTP)) && data->set.upload) { httpreq = HTTPREQ_PUT; } /* Now set the 'request' pointer to the proper request string */ if(data->set.str[STRING_CUSTOMREQUEST]) request = data->set.str[STRING_CUSTOMREQUEST]; else { if(data->set.opt_no_body) request = "HEAD"; else { DEBUGASSERT((httpreq > HTTPREQ_NONE) && (httpreq < HTTPREQ_LAST)); switch(httpreq) { case HTTPREQ_POST: case HTTPREQ_POST_FORM: case HTTPREQ_POST_MIME: request = "POST"; break; case HTTPREQ_PUT: request = "PUT"; break; case HTTPREQ_OPTIONS: request = "OPTIONS"; break; default: /* this should never happen */ case HTTPREQ_GET: request = "GET"; break; case HTTPREQ_HEAD: request = "HEAD"; break; } } } /* The User-Agent string might have been allocated in url.c already, because it might have been used in the proxy connect, but if we have got a header with the user-agent string specified, we erase the previously made string here. */ if(Curl_checkheaders(conn, "User-Agent")) { free(conn->allocptr.uagent); conn->allocptr.uagent = NULL; } /* setup the authentication headers */ { char *pq = NULL; if(query && *query) { pq = aprintf("%s?%s", path, query); if(!pq) return CURLE_OUT_OF_MEMORY; } result = Curl_http_output_auth(conn, request, (pq ? pq : path), FALSE); free(pq); if(result) return result; } if(((data->state.authhost.multipass && !data->state.authhost.done) || (data->state.authproxy.multipass && !data->state.authproxy.done)) && (httpreq != HTTPREQ_GET) && (httpreq != HTTPREQ_HEAD)) { /* Auth is required and we are not authenticated yet. Make a PUT or POST with content-length zero as a "probe". */ conn->bits.authneg = TRUE; } else conn->bits.authneg = FALSE; Curl_safefree(conn->allocptr.ref); if(data->change.referer && !Curl_checkheaders(conn, "Referer")) { conn->allocptr.ref = aprintf("Referer: %s\r\n", data->change.referer); if(!conn->allocptr.ref) return CURLE_OUT_OF_MEMORY; } else conn->allocptr.ref = NULL; #if !defined(CURL_DISABLE_COOKIES) if(data->set.str[STRING_COOKIE] && !Curl_checkheaders(conn, "Cookie")) addcookies = data->set.str[STRING_COOKIE]; #endif if(!Curl_checkheaders(conn, "Accept-Encoding") && data->set.str[STRING_ENCODING]) { Curl_safefree(conn->allocptr.accept_encoding); conn->allocptr.accept_encoding = aprintf("Accept-Encoding: %s\r\n", data->set.str[STRING_ENCODING]); if(!conn->allocptr.accept_encoding) return CURLE_OUT_OF_MEMORY; } else { Curl_safefree(conn->allocptr.accept_encoding); conn->allocptr.accept_encoding = NULL; } #ifdef HAVE_LIBZ /* we only consider transfer-encoding magic if libz support is built-in */ if(!Curl_checkheaders(conn, "TE") && data->set.http_transfer_encoding) { /* When we are to insert a TE: header in the request, we must also insert TE in a Connection: header, so we need to merge the custom provided Connection: header and prevent the original to get sent. Note that if the user has inserted his/hers own TE: header we don't do this magic but then assume that the user will handle it all! */ char *cptr = Curl_checkheaders(conn, "Connection"); #define TE_HEADER "TE: gzip\r\n" Curl_safefree(conn->allocptr.te); if(cptr) { cptr = Curl_copy_header_value(cptr); if(!cptr) return CURLE_OUT_OF_MEMORY; } /* Create the (updated) Connection: header */ conn->allocptr.te = aprintf("Connection: %s%sTE\r\n" TE_HEADER, cptr ? cptr : "", (cptr && *cptr) ? ", ":""); free(cptr); if(!conn->allocptr.te) return CURLE_OUT_OF_MEMORY; } #endif switch(httpreq) { case HTTPREQ_POST_MIME: http->sendit = &data->set.mimepost; break; case HTTPREQ_POST_FORM: /* Convert the form structure into a mime structure. */ Curl_mime_cleanpart(&http->form); result = Curl_getformdata(data, &http->form, data->set.httppost, data->state.fread_func); if(result) return result; http->sendit = &http->form; break; default: http->sendit = NULL; } #ifndef CURL_DISABLE_MIME if(http->sendit) { const char *cthdr = Curl_checkheaders(conn, "Content-Type"); /* Read and seek body only. */ http->sendit->flags |= MIME_BODY_ONLY; /* Prepare the mime structure headers & set content type. */ if(cthdr) for(cthdr += 13; *cthdr == ' '; cthdr++) ; else if(http->sendit->kind == MIMEKIND_MULTIPART) cthdr = "multipart/form-data"; curl_mime_headers(http->sendit, data->set.headers, 0); result = Curl_mime_prepare_headers(http->sendit, cthdr, NULL, MIMESTRATEGY_FORM); curl_mime_headers(http->sendit, NULL, 0); if(!result) result = Curl_mime_rewind(http->sendit); if(result) return result; http->postsize = Curl_mime_size(http->sendit); } #endif ptr = Curl_checkheaders(conn, "Transfer-Encoding"); if(ptr) { /* Some kind of TE is requested, check if 'chunked' is chosen */ data->req.upload_chunky = Curl_compareheader(ptr, "Transfer-Encoding:", "chunked"); } else { if((conn->handler->protocol & PROTO_FAMILY_HTTP) && (((httpreq == HTTPREQ_POST_MIME || httpreq == HTTPREQ_POST_FORM) && http->postsize < 0) || (data->set.upload && data->state.infilesize == -1))) { if(conn->bits.authneg) /* don't enable chunked during auth neg */ ; else if(use_http_1_1plus(data, conn)) { /* HTTP, upload, unknown file size and not HTTP 1.0 */ data->req.upload_chunky = TRUE; } else { failf(data, "Chunky upload is not supported by HTTP 1.0"); return CURLE_UPLOAD_FAILED; } } else { /* else, no chunky upload */ data->req.upload_chunky = FALSE; } if(data->req.upload_chunky) te = "Transfer-Encoding: chunked\r\n"; } Curl_safefree(conn->allocptr.host); ptr = Curl_checkheaders(conn, "Host"); if(ptr && (!data->state.this_is_a_follow || strcasecompare(data->state.first_host, conn->host.name))) { #if !defined(CURL_DISABLE_COOKIES) /* If we have a given custom Host: header, we extract the host name in order to possibly use it for cookie reasons later on. We only allow the custom Host: header if this is NOT a redirect, as setting Host: in the redirected request is being out on thin ice. Except if the host name is the same as the first one! */ char *cookiehost = Curl_copy_header_value(ptr); if(!cookiehost) return CURLE_OUT_OF_MEMORY; if(!*cookiehost) /* ignore empty data */ free(cookiehost); else { /* If the host begins with '[', we start searching for the port after the bracket has been closed */ if(*cookiehost == '[') { char *closingbracket; /* since the 'cookiehost' is an allocated memory area that will be freed later we cannot simply increment the pointer */ memmove(cookiehost, cookiehost + 1, strlen(cookiehost) - 1); closingbracket = strchr(cookiehost, ']'); if(closingbracket) *closingbracket = 0; } else { int startsearch = 0; char *colon = strchr(cookiehost + startsearch, ':'); if(colon) *colon = 0; /* The host must not include an embedded port number */ } Curl_safefree(conn->allocptr.cookiehost); conn->allocptr.cookiehost = cookiehost; } #endif if(strcmp("Host:", ptr)) { conn->allocptr.host = aprintf("Host:%s\r\n", &ptr[5]); if(!conn->allocptr.host) return CURLE_OUT_OF_MEMORY; } else /* when clearing the header */ conn->allocptr.host = NULL; } else { /* When building Host: headers, we must put the host name within [brackets] if the host name is a plain IPv6-address. RFC2732-style. */ if(((conn->given->protocol&CURLPROTO_HTTPS) && (conn->remote_port == PORT_HTTPS)) || ((conn->given->protocol&CURLPROTO_HTTP) && (conn->remote_port == PORT_HTTP)) ) /* if(HTTPS on port 443) OR (HTTP on port 80) then don't include the port number in the host string */ conn->allocptr.host = aprintf("Host: %s%s%s\r\n", conn->bits.ipv6_ip?"[":"", host, conn->bits.ipv6_ip?"]":""); else conn->allocptr.host = aprintf("Host: %s%s%s:%d\r\n", conn->bits.ipv6_ip?"[":"", host, conn->bits.ipv6_ip?"]":"", conn->remote_port); if(!conn->allocptr.host) /* without Host: we can't make a nice request */ return CURLE_OUT_OF_MEMORY; } #ifndef CURL_DISABLE_PROXY if(conn->bits.httpproxy && !conn->bits.tunnel_proxy) { /* Using a proxy but does not tunnel through it */ /* The path sent to the proxy is in fact the entire URL. But if the remote host is a IDN-name, we must make sure that the request we produce only uses the encoded host name! */ /* and no fragment part */ CURLUcode uc; char *url; CURLU *h = curl_url_dup(data->state.uh); if(!h) return CURLE_OUT_OF_MEMORY; if(conn->host.dispname != conn->host.name) { uc = curl_url_set(h, CURLUPART_HOST, conn->host.name, 0); if(uc) { curl_url_cleanup(h); return CURLE_OUT_OF_MEMORY; } } uc = curl_url_set(h, CURLUPART_FRAGMENT, NULL, 0); if(uc) { curl_url_cleanup(h); return CURLE_OUT_OF_MEMORY; } if(strcasecompare("http", data->state.up.scheme)) { /* when getting HTTP, we don't want the userinfo the URL */ uc = curl_url_set(h, CURLUPART_USER, NULL, 0); if(uc) { curl_url_cleanup(h); return CURLE_OUT_OF_MEMORY; } uc = curl_url_set(h, CURLUPART_PASSWORD, NULL, 0); if(uc) { curl_url_cleanup(h); return CURLE_OUT_OF_MEMORY; } } /* now extract the new version of the URL */ uc = curl_url_get(h, CURLUPART_URL, &url, 0); if(uc) { curl_url_cleanup(h); return CURLE_OUT_OF_MEMORY; } if(data->change.url_alloc) free(data->change.url); data->change.url = url; data->change.url_alloc = TRUE; curl_url_cleanup(h); if(strcasecompare("ftp", data->state.up.scheme)) { if(data->set.proxy_transfer_mode) { /* when doing ftp, append ;type=<a|i> if not present */ char *type = strstr(path, ";type="); if(type && type[6] && type[7] == 0) { switch(Curl_raw_toupper(type[6])) { case 'A': case 'D': case 'I': break; default: type = NULL; } } if(!type) { char *p = ftp_typecode; /* avoid sending invalid URLs like ftp://example.com;type=i if the * user specified ftp://example.com without the slash */ if(!*data->state.up.path && path[strlen(path) - 1] != '/') { *p++ = '/'; } msnprintf(p, sizeof(ftp_typecode) - 1, ";type=%c", data->set.prefer_ascii ? 'a' : 'i'); } } if(conn->bits.user_passwd && !conn->bits.userpwd_in_url) paste_ftp_userpwd = TRUE; } } #endif /* CURL_DISABLE_PROXY */ http->p_accept = Curl_checkheaders(conn, "Accept")?NULL:"Accept: */*\r\n"; if((HTTPREQ_POST == httpreq || HTTPREQ_PUT == httpreq) && data->state.resume_from) { /********************************************************************** * Resuming upload in HTTP means that we PUT or POST and that we have * got a resume_from value set. The resume value has already created * a Range: header that will be passed along. We need to "fast forward" * the file the given number of bytes and decrease the assume upload * file size before we continue this venture in the dark lands of HTTP. * Resuming mime/form posting at an offset > 0 has no sense and is ignored. *********************************************************************/ if(data->state.resume_from < 0) { /* * This is meant to get the size of the present remote-file by itself. * We don't support this now. Bail out! */ data->state.resume_from = 0; } if(data->state.resume_from && !data->state.this_is_a_follow) { /* do we still game? */ /* Now, let's read off the proper amount of bytes from the input. */ int seekerr = CURL_SEEKFUNC_CANTSEEK; if(conn->seek_func) { Curl_set_in_callback(data, true); seekerr = conn->seek_func(conn->seek_client, data->state.resume_from, SEEK_SET); Curl_set_in_callback(data, false); } if(seekerr != CURL_SEEKFUNC_OK) { curl_off_t passed = 0; if(seekerr != CURL_SEEKFUNC_CANTSEEK) { failf(data, "Could not seek stream"); return CURLE_READ_ERROR; } /* when seekerr == CURL_SEEKFUNC_CANTSEEK (can't seek to offset) */ do { size_t readthisamountnow = (data->state.resume_from - passed > data->set.buffer_size) ? (size_t)data->set.buffer_size : curlx_sotouz(data->state.resume_from - passed); size_t actuallyread = data->state.fread_func(data->state.buffer, 1, readthisamountnow, data->state.in); passed += actuallyread; if((actuallyread == 0) || (actuallyread > readthisamountnow)) { /* this checks for greater-than only to make sure that the CURL_READFUNC_ABORT return code still aborts */ failf(data, "Could only read %" CURL_FORMAT_CURL_OFF_T " bytes from the input", passed); return CURLE_READ_ERROR; } } while(passed < data->state.resume_from); } /* now, decrease the size of the read */ if(data->state.infilesize>0) { data->state.infilesize -= data->state.resume_from; if(data->state.infilesize <= 0) { failf(data, "File already completely uploaded"); return CURLE_PARTIAL_FILE; } } /* we've passed, proceed as normal */ } } if(data->state.use_range) { /* * A range is selected. We use different headers whether we're downloading * or uploading and we always let customized headers override our internal * ones if any such are specified. */ if(((httpreq == HTTPREQ_GET) || (httpreq == HTTPREQ_HEAD)) && !Curl_checkheaders(conn, "Range")) { /* if a line like this was already allocated, free the previous one */ free(conn->allocptr.rangeline); conn->allocptr.rangeline = aprintf("Range: bytes=%s\r\n", data->state.range); } else if((httpreq == HTTPREQ_POST || httpreq == HTTPREQ_PUT) && !Curl_checkheaders(conn, "Content-Range")) { /* if a line like this was already allocated, free the previous one */ free(conn->allocptr.rangeline); if(data->set.set_resume_from < 0) { /* Upload resume was asked for, but we don't know the size of the remote part so we tell the server (and act accordingly) that we upload the whole file (again) */ conn->allocptr.rangeline = aprintf("Content-Range: bytes 0-%" CURL_FORMAT_CURL_OFF_T "/%" CURL_FORMAT_CURL_OFF_T "\r\n", data->state.infilesize - 1, data->state.infilesize); } else if(data->state.resume_from) { /* This is because "resume" was selected */ curl_off_t total_expected_size = data->state.resume_from + data->state.infilesize; conn->allocptr.rangeline = aprintf("Content-Range: bytes %s%" CURL_FORMAT_CURL_OFF_T "/%" CURL_FORMAT_CURL_OFF_T "\r\n", data->state.range, total_expected_size-1, total_expected_size); } else { /* Range was selected and then we just pass the incoming range and append total size */ conn->allocptr.rangeline = aprintf("Content-Range: bytes %s/%" CURL_FORMAT_CURL_OFF_T "\r\n", data->state.range, data->state.infilesize); } if(!conn->allocptr.rangeline) return CURLE_OUT_OF_MEMORY; } } httpstring = get_http_string(data, conn); /* initialize a dynamic send-buffer */ req_buffer = Curl_add_buffer_init(); if(!req_buffer) return CURLE_OUT_OF_MEMORY; /* add the main request stuff */ /* GET/HEAD/POST/PUT */ result = Curl_add_bufferf(&req_buffer, "%s ", request); if(result) return result; if(data->set.str[STRING_TARGET]) { path = data->set.str[STRING_TARGET]; query = NULL; } /* url */ if(conn->bits.httpproxy && !conn->bits.tunnel_proxy) { char *url = data->change.url; result = Curl_add_buffer(&req_buffer, url, strlen(url)); } else if(paste_ftp_userpwd) result = Curl_add_bufferf(&req_buffer, "ftp://%s:%s@%s", conn->user, conn->passwd, path + sizeof("ftp://") - 1); else { result = Curl_add_buffer(&req_buffer, path, strlen(path)); if(result) return result; if(query) result = Curl_add_bufferf(&req_buffer, "?%s", query); } if(result) return result; result = Curl_add_bufferf(&req_buffer, "%s" /* ftp typecode (;type=x) */ " HTTP/%s\r\n" /* HTTP version */ "%s" /* host */ "%s" /* proxyuserpwd */ "%s" /* userpwd */ "%s" /* range */ "%s" /* user agent */ "%s" /* accept */ "%s" /* TE: */ "%s" /* accept-encoding */ "%s" /* referer */ "%s" /* Proxy-Connection */ "%s",/* transfer-encoding */ ftp_typecode, httpstring, (conn->allocptr.host?conn->allocptr.host:""), conn->allocptr.proxyuserpwd? conn->allocptr.proxyuserpwd:"", conn->allocptr.userpwd?conn->allocptr.userpwd:"", (data->state.use_range && conn->allocptr.rangeline)? conn->allocptr.rangeline:"", (data->set.str[STRING_USERAGENT] && *data->set.str[STRING_USERAGENT] && conn->allocptr.uagent)? conn->allocptr.uagent:"", http->p_accept?http->p_accept:"", conn->allocptr.te?conn->allocptr.te:"", (data->set.str[STRING_ENCODING] && *data->set.str[STRING_ENCODING] && conn->allocptr.accept_encoding)? conn->allocptr.accept_encoding:"", (data->change.referer && conn->allocptr.ref)? conn->allocptr.ref:"" /* Referer: <data> */, (conn->bits.httpproxy && !conn->bits.tunnel_proxy && !Curl_checkProxyheaders(conn, "Proxy-Connection"))? "Proxy-Connection: Keep-Alive\r\n":"", te ); /* clear userpwd and proxyuserpwd to avoid re-using old credentials * from re-used connections */ Curl_safefree(conn->allocptr.userpwd); Curl_safefree(conn->allocptr.proxyuserpwd); if(result) return result; if(!(conn->handler->flags&PROTOPT_SSL) && conn->httpversion != 20 && (data->set.httpversion == CURL_HTTP_VERSION_2)) { /* append HTTP2 upgrade magic stuff to the HTTP request if it isn't done over SSL */ result = Curl_http2_request_upgrade(req_buffer, conn); if(result) return result; } #if !defined(CURL_DISABLE_COOKIES) if(data->cookies || addcookies) { struct Cookie *co = NULL; /* no cookies from start */ int count = 0; if(data->cookies) { Curl_share_lock(data, CURL_LOCK_DATA_COOKIE, CURL_LOCK_ACCESS_SINGLE); co = Curl_cookie_getlist(data->cookies, conn->allocptr.cookiehost? conn->allocptr.cookiehost:host, data->state.up.path, (conn->handler->protocol&CURLPROTO_HTTPS)? TRUE:FALSE); Curl_share_unlock(data, CURL_LOCK_DATA_COOKIE); } if(co) { struct Cookie *store = co; /* now loop through all cookies that matched */ while(co) { if(co->value) { if(0 == count) { result = Curl_add_bufferf(&req_buffer, "Cookie: "); if(result) break; } result = Curl_add_bufferf(&req_buffer, "%s%s=%s", count?"; ":"", co->name, co->value); if(result) break; count++; } co = co->next; /* next cookie please */ } Curl_cookie_freelist(store); } if(addcookies && !result) { if(!count) result = Curl_add_bufferf(&req_buffer, "Cookie: "); if(!result) { result = Curl_add_bufferf(&req_buffer, "%s%s", count?"; ":"", addcookies); count++; } } if(count && !result) result = Curl_add_buffer(&req_buffer, "\r\n", 2); if(result) return result; } #endif result = Curl_add_timecondition(data, req_buffer); if(result) return result; result = Curl_add_custom_headers(conn, FALSE, req_buffer); if(result) return result; http->postdata = NULL; /* nothing to post at this point */ Curl_pgrsSetUploadSize(data, -1); /* upload size is unknown atm */ /* If 'authdone' is FALSE, we must not set the write socket index to the Curl_transfer() call below, as we're not ready to actually upload any data yet. */ switch(httpreq) { case HTTPREQ_PUT: /* Let's PUT the data to the server! */ if(conn->bits.authneg) postsize = 0; else postsize = data->state.infilesize; if((postsize != -1) && !data->req.upload_chunky && (conn->bits.authneg || !Curl_checkheaders(conn, "Content-Length"))) { /* only add Content-Length if not uploading chunked */ result = Curl_add_bufferf(&req_buffer, "Content-Length: %" CURL_FORMAT_CURL_OFF_T "\r\n", postsize); if(result) return result; } if(postsize != 0) { result = expect100(data, conn, req_buffer); if(result) return result; } result = Curl_add_buffer(&req_buffer, "\r\n", 2); /* end of headers */ if(result) return result; /* set the upload size to the progress meter */ Curl_pgrsSetUploadSize(data, postsize); /* this sends the buffer and frees all the buffer resources */ result = Curl_add_buffer_send(&req_buffer, conn, &data->info.request_size, 0, FIRSTSOCKET); if(result) failf(data, "Failed sending PUT request"); else /* prepare for transfer */ Curl_setup_transfer(data, FIRSTSOCKET, -1, TRUE, postsize?FIRSTSOCKET:-1); if(result) return result; break; case HTTPREQ_POST_FORM: case HTTPREQ_POST_MIME: /* This is form posting using mime data. */ if(conn->bits.authneg) { /* nothing to post! */ result = Curl_add_bufferf(&req_buffer, "Content-Length: 0\r\n\r\n"); if(result) return result; result = Curl_add_buffer_send(&req_buffer, conn, &data->info.request_size, 0, FIRSTSOCKET); if(result) failf(data, "Failed sending POST request"); else /* setup variables for the upcoming transfer */ Curl_setup_transfer(data, FIRSTSOCKET, -1, TRUE, -1); break; } data->state.infilesize = postsize = http->postsize; /* We only set Content-Length and allow a custom Content-Length if we don't upload data chunked, as RFC2616 forbids us to set both kinds of headers (Transfer-Encoding: chunked and Content-Length) */ if(postsize != -1 && !data->req.upload_chunky && (conn->bits.authneg || !Curl_checkheaders(conn, "Content-Length"))) { /* we allow replacing this header if not during auth negotiation, although it isn't very wise to actually set your own */ result = Curl_add_bufferf(&req_buffer, "Content-Length: %" CURL_FORMAT_CURL_OFF_T "\r\n", postsize); if(result) return result; } #ifndef CURL_DISABLE_MIME /* Output mime-generated headers. */ { struct curl_slist *hdr; for(hdr = http->sendit->curlheaders; hdr; hdr = hdr->next) { result = Curl_add_bufferf(&req_buffer, "%s\r\n", hdr->data); if(result) return result; } } #endif /* For really small posts we don't use Expect: headers at all, and for the somewhat bigger ones we allow the app to disable it. Just make sure that the expect100header is always set to the preferred value here. */ ptr = Curl_checkheaders(conn, "Expect"); if(ptr) { data->state.expect100header = Curl_compareheader(ptr, "Expect:", "100-continue"); } else if(postsize > EXPECT_100_THRESHOLD || postsize < 0) { result = expect100(data, conn, req_buffer); if(result) return result; } else data->state.expect100header = FALSE; /* make the request end in a true CRLF */ result = Curl_add_buffer(&req_buffer, "\r\n", 2); if(result) return result; /* set the upload size to the progress meter */ Curl_pgrsSetUploadSize(data, postsize); /* Read from mime structure. */ data->state.fread_func = (curl_read_callback) Curl_mime_read; data->state.in = (void *) http->sendit; http->sending = HTTPSEND_BODY; /* this sends the buffer and frees all the buffer resources */ result = Curl_add_buffer_send(&req_buffer, conn, &data->info.request_size, 0, FIRSTSOCKET); if(result) failf(data, "Failed sending POST request"); else /* prepare for transfer */ Curl_setup_transfer(data, FIRSTSOCKET, -1, TRUE, postsize?FIRSTSOCKET:-1); if(result) return result; break; case HTTPREQ_POST: /* this is the simple POST, using x-www-form-urlencoded style */ if(conn->bits.authneg) postsize = 0; else /* the size of the post body */ postsize = data->state.infilesize; /* We only set Content-Length and allow a custom Content-Length if we don't upload data chunked, as RFC2616 forbids us to set both kinds of headers (Transfer-Encoding: chunked and Content-Length) */ if((postsize != -1) && !data->req.upload_chunky && (conn->bits.authneg || !Curl_checkheaders(conn, "Content-Length"))) { /* we allow replacing this header if not during auth negotiation, although it isn't very wise to actually set your own */ result = Curl_add_bufferf(&req_buffer, "Content-Length: %" CURL_FORMAT_CURL_OFF_T "\r\n", postsize); if(result) return result; } if(!Curl_checkheaders(conn, "Content-Type")) { result = Curl_add_bufferf(&req_buffer, "Content-Type: application/" "x-www-form-urlencoded\r\n"); if(result) return result; } /* For really small posts we don't use Expect: headers at all, and for the somewhat bigger ones we allow the app to disable it. Just make sure that the expect100header is always set to the preferred value here. */ ptr = Curl_checkheaders(conn, "Expect"); if(ptr) { data->state.expect100header = Curl_compareheader(ptr, "Expect:", "100-continue"); } else if(postsize > EXPECT_100_THRESHOLD || postsize < 0) { result = expect100(data, conn, req_buffer); if(result) return result; } else data->state.expect100header = FALSE; if(data->set.postfields) { /* In HTTP2, we send request body in DATA frame regardless of its size. */ if(conn->httpversion != 20 && !data->state.expect100header && (postsize < MAX_INITIAL_POST_SIZE)) { /* if we don't use expect: 100 AND postsize is less than MAX_INITIAL_POST_SIZE then append the post data to the HTTP request header. This limit is no magic limit but only set to prevent really huge POSTs to get the data duplicated with malloc() and family. */ result = Curl_add_buffer(&req_buffer, "\r\n", 2); /* end of headers! */ if(result) return result; if(!data->req.upload_chunky) { /* We're not sending it 'chunked', append it to the request already now to reduce the number if send() calls */ result = Curl_add_buffer(&req_buffer, data->set.postfields, (size_t)postsize); included_body = postsize; } else { if(postsize) { /* Append the POST data chunky-style */ result = Curl_add_bufferf(&req_buffer, "%x\r\n", (int)postsize); if(!result) { result = Curl_add_buffer(&req_buffer, data->set.postfields, (size_t)postsize); if(!result) result = Curl_add_buffer(&req_buffer, "\r\n", 2); included_body = postsize + 2; } } if(!result) result = Curl_add_buffer(&req_buffer, "\x30\x0d\x0a\x0d\x0a", 5); /* 0 CR LF CR LF */ included_body += 5; } if(result) return result; /* Make sure the progress information is accurate */ Curl_pgrsSetUploadSize(data, postsize); } else { /* A huge POST coming up, do data separate from the request */ http->postsize = postsize; http->postdata = data->set.postfields; http->sending = HTTPSEND_BODY; data->state.fread_func = (curl_read_callback)readmoredata; data->state.in = (void *)conn; /* set the upload size to the progress meter */ Curl_pgrsSetUploadSize(data, http->postsize); result = Curl_add_buffer(&req_buffer, "\r\n", 2); /* end of headers! */ if(result) return result; } } else { result = Curl_add_buffer(&req_buffer, "\r\n", 2); /* end of headers! */ if(result) return result; if(data->req.upload_chunky && conn->bits.authneg) { /* Chunky upload is selected and we're negotiating auth still, send end-of-data only */ result = Curl_add_buffer(&req_buffer, "\x30\x0d\x0a\x0d\x0a", 5); /* 0 CR LF CR LF */ if(result) return result; } else if(data->state.infilesize) { /* set the upload size to the progress meter */ Curl_pgrsSetUploadSize(data, postsize?postsize:-1); /* set the pointer to mark that we will send the post body using the read callback, but only if we're not in authenticate negotiation */ if(!conn->bits.authneg) { http->postdata = (char *)&http->postdata; http->postsize = postsize; } } } /* issue the request */ result = Curl_add_buffer_send(&req_buffer, conn, &data->info.request_size, (size_t)included_body, FIRSTSOCKET); if(result) failf(data, "Failed sending HTTP POST request"); else Curl_setup_transfer(data, FIRSTSOCKET, -1, TRUE, http->postdata?FIRSTSOCKET:-1); break; default: result = Curl_add_buffer(&req_buffer, "\r\n", 2); if(result) return result; /* issue the request */ result = Curl_add_buffer_send(&req_buffer, conn, &data->info.request_size, 0, FIRSTSOCKET); if(result) failf(data, "Failed sending HTTP request"); else /* HTTP GET/HEAD download: */ Curl_setup_transfer(data, FIRSTSOCKET, -1, TRUE, http->postdata?FIRSTSOCKET:-1); } if(result) return result; if(data->req.writebytecount) { /* if a request-body has been sent off, we make sure this progress is noted properly */ Curl_pgrsSetUploadCounter(data, data->req.writebytecount); if(Curl_pgrsUpdate(conn)) result = CURLE_ABORTED_BY_CALLBACK; if(data->req.writebytecount >= postsize) { /* already sent the entire request body, mark the "upload" as complete */ infof(data, "upload completely sent off: %" CURL_FORMAT_CURL_OFF_T " out of %" CURL_FORMAT_CURL_OFF_T " bytes\n", data->req.writebytecount, postsize); data->req.upload_done = TRUE; data->req.keepon &= ~KEEP_SEND; /* we're done writing */ data->req.exp100 = EXP100_SEND_DATA; /* already sent */ Curl_expire_done(data, EXPIRE_100_TIMEOUT); } } if((conn->httpversion == 20) && data->req.upload_chunky) /* upload_chunky was set above to set up the request in a chunky fashion, but is disabled here again to avoid that the chunked encoded version is actually used when sending the request body over h2 */ data->req.upload_chunky = FALSE; return result; } typedef enum { STATUS_UNKNOWN, /* not enough data to tell yet */ STATUS_DONE, /* a status line was read */ STATUS_BAD /* not a status line */ } statusline; /* Check a string for a prefix. Check no more than 'len' bytes */ static bool checkprefixmax(const char *prefix, const char *buffer, size_t len) { size_t ch = CURLMIN(strlen(prefix), len); return curl_strnequal(prefix, buffer, ch); } /* * checkhttpprefix() * * Returns TRUE if member of the list matches prefix of string */ static statusline checkhttpprefix(struct Curl_easy *data, const char *s, size_t len) { struct curl_slist *head = data->set.http200aliases; statusline rc = STATUS_BAD; statusline onmatch = len >= 5? STATUS_DONE : STATUS_UNKNOWN; #ifdef CURL_DOES_CONVERSIONS /* convert from the network encoding using a scratch area */ char *scratch = strdup(s); if(NULL == scratch) { failf(data, "Failed to allocate memory for conversion!"); return FALSE; /* can't return CURLE_OUT_OF_MEMORY so return FALSE */ } if(CURLE_OK != Curl_convert_from_network(data, scratch, strlen(s) + 1)) { /* Curl_convert_from_network calls failf if unsuccessful */ free(scratch); return FALSE; /* can't return CURLE_foobar so return FALSE */ } s = scratch; #endif /* CURL_DOES_CONVERSIONS */ while(head) { if(checkprefixmax(head->data, s, len)) { rc = onmatch; break; } head = head->next; } if((rc != STATUS_DONE) && (checkprefixmax("HTTP/", s, len))) rc = onmatch; #ifdef CURL_DOES_CONVERSIONS free(scratch); #endif /* CURL_DOES_CONVERSIONS */ return rc; } #ifndef CURL_DISABLE_RTSP static statusline checkrtspprefix(struct Curl_easy *data, const char *s, size_t len) { statusline result = STATUS_BAD; statusline onmatch = len >= 5? STATUS_DONE : STATUS_UNKNOWN; #ifdef CURL_DOES_CONVERSIONS /* convert from the network encoding using a scratch area */ char *scratch = strdup(s); if(NULL == scratch) { failf(data, "Failed to allocate memory for conversion!"); return FALSE; /* can't return CURLE_OUT_OF_MEMORY so return FALSE */ } if(CURLE_OK != Curl_convert_from_network(data, scratch, strlen(s) + 1)) { /* Curl_convert_from_network calls failf if unsuccessful */ result = FALSE; /* can't return CURLE_foobar so return FALSE */ } else if(checkprefixmax("RTSP/", scratch, len)) result = onmatch; free(scratch); #else (void)data; /* unused */ if(checkprefixmax("RTSP/", s, len)) result = onmatch; #endif /* CURL_DOES_CONVERSIONS */ return result; } #endif /* CURL_DISABLE_RTSP */ static statusline checkprotoprefix(struct Curl_easy *data, struct connectdata *conn, const char *s, size_t len) { #ifndef CURL_DISABLE_RTSP if(conn->handler->protocol & CURLPROTO_RTSP) return checkrtspprefix(data, s, len); #else (void)conn; #endif /* CURL_DISABLE_RTSP */ return checkhttpprefix(data, s, len); } /* * header_append() copies a chunk of data to the end of the already received * header. We make sure that the full string fit in the allocated header * buffer, or else we enlarge it. */ static CURLcode header_append(struct Curl_easy *data, struct SingleRequest *k, size_t length) { size_t newsize = k->hbuflen + length; if(newsize > CURL_MAX_HTTP_HEADER) { /* The reason to have a max limit for this is to avoid the risk of a bad server feeding libcurl with a never-ending header that will cause reallocs infinitely */ failf(data, "Rejected %zu bytes header (max is %d)!", newsize, CURL_MAX_HTTP_HEADER); return CURLE_OUT_OF_MEMORY; } if(newsize >= data->state.headersize) { /* We enlarge the header buffer as it is too small */ char *newbuff; size_t hbufp_index; newsize = CURLMAX((k->hbuflen + length) * 3 / 2, data->state.headersize*2); hbufp_index = k->hbufp - data->state.headerbuff; newbuff = realloc(data->state.headerbuff, newsize); if(!newbuff) { failf(data, "Failed to alloc memory for big header!"); return CURLE_OUT_OF_MEMORY; } data->state.headersize = newsize; data->state.headerbuff = newbuff; k->hbufp = data->state.headerbuff + hbufp_index; } memcpy(k->hbufp, k->str_start, length); k->hbufp += length; k->hbuflen += length; *k->hbufp = 0; return CURLE_OK; } static void print_http_error(struct Curl_easy *data) { struct SingleRequest *k = &data->req; char *beg = k->p; /* make sure that data->req.p points to the HTTP status line */ if(!strncmp(beg, "HTTP", 4)) { /* skip to HTTP status code */ beg = strchr(beg, ' '); if(beg && *++beg) { /* find trailing CR */ char end_char = '\r'; char *end = strchr(beg, end_char); if(!end) { /* try to find LF (workaround for non-compliant HTTP servers) */ end_char = '\n'; end = strchr(beg, end_char); } if(end) { /* temporarily replace CR or LF by NUL and print the error message */ *end = '\0'; failf(data, "The requested URL returned error: %s", beg); /* restore the previously replaced CR or LF */ *end = end_char; return; } } } /* fall-back to printing the HTTP status code only */ failf(data, "The requested URL returned error: %d", k->httpcode); } /* * Read any HTTP header lines from the server and pass them to the client app. */ CURLcode Curl_http_readwrite_headers(struct Curl_easy *data, struct connectdata *conn, ssize_t *nread, bool *stop_reading) { CURLcode result; struct SingleRequest *k = &data->req; ssize_t onread = *nread; char *ostr = k->str; /* header line within buffer loop */ do { size_t rest_length; size_t full_length; int writetype; /* str_start is start of line within buf */ k->str_start = k->str; /* data is in network encoding so use 0x0a instead of '\n' */ k->end_ptr = memchr(k->str_start, 0x0a, *nread); if(!k->end_ptr) { /* Not a complete header line within buffer, append the data to the end of the headerbuff. */ result = header_append(data, k, *nread); if(result) return result; if(!k->headerline) { /* check if this looks like a protocol header */ statusline st = checkprotoprefix(data, conn, data->state.headerbuff, k->hbuflen); if(st == STATUS_BAD) { /* this is not the beginning of a protocol first header line */ k->header = FALSE; k->badheader = HEADER_ALLBAD; streamclose(conn, "bad HTTP: No end-of-message indicator"); if(!data->set.http09_allowed) { failf(data, "Received HTTP/0.9 when not allowed\n"); return CURLE_UNSUPPORTED_PROTOCOL; } break; } } break; /* read more and try again */ } /* decrease the size of the remaining (supposed) header line */ rest_length = (k->end_ptr - k->str) + 1; *nread -= (ssize_t)rest_length; k->str = k->end_ptr + 1; /* move past new line */ full_length = k->str - k->str_start; result = header_append(data, k, full_length); if(result) return result; k->end_ptr = k->hbufp; k->p = data->state.headerbuff; /**** * We now have a FULL header line that p points to *****/ if(!k->headerline) { /* the first read header */ statusline st = checkprotoprefix(data, conn, data->state.headerbuff, k->hbuflen); if(st == STATUS_BAD) { streamclose(conn, "bad HTTP: No end-of-message indicator"); /* this is not the beginning of a protocol first header line */ if(!data->set.http09_allowed) { failf(data, "Received HTTP/0.9 when not allowed\n"); return CURLE_UNSUPPORTED_PROTOCOL; } k->header = FALSE; if(*nread) /* since there's more, this is a partial bad header */ k->badheader = HEADER_PARTHEADER; else { /* this was all we read so it's all a bad header */ k->badheader = HEADER_ALLBAD; *nread = onread; k->str = ostr; return CURLE_OK; } break; } } /* headers are in network encoding so use 0x0a and 0x0d instead of '\n' and '\r' */ if((0x0a == *k->p) || (0x0d == *k->p)) { size_t headerlen; /* Zero-length header line means end of headers! */ #ifdef CURL_DOES_CONVERSIONS if(0x0d == *k->p) { *k->p = '\r'; /* replace with CR in host encoding */ k->p++; /* pass the CR byte */ } if(0x0a == *k->p) { *k->p = '\n'; /* replace with LF in host encoding */ k->p++; /* pass the LF byte */ } #else if('\r' == *k->p) k->p++; /* pass the \r byte */ if('\n' == *k->p) k->p++; /* pass the \n byte */ #endif /* CURL_DOES_CONVERSIONS */ if(100 <= k->httpcode && 199 >= k->httpcode) { /* "A user agent MAY ignore unexpected 1xx status responses." */ switch(k->httpcode) { case 100: /* * We have made a HTTP PUT or POST and this is 1.1-lingo * that tells us that the server is OK with this and ready * to receive the data. * However, we'll get more headers now so we must get * back into the header-parsing state! */ k->header = TRUE; k->headerline = 0; /* restart the header line counter */ /* if we did wait for this do enable write now! */ if(k->exp100 > EXP100_SEND_DATA) { k->exp100 = EXP100_SEND_DATA; k->keepon |= KEEP_SEND; Curl_expire_done(data, EXPIRE_100_TIMEOUT); } break; case 101: /* Switching Protocols */ if(k->upgr101 == UPGR101_REQUESTED) { /* Switching to HTTP/2 */ infof(data, "Received 101\n"); k->upgr101 = UPGR101_RECEIVED; /* we'll get more headers (HTTP/2 response) */ k->header = TRUE; k->headerline = 0; /* restart the header line counter */ /* switch to http2 now. The bytes after response headers are also processed here, otherwise they are lost. */ result = Curl_http2_switched(conn, k->str, *nread); if(result) return result; *nread = 0; } else { /* Switching to another protocol (e.g. WebSocket) */ k->header = FALSE; /* no more header to parse! */ } break; default: /* the status code 1xx indicates a provisional response, so we'll get another set of headers */ k->header = TRUE; k->headerline = 0; /* restart the header line counter */ break; } } else { k->header = FALSE; /* no more header to parse! */ if((k->size == -1) && !k->chunk && !conn->bits.close && (conn->httpversion == 11) && !(conn->handler->protocol & CURLPROTO_RTSP) && data->set.httpreq != HTTPREQ_HEAD) { /* On HTTP 1.1, when connection is not to get closed, but no Content-Length nor Transfer-Encoding chunked have been received, according to RFC2616 section 4.4 point 5, we assume that the server will close the connection to signal the end of the document. */ infof(data, "no chunk, no close, no size. Assume close to " "signal end\n"); streamclose(conn, "HTTP: No end-of-message indicator"); } } /* At this point we have some idea about the fate of the connection. If we are closing the connection it may result auth failure. */ #if defined(USE_NTLM) if(conn->bits.close && (((data->req.httpcode == 401) && (conn->http_ntlm_state == NTLMSTATE_TYPE2)) || ((data->req.httpcode == 407) && (conn->proxy_ntlm_state == NTLMSTATE_TYPE2)))) { infof(data, "Connection closure while negotiating auth (HTTP 1.0?)\n"); data->state.authproblem = TRUE; } #endif #if defined(USE_SPNEGO) if(conn->bits.close && (((data->req.httpcode == 401) && (conn->http_negotiate_state == GSS_AUTHRECV)) || ((data->req.httpcode == 407) && (conn->proxy_negotiate_state == GSS_AUTHRECV)))) { infof(data, "Connection closure while negotiating auth (HTTP 1.0?)\n"); data->state.authproblem = TRUE; } if((conn->http_negotiate_state == GSS_AUTHDONE) && (data->req.httpcode != 401)) { conn->http_negotiate_state = GSS_AUTHSUCC; } if((conn->proxy_negotiate_state == GSS_AUTHDONE) && (data->req.httpcode != 407)) { conn->proxy_negotiate_state = GSS_AUTHSUCC; } #endif /* * When all the headers have been parsed, see if we should give * up and return an error. */ if(http_should_fail(conn)) { failf(data, "The requested URL returned error: %d", k->httpcode); return CURLE_HTTP_RETURNED_ERROR; } /* now, only output this if the header AND body are requested: */ writetype = CLIENTWRITE_HEADER; if(data->set.include_header) writetype |= CLIENTWRITE_BODY; headerlen = k->p - data->state.headerbuff; result = Curl_client_write(conn, writetype, data->state.headerbuff, headerlen); if(result) return result; data->info.header_size += (long)headerlen; data->req.headerbytecount += (long)headerlen; data->req.deductheadercount = (100 <= k->httpcode && 199 >= k->httpcode)?data->req.headerbytecount:0; /* Curl_http_auth_act() checks what authentication methods * that are available and decides which one (if any) to * use. It will set 'newurl' if an auth method was picked. */ result = Curl_http_auth_act(conn); if(result) return result; if(k->httpcode >= 300) { if((!conn->bits.authneg) && !conn->bits.close && !conn->bits.rewindaftersend) { /* * General treatment of errors when about to send data. Including : * "417 Expectation Failed", while waiting for 100-continue. * * The check for close above is done simply because of something * else has already deemed the connection to get closed then * something else should've considered the big picture and we * avoid this check. * * rewindaftersend indicates that something has told libcurl to * continue sending even if it gets discarded */ switch(data->set.httpreq) { case HTTPREQ_PUT: case HTTPREQ_POST: case HTTPREQ_POST_FORM: case HTTPREQ_POST_MIME: /* We got an error response. If this happened before the whole * request body has been sent we stop sending and mark the * connection for closure after we've read the entire response. */ Curl_expire_done(data, EXPIRE_100_TIMEOUT); if(!k->upload_done) { if(data->set.http_keep_sending_on_error) { infof(data, "HTTP error before end of send, keep sending\n"); if(k->exp100 > EXP100_SEND_DATA) { k->exp100 = EXP100_SEND_DATA; k->keepon |= KEEP_SEND; } } else { infof(data, "HTTP error before end of send, stop sending\n"); streamclose(conn, "Stop sending data before everything sent"); k->upload_done = TRUE; k->keepon &= ~KEEP_SEND; /* don't send */ if(data->state.expect100header) k->exp100 = EXP100_FAILED; } } break; default: /* default label present to avoid compiler warnings */ break; } } if(conn->bits.rewindaftersend) { /* We rewind after a complete send, so thus we continue sending now */ infof(data, "Keep sending data to get tossed away!\n"); k->keepon |= KEEP_SEND; } } if(!k->header) { /* * really end-of-headers. * * If we requested a "no body", this is a good time to get * out and return home. */ if(data->set.opt_no_body) *stop_reading = TRUE; #ifndef CURL_DISABLE_RTSP else if((conn->handler->protocol & CURLPROTO_RTSP) && (data->set.rtspreq == RTSPREQ_DESCRIBE) && (k->size <= -1)) /* Respect section 4.4 of rfc2326: If the Content-Length header is absent, a length 0 must be assumed. It will prevent libcurl from hanging on DESCRIBE request that got refused for whatever reason */ *stop_reading = TRUE; #endif else { /* If we know the expected size of this document, we set the maximum download size to the size of the expected document or else, we won't know when to stop reading! Note that we set the download maximum even if we read a "Connection: close" header, to make sure that "Content-Length: 0" still prevents us from attempting to read the (missing) response-body. */ /* According to RFC2616 section 4.4, we MUST ignore Content-Length: headers if we are now receiving data using chunked Transfer-Encoding. */ if(k->chunk) k->maxdownload = k->size = -1; } if(-1 != k->size) { /* We do this operation even if no_body is true, since this data might be retrieved later with curl_easy_getinfo() and its CURLINFO_CONTENT_LENGTH_DOWNLOAD option. */ Curl_pgrsSetDownloadSize(data, k->size); k->maxdownload = k->size; } /* If max download size is *zero* (nothing) we already have nothing and can safely return ok now! But for HTTP/2, we'd like to call http2_handle_stream_close to properly close a stream. In order to do this, we keep reading until we close the stream. */ if(0 == k->maxdownload #if defined(USE_NGHTTP2) && !((conn->handler->protocol & PROTO_FAMILY_HTTP) && conn->httpversion == 20) #endif ) *stop_reading = TRUE; if(*stop_reading) { /* we make sure that this socket isn't read more now */ k->keepon &= ~KEEP_RECV; } if(data->set.verbose) Curl_debug(data, CURLINFO_HEADER_IN, k->str_start, headerlen); break; /* exit header line loop */ } /* We continue reading headers, so reset the line-based header parsing variables hbufp && hbuflen */ k->hbufp = data->state.headerbuff; k->hbuflen = 0; continue; } /* * Checks for special headers coming up. */ if(!k->headerline++) { /* This is the first header, it MUST be the error code line or else we consider this to be the body right away! */ int httpversion_major; int rtspversion_major; int nc = 0; #ifdef CURL_DOES_CONVERSIONS #define HEADER1 scratch #define SCRATCHSIZE 21 CURLcode res; char scratch[SCRATCHSIZE + 1]; /* "HTTP/major.minor 123" */ /* We can't really convert this yet because we don't know if it's the 1st header line or the body. So we do a partial conversion into a scratch area, leaving the data at k->p as-is. */ strncpy(&scratch[0], k->p, SCRATCHSIZE); scratch[SCRATCHSIZE] = 0; /* null terminate */ res = Curl_convert_from_network(data, &scratch[0], SCRATCHSIZE); if(res) /* Curl_convert_from_network calls failf if unsuccessful */ return res; #else #define HEADER1 k->p /* no conversion needed, just use k->p */ #endif /* CURL_DOES_CONVERSIONS */ if(conn->handler->protocol & PROTO_FAMILY_HTTP) { /* * https://tools.ietf.org/html/rfc7230#section-3.1.2 * * The response code is always a three-digit number in HTTP as the spec * says. We try to allow any number here, but we cannot make * guarantees on future behaviors since it isn't within the protocol. */ char separator; nc = sscanf(HEADER1, " HTTP/%1d.%1d%c%3d", &httpversion_major, &conn->httpversion, &separator, &k->httpcode); if(nc == 1 && httpversion_major == 2 && 1 == sscanf(HEADER1, " HTTP/2 %d", &k->httpcode)) { conn->httpversion = 0; nc = 4; separator = ' '; } if((nc == 4) && (' ' == separator)) { conn->httpversion += 10 * httpversion_major; if(k->upgr101 == UPGR101_RECEIVED) { /* supposedly upgraded to http2 now */ if(conn->httpversion != 20) infof(data, "Lying server, not serving HTTP/2\n"); } if(conn->httpversion < 20) { conn->bundle->multiuse = BUNDLE_NO_MULTIUSE; infof(data, "Mark bundle as not supporting multiuse\n"); } } else if(!nc) { /* this is the real world, not a Nirvana NCSA 1.5.x returns this crap when asked for HTTP/1.1 */ nc = sscanf(HEADER1, " HTTP %3d", &k->httpcode); conn->httpversion = 10; /* If user has set option HTTP200ALIASES, compare header line against list of aliases */ if(!nc) { if(checkhttpprefix(data, k->p, k->hbuflen) == STATUS_DONE) { nc = 1; k->httpcode = 200; conn->httpversion = 10; } } } else { failf(data, "Unsupported HTTP version in response\n"); return CURLE_UNSUPPORTED_PROTOCOL; } } else if(conn->handler->protocol & CURLPROTO_RTSP) { char separator; nc = sscanf(HEADER1, " RTSP/%1d.%1d%c%3d", &rtspversion_major, &conn->rtspversion, &separator, &k->httpcode); if((nc == 4) && (' ' == separator)) { conn->rtspversion += 10 * rtspversion_major; conn->httpversion = 11; /* For us, RTSP acts like HTTP 1.1 */ } else { nc = 0; } } if(nc) { data->info.httpcode = k->httpcode; data->info.httpversion = conn->httpversion; if(!data->state.httpversion || data->state.httpversion > conn->httpversion) /* store the lowest server version we encounter */ data->state.httpversion = conn->httpversion; /* * This code executes as part of processing the header. As a * result, it's not totally clear how to interpret the * response code yet as that depends on what other headers may * be present. 401 and 407 may be errors, but may be OK * depending on how authentication is working. Other codes * are definitely errors, so give up here. */ if(data->state.resume_from && data->set.httpreq == HTTPREQ_GET && k->httpcode == 416) { /* "Requested Range Not Satisfiable", just proceed and pretend this is no error */ k->ignorebody = TRUE; /* Avoid appending error msg to good data. */ } else if(data->set.http_fail_on_error && (k->httpcode >= 400) && ((k->httpcode != 401) || !conn->bits.user_passwd) && ((k->httpcode != 407) || !conn->bits.proxy_user_passwd) ) { /* serious error, go home! */ print_http_error(data); return CURLE_HTTP_RETURNED_ERROR; } if(conn->httpversion == 10) { /* Default action for HTTP/1.0 must be to close, unless we get one of those fancy headers that tell us the server keeps it open for us! */ infof(data, "HTTP 1.0, assume close after body\n"); connclose(conn, "HTTP/1.0 close after body"); } else if(conn->httpversion == 20 || (k->upgr101 == UPGR101_REQUESTED && k->httpcode == 101)) { DEBUGF(infof(data, "HTTP/2 found, allow multiplexing\n")); /* HTTP/2 cannot blacklist multiplexing since it is a core functionality of the protocol */ conn->bundle->multiuse = BUNDLE_MULTIPLEX; } else if(conn->httpversion >= 11 && !conn->bits.close) { /* If HTTP version is >= 1.1 and connection is persistent */ DEBUGF(infof(data, "HTTP 1.1 or later with persistent connection\n")); } switch(k->httpcode) { case 304: /* (quote from RFC2616, section 10.3.5): The 304 response * MUST NOT contain a message-body, and thus is always * terminated by the first empty line after the header * fields. */ if(data->set.timecondition) data->info.timecond = TRUE; /* FALLTHROUGH */ case 204: /* (quote from RFC2616, section 10.2.5): The server has * fulfilled the request but does not need to return an * entity-body ... The 204 response MUST NOT include a * message-body, and thus is always terminated by the first * empty line after the header fields. */ k->size = 0; k->maxdownload = 0; k->ignorecl = TRUE; /* ignore Content-Length headers */ break; default: /* nothing */ break; } } else { k->header = FALSE; /* this is not a header line */ break; } } result = Curl_convert_from_network(data, k->p, strlen(k->p)); /* Curl_convert_from_network calls failf if unsuccessful */ if(result) return result; /* Check for Content-Length: header lines to get size */ if(!k->ignorecl && !data->set.ignorecl && checkprefix("Content-Length:", k->p)) { curl_off_t contentlength; CURLofft offt = curlx_strtoofft(k->p + 15, NULL, 10, &contentlength); if(offt == CURL_OFFT_OK) { if(data->set.max_filesize && contentlength > data->set.max_filesize) { failf(data, "Maximum file size exceeded"); return CURLE_FILESIZE_EXCEEDED; } k->size = contentlength; k->maxdownload = k->size; /* we set the progress download size already at this point just to make it easier for apps/callbacks to extract this info as soon as possible */ Curl_pgrsSetDownloadSize(data, k->size); } else if(offt == CURL_OFFT_FLOW) { /* out of range */ if(data->set.max_filesize) { failf(data, "Maximum file size exceeded"); return CURLE_FILESIZE_EXCEEDED; } streamclose(conn, "overflow content-length"); infof(data, "Overflow Content-Length: value!\n"); } else { /* negative or just rubbish - bad HTTP */ failf(data, "Invalid Content-Length: value"); return CURLE_WEIRD_SERVER_REPLY; } } /* check for Content-Type: header lines to get the MIME-type */ else if(checkprefix("Content-Type:", k->p)) { char *contenttype = Curl_copy_header_value(k->p); if(!contenttype) return CURLE_OUT_OF_MEMORY; if(!*contenttype) /* ignore empty data */ free(contenttype); else { Curl_safefree(data->info.contenttype); data->info.contenttype = contenttype; } } else if((conn->httpversion == 10) && conn->bits.httpproxy && Curl_compareheader(k->p, "Proxy-Connection:", "keep-alive")) { /* * When a HTTP/1.0 reply comes when using a proxy, the * 'Proxy-Connection: keep-alive' line tells us the * connection will be kept alive for our pleasure. * Default action for 1.0 is to close. */ connkeep(conn, "Proxy-Connection keep-alive"); /* don't close */ infof(data, "HTTP/1.0 proxy connection set to keep alive!\n"); } else if((conn->httpversion == 11) && conn->bits.httpproxy && Curl_compareheader(k->p, "Proxy-Connection:", "close")) { /* * We get a HTTP/1.1 response from a proxy and it says it'll * close down after this transfer. */ connclose(conn, "Proxy-Connection: asked to close after done"); infof(data, "HTTP/1.1 proxy connection set close!\n"); } else if((conn->httpversion == 10) && Curl_compareheader(k->p, "Connection:", "keep-alive")) { /* * A HTTP/1.0 reply with the 'Connection: keep-alive' line * tells us the connection will be kept alive for our * pleasure. Default action for 1.0 is to close. * * [RFC2068, section 19.7.1] */ connkeep(conn, "Connection keep-alive"); infof(data, "HTTP/1.0 connection set to keep alive!\n"); } else if(Curl_compareheader(k->p, "Connection:", "close")) { /* * [RFC 2616, section 8.1.2.1] * "Connection: close" is HTTP/1.1 language and means that * the connection will close when this request has been * served. */ streamclose(conn, "Connection: close used"); } else if(checkprefix("Transfer-Encoding:", k->p)) { /* One or more encodings. We check for chunked and/or a compression algorithm. */ /* * [RFC 2616, section 3.6.1] A 'chunked' transfer encoding * means that the server will send a series of "chunks". Each * chunk starts with line with info (including size of the * coming block) (terminated with CRLF), then a block of data * with the previously mentioned size. There can be any amount * of chunks, and a chunk-data set to zero signals the * end-of-chunks. */ result = Curl_build_unencoding_stack(conn, k->p + 18, TRUE); if(result) return result; } else if(checkprefix("Content-Encoding:", k->p) && data->set.str[STRING_ENCODING]) { /* * Process Content-Encoding. Look for the values: identity, * gzip, deflate, compress, x-gzip and x-compress. x-gzip and * x-compress are the same as gzip and compress. (Sec 3.5 RFC * 2616). zlib cannot handle compress. However, errors are * handled further down when the response body is processed */ result = Curl_build_unencoding_stack(conn, k->p + 17, FALSE); if(result) return result; } else if(checkprefix("Content-Range:", k->p)) { /* Content-Range: bytes [num]- Content-Range: bytes: [num]- Content-Range: [num]- Content-Range: [asterisk]/[total] The second format was added since Sun's webserver JavaWebServer/1.1.1 obviously sends the header this way! The third added since some servers use that! The forth means the requested range was unsatisfied. */ char *ptr = k->p + 14; /* Move forward until first digit or asterisk */ while(*ptr && !ISDIGIT(*ptr) && *ptr != '*') ptr++; /* if it truly stopped on a digit */ if(ISDIGIT(*ptr)) { if(!curlx_strtoofft(ptr, NULL, 10, &k->offset)) { if(data->state.resume_from == k->offset) /* we asked for a resume and we got it */ k->content_range = TRUE; } } else data->state.resume_from = 0; /* get everything */ } #if !defined(CURL_DISABLE_COOKIES) else if(data->cookies && checkprefix("Set-Cookie:", k->p)) { Curl_share_lock(data, CURL_LOCK_DATA_COOKIE, CURL_LOCK_ACCESS_SINGLE); Curl_cookie_add(data, data->cookies, TRUE, FALSE, k->p + 11, /* If there is a custom-set Host: name, use it here, or else use real peer host name. */ conn->allocptr.cookiehost? conn->allocptr.cookiehost:conn->host.name, data->state.up.path, (conn->handler->protocol&CURLPROTO_HTTPS)? TRUE:FALSE); Curl_share_unlock(data, CURL_LOCK_DATA_COOKIE); } #endif else if(checkprefix("Last-Modified:", k->p) && (data->set.timecondition || data->set.get_filetime) ) { time_t secs = time(NULL); k->timeofdoc = curl_getdate(k->p + strlen("Last-Modified:"), &secs); if(data->set.get_filetime) data->info.filetime = k->timeofdoc; } else if((checkprefix("WWW-Authenticate:", k->p) && (401 == k->httpcode)) || (checkprefix("Proxy-authenticate:", k->p) && (407 == k->httpcode))) { bool proxy = (k->httpcode == 407) ? TRUE : FALSE; char *auth = Curl_copy_header_value(k->p); if(!auth) return CURLE_OUT_OF_MEMORY; result = Curl_http_input_auth(conn, proxy, auth); free(auth); if(result) return result; } #ifdef USE_SPNEGO else if(checkprefix("Persistent-Auth", k->p)) { struct negotiatedata *negdata = &conn->negotiate; struct auth *authp = &data->state.authhost; if(authp->picked == CURLAUTH_NEGOTIATE) { char *persistentauth = Curl_copy_header_value(k->p); if(!persistentauth) return CURLE_OUT_OF_MEMORY; negdata->noauthpersist = checkprefix("false", persistentauth); negdata->havenoauthpersist = TRUE; infof(data, "Negotiate: noauthpersist -> %d, header part: %s", negdata->noauthpersist, persistentauth); free(persistentauth); } } #endif else if((k->httpcode >= 300 && k->httpcode < 400) && checkprefix("Location:", k->p) && !data->req.location) { /* this is the URL that the server advises us to use instead */ char *location = Curl_copy_header_value(k->p); if(!location) return CURLE_OUT_OF_MEMORY; if(!*location) /* ignore empty data */ free(location); else { data->req.location = location; if(data->set.http_follow_location) { DEBUGASSERT(!data->req.newurl); data->req.newurl = strdup(data->req.location); /* clone */ if(!data->req.newurl) return CURLE_OUT_OF_MEMORY; /* some cases of POST and PUT etc needs to rewind the data stream at this point */ result = http_perhapsrewind(conn); if(result) return result; } } } #ifdef USE_ALTSVC /* If enabled, the header is incoming and this is over HTTPS */ else if(data->asi && checkprefix("Alt-Svc:", k->p) && ((conn->handler->flags & PROTOPT_SSL) || #ifdef CURLDEBUG /* allow debug builds to circumvent the HTTPS restriction */ getenv("CURL_ALTSVC_HTTP") #else 0 #endif )) { /* the ALPN of the current request */ enum alpnid id = (conn->httpversion == 20) ? ALPN_h2 : ALPN_h1; result = Curl_altsvc_parse(data, data->asi, &k->p[ strlen("Alt-Svc:") ], id, conn->host.name, curlx_uitous(conn->remote_port)); if(result) return result; } #endif else if(conn->handler->protocol & CURLPROTO_RTSP) { result = Curl_rtsp_parseheader(conn, k->p); if(result) return result; } /* * End of header-checks. Write them to the client. */ writetype = CLIENTWRITE_HEADER; if(data->set.include_header) writetype |= CLIENTWRITE_BODY; if(data->set.verbose) Curl_debug(data, CURLINFO_HEADER_IN, k->p, (size_t)k->hbuflen); result = Curl_client_write(conn, writetype, k->p, k->hbuflen); if(result) return result; data->info.header_size += (long)k->hbuflen; data->req.headerbytecount += (long)k->hbuflen; /* reset hbufp pointer && hbuflen */ k->hbufp = data->state.headerbuff; k->hbuflen = 0; } while(*k->str); /* header line within buffer */ /* We might have reached the end of the header part here, but there might be a non-header part left in the end of the read buffer. */ return CURLE_OK; } #endif /* CURL_DISABLE_HTTP */
YifuLiu/AliOS-Things
components/curl/lib/http.c
C
apache-2.0
132,933
#ifndef HEADER_CURL_HTTP_H #define HEADER_CURL_HTTP_H /*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2019, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "curl_setup.h" #ifndef CURL_DISABLE_HTTP #ifdef USE_NGHTTP2 #include <nghttp2/nghttp2.h> #endif extern const struct Curl_handler Curl_handler_http; #ifdef USE_SSL extern const struct Curl_handler Curl_handler_https; #endif /* Header specific functions */ bool Curl_compareheader(const char *headerline, /* line to check */ const char *header, /* header keyword _with_ colon */ const char *content); /* content string to find */ char *Curl_copy_header_value(const char *header); char *Curl_checkProxyheaders(const struct connectdata *conn, const char *thisheader); /* ------------------------------------------------------------------------- */ /* * The add_buffer series of functions are used to build one large memory chunk * from repeated function invokes. Used so that the entire HTTP request can * be sent in one go. */ struct Curl_send_buffer { char *buffer; size_t size_max; size_t size_used; }; typedef struct Curl_send_buffer Curl_send_buffer; Curl_send_buffer *Curl_add_buffer_init(void); void Curl_add_buffer_free(Curl_send_buffer **inp); CURLcode Curl_add_bufferf(Curl_send_buffer **inp, const char *fmt, ...) WARN_UNUSED_RESULT; CURLcode Curl_add_buffer(Curl_send_buffer **inp, const void *inptr, size_t size) WARN_UNUSED_RESULT; CURLcode Curl_add_buffer_send(Curl_send_buffer **inp, struct connectdata *conn, curl_off_t *bytes_written, size_t included_body_bytes, int socketindex); CURLcode Curl_add_timecondition(struct Curl_easy *data, Curl_send_buffer *buf); CURLcode Curl_add_custom_headers(struct connectdata *conn, bool is_connect, Curl_send_buffer *req_buffer); CURLcode Curl_http_compile_trailers(struct curl_slist *trailers, Curl_send_buffer *buffer, struct Curl_easy *handle); /* protocol-specific functions set up to be called by the main engine */ CURLcode Curl_http(struct connectdata *conn, bool *done); CURLcode Curl_http_done(struct connectdata *, CURLcode, bool premature); CURLcode Curl_http_connect(struct connectdata *conn, bool *done); CURLcode Curl_http_setup_conn(struct connectdata *conn); /* The following functions are defined in http_chunks.c */ void Curl_httpchunk_init(struct connectdata *conn); CHUNKcode Curl_httpchunk_read(struct connectdata *conn, char *datap, ssize_t length, ssize_t *wrote); /* These functions are in http.c */ void Curl_http_auth_stage(struct Curl_easy *data, int stage); CURLcode Curl_http_input_auth(struct connectdata *conn, bool proxy, const char *auth); CURLcode Curl_http_auth_act(struct connectdata *conn); CURLcode Curl_http_perhapsrewind(struct connectdata *conn); /* If only the PICKNONE bit is set, there has been a round-trip and we selected to use no auth at all. Ie, we actively select no auth, as opposed to not having one selected. The other CURLAUTH_* defines are present in the public curl/curl.h header. */ #define CURLAUTH_PICKNONE (1<<30) /* don't use auth */ /* MAX_INITIAL_POST_SIZE indicates the number of bytes that will make the POST data get included in the initial data chunk sent to the server. If the data is larger than this, it will automatically get split up in multiple system calls. This value used to be fairly big (100K), but we must take into account that if the server rejects the POST due for authentication reasons, this data will always be unconditionally sent and thus it may not be larger than can always be afforded to send twice. It must not be greater than 64K to work on VMS. */ #ifndef MAX_INITIAL_POST_SIZE #define MAX_INITIAL_POST_SIZE (64*1024) #endif /* EXPECT_100_THRESHOLD is the request body size limit for when libcurl will * automatically add an "Expect: 100-continue" header in HTTP requests. When * the size is unknown, it will always add it. * */ #ifndef EXPECT_100_THRESHOLD #define EXPECT_100_THRESHOLD 1024 #endif #endif /* CURL_DISABLE_HTTP */ /**************************************************************************** * HTTP unique setup ***************************************************************************/ struct HTTP { curl_mimepart *sendit; curl_off_t postsize; /* off_t to handle large file sizes */ const char *postdata; const char *p_pragma; /* Pragma: string */ const char *p_accept; /* Accept: string */ /* For FORM posting */ curl_mimepart form; struct back { curl_read_callback fread_func; /* backup storage for fread pointer */ void *fread_in; /* backup storage for fread_in pointer */ const char *postdata; curl_off_t postsize; } backup; enum { HTTPSEND_NADA, /* init */ HTTPSEND_REQUEST, /* sending a request */ HTTPSEND_BODY, /* sending body */ HTTPSEND_LAST /* never use this */ } sending; #ifndef CURL_DISABLE_HTTP Curl_send_buffer *send_buffer; /* used if the request couldn't be sent in one chunk, points to an allocated send_buffer struct */ #endif #ifdef USE_NGHTTP2 /*********** for HTTP/2 we store stream-local data here *************/ int32_t stream_id; /* stream we are interested in */ bool bodystarted; /* We store non-final and final response headers here, per-stream */ Curl_send_buffer *header_recvbuf; size_t nread_header_recvbuf; /* number of bytes in header_recvbuf fed into upper layer */ Curl_send_buffer *trailer_recvbuf; int status_code; /* HTTP status code */ const uint8_t *pausedata; /* pointer to data received in on_data_chunk */ size_t pauselen; /* the number of bytes left in data */ bool closed; /* TRUE on HTTP2 stream close */ bool close_handled; /* TRUE if stream closure is handled by libcurl */ char *mem; /* points to a buffer in memory to store received data */ size_t len; /* size of the buffer 'mem' points to */ size_t memlen; /* size of data copied to mem */ const uint8_t *upload_mem; /* points to a buffer to read from */ size_t upload_len; /* size of the buffer 'upload_mem' points to */ curl_off_t upload_left; /* number of bytes left to upload */ char **push_headers; /* allocated array */ size_t push_headers_used; /* number of entries filled in */ size_t push_headers_alloc; /* number of entries allocated */ #endif }; #ifdef USE_NGHTTP2 /* h2 settings for this connection */ struct h2settings { uint32_t max_concurrent_streams; bool enable_push; }; #endif struct http_conn { #ifdef USE_NGHTTP2 #define H2_BINSETTINGS_LEN 80 nghttp2_session *h2; uint8_t binsettings[H2_BINSETTINGS_LEN]; size_t binlen; /* length of the binsettings data */ Curl_send *send_underlying; /* underlying send Curl_send callback */ Curl_recv *recv_underlying; /* underlying recv Curl_recv callback */ char *inbuf; /* buffer to receive data from underlying socket */ size_t inbuflen; /* number of bytes filled in inbuf */ size_t nread_inbuf; /* number of bytes read from in inbuf */ /* We need separate buffer for transmission and reception because we may call nghttp2_session_send() after the nghttp2_session_mem_recv() but mem buffer is still not full. In this case, we wrongly sends the content of mem buffer if we share them for both cases. */ int32_t pause_stream_id; /* stream ID which paused nghttp2_session_mem_recv */ size_t drain_total; /* sum of all stream's UrlState.drain */ /* this is a hash of all individual streams (Curl_easy structs) */ struct h2settings settings; /* list of settings that will be sent */ nghttp2_settings_entry local_settings[3]; size_t local_settings_num; uint32_t error_code; /* HTTP/2 error code */ #else int unused; /* prevent a compiler warning */ #endif }; CURLcode Curl_http_readwrite_headers(struct Curl_easy *data, struct connectdata *conn, ssize_t *nread, bool *stop_reading); /** * Curl_http_output_auth() setups the authentication headers for the * host/proxy and the correct authentication * method. conn->data->state.authdone is set to TRUE when authentication is * done. * * @param conn all information about the current connection * @param request pointer to the request keyword * @param path pointer to the requested path * @param proxytunnel boolean if this is the request setting up a "proxy * tunnel" * * @returns CURLcode */ CURLcode Curl_http_output_auth(struct connectdata *conn, const char *request, const char *path, bool proxytunnel); /* TRUE if this is the request setting up the proxy tunnel */ #endif /* HEADER_CURL_HTTP_H */
YifuLiu/AliOS-Things
components/curl/lib/http.h
C
apache-2.0
10,273
/*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2019, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "curl_setup.h" #ifdef USE_NGHTTP2 #include <nghttp2/nghttp2.h> #include "urldata.h" #include "http2.h" #include "http.h" #include "sendf.h" #include "select.h" #include "curl_base64.h" #include "strcase.h" #include "multiif.h" #include "url.h" #include "connect.h" #include "strtoofft.h" #include "strdup.h" /* The last 3 #include files should be in this order */ #include "curl_printf.h" #include "curl_memory.h" #include "memdebug.h" #define H2_BUFSIZE 32768 #if (NGHTTP2_VERSION_NUM < 0x010000) #error too old nghttp2 version, upgrade! #endif #if (NGHTTP2_VERSION_NUM > 0x010800) #define NGHTTP2_HAS_HTTP2_STRERROR 1 #endif #if (NGHTTP2_VERSION_NUM >= 0x010900) /* nghttp2_session_callbacks_set_error_callback is present in nghttp2 1.9.0 or later */ #define NGHTTP2_HAS_ERROR_CALLBACK 1 #else #define nghttp2_session_callbacks_set_error_callback(x,y) #endif #if (NGHTTP2_VERSION_NUM >= 0x010c00) #define NGHTTP2_HAS_SET_LOCAL_WINDOW_SIZE 1 #endif #define HTTP2_HUGE_WINDOW_SIZE (1 << 30) #ifdef DEBUG_HTTP2 #define H2BUGF(x) x #else #define H2BUGF(x) do { } WHILE_FALSE #endif static ssize_t http2_recv(struct connectdata *conn, int sockindex, char *mem, size_t len, CURLcode *err); static bool http2_connisdead(struct connectdata *conn); static int h2_session_send(struct Curl_easy *data, nghttp2_session *h2); static int h2_process_pending_input(struct connectdata *conn, struct http_conn *httpc, CURLcode *err); /* * Curl_http2_init_state() is called when the easy handle is created and * allows for HTTP/2 specific init of state. */ void Curl_http2_init_state(struct UrlState *state) { state->stream_weight = NGHTTP2_DEFAULT_WEIGHT; } /* * Curl_http2_init_userset() is called when the easy handle is created and * allows for HTTP/2 specific user-set fields. */ void Curl_http2_init_userset(struct UserDefined *set) { set->stream_weight = NGHTTP2_DEFAULT_WEIGHT; } static int http2_perform_getsock(const struct connectdata *conn, curl_socket_t *sock, /* points to numsocks number of sockets */ int numsocks) { const struct http_conn *c = &conn->proto.httpc; struct SingleRequest *k = &conn->data->req; int bitmap = GETSOCK_BLANK; (void)numsocks; sock[0] = conn->sock[FIRSTSOCKET]; /* in a HTTP/2 connection we can basically always get a frame so we should always be ready for one */ bitmap |= GETSOCK_READSOCK(FIRSTSOCKET); /* we're still uploading or the HTTP/2 layer wants to send data */ if(((k->keepon & (KEEP_SEND|KEEP_SEND_PAUSE)) == KEEP_SEND) || nghttp2_session_want_write(c->h2)) bitmap |= GETSOCK_WRITESOCK(FIRSTSOCKET); return bitmap; } static int http2_getsock(struct connectdata *conn, curl_socket_t *sock, /* points to numsocks number of sockets */ int numsocks) { return http2_perform_getsock(conn, sock, numsocks); } /* * http2_stream_free() free HTTP2 stream related data */ static void http2_stream_free(struct HTTP *http) { if(http) { Curl_add_buffer_free(&http->header_recvbuf); Curl_add_buffer_free(&http->trailer_recvbuf); for(; http->push_headers_used > 0; --http->push_headers_used) { free(http->push_headers[http->push_headers_used - 1]); } free(http->push_headers); http->push_headers = NULL; } } /* * Disconnects *a* connection used for HTTP/2. It might be an old one from the * connection cache and not the "main" one. Don't touch the easy handle! */ static CURLcode http2_disconnect(struct connectdata *conn, bool dead_connection) { struct http_conn *c = &conn->proto.httpc; (void)dead_connection; H2BUGF(infof(conn->data, "HTTP/2 DISCONNECT starts now\n")); nghttp2_session_del(c->h2); Curl_safefree(c->inbuf); H2BUGF(infof(conn->data, "HTTP/2 DISCONNECT done\n")); return CURLE_OK; } /* * The server may send us data at any point (e.g. PING frames). Therefore, * we cannot assume that an HTTP/2 socket is dead just because it is readable. * * Instead, if it is readable, run Curl_connalive() to peek at the socket * and distinguish between closed and data. */ static bool http2_connisdead(struct connectdata *conn) { int sval; bool dead = TRUE; if(conn->bits.close) return TRUE; sval = SOCKET_READABLE(conn->sock[FIRSTSOCKET], 0); if(sval == 0) { /* timeout */ dead = FALSE; } else if(sval & CURL_CSELECT_ERR) { /* socket is in an error state */ dead = TRUE; } else if(sval & CURL_CSELECT_IN) { /* readable with no error. could still be closed */ dead = !Curl_connalive(conn); if(!dead) { /* This happens before we've sent off a request and the connection is not in use by any other transfer, there shouldn't be any data here, only "protocol frames" */ CURLcode result; struct http_conn *httpc = &conn->proto.httpc; ssize_t nread = -1; if(httpc->recv_underlying) /* if called "too early", this pointer isn't setup yet! */ nread = ((Curl_recv *)httpc->recv_underlying)( conn, FIRSTSOCKET, httpc->inbuf, H2_BUFSIZE, &result); if(nread != -1) { infof(conn->data, "%d bytes stray data read before trying h2 connection\n", (int)nread); httpc->nread_inbuf = 0; httpc->inbuflen = nread; (void)h2_process_pending_input(conn, httpc, &result); } else /* the read failed so let's say this is dead anyway */ dead = TRUE; } } return dead; } static unsigned int http2_conncheck(struct connectdata *check, unsigned int checks_to_perform) { unsigned int ret_val = CONNRESULT_NONE; struct http_conn *c = &check->proto.httpc; int rc; bool send_frames = false; if(checks_to_perform & CONNCHECK_ISDEAD) { if(http2_connisdead(check)) ret_val |= CONNRESULT_DEAD; } if(checks_to_perform & CONNCHECK_KEEPALIVE) { struct curltime now = Curl_now(); time_t elapsed = Curl_timediff(now, check->keepalive); if(elapsed > check->upkeep_interval_ms) { /* Perform an HTTP/2 PING */ rc = nghttp2_submit_ping(c->h2, 0, ZERO_NULL); if(!rc) { /* Successfully added a PING frame to the session. Need to flag this so the frame is sent. */ send_frames = true; } else { failf(check->data, "nghttp2_submit_ping() failed: %s(%d)", nghttp2_strerror(rc), rc); } check->keepalive = now; } } if(send_frames) { rc = nghttp2_session_send(c->h2); if(rc) failf(check->data, "nghttp2_session_send() failed: %s(%d)", nghttp2_strerror(rc), rc); } return ret_val; } /* called from Curl_http_setup_conn */ void Curl_http2_setup_req(struct Curl_easy *data) { struct HTTP *http = data->req.protop; http->nread_header_recvbuf = 0; http->bodystarted = FALSE; http->status_code = -1; http->pausedata = NULL; http->pauselen = 0; http->closed = FALSE; http->close_handled = FALSE; http->mem = data->state.buffer; http->len = data->set.buffer_size; http->memlen = 0; } /* called from Curl_http_setup_conn */ void Curl_http2_setup_conn(struct connectdata *conn) { conn->proto.httpc.settings.max_concurrent_streams = DEFAULT_MAX_CONCURRENT_STREAMS; conn->proto.httpc.error_code = NGHTTP2_NO_ERROR; } /* * HTTP2 handler interface. This isn't added to the general list of protocols * but will be used at run-time when the protocol is dynamically switched from * HTTP to HTTP2. */ static const struct Curl_handler Curl_handler_http2 = { "HTTP", /* scheme */ ZERO_NULL, /* setup_connection */ Curl_http, /* do_it */ Curl_http_done, /* done */ ZERO_NULL, /* do_more */ ZERO_NULL, /* connect_it */ ZERO_NULL, /* connecting */ ZERO_NULL, /* doing */ http2_getsock, /* proto_getsock */ http2_getsock, /* doing_getsock */ ZERO_NULL, /* domore_getsock */ http2_perform_getsock, /* perform_getsock */ http2_disconnect, /* disconnect */ ZERO_NULL, /* readwrite */ http2_conncheck, /* connection_check */ PORT_HTTP, /* defport */ CURLPROTO_HTTP, /* protocol */ PROTOPT_STREAM /* flags */ }; static const struct Curl_handler Curl_handler_http2_ssl = { "HTTPS", /* scheme */ ZERO_NULL, /* setup_connection */ Curl_http, /* do_it */ Curl_http_done, /* done */ ZERO_NULL, /* do_more */ ZERO_NULL, /* connect_it */ ZERO_NULL, /* connecting */ ZERO_NULL, /* doing */ http2_getsock, /* proto_getsock */ http2_getsock, /* doing_getsock */ ZERO_NULL, /* domore_getsock */ http2_perform_getsock, /* perform_getsock */ http2_disconnect, /* disconnect */ ZERO_NULL, /* readwrite */ http2_conncheck, /* connection_check */ PORT_HTTP, /* defport */ CURLPROTO_HTTPS, /* protocol */ PROTOPT_SSL | PROTOPT_STREAM /* flags */ }; /* * Store nghttp2 version info in this buffer, Prefix with a space. Return * total length written. */ int Curl_http2_ver(char *p, size_t len) { nghttp2_info *h2 = nghttp2_version(0); return msnprintf(p, len, " nghttp2/%s", h2->version_str); } /* HTTP/2 error code to name based on the Error Code Registry. https://tools.ietf.org/html/rfc7540#page-77 nghttp2_error_code enums are identical. */ static const char *http2_strerror(uint32_t err) { #ifndef NGHTTP2_HAS_HTTP2_STRERROR const char *str[] = { "NO_ERROR", /* 0x0 */ "PROTOCOL_ERROR", /* 0x1 */ "INTERNAL_ERROR", /* 0x2 */ "FLOW_CONTROL_ERROR", /* 0x3 */ "SETTINGS_TIMEOUT", /* 0x4 */ "STREAM_CLOSED", /* 0x5 */ "FRAME_SIZE_ERROR", /* 0x6 */ "REFUSED_STREAM", /* 0x7 */ "CANCEL", /* 0x8 */ "COMPRESSION_ERROR", /* 0x9 */ "CONNECT_ERROR", /* 0xA */ "ENHANCE_YOUR_CALM", /* 0xB */ "INADEQUATE_SECURITY", /* 0xC */ "HTTP_1_1_REQUIRED" /* 0xD */ }; return (err < sizeof(str) / sizeof(str[0])) ? str[err] : "unknown"; #else return nghttp2_http2_strerror(err); #endif } /* * The implementation of nghttp2_send_callback type. Here we write |data| with * size |length| to the network and return the number of bytes actually * written. See the documentation of nghttp2_send_callback for the details. */ static ssize_t send_callback(nghttp2_session *h2, const uint8_t *data, size_t length, int flags, void *userp) { struct connectdata *conn = (struct connectdata *)userp; struct http_conn *c = &conn->proto.httpc; ssize_t written; CURLcode result = CURLE_OK; (void)h2; (void)flags; if(!c->send_underlying) /* called before setup properly! */ return NGHTTP2_ERR_CALLBACK_FAILURE; written = ((Curl_send*)c->send_underlying)(conn, FIRSTSOCKET, data, length, &result); if(result == CURLE_AGAIN) { return NGHTTP2_ERR_WOULDBLOCK; } if(written == -1) { failf(conn->data, "Failed sending HTTP2 data"); return NGHTTP2_ERR_CALLBACK_FAILURE; } if(!written) return NGHTTP2_ERR_WOULDBLOCK; return written; } /* We pass a pointer to this struct in the push callback, but the contents of the struct are hidden from the user. */ struct curl_pushheaders { struct Curl_easy *data; const nghttp2_push_promise *frame; }; /* * push header access function. Only to be used from within the push callback */ char *curl_pushheader_bynum(struct curl_pushheaders *h, size_t num) { /* Verify that we got a good easy handle in the push header struct, mostly to detect rubbish input fast(er). */ if(!h || !GOOD_EASY_HANDLE(h->data)) return NULL; else { struct HTTP *stream = h->data->req.protop; if(num < stream->push_headers_used) return stream->push_headers[num]; } return NULL; } /* * push header access function. Only to be used from within the push callback */ char *curl_pushheader_byname(struct curl_pushheaders *h, const char *header) { /* Verify that we got a good easy handle in the push header struct, mostly to detect rubbish input fast(er). Also empty header name is just a rubbish too. We have to allow ":" at the beginning of the header, but header == ":" must be rejected. If we have ':' in the middle of header, it could be matched in middle of the value, this is because we do prefix match.*/ if(!h || !GOOD_EASY_HANDLE(h->data) || !header || !header[0] || !strcmp(header, ":") || strchr(header + 1, ':')) return NULL; else { struct HTTP *stream = h->data->req.protop; size_t len = strlen(header); size_t i; for(i = 0; i<stream->push_headers_used; i++) { if(!strncmp(header, stream->push_headers[i], len)) { /* sub-match, make sure that it is followed by a colon */ if(stream->push_headers[i][len] != ':') continue; return &stream->push_headers[i][len + 1]; } } } return NULL; } /* * This specific transfer on this connection has been "drained". */ static void drained_transfer(struct Curl_easy *data, struct http_conn *httpc) { DEBUGASSERT(httpc->drain_total >= data->state.drain); httpc->drain_total -= data->state.drain; data->state.drain = 0; } /* * Mark this transfer to get "drained". */ static void drain_this(struct Curl_easy *data, struct http_conn *httpc) { data->state.drain++; httpc->drain_total++; DEBUGASSERT(httpc->drain_total >= data->state.drain); } static struct Curl_easy *duphandle(struct Curl_easy *data) { struct Curl_easy *second = curl_easy_duphandle(data); if(second) { /* setup the request struct */ struct HTTP *http = calloc(1, sizeof(struct HTTP)); if(!http) { (void)Curl_close(second); second = NULL; } else { second->req.protop = http; http->header_recvbuf = Curl_add_buffer_init(); if(!http->header_recvbuf) { free(http); (void)Curl_close(second); second = NULL; } else { Curl_http2_setup_req(second); second->state.stream_weight = data->state.stream_weight; } } } return second; } static int push_promise(struct Curl_easy *data, struct connectdata *conn, const nghttp2_push_promise *frame) { int rv; H2BUGF(infof(data, "PUSH_PROMISE received, stream %u!\n", frame->promised_stream_id)); if(data->multi->push_cb) { struct HTTP *stream; struct HTTP *newstream; struct curl_pushheaders heads; CURLMcode rc; struct http_conn *httpc; size_t i; /* clone the parent */ struct Curl_easy *newhandle = duphandle(data); if(!newhandle) { infof(data, "failed to duplicate handle\n"); rv = 1; /* FAIL HARD */ goto fail; } heads.data = data; heads.frame = frame; /* ask the application */ H2BUGF(infof(data, "Got PUSH_PROMISE, ask application!\n")); stream = data->req.protop; if(!stream) { failf(data, "Internal NULL stream!\n"); (void)Curl_close(newhandle); rv = 1; goto fail; } Curl_set_in_callback(data, true); rv = data->multi->push_cb(data, newhandle, stream->push_headers_used, &heads, data->multi->push_userp); Curl_set_in_callback(data, false); /* free the headers again */ for(i = 0; i<stream->push_headers_used; i++) free(stream->push_headers[i]); free(stream->push_headers); stream->push_headers = NULL; stream->push_headers_used = 0; if(rv) { /* denied, kill off the new handle again */ http2_stream_free(newhandle->req.protop); newhandle->req.protop = NULL; (void)Curl_close(newhandle); goto fail; } newstream = newhandle->req.protop; newstream->stream_id = frame->promised_stream_id; newhandle->req.maxdownload = -1; newhandle->req.size = -1; /* approved, add to the multi handle and immediately switch to PERFORM state with the given connection !*/ rc = Curl_multi_add_perform(data->multi, newhandle, conn); if(rc) { infof(data, "failed to add handle to multi\n"); http2_stream_free(newhandle->req.protop); newhandle->req.protop = NULL; Curl_close(newhandle); rv = 1; goto fail; } httpc = &conn->proto.httpc; rv = nghttp2_session_set_stream_user_data(httpc->h2, frame->promised_stream_id, newhandle); if(rv) { infof(data, "failed to set user_data for stream %d\n", frame->promised_stream_id); DEBUGASSERT(0); goto fail; } } else { H2BUGF(infof(data, "Got PUSH_PROMISE, ignore it!\n")); rv = 1; } fail: return rv; } /* * multi_connchanged() is called to tell that there is a connection in * this multi handle that has changed state (multiplexing become possible, the * number of allowed streams changed or similar), and a subsequent use of this * multi handle should move CONNECT_PEND handles back to CONNECT to have them * retry. */ static void multi_connchanged(struct Curl_multi *multi) { multi->recheckstate = TRUE; } static int on_frame_recv(nghttp2_session *session, const nghttp2_frame *frame, void *userp) { struct connectdata *conn = (struct connectdata *)userp; struct http_conn *httpc = &conn->proto.httpc; struct Curl_easy *data_s = NULL; struct HTTP *stream = NULL; int rv; size_t left, ncopy; int32_t stream_id = frame->hd.stream_id; CURLcode result; if(!stream_id) { /* stream ID zero is for connection-oriented stuff */ if(frame->hd.type == NGHTTP2_SETTINGS) { uint32_t max_conn = httpc->settings.max_concurrent_streams; H2BUGF(infof(conn->data, "Got SETTINGS\n")); httpc->settings.max_concurrent_streams = nghttp2_session_get_remote_settings( session, NGHTTP2_SETTINGS_MAX_CONCURRENT_STREAMS); httpc->settings.enable_push = nghttp2_session_get_remote_settings( session, NGHTTP2_SETTINGS_ENABLE_PUSH); H2BUGF(infof(conn->data, "MAX_CONCURRENT_STREAMS == %d\n", httpc->settings.max_concurrent_streams)); H2BUGF(infof(conn->data, "ENABLE_PUSH == %s\n", httpc->settings.enable_push?"TRUE":"false")); if(max_conn != httpc->settings.max_concurrent_streams) { /* only signal change if the value actually changed */ infof(conn->data, "Connection state changed (MAX_CONCURRENT_STREAMS == %u)!\n", httpc->settings.max_concurrent_streams); multi_connchanged(conn->data->multi); } } return 0; } data_s = nghttp2_session_get_stream_user_data(session, stream_id); if(!data_s) { H2BUGF(infof(conn->data, "No Curl_easy associated with stream: %x\n", stream_id)); return 0; } stream = data_s->req.protop; if(!stream) { H2BUGF(infof(data_s, "No proto pointer for stream: %x\n", stream_id)); return NGHTTP2_ERR_CALLBACK_FAILURE; } H2BUGF(infof(data_s, "on_frame_recv() header %x stream %x\n", frame->hd.type, stream_id)); switch(frame->hd.type) { case NGHTTP2_DATA: /* If body started on this stream, then receiving DATA is illegal. */ if(!stream->bodystarted) { rv = nghttp2_submit_rst_stream(session, NGHTTP2_FLAG_NONE, stream_id, NGHTTP2_PROTOCOL_ERROR); if(nghttp2_is_fatal(rv)) { return NGHTTP2_ERR_CALLBACK_FAILURE; } } break; case NGHTTP2_HEADERS: if(stream->bodystarted) { /* Only valid HEADERS after body started is trailer HEADERS. We buffer them in on_header callback. */ break; } /* nghttp2 guarantees that :status is received, and we store it to stream->status_code. Fuzzing has proven this can still be reached without status code having been set. */ if(stream->status_code == -1) return NGHTTP2_ERR_CALLBACK_FAILURE; /* Only final status code signals the end of header */ if(stream->status_code / 100 != 1) { stream->bodystarted = TRUE; stream->status_code = -1; } result = Curl_add_buffer(&stream->header_recvbuf, "\r\n", 2); if(result) return NGHTTP2_ERR_CALLBACK_FAILURE; left = stream->header_recvbuf->size_used - stream->nread_header_recvbuf; ncopy = CURLMIN(stream->len, left); memcpy(&stream->mem[stream->memlen], stream->header_recvbuf->buffer + stream->nread_header_recvbuf, ncopy); stream->nread_header_recvbuf += ncopy; H2BUGF(infof(data_s, "Store %zu bytes headers from stream %u at %p\n", ncopy, stream_id, stream->mem)); stream->len -= ncopy; stream->memlen += ncopy; drain_this(data_s, httpc); { /* get the pointer from userp again since it was re-assigned above */ struct connectdata *conn_s = (struct connectdata *)userp; /* if we receive data for another handle, wake that up */ if(conn_s->data != data_s) Curl_expire(data_s, 0, EXPIRE_RUN_NOW); } break; case NGHTTP2_PUSH_PROMISE: rv = push_promise(data_s, conn, &frame->push_promise); if(rv) { /* deny! */ rv = nghttp2_submit_rst_stream(session, NGHTTP2_FLAG_NONE, frame->push_promise.promised_stream_id, NGHTTP2_CANCEL); if(nghttp2_is_fatal(rv)) { return rv; } } break; default: H2BUGF(infof(data_s, "Got frame type %x for stream %u!\n", frame->hd.type, stream_id)); break; } return 0; } static int on_data_chunk_recv(nghttp2_session *session, uint8_t flags, int32_t stream_id, const uint8_t *data, size_t len, void *userp) { struct HTTP *stream; struct Curl_easy *data_s; size_t nread; struct connectdata *conn = (struct connectdata *)userp; (void)session; (void)flags; (void)data; DEBUGASSERT(stream_id); /* should never be a zero stream ID here */ /* get the stream from the hash based on Stream ID */ data_s = nghttp2_session_get_stream_user_data(session, stream_id); if(!data_s) /* Receiving a Stream ID not in the hash should not happen, this is an internal error more than anything else! */ return NGHTTP2_ERR_CALLBACK_FAILURE; stream = data_s->req.protop; if(!stream) return NGHTTP2_ERR_CALLBACK_FAILURE; nread = CURLMIN(stream->len, len); memcpy(&stream->mem[stream->memlen], data, nread); stream->len -= nread; stream->memlen += nread; drain_this(data_s, &conn->proto.httpc); /* if we receive data for another handle, wake that up */ if(conn->data != data_s) Curl_expire(data_s, 0, EXPIRE_RUN_NOW); H2BUGF(infof(data_s, "%zu data received for stream %u " "(%zu left in buffer %p, total %zu)\n", nread, stream_id, stream->len, stream->mem, stream->memlen)); if(nread < len) { stream->pausedata = data + nread; stream->pauselen = len - nread; H2BUGF(infof(data_s, "NGHTTP2_ERR_PAUSE - %zu bytes out of buffer" ", stream %u\n", len - nread, stream_id)); data_s->conn->proto.httpc.pause_stream_id = stream_id; return NGHTTP2_ERR_PAUSE; } /* pause execution of nghttp2 if we received data for another handle in order to process them first. */ if(conn->data != data_s) { data_s->conn->proto.httpc.pause_stream_id = stream_id; return NGHTTP2_ERR_PAUSE; } return 0; } static int on_stream_close(nghttp2_session *session, int32_t stream_id, uint32_t error_code, void *userp) { struct Curl_easy *data_s; struct HTTP *stream; struct connectdata *conn = (struct connectdata *)userp; int rv; (void)session; (void)stream_id; if(stream_id) { struct http_conn *httpc; /* get the stream from the hash based on Stream ID, stream ID zero is for connection-oriented stuff */ data_s = nghttp2_session_get_stream_user_data(session, stream_id); if(!data_s) { /* We could get stream ID not in the hash. For example, if we decided to reject stream (e.g., PUSH_PROMISE). */ return 0; } H2BUGF(infof(data_s, "on_stream_close(), %s (err %d), stream %u\n", http2_strerror(error_code), error_code, stream_id)); stream = data_s->req.protop; if(!stream) return NGHTTP2_ERR_CALLBACK_FAILURE; stream->closed = TRUE; httpc = &conn->proto.httpc; drain_this(data_s, httpc); httpc->error_code = error_code; /* remove the entry from the hash as the stream is now gone */ rv = nghttp2_session_set_stream_user_data(session, stream_id, 0); if(rv) { infof(data_s, "http/2: failed to clear user_data for stream %d!\n", stream_id); DEBUGASSERT(0); } if(stream_id == httpc->pause_stream_id) { H2BUGF(infof(data_s, "Stopped the pause stream!\n")); httpc->pause_stream_id = 0; } H2BUGF(infof(data_s, "Removed stream %u hash!\n", stream_id)); stream->stream_id = 0; /* cleared */ } return 0; } static int on_begin_headers(nghttp2_session *session, const nghttp2_frame *frame, void *userp) { struct HTTP *stream; struct Curl_easy *data_s = NULL; (void)userp; data_s = nghttp2_session_get_stream_user_data(session, frame->hd.stream_id); if(!data_s) { return 0; } H2BUGF(infof(data_s, "on_begin_headers() was called\n")); if(frame->hd.type != NGHTTP2_HEADERS) { return 0; } stream = data_s->req.protop; if(!stream || !stream->bodystarted) { return 0; } if(!stream->trailer_recvbuf) { stream->trailer_recvbuf = Curl_add_buffer_init(); if(!stream->trailer_recvbuf) { return NGHTTP2_ERR_TEMPORAL_CALLBACK_FAILURE; } } return 0; } /* Decode HTTP status code. Returns -1 if no valid status code was decoded. */ static int decode_status_code(const uint8_t *value, size_t len) { int i; int res; if(len != 3) { return -1; } res = 0; for(i = 0; i < 3; ++i) { char c = value[i]; if(c < '0' || c > '9') { return -1; } res *= 10; res += c - '0'; } return res; } /* frame->hd.type is either NGHTTP2_HEADERS or NGHTTP2_PUSH_PROMISE */ static int on_header(nghttp2_session *session, const nghttp2_frame *frame, const uint8_t *name, size_t namelen, const uint8_t *value, size_t valuelen, uint8_t flags, void *userp) { struct HTTP *stream; struct Curl_easy *data_s; int32_t stream_id = frame->hd.stream_id; struct connectdata *conn = (struct connectdata *)userp; CURLcode result; (void)flags; DEBUGASSERT(stream_id); /* should never be a zero stream ID here */ /* get the stream from the hash based on Stream ID */ data_s = nghttp2_session_get_stream_user_data(session, stream_id); if(!data_s) /* Receiving a Stream ID not in the hash should not happen, this is an internal error more than anything else! */ return NGHTTP2_ERR_CALLBACK_FAILURE; stream = data_s->req.protop; if(!stream) { failf(data_s, "Internal NULL stream! 5\n"); return NGHTTP2_ERR_CALLBACK_FAILURE; } /* Store received PUSH_PROMISE headers to be used when the subsequent PUSH_PROMISE callback comes */ if(frame->hd.type == NGHTTP2_PUSH_PROMISE) { char *h; if(!strcmp(":authority", (const char *)name)) { /* pseudo headers are lower case */ int rc = 0; char *check = aprintf("%s:%d", conn->host.name, conn->remote_port); if(!check) /* no memory */ return NGHTTP2_ERR_CALLBACK_FAILURE; if(!Curl_strcasecompare(check, (const char *)value)) { /* This is push is not for the same authority that was asked for in * the URL. RFC 7540 section 8.2 says: "A client MUST treat a * PUSH_PROMISE for which the server is not authoritative as a stream * error of type PROTOCOL_ERROR." */ (void)nghttp2_submit_rst_stream(session, NGHTTP2_FLAG_NONE, stream_id, NGHTTP2_PROTOCOL_ERROR); rc = NGHTTP2_ERR_CALLBACK_FAILURE; } free(check); if(rc) return rc; } if(!stream->push_headers) { stream->push_headers_alloc = 10; stream->push_headers = malloc(stream->push_headers_alloc * sizeof(char *)); if(!stream->push_headers) return NGHTTP2_ERR_TEMPORAL_CALLBACK_FAILURE; stream->push_headers_used = 0; } else if(stream->push_headers_used == stream->push_headers_alloc) { char **headp; stream->push_headers_alloc *= 2; headp = Curl_saferealloc(stream->push_headers, stream->push_headers_alloc * sizeof(char *)); if(!headp) { stream->push_headers = NULL; return NGHTTP2_ERR_TEMPORAL_CALLBACK_FAILURE; } stream->push_headers = headp; } h = aprintf("%s:%s", name, value); if(h) stream->push_headers[stream->push_headers_used++] = h; return 0; } if(stream->bodystarted) { /* This is trailer fields. */ /* 4 is for ": " and "\r\n". */ uint32_t n = (uint32_t)(namelen + valuelen + 4); H2BUGF(infof(data_s, "h2 trailer: %.*s: %.*s\n", namelen, name, valuelen, value)); result = Curl_add_buffer(&stream->trailer_recvbuf, &n, sizeof(n)); if(result) return NGHTTP2_ERR_CALLBACK_FAILURE; result = Curl_add_buffer(&stream->trailer_recvbuf, name, namelen); if(result) return NGHTTP2_ERR_CALLBACK_FAILURE; result = Curl_add_buffer(&stream->trailer_recvbuf, ": ", 2); if(result) return NGHTTP2_ERR_CALLBACK_FAILURE; result = Curl_add_buffer(&stream->trailer_recvbuf, value, valuelen); if(result) return NGHTTP2_ERR_CALLBACK_FAILURE; result = Curl_add_buffer(&stream->trailer_recvbuf, "\r\n\0", 3); if(result) return NGHTTP2_ERR_CALLBACK_FAILURE; return 0; } if(namelen == sizeof(":status") - 1 && memcmp(":status", name, namelen) == 0) { /* nghttp2 guarantees :status is received first and only once, and value is 3 digits status code, and decode_status_code always succeeds. */ stream->status_code = decode_status_code(value, valuelen); DEBUGASSERT(stream->status_code != -1); result = Curl_add_buffer(&stream->header_recvbuf, "HTTP/2 ", 7); if(result) return NGHTTP2_ERR_CALLBACK_FAILURE; result = Curl_add_buffer(&stream->header_recvbuf, value, valuelen); if(result) return NGHTTP2_ERR_CALLBACK_FAILURE; /* the space character after the status code is mandatory */ result = Curl_add_buffer(&stream->header_recvbuf, " \r\n", 3); if(result) return NGHTTP2_ERR_CALLBACK_FAILURE; /* if we receive data for another handle, wake that up */ if(conn->data != data_s) Curl_expire(data_s, 0, EXPIRE_RUN_NOW); H2BUGF(infof(data_s, "h2 status: HTTP/2 %03d (easy %p)\n", stream->status_code, data_s)); return 0; } /* nghttp2 guarantees that namelen > 0, and :status was already received, and this is not pseudo-header field . */ /* convert to a HTTP1-style header */ result = Curl_add_buffer(&stream->header_recvbuf, name, namelen); if(result) return NGHTTP2_ERR_CALLBACK_FAILURE; result = Curl_add_buffer(&stream->header_recvbuf, ": ", 2); if(result) return NGHTTP2_ERR_CALLBACK_FAILURE; result = Curl_add_buffer(&stream->header_recvbuf, value, valuelen); if(result) return NGHTTP2_ERR_CALLBACK_FAILURE; result = Curl_add_buffer(&stream->header_recvbuf, "\r\n", 2); if(result) return NGHTTP2_ERR_CALLBACK_FAILURE; /* if we receive data for another handle, wake that up */ if(conn->data != data_s) Curl_expire(data_s, 0, EXPIRE_RUN_NOW); H2BUGF(infof(data_s, "h2 header: %.*s: %.*s\n", namelen, name, valuelen, value)); return 0; /* 0 is successful */ } static ssize_t data_source_read_callback(nghttp2_session *session, int32_t stream_id, uint8_t *buf, size_t length, uint32_t *data_flags, nghttp2_data_source *source, void *userp) { struct Curl_easy *data_s; struct HTTP *stream = NULL; size_t nread; (void)source; (void)userp; if(stream_id) { /* get the stream from the hash based on Stream ID, stream ID zero is for connection-oriented stuff */ data_s = nghttp2_session_get_stream_user_data(session, stream_id); if(!data_s) /* Receiving a Stream ID not in the hash should not happen, this is an internal error more than anything else! */ return NGHTTP2_ERR_CALLBACK_FAILURE; stream = data_s->req.protop; if(!stream) return NGHTTP2_ERR_CALLBACK_FAILURE; } else return NGHTTP2_ERR_INVALID_ARGUMENT; nread = CURLMIN(stream->upload_len, length); if(nread > 0) { memcpy(buf, stream->upload_mem, nread); stream->upload_mem += nread; stream->upload_len -= nread; if(data_s->state.infilesize != -1) stream->upload_left -= nread; } if(stream->upload_left == 0) *data_flags = NGHTTP2_DATA_FLAG_EOF; else if(nread == 0) return NGHTTP2_ERR_DEFERRED; H2BUGF(infof(data_s, "data_source_read_callback: " "returns %zu bytes stream %u\n", nread, stream_id)); return nread; } #if defined(NGHTTP2_HAS_ERROR_CALLBACK) && \ !defined(CURL_DISABLE_VERBOSE_STRINGS) static int error_callback(nghttp2_session *session, const char *msg, size_t len, void *userp) { struct connectdata *conn = (struct connectdata *)userp; (void)session; infof(conn->data, "http2 error: %.*s\n", len, msg); return 0; } #endif static void populate_settings(struct connectdata *conn, struct http_conn *httpc) { nghttp2_settings_entry *iv = httpc->local_settings; iv[0].settings_id = NGHTTP2_SETTINGS_MAX_CONCURRENT_STREAMS; iv[0].value = 100; iv[1].settings_id = NGHTTP2_SETTINGS_INITIAL_WINDOW_SIZE; iv[1].value = HTTP2_HUGE_WINDOW_SIZE; iv[2].settings_id = NGHTTP2_SETTINGS_ENABLE_PUSH; iv[2].value = conn->data->multi->push_cb != NULL; httpc->local_settings_num = 3; } void Curl_http2_done(struct connectdata *conn, bool premature) { struct Curl_easy *data = conn->data; struct HTTP *http = data->req.protop; struct http_conn *httpc = &conn->proto.httpc; /* there might be allocated resources done before this got the 'h2' pointer setup */ if(http->header_recvbuf) { Curl_add_buffer_free(&http->header_recvbuf); Curl_add_buffer_free(&http->trailer_recvbuf); if(http->push_headers) { /* if they weren't used and then freed before */ for(; http->push_headers_used > 0; --http->push_headers_used) { free(http->push_headers[http->push_headers_used - 1]); } free(http->push_headers); http->push_headers = NULL; } } if(!httpc->h2) /* not HTTP/2 ? */ return; if(data->state.drain) drained_transfer(data, httpc); if(premature) { /* RST_STREAM */ if(!nghttp2_submit_rst_stream(httpc->h2, NGHTTP2_FLAG_NONE, http->stream_id, NGHTTP2_STREAM_CLOSED)) (void)nghttp2_session_send(httpc->h2); if(http->stream_id == httpc->pause_stream_id) { infof(data, "stopped the pause stream!\n"); httpc->pause_stream_id = 0; } } /* -1 means unassigned and 0 means cleared */ if(http->stream_id > 0) { int rv = nghttp2_session_set_stream_user_data(httpc->h2, http->stream_id, 0); if(rv) { infof(data, "http/2: failed to clear user_data for stream %d!\n", http->stream_id); DEBUGASSERT(0); } http->stream_id = 0; } } /* * Initialize nghttp2 for a Curl connection */ static CURLcode http2_init(struct connectdata *conn) { if(!conn->proto.httpc.h2) { int rc; nghttp2_session_callbacks *callbacks; conn->proto.httpc.inbuf = malloc(H2_BUFSIZE); if(conn->proto.httpc.inbuf == NULL) return CURLE_OUT_OF_MEMORY; rc = nghttp2_session_callbacks_new(&callbacks); if(rc) { failf(conn->data, "Couldn't initialize nghttp2 callbacks!"); return CURLE_OUT_OF_MEMORY; /* most likely at least */ } /* nghttp2_send_callback */ nghttp2_session_callbacks_set_send_callback(callbacks, send_callback); /* nghttp2_on_frame_recv_callback */ nghttp2_session_callbacks_set_on_frame_recv_callback (callbacks, on_frame_recv); /* nghttp2_on_data_chunk_recv_callback */ nghttp2_session_callbacks_set_on_data_chunk_recv_callback (callbacks, on_data_chunk_recv); /* nghttp2_on_stream_close_callback */ nghttp2_session_callbacks_set_on_stream_close_callback (callbacks, on_stream_close); /* nghttp2_on_begin_headers_callback */ nghttp2_session_callbacks_set_on_begin_headers_callback (callbacks, on_begin_headers); /* nghttp2_on_header_callback */ nghttp2_session_callbacks_set_on_header_callback(callbacks, on_header); #ifndef CURL_DISABLE_VERBOSE_STRINGS nghttp2_session_callbacks_set_error_callback(callbacks, error_callback); #endif /* The nghttp2 session is not yet setup, do it */ rc = nghttp2_session_client_new(&conn->proto.httpc.h2, callbacks, conn); nghttp2_session_callbacks_del(callbacks); if(rc) { failf(conn->data, "Couldn't initialize nghttp2!"); return CURLE_OUT_OF_MEMORY; /* most likely at least */ } } return CURLE_OK; } /* * Append headers to ask for a HTTP1.1 to HTTP2 upgrade. */ CURLcode Curl_http2_request_upgrade(Curl_send_buffer *req, struct connectdata *conn) { CURLcode result; ssize_t binlen; char *base64; size_t blen; struct SingleRequest *k = &conn->data->req; uint8_t *binsettings = conn->proto.httpc.binsettings; struct http_conn *httpc = &conn->proto.httpc; populate_settings(conn, httpc); /* this returns number of bytes it wrote */ binlen = nghttp2_pack_settings_payload(binsettings, H2_BINSETTINGS_LEN, httpc->local_settings, httpc->local_settings_num); if(!binlen) { failf(conn->data, "nghttp2 unexpectedly failed on pack_settings_payload"); Curl_add_buffer_free(&req); return CURLE_FAILED_INIT; } conn->proto.httpc.binlen = binlen; result = Curl_base64url_encode(conn->data, (const char *)binsettings, binlen, &base64, &blen); if(result) { Curl_add_buffer_free(&req); return result; } result = Curl_add_bufferf(&req, "Connection: Upgrade, HTTP2-Settings\r\n" "Upgrade: %s\r\n" "HTTP2-Settings: %s\r\n", NGHTTP2_CLEARTEXT_PROTO_VERSION_ID, base64); free(base64); k->upgr101 = UPGR101_REQUESTED; return result; } /* * Returns nonzero if current HTTP/2 session should be closed. */ static int should_close_session(struct http_conn *httpc) { return httpc->drain_total == 0 && !nghttp2_session_want_read(httpc->h2) && !nghttp2_session_want_write(httpc->h2); } /* * h2_process_pending_input() processes pending input left in * httpc->inbuf. Then, call h2_session_send() to send pending data. * This function returns 0 if it succeeds, or -1 and error code will * be assigned to *err. */ static int h2_process_pending_input(struct connectdata *conn, struct http_conn *httpc, CURLcode *err) { ssize_t nread; char *inbuf; ssize_t rv; struct Curl_easy *data = conn->data; nread = httpc->inbuflen - httpc->nread_inbuf; inbuf = httpc->inbuf + httpc->nread_inbuf; rv = nghttp2_session_mem_recv(httpc->h2, (const uint8_t *)inbuf, nread); if(rv < 0) { failf(data, "h2_process_pending_input: nghttp2_session_mem_recv() returned " "%zd:%s\n", rv, nghttp2_strerror((int)rv)); *err = CURLE_RECV_ERROR; return -1; } if(nread == rv) { H2BUGF(infof(data, "h2_process_pending_input: All data in connection buffer " "processed\n")); httpc->inbuflen = 0; httpc->nread_inbuf = 0; } else { httpc->nread_inbuf += rv; H2BUGF(infof(data, "h2_process_pending_input: %zu bytes left in connection " "buffer\n", httpc->inbuflen - httpc->nread_inbuf)); } rv = h2_session_send(data, httpc->h2); if(rv != 0) { *err = CURLE_SEND_ERROR; return -1; } if(should_close_session(httpc)) { H2BUGF(infof(data, "h2_process_pending_input: nothing to do in this session\n")); if(httpc->error_code) *err = CURLE_HTTP2; else { /* not an error per se, but should still close the connection */ connclose(conn, "GOAWAY received"); *err = CURLE_OK; } return -1; } return 0; } /* * Called from transfer.c:done_sending when we stop uploading. */ CURLcode Curl_http2_done_sending(struct connectdata *conn) { CURLcode result = CURLE_OK; if((conn->handler == &Curl_handler_http2_ssl) || (conn->handler == &Curl_handler_http2)) { /* make sure this is only attempted for HTTP/2 transfers */ struct HTTP *stream = conn->data->req.protop; if(stream->upload_left) { /* If the stream still thinks there's data left to upload. */ struct http_conn *httpc = &conn->proto.httpc; nghttp2_session *h2 = httpc->h2; stream->upload_left = 0; /* DONE! */ /* resume sending here to trigger the callback to get called again so that it can signal EOF to nghttp2 */ (void)nghttp2_session_resume_data(h2, stream->stream_id); (void)h2_process_pending_input(conn, httpc, &result); } } return result; } static ssize_t http2_handle_stream_close(struct connectdata *conn, struct Curl_easy *data, struct HTTP *stream, CURLcode *err) { char *trailer_pos, *trailer_end; CURLcode result; struct http_conn *httpc = &conn->proto.httpc; if(httpc->pause_stream_id == stream->stream_id) { httpc->pause_stream_id = 0; } drained_transfer(data, httpc); if(httpc->pause_stream_id == 0) { if(h2_process_pending_input(conn, httpc, err) != 0) { return -1; } } DEBUGASSERT(data->state.drain == 0); /* Reset to FALSE to prevent infinite loop in readwrite_data function. */ stream->closed = FALSE; if(httpc->error_code == NGHTTP2_REFUSED_STREAM) { H2BUGF(infof(data, "REFUSED_STREAM (%d), try again on a new connection!\n", stream->stream_id)); connclose(conn, "REFUSED_STREAM"); /* don't use this anymore */ data->state.refused_stream = TRUE; *err = CURLE_RECV_ERROR; /* trigger Curl_retry_request() later */ return -1; } else if(httpc->error_code != NGHTTP2_NO_ERROR) { failf(data, "HTTP/2 stream %d was not closed cleanly: %s (err %u)", stream->stream_id, http2_strerror(httpc->error_code), httpc->error_code); *err = CURLE_HTTP2_STREAM; return -1; } if(!stream->bodystarted) { failf(data, "HTTP/2 stream %d was closed cleanly, but before getting " " all response header fields, treated as error", stream->stream_id); *err = CURLE_HTTP2_STREAM; return -1; } if(stream->trailer_recvbuf && stream->trailer_recvbuf->buffer) { trailer_pos = stream->trailer_recvbuf->buffer; trailer_end = trailer_pos + stream->trailer_recvbuf->size_used; for(; trailer_pos < trailer_end;) { uint32_t n; memcpy(&n, trailer_pos, sizeof(n)); trailer_pos += sizeof(n); result = Curl_client_write(conn, CLIENTWRITE_HEADER, trailer_pos, n); if(result) { *err = result; return -1; } trailer_pos += n + 1; } } stream->close_handled = TRUE; H2BUGF(infof(data, "http2_recv returns 0, http2_handle_stream_close\n")); return 0; } /* * h2_pri_spec() fills in the pri_spec struct, used by nghttp2 to send weight * and dependency to the peer. It also stores the updated values in the state * struct. */ static void h2_pri_spec(struct Curl_easy *data, nghttp2_priority_spec *pri_spec) { struct HTTP *depstream = (data->set.stream_depends_on? data->set.stream_depends_on->req.protop:NULL); int32_t depstream_id = depstream? depstream->stream_id:0; nghttp2_priority_spec_init(pri_spec, depstream_id, data->set.stream_weight, data->set.stream_depends_e); data->state.stream_weight = data->set.stream_weight; data->state.stream_depends_e = data->set.stream_depends_e; data->state.stream_depends_on = data->set.stream_depends_on; } /* * h2_session_send() checks if there's been an update in the priority / * dependency settings and if so it submits a PRIORITY frame with the updated * info. */ static int h2_session_send(struct Curl_easy *data, nghttp2_session *h2) { struct HTTP *stream = data->req.protop; if((data->set.stream_weight != data->state.stream_weight) || (data->set.stream_depends_e != data->state.stream_depends_e) || (data->set.stream_depends_on != data->state.stream_depends_on) ) { /* send new weight and/or dependency */ nghttp2_priority_spec pri_spec; int rv; h2_pri_spec(data, &pri_spec); H2BUGF(infof(data, "Queuing PRIORITY on stream %u (easy %p)\n", stream->stream_id, data)); rv = nghttp2_submit_priority(h2, NGHTTP2_FLAG_NONE, stream->stream_id, &pri_spec); if(rv) return rv; } return nghttp2_session_send(h2); } static ssize_t http2_recv(struct connectdata *conn, int sockindex, char *mem, size_t len, CURLcode *err) { CURLcode result = CURLE_OK; ssize_t rv; ssize_t nread; struct http_conn *httpc = &conn->proto.httpc; struct Curl_easy *data = conn->data; struct HTTP *stream = data->req.protop; (void)sockindex; /* we always do HTTP2 on sockindex 0 */ if(should_close_session(httpc)) { H2BUGF(infof(data, "http2_recv: nothing to do in this session\n")); *err = CURLE_HTTP2; return -1; } /* Nullify here because we call nghttp2_session_send() and they might refer to the old buffer. */ stream->upload_mem = NULL; stream->upload_len = 0; /* * At this point 'stream' is just in the Curl_easy the connection * identifies as its owner at this time. */ if(stream->bodystarted && stream->nread_header_recvbuf < stream->header_recvbuf->size_used) { /* If there is body data pending for this stream to return, do that */ size_t left = stream->header_recvbuf->size_used - stream->nread_header_recvbuf; size_t ncopy = CURLMIN(len, left); memcpy(mem, stream->header_recvbuf->buffer + stream->nread_header_recvbuf, ncopy); stream->nread_header_recvbuf += ncopy; H2BUGF(infof(data, "http2_recv: Got %d bytes from header_recvbuf\n", (int)ncopy)); return ncopy; } H2BUGF(infof(data, "http2_recv: easy %p (stream %u)\n", data, stream->stream_id)); if((data->state.drain) && stream->memlen) { H2BUGF(infof(data, "http2_recv: DRAIN %zu bytes stream %u!! (%p => %p)\n", stream->memlen, stream->stream_id, stream->mem, mem)); if(mem != stream->mem) { /* if we didn't get the same buffer this time, we must move the data to the beginning */ memmove(mem, stream->mem, stream->memlen); stream->len = len - stream->memlen; stream->mem = mem; } if(httpc->pause_stream_id == stream->stream_id && !stream->pausedata) { /* We have paused nghttp2, but we have no pause data (see on_data_chunk_recv). */ httpc->pause_stream_id = 0; if(h2_process_pending_input(conn, httpc, &result) != 0) { *err = result; return -1; } } } else if(stream->pausedata) { DEBUGASSERT(httpc->pause_stream_id == stream->stream_id); nread = CURLMIN(len, stream->pauselen); memcpy(mem, stream->pausedata, nread); stream->pausedata += nread; stream->pauselen -= nread; infof(data, "%zd data bytes written\n", nread); if(stream->pauselen == 0) { H2BUGF(infof(data, "Unpaused by stream %u\n", stream->stream_id)); DEBUGASSERT(httpc->pause_stream_id == stream->stream_id); httpc->pause_stream_id = 0; stream->pausedata = NULL; stream->pauselen = 0; /* When NGHTTP2_ERR_PAUSE is returned from data_source_read_callback, we might not process DATA frame fully. Calling nghttp2_session_mem_recv() again will continue to process DATA frame, but if there is no incoming frames, then we have to call it again with 0-length data. Without this, on_stream_close callback will not be called, and stream could be hanged. */ if(h2_process_pending_input(conn, httpc, &result) != 0) { *err = result; return -1; } } H2BUGF(infof(data, "http2_recv: returns unpaused %zd bytes on stream %u\n", nread, stream->stream_id)); return nread; } else if(httpc->pause_stream_id) { /* If a stream paused nghttp2_session_mem_recv previously, and has not processed all data, it still refers to the buffer in nghttp2_session. If we call nghttp2_session_mem_recv(), we may overwrite that buffer. To avoid that situation, just return here with CURLE_AGAIN. This could be busy loop since data in socket is not read. But it seems that usually streams are notified with its drain property, and socket is read again quickly. */ H2BUGF(infof(data, "stream %x is paused, pause id: %x\n", stream->stream_id, httpc->pause_stream_id)); *err = CURLE_AGAIN; return -1; } else { char *inbuf; /* remember where to store incoming data for this stream and how big the buffer is */ stream->mem = mem; stream->len = len; stream->memlen = 0; if(httpc->inbuflen == 0) { nread = ((Curl_recv *)httpc->recv_underlying)( conn, FIRSTSOCKET, httpc->inbuf, H2_BUFSIZE, &result); if(nread == -1) { if(result != CURLE_AGAIN) failf(data, "Failed receiving HTTP2 data"); else if(stream->closed) /* received when the stream was already closed! */ return http2_handle_stream_close(conn, data, stream, err); *err = result; return -1; } if(nread == 0) { H2BUGF(infof(data, "end of stream\n")); *err = CURLE_OK; return 0; } H2BUGF(infof(data, "nread=%zd\n", nread)); httpc->inbuflen = nread; inbuf = httpc->inbuf; } else { nread = httpc->inbuflen - httpc->nread_inbuf; inbuf = httpc->inbuf + httpc->nread_inbuf; H2BUGF(infof(data, "Use data left in connection buffer, nread=%zd\n", nread)); } rv = nghttp2_session_mem_recv(httpc->h2, (const uint8_t *)inbuf, nread); if(nghttp2_is_fatal((int)rv)) { failf(data, "nghttp2_session_mem_recv() returned %zd:%s\n", rv, nghttp2_strerror((int)rv)); *err = CURLE_RECV_ERROR; return -1; } H2BUGF(infof(data, "nghttp2_session_mem_recv() returns %zd\n", rv)); if(nread == rv) { H2BUGF(infof(data, "All data in connection buffer processed\n")); httpc->inbuflen = 0; httpc->nread_inbuf = 0; } else { httpc->nread_inbuf += rv; H2BUGF(infof(data, "%zu bytes left in connection buffer\n", httpc->inbuflen - httpc->nread_inbuf)); } /* Always send pending frames in nghttp2 session, because nghttp2_session_mem_recv() may queue new frame */ rv = h2_session_send(data, httpc->h2); if(rv != 0) { *err = CURLE_SEND_ERROR; return -1; } if(should_close_session(httpc)) { H2BUGF(infof(data, "http2_recv: nothing to do in this session\n")); *err = CURLE_HTTP2; return -1; } } if(stream->memlen) { ssize_t retlen = stream->memlen; H2BUGF(infof(data, "http2_recv: returns %zd for stream %u\n", retlen, stream->stream_id)); stream->memlen = 0; if(httpc->pause_stream_id == stream->stream_id) { /* data for this stream is returned now, but this stream caused a pause already so we need it called again asap */ H2BUGF(infof(data, "Data returned for PAUSED stream %u\n", stream->stream_id)); } else if(!stream->closed) { drained_transfer(data, httpc); } return retlen; } /* If stream is closed, return 0 to signal the http routine to close the connection */ if(stream->closed) { return http2_handle_stream_close(conn, data, stream, err); } *err = CURLE_AGAIN; H2BUGF(infof(data, "http2_recv returns AGAIN for stream %u\n", stream->stream_id)); return -1; } /* Index where :authority header field will appear in request header field list. */ #define AUTHORITY_DST_IDX 3 #define HEADER_OVERFLOW(x) \ (x.namelen > (uint16_t)-1 || x.valuelen > (uint16_t)-1 - x.namelen) /* * Check header memory for the token "trailers". * Parse the tokens as separated by comma and surrounded by whitespace. * Returns TRUE if found or FALSE if not. */ static bool contains_trailers(const char *p, size_t len) { const char *end = p + len; for(;;) { for(; p != end && (*p == ' ' || *p == '\t'); ++p) ; if(p == end || (size_t)(end - p) < sizeof("trailers") - 1) return FALSE; if(strncasecompare("trailers", p, sizeof("trailers") - 1)) { p += sizeof("trailers") - 1; for(; p != end && (*p == ' ' || *p == '\t'); ++p) ; if(p == end || *p == ',') return TRUE; } /* skip to next token */ for(; p != end && *p != ','; ++p) ; if(p == end) return FALSE; ++p; } } typedef enum { /* Send header to server */ HEADERINST_FORWARD, /* Don't send header to server */ HEADERINST_IGNORE, /* Discard header, and replace it with "te: trailers" */ HEADERINST_TE_TRAILERS } header_instruction; /* Decides how to treat given header field. */ static header_instruction inspect_header(const char *name, size_t namelen, const char *value, size_t valuelen) { switch(namelen) { case 2: if(!strncasecompare("te", name, namelen)) return HEADERINST_FORWARD; return contains_trailers(value, valuelen) ? HEADERINST_TE_TRAILERS : HEADERINST_IGNORE; case 7: return strncasecompare("upgrade", name, namelen) ? HEADERINST_IGNORE : HEADERINST_FORWARD; case 10: return (strncasecompare("connection", name, namelen) || strncasecompare("keep-alive", name, namelen)) ? HEADERINST_IGNORE : HEADERINST_FORWARD; case 16: return strncasecompare("proxy-connection", name, namelen) ? HEADERINST_IGNORE : HEADERINST_FORWARD; case 17: return strncasecompare("transfer-encoding", name, namelen) ? HEADERINST_IGNORE : HEADERINST_FORWARD; default: return HEADERINST_FORWARD; } } static ssize_t http2_send(struct connectdata *conn, int sockindex, const void *mem, size_t len, CURLcode *err) { /* * Currently, we send request in this function, but this function is also * used to send request body. It would be nice to add dedicated function for * request. */ int rv; struct http_conn *httpc = &conn->proto.httpc; struct HTTP *stream = conn->data->req.protop; nghttp2_nv *nva = NULL; size_t nheader; size_t i; size_t authority_idx; char *hdbuf = (char *)mem; char *end, *line_end; nghttp2_data_provider data_prd; int32_t stream_id; nghttp2_session *h2 = httpc->h2; nghttp2_priority_spec pri_spec; (void)sockindex; H2BUGF(infof(conn->data, "http2_send len=%zu\n", len)); if(stream->stream_id != -1) { if(stream->close_handled) { infof(conn->data, "stream %d closed\n", stream->stream_id); *err = CURLE_HTTP2_STREAM; return -1; } else if(stream->closed) { return http2_handle_stream_close(conn, conn->data, stream, err); } /* If stream_id != -1, we have dispatched request HEADERS, and now are going to send or sending request body in DATA frame */ stream->upload_mem = mem; stream->upload_len = len; nghttp2_session_resume_data(h2, stream->stream_id); rv = h2_session_send(conn->data, h2); if(nghttp2_is_fatal(rv)) { *err = CURLE_SEND_ERROR; return -1; } len -= stream->upload_len; /* Nullify here because we call nghttp2_session_send() and they might refer to the old buffer. */ stream->upload_mem = NULL; stream->upload_len = 0; if(should_close_session(httpc)) { H2BUGF(infof(conn->data, "http2_send: nothing to do in this session\n")); *err = CURLE_HTTP2; return -1; } if(stream->upload_left) { /* we are sure that we have more data to send here. Calling the following API will make nghttp2_session_want_write() return nonzero if remote window allows it, which then libcurl checks socket is writable or not. See http2_perform_getsock(). */ nghttp2_session_resume_data(h2, stream->stream_id); } H2BUGF(infof(conn->data, "http2_send returns %zu for stream %u\n", len, stream->stream_id)); return len; } /* Calculate number of headers contained in [mem, mem + len) */ /* Here, we assume the curl http code generate *correct* HTTP header field block */ nheader = 0; for(i = 1; i < len; ++i) { if(hdbuf[i] == '\n' && hdbuf[i - 1] == '\r') { ++nheader; ++i; } } if(nheader < 2) goto fail; /* We counted additional 2 \r\n in the first and last line. We need 3 new headers: :method, :path and :scheme. Therefore we need one more space. */ nheader += 1; nva = malloc(sizeof(nghttp2_nv) * nheader); if(nva == NULL) { *err = CURLE_OUT_OF_MEMORY; return -1; } /* Extract :method, :path from request line We do line endings with CRLF so checking for CR is enough */ line_end = memchr(hdbuf, '\r', len); if(!line_end) goto fail; /* Method does not contain spaces */ end = memchr(hdbuf, ' ', line_end - hdbuf); if(!end || end == hdbuf) goto fail; nva[0].name = (unsigned char *)":method"; nva[0].namelen = strlen((char *)nva[0].name); nva[0].value = (unsigned char *)hdbuf; nva[0].valuelen = (size_t)(end - hdbuf); nva[0].flags = NGHTTP2_NV_FLAG_NONE; if(HEADER_OVERFLOW(nva[0])) { failf(conn->data, "Failed sending HTTP request: Header overflow"); goto fail; } hdbuf = end + 1; /* Path may contain spaces so scan backwards */ end = NULL; for(i = (size_t)(line_end - hdbuf); i; --i) { if(hdbuf[i - 1] == ' ') { end = &hdbuf[i - 1]; break; } } if(!end || end == hdbuf) goto fail; nva[1].name = (unsigned char *)":path"; nva[1].namelen = strlen((char *)nva[1].name); nva[1].value = (unsigned char *)hdbuf; nva[1].valuelen = (size_t)(end - hdbuf); nva[1].flags = NGHTTP2_NV_FLAG_NONE; if(HEADER_OVERFLOW(nva[1])) { failf(conn->data, "Failed sending HTTP request: Header overflow"); goto fail; } nva[2].name = (unsigned char *)":scheme"; nva[2].namelen = strlen((char *)nva[2].name); if(conn->handler->flags & PROTOPT_SSL) nva[2].value = (unsigned char *)"https"; else nva[2].value = (unsigned char *)"http"; nva[2].valuelen = strlen((char *)nva[2].value); nva[2].flags = NGHTTP2_NV_FLAG_NONE; if(HEADER_OVERFLOW(nva[2])) { failf(conn->data, "Failed sending HTTP request: Header overflow"); goto fail; } authority_idx = 0; i = 3; while(i < nheader) { size_t hlen; hdbuf = line_end + 2; /* check for next CR, but only within the piece of data left in the given buffer */ line_end = memchr(hdbuf, '\r', len - (hdbuf - (char *)mem)); if(!line_end || (line_end == hdbuf)) goto fail; /* header continuation lines are not supported */ if(*hdbuf == ' ' || *hdbuf == '\t') goto fail; for(end = hdbuf; end < line_end && *end != ':'; ++end) ; if(end == hdbuf || end == line_end) goto fail; hlen = end - hdbuf; if(hlen == 4 && strncasecompare("host", hdbuf, 4)) { authority_idx = i; nva[i].name = (unsigned char *)":authority"; nva[i].namelen = strlen((char *)nva[i].name); } else { nva[i].name = (unsigned char *)hdbuf; nva[i].namelen = (size_t)(end - hdbuf); } hdbuf = end + 1; while(*hdbuf == ' ' || *hdbuf == '\t') ++hdbuf; end = line_end; switch(inspect_header((const char *)nva[i].name, nva[i].namelen, hdbuf, end - hdbuf)) { case HEADERINST_IGNORE: /* skip header fields prohibited by HTTP/2 specification. */ --nheader; continue; case HEADERINST_TE_TRAILERS: nva[i].value = (uint8_t*)"trailers"; nva[i].valuelen = sizeof("trailers") - 1; break; default: nva[i].value = (unsigned char *)hdbuf; nva[i].valuelen = (size_t)(end - hdbuf); } nva[i].flags = NGHTTP2_NV_FLAG_NONE; if(HEADER_OVERFLOW(nva[i])) { failf(conn->data, "Failed sending HTTP request: Header overflow"); goto fail; } ++i; } /* :authority must come before non-pseudo header fields */ if(authority_idx != 0 && authority_idx != AUTHORITY_DST_IDX) { nghttp2_nv authority = nva[authority_idx]; for(i = authority_idx; i > AUTHORITY_DST_IDX; --i) { nva[i] = nva[i - 1]; } nva[i] = authority; } /* Warn stream may be rejected if cumulative length of headers is too large. It appears nghttp2 will not send a header frame larger than 64KB. */ #define MAX_ACC 60000 /* <64KB to account for some overhead */ { size_t acc = 0; for(i = 0; i < nheader; ++i) { acc += nva[i].namelen + nva[i].valuelen; H2BUGF(infof(conn->data, "h2 header: %.*s:%.*s\n", nva[i].namelen, nva[i].name, nva[i].valuelen, nva[i].value)); } if(acc > MAX_ACC) { infof(conn->data, "http2_send: Warning: The cumulative length of all " "headers exceeds %zu bytes and that could cause the " "stream to be rejected.\n", MAX_ACC); } } h2_pri_spec(conn->data, &pri_spec); switch(conn->data->set.httpreq) { case HTTPREQ_POST: case HTTPREQ_POST_FORM: case HTTPREQ_POST_MIME: case HTTPREQ_PUT: if(conn->data->state.infilesize != -1) stream->upload_left = conn->data->state.infilesize; else /* data sending without specifying the data amount up front */ stream->upload_left = -1; /* unknown, but not zero */ data_prd.read_callback = data_source_read_callback; data_prd.source.ptr = NULL; stream_id = nghttp2_submit_request(h2, &pri_spec, nva, nheader, &data_prd, conn->data); break; default: stream_id = nghttp2_submit_request(h2, &pri_spec, nva, nheader, NULL, conn->data); } Curl_safefree(nva); if(stream_id < 0) { H2BUGF(infof(conn->data, "http2_send() send error\n")); *err = CURLE_SEND_ERROR; return -1; } infof(conn->data, "Using Stream ID: %x (easy handle %p)\n", stream_id, (void *)conn->data); stream->stream_id = stream_id; /* this does not call h2_session_send() since there can not have been any * priority upodate since the nghttp2_submit_request() call above */ rv = nghttp2_session_send(h2); if(rv != 0) { *err = CURLE_SEND_ERROR; return -1; } if(should_close_session(httpc)) { H2BUGF(infof(conn->data, "http2_send: nothing to do in this session\n")); *err = CURLE_HTTP2; return -1; } if(stream->stream_id != -1) { /* If whole HEADERS frame was sent off to the underlying socket, the nghttp2 library calls data_source_read_callback. But only it found that no data available, so it deferred the DATA transmission. Which means that nghttp2_session_want_write() returns 0 on http2_perform_getsock(), which results that no writable socket check is performed. To workaround this, we issue nghttp2_session_resume_data() here to bring back DATA transmission from deferred state. */ nghttp2_session_resume_data(h2, stream->stream_id); } return len; fail: free(nva); *err = CURLE_SEND_ERROR; return -1; } CURLcode Curl_http2_setup(struct connectdata *conn) { CURLcode result; struct http_conn *httpc = &conn->proto.httpc; struct HTTP *stream = conn->data->req.protop; stream->stream_id = -1; if(!stream->header_recvbuf) { stream->header_recvbuf = Curl_add_buffer_init(); if(!stream->header_recvbuf) return CURLE_OUT_OF_MEMORY; } if((conn->handler == &Curl_handler_http2_ssl) || (conn->handler == &Curl_handler_http2)) return CURLE_OK; /* already done */ if(conn->handler->flags & PROTOPT_SSL) conn->handler = &Curl_handler_http2_ssl; else conn->handler = &Curl_handler_http2; result = http2_init(conn); if(result) { Curl_add_buffer_free(&stream->header_recvbuf); return result; } infof(conn->data, "Using HTTP2, server supports multi-use\n"); stream->upload_left = 0; stream->upload_mem = NULL; stream->upload_len = 0; httpc->inbuflen = 0; httpc->nread_inbuf = 0; httpc->pause_stream_id = 0; httpc->drain_total = 0; conn->bits.multiplex = TRUE; /* at least potentially multiplexed */ conn->httpversion = 20; conn->bundle->multiuse = BUNDLE_MULTIPLEX; infof(conn->data, "Connection state changed (HTTP/2 confirmed)\n"); multi_connchanged(conn->data->multi); return CURLE_OK; } CURLcode Curl_http2_switched(struct connectdata *conn, const char *mem, size_t nread) { CURLcode result; struct http_conn *httpc = &conn->proto.httpc; int rv; ssize_t nproc; struct Curl_easy *data = conn->data; struct HTTP *stream = conn->data->req.protop; result = Curl_http2_setup(conn); if(result) return result; httpc->recv_underlying = conn->recv[FIRSTSOCKET]; httpc->send_underlying = conn->send[FIRSTSOCKET]; conn->recv[FIRSTSOCKET] = http2_recv; conn->send[FIRSTSOCKET] = http2_send; if(conn->data->req.upgr101 == UPGR101_RECEIVED) { /* stream 1 is opened implicitly on upgrade */ stream->stream_id = 1; /* queue SETTINGS frame (again) */ rv = nghttp2_session_upgrade(httpc->h2, httpc->binsettings, httpc->binlen, NULL); if(rv != 0) { failf(data, "nghttp2_session_upgrade() failed: %s(%d)", nghttp2_strerror(rv), rv); return CURLE_HTTP2; } rv = nghttp2_session_set_stream_user_data(httpc->h2, stream->stream_id, data); if(rv) { infof(data, "http/2: failed to set user_data for stream %d!\n", stream->stream_id); DEBUGASSERT(0); } } else { populate_settings(conn, httpc); /* stream ID is unknown at this point */ stream->stream_id = -1; rv = nghttp2_submit_settings(httpc->h2, NGHTTP2_FLAG_NONE, httpc->local_settings, httpc->local_settings_num); if(rv != 0) { failf(data, "nghttp2_submit_settings() failed: %s(%d)", nghttp2_strerror(rv), rv); return CURLE_HTTP2; } } #ifdef NGHTTP2_HAS_SET_LOCAL_WINDOW_SIZE rv = nghttp2_session_set_local_window_size(httpc->h2, NGHTTP2_FLAG_NONE, 0, HTTP2_HUGE_WINDOW_SIZE); if(rv != 0) { failf(data, "nghttp2_session_set_local_window_size() failed: %s(%d)", nghttp2_strerror(rv), rv); return CURLE_HTTP2; } #endif /* we are going to copy mem to httpc->inbuf. This is required since mem is part of buffer pointed by stream->mem, and callbacks called by nghttp2_session_mem_recv() will write stream specific data into stream->mem, overwriting data already there. */ if(H2_BUFSIZE < nread) { failf(data, "connection buffer size is too small to store data following " "HTTP Upgrade response header: buflen=%zu, datalen=%zu", H2_BUFSIZE, nread); return CURLE_HTTP2; } infof(conn->data, "Copying HTTP/2 data in stream buffer to connection buffer" " after upgrade: len=%zu\n", nread); if(nread) memcpy(httpc->inbuf, mem, nread); httpc->inbuflen = nread; nproc = nghttp2_session_mem_recv(httpc->h2, (const uint8_t *)httpc->inbuf, httpc->inbuflen); if(nghttp2_is_fatal((int)nproc)) { failf(data, "nghttp2_session_mem_recv() failed: %s(%d)", nghttp2_strerror((int)nproc), (int)nproc); return CURLE_HTTP2; } H2BUGF(infof(data, "nghttp2_session_mem_recv() returns %zd\n", nproc)); if((ssize_t)nread == nproc) { httpc->inbuflen = 0; httpc->nread_inbuf = 0; } else { httpc->nread_inbuf += nproc; } /* Try to send some frames since we may read SETTINGS already. */ rv = h2_session_send(data, httpc->h2); if(rv != 0) { failf(data, "nghttp2_session_send() failed: %s(%d)", nghttp2_strerror(rv), rv); return CURLE_HTTP2; } if(should_close_session(httpc)) { H2BUGF(infof(data, "nghttp2_session_send(): nothing to do in this session\n")); return CURLE_HTTP2; } return CURLE_OK; } CURLcode Curl_http2_add_child(struct Curl_easy *parent, struct Curl_easy *child, bool exclusive) { if(parent) { struct Curl_http2_dep **tail; struct Curl_http2_dep *dep = calloc(1, sizeof(struct Curl_http2_dep)); if(!dep) return CURLE_OUT_OF_MEMORY; dep->data = child; if(parent->set.stream_dependents && exclusive) { struct Curl_http2_dep *node = parent->set.stream_dependents; while(node) { node->data->set.stream_depends_on = child; node = node->next; } tail = &child->set.stream_dependents; while(*tail) tail = &(*tail)->next; DEBUGASSERT(!*tail); *tail = parent->set.stream_dependents; parent->set.stream_dependents = 0; } tail = &parent->set.stream_dependents; while(*tail) { (*tail)->data->set.stream_depends_e = FALSE; tail = &(*tail)->next; } DEBUGASSERT(!*tail); *tail = dep; } child->set.stream_depends_on = parent; child->set.stream_depends_e = exclusive; return CURLE_OK; } void Curl_http2_remove_child(struct Curl_easy *parent, struct Curl_easy *child) { struct Curl_http2_dep *last = 0; struct Curl_http2_dep *data = parent->set.stream_dependents; DEBUGASSERT(child->set.stream_depends_on == parent); while(data && data->data != child) { last = data; data = data->next; } DEBUGASSERT(data); if(data) { if(last) { last->next = data->next; } else { parent->set.stream_dependents = data->next; } free(data); } child->set.stream_depends_on = 0; child->set.stream_depends_e = FALSE; } void Curl_http2_cleanup_dependencies(struct Curl_easy *data) { while(data->set.stream_dependents) { struct Curl_easy *tmp = data->set.stream_dependents->data; Curl_http2_remove_child(data, tmp); if(data->set.stream_depends_on) Curl_http2_add_child(data->set.stream_depends_on, tmp, FALSE); } if(data->set.stream_depends_on) Curl_http2_remove_child(data->set.stream_depends_on, data); } /* Only call this function for a transfer that already got a HTTP/2 CURLE_HTTP2_STREAM error! */ bool Curl_h2_http_1_1_error(struct connectdata *conn) { struct http_conn *httpc = &conn->proto.httpc; return (httpc->error_code == NGHTTP2_HTTP_1_1_REQUIRED); } #else /* !USE_NGHTTP2 */ /* Satisfy external references even if http2 is not compiled in. */ #define CURL_DISABLE_TYPECHECK #include <curl/curl.h> char *curl_pushheader_bynum(struct curl_pushheaders *h, size_t num) { (void) h; (void) num; return NULL; } char *curl_pushheader_byname(struct curl_pushheaders *h, const char *header) { (void) h; (void) header; return NULL; } #endif /* USE_NGHTTP2 */
YifuLiu/AliOS-Things
components/curl/lib/http2.c
C
apache-2.0
75,665
#ifndef HEADER_CURL_HTTP2_H #define HEADER_CURL_HTTP2_H /*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2019, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "curl_setup.h" #ifdef USE_NGHTTP2 #include "http.h" /* value for MAX_CONCURRENT_STREAMS we use until we get an updated setting from the peer */ #define DEFAULT_MAX_CONCURRENT_STREAMS 13 /* * Store nghttp2 version info in this buffer, Prefix with a space. Return * total length written. */ int Curl_http2_ver(char *p, size_t len); const char *Curl_http2_strerror(uint32_t err); CURLcode Curl_http2_init(struct connectdata *conn); void Curl_http2_init_state(struct UrlState *state); void Curl_http2_init_userset(struct UserDefined *set); CURLcode Curl_http2_send_request(struct connectdata *conn); CURLcode Curl_http2_request_upgrade(Curl_send_buffer *req, struct connectdata *conn); CURLcode Curl_http2_setup(struct connectdata *conn); CURLcode Curl_http2_switched(struct connectdata *conn, const char *data, size_t nread); /* called from Curl_http_setup_conn */ void Curl_http2_setup_conn(struct connectdata *conn); void Curl_http2_setup_req(struct Curl_easy *data); void Curl_http2_done(struct connectdata *conn, bool premature); CURLcode Curl_http2_done_sending(struct connectdata *conn); CURLcode Curl_http2_add_child(struct Curl_easy *parent, struct Curl_easy *child, bool exclusive); void Curl_http2_remove_child(struct Curl_easy *parent, struct Curl_easy *child); void Curl_http2_cleanup_dependencies(struct Curl_easy *data); /* returns true if the HTTP/2 stream error was HTTP_1_1_REQUIRED */ bool Curl_h2_http_1_1_error(struct connectdata *conn); #else /* USE_NGHTTP2 */ #define Curl_http2_send_request(x) CURLE_UNSUPPORTED_PROTOCOL #define Curl_http2_request_upgrade(x,y) CURLE_UNSUPPORTED_PROTOCOL #define Curl_http2_setup(x) CURLE_UNSUPPORTED_PROTOCOL #define Curl_http2_switched(x,y,z) CURLE_UNSUPPORTED_PROTOCOL #define Curl_http2_setup_conn(x) Curl_nop_stmt #define Curl_http2_setup_req(x) #define Curl_http2_init_state(x) #define Curl_http2_init_userset(x) #define Curl_http2_done(x,y) #define Curl_http2_done_sending(x) #define Curl_http2_add_child(x, y, z) #define Curl_http2_remove_child(x, y) #define Curl_http2_cleanup_dependencies(x) #define Curl_h2_http_1_1_error(x) 0 #endif #endif /* HEADER_CURL_HTTP2_H */
YifuLiu/AliOS-Things
components/curl/lib/http2.h
C
apache-2.0
3,391
/*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2018, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "curl_setup.h" #ifndef CURL_DISABLE_HTTP #include "urldata.h" /* it includes http_chunks.h */ #include "sendf.h" /* for the client write stuff */ #include "content_encoding.h" #include "http.h" #include "non-ascii.h" /* for Curl_convert_to_network prototype */ #include "strtoofft.h" #include "warnless.h" /* The last #include files should be: */ #include "curl_memory.h" #include "memdebug.h" /* * Chunk format (simplified): * * <HEX SIZE>[ chunk extension ] CRLF * <DATA> CRLF * * Highlights from RFC2616 section 3.6 say: The chunked encoding modifies the body of a message in order to transfer it as a series of chunks, each with its own size indicator, followed by an OPTIONAL trailer containing entity-header fields. This allows dynamically produced content to be transferred along with the information necessary for the recipient to verify that it has received the full message. Chunked-Body = *chunk last-chunk trailer CRLF chunk = chunk-size [ chunk-extension ] CRLF chunk-data CRLF chunk-size = 1*HEX last-chunk = 1*("0") [ chunk-extension ] CRLF chunk-extension= *( ";" chunk-ext-name [ "=" chunk-ext-val ] ) chunk-ext-name = token chunk-ext-val = token | quoted-string chunk-data = chunk-size(OCTET) trailer = *(entity-header CRLF) The chunk-size field is a string of hex digits indicating the size of the chunk. The chunked encoding is ended by any chunk whose size is zero, followed by the trailer, which is terminated by an empty line. */ #ifdef CURL_DOES_CONVERSIONS /* Check for an ASCII hex digit. We avoid the use of ISXDIGIT to accommodate non-ASCII hosts. */ static bool Curl_isxdigit_ascii(char digit) { return (digit >= 0x30 && digit <= 0x39) /* 0-9 */ || (digit >= 0x41 && digit <= 0x46) /* A-F */ || (digit >= 0x61 && digit <= 0x66); /* a-f */ } #else #define Curl_isxdigit_ascii(x) Curl_isxdigit(x) #endif void Curl_httpchunk_init(struct connectdata *conn) { struct Curl_chunker *chunk = &conn->chunk; chunk->hexindex = 0; /* start at 0 */ chunk->dataleft = 0; /* no data left yet! */ chunk->state = CHUNK_HEX; /* we get hex first! */ } /* * chunk_read() returns a OK for normal operations, or a positive return code * for errors. STOP means this sequence of chunks is complete. The 'wrote' * argument is set to tell the caller how many bytes we actually passed to the * client (for byte-counting and whatever). * * The states and the state-machine is further explained in the header file. * * This function always uses ASCII hex values to accommodate non-ASCII hosts. * For example, 0x0d and 0x0a are used instead of '\r' and '\n'. */ CHUNKcode Curl_httpchunk_read(struct connectdata *conn, char *datap, ssize_t datalen, ssize_t *wrotep) { CURLcode result = CURLE_OK; struct Curl_easy *data = conn->data; struct Curl_chunker *ch = &conn->chunk; struct SingleRequest *k = &data->req; size_t piece; curl_off_t length = (curl_off_t)datalen; size_t *wrote = (size_t *)wrotep; *wrote = 0; /* nothing's written yet */ /* the original data is written to the client, but we go on with the chunk read process, to properly calculate the content length*/ if(data->set.http_te_skip && !k->ignorebody) { result = Curl_client_write(conn, CLIENTWRITE_BODY, datap, datalen); if(result) return CHUNKE_WRITE_ERROR; } while(length) { switch(ch->state) { case CHUNK_HEX: if(Curl_isxdigit_ascii(*datap)) { if(ch->hexindex < MAXNUM_SIZE) { ch->hexbuffer[ch->hexindex] = *datap; datap++; length--; ch->hexindex++; } else { return CHUNKE_TOO_LONG_HEX; /* longer hex than we support */ } } else { char *endptr; if(0 == ch->hexindex) /* This is illegal data, we received junk where we expected a hexadecimal digit. */ return CHUNKE_ILLEGAL_HEX; /* length and datap are unmodified */ ch->hexbuffer[ch->hexindex] = 0; /* convert to host encoding before calling strtoul */ result = Curl_convert_from_network(conn->data, ch->hexbuffer, ch->hexindex); if(result) { /* Curl_convert_from_network calls failf if unsuccessful */ /* Treat it as a bad hex character */ return CHUNKE_ILLEGAL_HEX; } if(curlx_strtoofft(ch->hexbuffer, &endptr, 16, &ch->datasize)) return CHUNKE_ILLEGAL_HEX; ch->state = CHUNK_LF; /* now wait for the CRLF */ } break; case CHUNK_LF: /* waiting for the LF after a chunk size */ if(*datap == 0x0a) { /* we're now expecting data to come, unless size was zero! */ if(0 == ch->datasize) { ch->state = CHUNK_TRAILER; /* now check for trailers */ conn->trlPos = 0; } else ch->state = CHUNK_DATA; } datap++; length--; break; case CHUNK_DATA: /* We expect 'datasize' of data. We have 'length' right now, it can be more or less than 'datasize'. Get the smallest piece. */ piece = curlx_sotouz((ch->datasize >= length)?length:ch->datasize); /* Write the data portion available */ if(!conn->data->set.http_te_skip && !k->ignorebody) { if(!conn->data->set.http_ce_skip && k->writer_stack) result = Curl_unencode_write(conn, k->writer_stack, datap, piece); else result = Curl_client_write(conn, CLIENTWRITE_BODY, datap, piece); if(result) return CHUNKE_WRITE_ERROR; } *wrote += piece; ch->datasize -= piece; /* decrease amount left to expect */ datap += piece; /* move read pointer forward */ length -= piece; /* decrease space left in this round */ if(0 == ch->datasize) /* end of data this round, we now expect a trailing CRLF */ ch->state = CHUNK_POSTLF; break; case CHUNK_POSTLF: if(*datap == 0x0a) { /* The last one before we go back to hex state and start all over. */ Curl_httpchunk_init(conn); /* sets state back to CHUNK_HEX */ } else if(*datap != 0x0d) return CHUNKE_BAD_CHUNK; datap++; length--; break; case CHUNK_TRAILER: if((*datap == 0x0d) || (*datap == 0x0a)) { /* this is the end of a trailer, but if the trailer was zero bytes there was no trailer and we move on */ if(conn->trlPos) { /* we allocate trailer with 3 bytes extra room to fit this */ conn->trailer[conn->trlPos++] = 0x0d; conn->trailer[conn->trlPos++] = 0x0a; conn->trailer[conn->trlPos] = 0; /* Convert to host encoding before calling Curl_client_write */ result = Curl_convert_from_network(conn->data, conn->trailer, conn->trlPos); if(result) /* Curl_convert_from_network calls failf if unsuccessful */ /* Treat it as a bad chunk */ return CHUNKE_BAD_CHUNK; if(!data->set.http_te_skip) { result = Curl_client_write(conn, CLIENTWRITE_HEADER, conn->trailer, conn->trlPos); if(result) return CHUNKE_WRITE_ERROR; } conn->trlPos = 0; ch->state = CHUNK_TRAILER_CR; if(*datap == 0x0a) /* already on the LF */ break; } else { /* no trailer, we're on the final CRLF pair */ ch->state = CHUNK_TRAILER_POSTCR; break; /* don't advance the pointer */ } } else { /* conn->trailer is assumed to be freed in url.c on a connection basis */ if(conn->trlPos >= conn->trlMax) { /* we always allocate three extra bytes, just because when the full header has been received we append CRLF\0 */ char *ptr; if(conn->trlMax) { conn->trlMax *= 2; ptr = realloc(conn->trailer, conn->trlMax + 3); } else { conn->trlMax = 128; ptr = malloc(conn->trlMax + 3); } if(!ptr) return CHUNKE_OUT_OF_MEMORY; conn->trailer = ptr; } conn->trailer[conn->trlPos++]=*datap; } datap++; length--; break; case CHUNK_TRAILER_CR: if(*datap == 0x0a) { ch->state = CHUNK_TRAILER_POSTCR; datap++; length--; } else return CHUNKE_BAD_CHUNK; break; case CHUNK_TRAILER_POSTCR: /* We enter this state when a CR should arrive so we expect to have to first pass a CR before we wait for LF */ if((*datap != 0x0d) && (*datap != 0x0a)) { /* not a CR then it must be another header in the trailer */ ch->state = CHUNK_TRAILER; break; } if(*datap == 0x0d) { /* skip if CR */ datap++; length--; } /* now wait for the final LF */ ch->state = CHUNK_STOP; break; case CHUNK_STOP: if(*datap == 0x0a) { length--; /* Record the length of any data left in the end of the buffer even if there's no more chunks to read */ ch->dataleft = curlx_sotouz(length); return CHUNKE_STOP; /* return stop */ } else return CHUNKE_BAD_CHUNK; } } return CHUNKE_OK; } const char *Curl_chunked_strerror(CHUNKcode code) { switch(code) { default: return "OK"; case CHUNKE_TOO_LONG_HEX: return "Too long hexadecimal number"; case CHUNKE_ILLEGAL_HEX: return "Illegal or missing hexadecimal sequence"; case CHUNKE_BAD_CHUNK: return "Malformed encoding found"; case CHUNKE_WRITE_ERROR: return "Write error"; case CHUNKE_BAD_ENCODING: return "Bad content-encoding found"; case CHUNKE_OUT_OF_MEMORY: return "Out of memory"; } } #endif /* CURL_DISABLE_HTTP */
YifuLiu/AliOS-Things
components/curl/lib/http_chunks.c
C
apache-2.0
11,394
#ifndef HEADER_CURL_HTTP_CHUNKS_H #define HEADER_CURL_HTTP_CHUNKS_H /*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2014, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ /* * The longest possible hexadecimal number we support in a chunked transfer. * Weird enough, RFC2616 doesn't set a maximum size! Since we use strtoul() * to convert it, we "only" support 2^32 bytes chunk data. */ #define MAXNUM_SIZE 16 typedef enum { /* await and buffer all hexadecimal digits until we get one that isn't a hexadecimal digit. When done, we go CHUNK_LF */ CHUNK_HEX, /* wait for LF, ignore all else */ CHUNK_LF, /* We eat the amount of data specified. When done, we move on to the POST_CR state. */ CHUNK_DATA, /* POSTLF should get a CR and then a LF and nothing else, then move back to HEX as the CRLF combination marks the end of a chunk. A missing CR is no big deal. */ CHUNK_POSTLF, /* Used to mark that we're out of the game. NOTE: that there's a 'dataleft' field in the struct that will tell how many bytes that were not passed to the client in the end of the last buffer! */ CHUNK_STOP, /* At this point optional trailer headers can be found, unless the next line is CRLF */ CHUNK_TRAILER, /* A trailer CR has been found - next state is CHUNK_TRAILER_POSTCR. Next char must be a LF */ CHUNK_TRAILER_CR, /* A trailer LF must be found now, otherwise CHUNKE_BAD_CHUNK will be signalled If this is an empty trailer CHUNKE_STOP will be signalled. Otherwise the trailer will be broadcasted via Curl_client_write() and the next state will be CHUNK_TRAILER */ CHUNK_TRAILER_POSTCR } ChunkyState; typedef enum { CHUNKE_STOP = -1, CHUNKE_OK = 0, CHUNKE_TOO_LONG_HEX = 1, CHUNKE_ILLEGAL_HEX, CHUNKE_BAD_CHUNK, CHUNKE_WRITE_ERROR, CHUNKE_BAD_ENCODING, CHUNKE_OUT_OF_MEMORY, CHUNKE_LAST } CHUNKcode; const char *Curl_chunked_strerror(CHUNKcode code); struct Curl_chunker { char hexbuffer[ MAXNUM_SIZE + 1]; int hexindex; ChunkyState state; curl_off_t datasize; size_t dataleft; /* untouched data amount at the end of the last buffer */ }; #endif /* HEADER_CURL_HTTP_CHUNKS_H */
YifuLiu/AliOS-Things
components/curl/lib/http_chunks.h
C
apache-2.0
3,116
/*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2019, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "curl_setup.h" #if !defined(CURL_DISABLE_HTTP) && !defined(CURL_DISABLE_CRYPTO_AUTH) #include "urldata.h" #include "strcase.h" #include "vauth/vauth.h" #include "http_digest.h" /* The last 3 #include files should be in this order */ #include "curl_printf.h" #include "curl_memory.h" #include "memdebug.h" /* Test example headers: WWW-Authenticate: Digest realm="testrealm", nonce="1053604598" Proxy-Authenticate: Digest realm="testrealm", nonce="1053604598" */ CURLcode Curl_input_digest(struct connectdata *conn, bool proxy, const char *header) /* rest of the *-authenticate: header */ { struct Curl_easy *data = conn->data; /* Point to the correct struct with this */ struct digestdata *digest; if(proxy) { digest = &data->state.proxydigest; } else { digest = &data->state.digest; } if(!checkprefix("Digest", header)) return CURLE_BAD_CONTENT_ENCODING; header += strlen("Digest"); while(*header && ISSPACE(*header)) header++; return Curl_auth_decode_digest_http_message(header, digest); } CURLcode Curl_output_digest(struct connectdata *conn, bool proxy, const unsigned char *request, const unsigned char *uripath) { CURLcode result; struct Curl_easy *data = conn->data; unsigned char *path = NULL; char *tmp = NULL; char *response; size_t len; bool have_chlg; /* Point to the address of the pointer that holds the string to send to the server, which is for a plain host or for a HTTP proxy */ char **allocuserpwd; /* Point to the name and password for this */ const char *userp; const char *passwdp; /* Point to the correct struct with this */ struct digestdata *digest; struct auth *authp; if(proxy) { digest = &data->state.proxydigest; allocuserpwd = &conn->allocptr.proxyuserpwd; userp = conn->http_proxy.user; passwdp = conn->http_proxy.passwd; authp = &data->state.authproxy; } else { digest = &data->state.digest; allocuserpwd = &conn->allocptr.userpwd; userp = conn->user; passwdp = conn->passwd; authp = &data->state.authhost; } Curl_safefree(*allocuserpwd); /* not set means empty */ if(!userp) userp = ""; if(!passwdp) passwdp = ""; #if defined(USE_WINDOWS_SSPI) have_chlg = digest->input_token ? TRUE : FALSE; #else have_chlg = digest->nonce ? TRUE : FALSE; #endif if(!have_chlg) { authp->done = FALSE; return CURLE_OK; } /* So IE browsers < v7 cut off the URI part at the query part when they evaluate the MD5 and some (IIS?) servers work with them so we may need to do the Digest IE-style. Note that the different ways cause different MD5 sums to get sent. Apache servers can be set to do the Digest IE-style automatically using the BrowserMatch feature: https://httpd.apache.org/docs/2.2/mod/mod_auth_digest.html#msie Further details on Digest implementation differences: http://www.fngtps.com/2006/09/http-authentication */ if(authp->iestyle) { tmp = strchr((char *)uripath, '?'); if(tmp) { size_t urilen = tmp - (char *)uripath; path = (unsigned char *) aprintf("%.*s", urilen, uripath); } } if(!tmp) path = (unsigned char *) strdup((char *) uripath); if(!path) return CURLE_OUT_OF_MEMORY; result = Curl_auth_create_digest_http_message(data, userp, passwdp, request, path, digest, &response, &len); free(path); if(result) return result; *allocuserpwd = aprintf("%sAuthorization: Digest %s\r\n", proxy ? "Proxy-" : "", response); free(response); if(!*allocuserpwd) return CURLE_OUT_OF_MEMORY; authp->done = TRUE; return CURLE_OK; } void Curl_http_auth_cleanup_digest(struct Curl_easy *data) { Curl_auth_digest_cleanup(&data->state.digest); Curl_auth_digest_cleanup(&data->state.proxydigest); } #endif
YifuLiu/AliOS-Things
components/curl/lib/http_digest.c
C
apache-2.0
5,141
#ifndef HEADER_CURL_HTTP_DIGEST_H #define HEADER_CURL_HTTP_DIGEST_H /*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2019, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "curl_setup.h" #if !defined(CURL_DISABLE_HTTP) && !defined(CURL_DISABLE_CRYPTO_AUTH) /* this is for digest header input */ CURLcode Curl_input_digest(struct connectdata *conn, bool proxy, const char *header); /* this is for creating digest header output */ CURLcode Curl_output_digest(struct connectdata *conn, bool proxy, const unsigned char *request, const unsigned char *uripath); void Curl_http_auth_cleanup_digest(struct Curl_easy *data); #endif /* !CURL_DISABLE_HTTP && !CURL_DISABLE_CRYPTO_AUTH */ #endif /* HEADER_CURL_HTTP_DIGEST_H */
YifuLiu/AliOS-Things
components/curl/lib/http_digest.h
C
apache-2.0
1,764
/*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2019, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "curl_setup.h" #if !defined(CURL_DISABLE_HTTP) && defined(USE_SPNEGO) #include "urldata.h" #include "sendf.h" #include "http_negotiate.h" #include "vauth/vauth.h" /* The last 3 #include files should be in this order */ #include "curl_printf.h" #include "curl_memory.h" #include "memdebug.h" CURLcode Curl_input_negotiate(struct connectdata *conn, bool proxy, const char *header) { CURLcode result; struct Curl_easy *data = conn->data; size_t len; /* Point to the username, password, service and host */ const char *userp; const char *passwdp; const char *service; const char *host; /* Point to the correct struct with this */ struct negotiatedata *neg_ctx; curlnegotiate state; if(proxy) { userp = conn->http_proxy.user; passwdp = conn->http_proxy.passwd; service = data->set.str[STRING_PROXY_SERVICE_NAME] ? data->set.str[STRING_PROXY_SERVICE_NAME] : "HTTP"; host = conn->http_proxy.host.name; neg_ctx = &conn->proxyneg; state = conn->proxy_negotiate_state; } else { userp = conn->user; passwdp = conn->passwd; service = data->set.str[STRING_SERVICE_NAME] ? data->set.str[STRING_SERVICE_NAME] : "HTTP"; host = conn->host.name; neg_ctx = &conn->negotiate; state = conn->http_negotiate_state; } /* Not set means empty */ if(!userp) userp = ""; if(!passwdp) passwdp = ""; /* Obtain the input token, if any */ header += strlen("Negotiate"); while(*header && ISSPACE(*header)) header++; len = strlen(header); neg_ctx->havenegdata = len != 0; if(!len) { if(state == GSS_AUTHSUCC) { infof(conn->data, "Negotiate auth restarted\n"); Curl_http_auth_cleanup_negotiate(conn); } else if(state != GSS_AUTHNONE) { /* The server rejected our authentication and hasn't supplied any more negotiation mechanisms */ Curl_http_auth_cleanup_negotiate(conn); return CURLE_LOGIN_DENIED; } } /* Supports SSL channel binding for Windows ISS extended protection */ #if defined(USE_WINDOWS_SSPI) && defined(SECPKG_ATTR_ENDPOINT_BINDINGS) neg_ctx->sslContext = conn->sslContext; #endif /* Initialize the security context and decode our challenge */ result = Curl_auth_decode_spnego_message(data, userp, passwdp, service, host, header, neg_ctx); if(result) Curl_http_auth_cleanup_negotiate(conn); return result; } CURLcode Curl_output_negotiate(struct connectdata *conn, bool proxy) { struct negotiatedata *neg_ctx = proxy ? &conn->proxyneg : &conn->negotiate; struct auth *authp = proxy ? &conn->data->state.authproxy : &conn->data->state.authhost; curlnegotiate *state = proxy ? &conn->proxy_negotiate_state : &conn->http_negotiate_state; char *base64 = NULL; size_t len = 0; char *userp; CURLcode result; authp->done = FALSE; if(*state == GSS_AUTHRECV) { if(neg_ctx->havenegdata) { neg_ctx->havemultiplerequests = TRUE; } } else if(*state == GSS_AUTHSUCC) { if(!neg_ctx->havenoauthpersist) { neg_ctx->noauthpersist = !neg_ctx->havemultiplerequests; } } if(neg_ctx->noauthpersist || (*state != GSS_AUTHDONE && *state != GSS_AUTHSUCC)) { if(neg_ctx->noauthpersist && *state == GSS_AUTHSUCC) { infof(conn->data, "Curl_output_negotiate, " "no persistent authentication: cleanup existing context"); Curl_http_auth_cleanup_negotiate(conn); } if(!neg_ctx->context) { result = Curl_input_negotiate(conn, proxy, "Negotiate"); if(result == CURLE_LOGIN_DENIED) { /* negotiate auth failed, let's continue unauthenticated to stay * compatible with the behavior before curl-7_64_0-158-g6c6035532 */ conn->data->state.authproblem = TRUE; return CURLE_OK; } else if(result) return result; } result = Curl_auth_create_spnego_message(conn->data, neg_ctx, &base64, &len); if(result) return result; userp = aprintf("%sAuthorization: Negotiate %s\r\n", proxy ? "Proxy-" : "", base64); if(proxy) { Curl_safefree(conn->allocptr.proxyuserpwd); conn->allocptr.proxyuserpwd = userp; } else { Curl_safefree(conn->allocptr.userpwd); conn->allocptr.userpwd = userp; } free(base64); if(userp == NULL) { return CURLE_OUT_OF_MEMORY; } *state = GSS_AUTHSENT; #ifdef HAVE_GSSAPI if(neg_ctx->status == GSS_S_COMPLETE || neg_ctx->status == GSS_S_CONTINUE_NEEDED) { *state = GSS_AUTHDONE; } #else #ifdef USE_WINDOWS_SSPI if(neg_ctx->status == SEC_E_OK || neg_ctx->status == SEC_I_CONTINUE_NEEDED) { *state = GSS_AUTHDONE; } #endif #endif } if(*state == GSS_AUTHDONE || *state == GSS_AUTHSUCC) { /* connection is already authenticated, * don't send a header in future requests */ authp->done = TRUE; } neg_ctx->havenegdata = FALSE; return CURLE_OK; } void Curl_http_auth_cleanup_negotiate(struct connectdata *conn) { conn->http_negotiate_state = GSS_AUTHNONE; conn->proxy_negotiate_state = GSS_AUTHNONE; Curl_auth_cleanup_spnego(&conn->negotiate); Curl_auth_cleanup_spnego(&conn->proxyneg); } #endif /* !CURL_DISABLE_HTTP && USE_SPNEGO */
YifuLiu/AliOS-Things
components/curl/lib/http_negotiate.c
C
apache-2.0
6,397
#ifndef HEADER_CURL_HTTP_NEGOTIATE_H #define HEADER_CURL_HTTP_NEGOTIATE_H /*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2019, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #if !defined(CURL_DISABLE_HTTP) && defined(USE_SPNEGO) /* this is for Negotiate header input */ CURLcode Curl_input_negotiate(struct connectdata *conn, bool proxy, const char *header); /* this is for creating Negotiate header output */ CURLcode Curl_output_negotiate(struct connectdata *conn, bool proxy); void Curl_http_auth_cleanup_negotiate(struct connectdata *conn); #endif /* !CURL_DISABLE_HTTP && USE_SPNEGO */ #endif /* HEADER_CURL_HTTP_NEGOTIATE_H */
YifuLiu/AliOS-Things
components/curl/lib/http_negotiate.h
C
apache-2.0
1,595