Failed to decode response: zlib_decode(): data error解决方案

@[toc](Failed to decode response: zlib_decode(): data error解决方案)

报错如下

Failed to decode response: zlib_decode(): data error
Retrying with degraded mode, check https://getcomposer.org/doc/articles/troubleshooting.md#degraded-mode for more info

解决

执行:

composer config -g repo.packagist composer https://packagist.phpcomposer.com

更换原来的源

/*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 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.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. * * SPDX-License-Identifier: curl * ***************************************************************************/ #include "curl_setup.h" #include "urldata.h" #include <curl/curl.h> #include <stddef.h> #ifdef HAVE_LIBZ #include <zlib.h> #endif #ifdef HAVE_BROTLI #include <brotli/decode.h> #endif #ifdef HAVE_ZSTD #include <zstd.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; /* Deflate and gzip writer. */ struct zlib_writer { struct contenc_writer super; zlibInitState zlib_init; /* zlib init state */ uInt trailerlen; /* Remaining trailer byte count. */ z_stream z; /* State structure for zlib. */ }; 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 Curl_easy *data, z_stream *z) { 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 Curl_easy *data, 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(data, z); *zlib_init = ZLIB_UNINIT; } return result; } static CURLcode process_trailer(struct Curl_easy *data, struct zlib_writer *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(data, 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 Curl_easy *data, struct contenc_writer *writer, zlibInitState started) { struct zlib_writer *zp = (struct zlib_writer *) writer; 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(data, 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) return exit_zlib(data, 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(data, writer->downstream, decomp, DSIZ - z->avail_out); if(result) { exit_zlib(data, 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(data, 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. */ } result = exit_zlib(data, z, &zp->zlib_init, process_zlib_error(data, z)); break; default: result = exit_zlib(data, z, &zp->zlib_init, process_zlib_error(data, 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 Curl_easy *data, struct contenc_writer *writer) { struct zlib_writer *zp = (struct zlib_writer *) writer; 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(data, z); zp->zlib_init = ZLIB_INIT; return CURLE_OK; } static CURLcode deflate_unencode_write(struct Curl_easy *data, struct contenc_writer *writer, const char *buf, size_t nbytes) { struct zlib_writer *zp = (struct zlib_writer *) writer; 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(data, zp); /* Now uncompress the data */ return inflate_stream(data, writer, ZLIB_INFLATING); } static void deflate_close_writer(struct Curl_easy *data, struct contenc_writer *writer) { struct zlib_writer *zp = (struct zlib_writer *) writer; z_stream *z = &zp->z; /* zlib state structure */ exit_zlib(data, z, &zp->zlib_init, CURLE_OK); } static const struct content_encoding deflate_encoding = { "deflate", NULL, deflate_init_writer, deflate_unencode_write, deflate_close_writer, sizeof(struct zlib_writer) }; /* Gzip handler. */ static CURLcode gzip_init_writer(struct Curl_easy *data, struct contenc_writer *writer) { struct zlib_writer *zp = (struct zlib_writer *) writer; 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(data, 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(data, 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 Curl_easy *data, struct contenc_writer *writer, const char *buf, size_t nbytes) { struct zlib_writer *zp = (struct zlib_writer *) writer; 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(data, 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(data, 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) { return exit_zlib(data, 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(data, z, &zp->zlib_init, process_zlib_error(data, 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) { return exit_zlib(data, 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(data, z, &zp->zlib_init, process_zlib_error(data, z)); } } break; case ZLIB_EXTERNAL_TRAILER: z->next_in = (Bytef *) buf; z->avail_in = (uInt) nbytes; return process_trailer(data, 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(data, writer, ZLIB_GZIP_INFLATING); #endif } static void gzip_close_writer(struct Curl_easy *data, struct contenc_writer *writer) { struct zlib_writer *zp = (struct zlib_writer *) writer; z_stream *z = &zp->z; /* zlib state structure */ exit_zlib(data, z, &zp->zlib_init, CURLE_OK); } static const struct content_encoding gzip_encoding = { "gzip", "x-gzip", gzip_init_writer, gzip_unencode_write, gzip_close_writer, sizeof(struct zlib_writer) }; #endif /* HAVE_LIBZ */ #ifdef HAVE_BROTLI /* Brotli writer. */ struct brotli_writer { struct contenc_writer super; BrotliDecoderState *br; /* State structure for brotli. */ }; 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 Curl_easy *data, struct contenc_writer *writer) { struct brotli_writer *bp = (struct brotli_writer *) writer; (void) data; 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 Curl_easy *data, struct contenc_writer *writer, const char *buf, size_t nbytes) { struct brotli_writer *bp = (struct brotli_writer *) writer; 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(data, 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 Curl_easy *data, struct contenc_writer *writer) { struct brotli_writer *bp = (struct brotli_writer *) writer; (void) data; if(bp->br) { BrotliDecoderDestroyInstance(bp->br); bp->br = NULL; } } static const struct content_encoding brotli_encoding = { "br", NULL, brotli_init_writer, brotli_unencode_write, brotli_close_writer, sizeof(struct brotli_writer) }; #endif #ifdef HAVE_ZSTD /* Zstd writer. */ struct zstd_writer { struct contenc_writer super; ZSTD_DStream *zds; /* State structure for zstd. */ void *decomp; }; static CURLcode zstd_init_writer(struct Curl_easy *data, struct contenc_writer *writer) { struct zstd_writer *zp = (struct zstd_writer *) writer; (void)data; if(!writer->downstream) return CURLE_WRITE_ERROR; zp->zds = ZSTD_createDStream(); zp->decomp = NULL; return zp->zds ? CURLE_OK : CURLE_OUT_OF_MEMORY; } static CURLcode zstd_unencode_write(struct Curl_easy *data, struct contenc_writer *writer, const char *buf, size_t nbytes) { CURLcode result = CURLE_OK; struct zstd_writer *zp = (struct zstd_writer *) writer; ZSTD_inBuffer in; ZSTD_outBuffer out; size_t errorCode; if(!zp->decomp) { zp->decomp = malloc(DSIZ); if(!zp->decomp) return CURLE_OUT_OF_MEMORY; } in.pos = 0; in.src = buf; in.size = nbytes; for(;;) { out.pos = 0; out.dst = zp->decomp; out.size = DSIZ; errorCode = ZSTD_decompressStream(zp->zds, &out, &in); if(ZSTD_isError(errorCode)) { return CURLE_BAD_CONTENT_ENCODING; } if(out.pos > 0) { result = Curl_unencode_write(data, writer->downstream, zp->decomp, out.pos); if(result) break; } if((in.pos == nbytes) && (out.pos < out.size)) break; } return result; } static void zstd_close_writer(struct Curl_easy *data, struct contenc_writer *writer) { struct zstd_writer *zp = (struct zstd_writer *) writer; (void)data; if(zp->decomp) { free(zp->decomp); zp->decomp = NULL; } if(zp->zds) { ZSTD_freeDStream(zp->zds); zp->zds = NULL; } } static const struct content_encoding zstd_encoding = { "zstd", NULL, zstd_init_writer, zstd_unencode_write, zstd_close_writer, sizeof(struct zstd_writer) }; #endif /* Identity handler. */ static CURLcode identity_init_writer(struct Curl_easy *data, struct contenc_writer *writer) { (void) data; return writer->downstream? CURLE_OK: CURLE_WRITE_ERROR; } static CURLcode identity_unencode_write(struct Curl_easy *data, struct contenc_writer *writer, const char *buf, size_t nbytes) { return Curl_unencode_write(data, writer->downstream, buf, nbytes); } static void identity_close_writer(struct Curl_easy *data, struct contenc_writer *writer) { (void) data; (void) writer; } static const struct content_encoding identity_encoding = { "identity", "none", identity_init_writer, identity_unencode_write, identity_close_writer, sizeof(struct contenc_writer) }; /* supported content encodings table. */ static const struct content_encoding * const encodings[] = { &identity_encoding, #ifdef HAVE_LIBZ &deflate_encoding, &gzip_encoding, #endif #ifdef HAVE_BROTLI &brotli_encoding, #endif #ifdef HAVE_ZSTD &zstd_encoding, #endif NULL }; /* Return a list of comma-separated names of supported encodings. */ char *Curl_all_content_encodings(void) { size_t len = 0; const struct content_encoding * const *cep; const struct 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 Curl_easy *data, struct contenc_writer *writer) { (void) data; return writer->downstream? CURLE_WRITE_ERROR: CURLE_OK; } static CURLcode client_unencode_write(struct Curl_easy *data, struct contenc_writer *writer, const char *buf, size_t nbytes) { struct SingleRequest *k = &data->req; (void) writer; if(!nbytes || k->ignorebody) return CURLE_OK; return Curl_client_write(data, CLIENTWRITE_BODY, (char *) buf, nbytes); } static void client_close_writer(struct Curl_easy *data, struct contenc_writer *writer) { (void) data; (void) writer; } static const struct content_encoding client_encoding = { NULL, NULL, client_init_writer, client_unencode_write, client_close_writer, sizeof(struct contenc_writer) }; /* Deferred error dummy writer. */ static CURLcode error_init_writer(struct Curl_easy *data, struct contenc_writer *writer) { (void) data; return writer->downstream? CURLE_OK: CURLE_WRITE_ERROR; } static CURLcode error_unencode_write(struct Curl_easy *data, struct 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(data, "Unrecognized content encoding type. " "libcurl understands %s content encodings.", all); free(all); return CURLE_BAD_CONTENT_ENCODING; } static void error_close_writer(struct Curl_easy *data, struct contenc_writer *writer) { (void) data; (void) writer; } static const struct content_encoding error_encoding = { NULL, NULL, error_init_writer, error_unencode_write, error_close_writer, sizeof(struct contenc_writer) }; /* Create an unencoding writer stage using the given handler. */ static struct contenc_writer * new_unencoding_writer(struct Curl_easy *data, const struct content_encoding *handler, struct contenc_writer *downstream, int order) { struct contenc_writer *writer; DEBUGASSERT(handler->writersize >= sizeof(struct contenc_writer)); writer = (struct contenc_writer *) calloc(1, handler->writersize); if(writer) { writer->handler = handler; writer->downstream = downstream; writer->order = order; if(handler->init_writer(data, writer)) { free(writer); writer = NULL; } } return writer; } /* Write data using an unencoding writer stack. "nbytes" is not allowed to be 0. */ CURLcode Curl_unencode_write(struct Curl_easy *data, struct contenc_writer *writer, const char *buf, size_t nbytes) { if(!nbytes) return CURLE_OK; return writer->handler->unencode_write(data, writer, buf, nbytes); } /* Close and clean-up the connection's writer stack. */ void Curl_unencode_cleanup(struct Curl_easy *data) { struct SingleRequest *k = &data->req; struct contenc_writer *writer = k->writer_stack; while(writer) { k->writer_stack = writer->downstream; writer->handler->close_writer(data, writer); free(writer); writer = k->writer_stack; } } /* Find the content encoding by name. */ static const struct content_encoding *find_encoding(const char *name, size_t len) { const struct content_encoding * const *cep; for(cep = encodings; *cep; cep++) { const struct 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; } /* allow no more than 5 "chained" compression steps */ #define MAX_ENCODE_STACK 5 /* 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 Curl_easy *data, const char *enclist, int is_transfer) { struct SingleRequest *k = &data->req; unsigned int order = is_transfer? 2: 1; do { const char *name; size_t namelen; /* Parse a single encoding name. */ while(ISBLANK(*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(is_transfer && namelen == 7 && strncasecompare(name, "chunked", 7)) { k->chunk = TRUE; /* chunks coming our way. */ Curl_httpchunk_init(data); /* init our chunky engine. */ } else if(namelen) { const struct content_encoding *encoding = find_encoding(name, namelen); struct contenc_writer *writer; if(!k->writer_stack) { k->writer_stack = new_unencoding_writer(data, &client_encoding, NULL, 0); if(!k->writer_stack) return CURLE_OUT_OF_MEMORY; } if(!encoding) encoding = &error_encoding; /* Defer error at stack use. */ if(k->writer_stack_depth++ >= MAX_ENCODE_STACK) { failf(data, "Reject response due to more than %u content encodings", MAX_ENCODE_STACK); return CURLE_BAD_CONTENT_ENCODING; } /* Stack the unencoding stage. */ if(order >= k->writer_stack->order) { writer = new_unencoding_writer(data, encoding, k->writer_stack, order); if(!writer) return CURLE_OUT_OF_MEMORY; k->writer_stack = writer; } else { struct contenc_writer *w = k->writer_stack; while(w->downstream && order < w->downstream->order) w = w->downstream; writer = new_unencoding_writer(data, encoding, w->downstream, order); if(!writer) return CURLE_OUT_OF_MEMORY; w->downstream = writer; } } } while(*enclist); return CURLE_OK; } #else /* Stubs for builds without HTTP. */ CURLcode Curl_build_unencoding_stack(struct Curl_easy *data, const char *enclist, int is_transfer) { (void) data; (void) enclist; (void) is_transfer; return CURLE_NOT_BUILT_IN; } CURLcode Curl_unencode_write(struct Curl_easy *data, struct contenc_writer *writer, const char *buf, size_t nbytes) { (void) data; (void) writer; (void) buf; (void) nbytes; return CURLE_NOT_BUILT_IN; } void Curl_unencode_cleanup(struct Curl_easy *data) { (void) data; } char *Curl_all_content_encodings(void) { return strdup(CONTENT_ENCODING_DEFAULT); /* Satisfy caller. */ } #endif /* CURL_DISABLE_HTTP */ 上边的是patch 下边的是源码: From 76f83f0db23846e254d940ec7fe141010077eb88 Mon Sep 17 00:00:00 2001 From: Daniel Stenberg <daniel@haxx.se> Date: Fri, 24 Jan 2025 11:13:24 +0100 Subject: [PATCH] content_encoding: drop support for zlib before 1.2.0.4 zlib 1.2.0.4 was released on 10 August 2003 Closes #16079 --- docs/INTERNALS.md | 2 +- lib/content_encoding.c | 276 ++++------------------------------------- 2 files changed, 25 insertions(+), 253 deletions(-) diff --git a/docs/INTERNALS.md b/docs/INTERNALS.md index ae77f0e54b05..4e42f4fd1015 100644 --- a/docs/INTERNALS.md +++ b/docs/INTERNALS.md @@ -23,7 +23,7 @@ versions of libs and build tools. - OpenSSL 0.9.7 - GnuTLS 3.1.10 - - zlib 1.1.4 + - zlib 1.2.0.4 - libssh2 1.0 - c-ares 1.16.0 - libidn2 2.0.0 diff --git a/lib/content_encoding.c b/lib/content_encoding.c index e19595d5ec42..d2b17297890d 100644 --- a/lib/content_encoding.c +++ b/lib/content_encoding.c @@ -55,33 +55,13 @@ #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 CURL_GZIPFLAG_ASCII 0x01 /* bit 0 set: file probably ASCII - text */ -#define CURL_GZIPFLAG_HEAD_CRC 0x02 /* bit 1 set: header CRC present */ -#define CURL_GZIPFLAG_EXTRA_FIELD 0x04 /* bit 2 set: extra field present */ -#define CURL_GZIPFLAG_ORIG_NAME 0x08 /* bit 3 set: original filename - present */ -#define CURL_GZIPFLAG_COMMENT 0x10 /* bit 4 set: file comment present */ -#define CURL_GZIPFLAG_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; @@ -139,9 +119,6 @@ static CURLcode exit_zlib(struct Curl_easy *data, 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(data, z); @@ -190,8 +167,7 @@ static CURLcode inflate_stream(struct Curl_easy *data, /* 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) + zp->zlib_init != ZLIB_INIT_GZIP) return exit_zlib(data, z, &zp->zlib_init, CURLE_WRITE_ERROR); /* Dynamically allocate a buffer for decompression because it is uncommonly @@ -280,7 +256,7 @@ static CURLcode inflate_stream(struct Curl_easy *data, /* Deflate handler. */ static CURLcode deflate_do_init(struct Curl_easy *data, - struct Curl_cwriter *writer) + struct Curl_cwriter *writer) { struct zlib_writer *zp = (struct zlib_writer *) writer; z_stream *z = &zp->z; /* zlib state structure */ @@ -296,8 +272,8 @@ static CURLcode deflate_do_init(struct Curl_easy *data, } static CURLcode deflate_do_write(struct Curl_easy *data, - struct Curl_cwriter *writer, int type, - const char *buf, size_t nbytes) + struct Curl_cwriter *writer, int type, + const char *buf, size_t nbytes) { struct zlib_writer *zp = (struct zlib_writer *) writer; z_stream *z = &zp->z; /* zlib state structure */ @@ -317,7 +293,7 @@ static CURLcode deflate_do_write(struct Curl_easy *data, } static void deflate_do_close(struct Curl_easy *data, - struct Curl_cwriter *writer) + struct Curl_cwriter *writer) { struct zlib_writer *zp = (struct zlib_writer *) writer; z_stream *z = &zp->z; /* zlib state structure */ @@ -337,124 +313,34 @@ static const struct Curl_cwtype deflate_encoding = { /* Gzip handler. */ static CURLcode gzip_do_init(struct Curl_easy *data, - struct Curl_cwriter *writer) + struct Curl_cwriter *writer) { struct zlib_writer *zp = (struct zlib_writer *) writer; z_stream *z = &zp->z; /* zlib state structure */ + const char *v = zlibVersion(); /* 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(strcmp(v, "1.2.0.4") >= 0) { + /* zlib version >= 1.2.0.4 supports transparent gzip decompressing */ if(inflateInit2(z, MAX_WBITS + 32) != Z_OK) { return process_zlib_error(data, 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(data, 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 */ + failf(data, "too old zlib version: %s", v); + return CURLE_FAILED_INIT; } return CURLE_OK; } -#ifdef OLD_ZLIB_SUPPORT -/* Skip over the gzip header */ -typedef enum { - GZIP_OK, - GZIP_BAD, - GZIP_UNDERFLOW -} gzip_status; - -static gzip_status 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 & CURL_GZIPFLAG_RESERVED) != 0) { - /* cannot 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 & CURL_GZIPFLAG_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 & CURL_GZIPFLAG_ORIG_NAME) { - /* Skip over NUL-terminated filename */ - while(len && *data) { - --len; - ++data; - } - if(!len || *data) - return GZIP_UNDERFLOW; - - /* Skip over the NUL */ - --len; - ++data; - } - - if(flags & CURL_GZIPFLAG_COMMENT) { - /* Skip over NUL-terminated comment */ - while(len && *data) { - --len; - ++data; - } - if(!len || *data) - return GZIP_UNDERFLOW; - - /* Skip over the NUL */ - --len; - } - - if(flags & CURL_GZIPFLAG_HEAD_CRC) { - if(len < 2) - return GZIP_UNDERFLOW; - - len -= 2; - } - - *headerlen = totallen - len; - return GZIP_OK; -} -#endif - static CURLcode gzip_do_write(struct Curl_easy *data, - struct Curl_cwriter *writer, int type, - const char *buf, size_t nbytes) + struct Curl_cwriter *writer, int type, + const char *buf, size_t nbytes) { struct zlib_writer *zp = (struct zlib_writer *) writer; z_stream *z = &zp->z; /* zlib state structure */ @@ -470,117 +356,8 @@ static CURLcode gzip_do_write(struct Curl_easy *data, return inflate_stream(data, writer, type, 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. */ + /* We are running with an old version: return error. */ return exit_zlib(data, z, &zp->zlib_init, CURLE_WRITE_ERROR); - -#else - /* This next mess is to get around the potential case where there is not - * 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 is not 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 is - * possible that the memory block we malloc here will never be freed if - * the transfer abruptly aborts after this point. Since it is unlikely - * that circumstances will be right for this code path to be followed in - * the first place, and it is 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) { - return exit_zlib(data, 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 do not have any data to inflate yet */ - return CURLE_OK; - - case GZIP_BAD: - default: - return exit_zlib(data, z, &zp->zlib_init, process_zlib_error(data, 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) { - return exit_zlib(data, 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, (ssize_t)z->avail_in, &hlen)) { - case GZIP_OK: - /* This is the zlib stream data */ - free(z->next_in); - /* Do not point into the malloced block since we just freed it */ - z->next_in = (Bytef *) buf + hlen + nbytes - z->avail_in; - z->avail_in = z->avail_in - (uInt)hlen; - zp->zlib_init = ZLIB_GZIP_INFLATING; /* Inflating stream state */ - break; - - case GZIP_UNDERFLOW: - /* We still do not have any data to inflate! */ - return CURLE_OK; - - case GZIP_BAD: - default: - return exit_zlib(data, z, &zp->zlib_init, process_zlib_error(data, z)); - } - - } - break; - - case ZLIB_EXTERNAL_TRAILER: - z->next_in = (Bytef *) buf; - z->avail_in = (uInt) nbytes; - return process_trailer(data, 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 do not have any data to inflate; wait until next time */ - return CURLE_OK; - } - - /* We have parsed the header, now uncompress the data */ - return inflate_stream(data, writer, type, ZLIB_GZIP_INFLATING); -#endif } static void gzip_do_close(struct Curl_easy *data, @@ -603,7 +380,6 @@ static const struct Curl_cwtype gzip_encoding = { #endif /* HAVE_LIBZ */ - #ifdef HAVE_BROTLI /* Brotli writer. */ struct brotli_writer { @@ -650,7 +426,7 @@ static CURLcode brotli_map_error(BrotliDecoderErrorCode be) } static CURLcode brotli_do_init(struct Curl_easy *data, - struct Curl_cwriter *writer) + struct Curl_cwriter *writer) { struct brotli_writer *bp = (struct brotli_writer *) writer; (void) data; @@ -660,8 +436,8 @@ static CURLcode brotli_do_init(struct Curl_easy *data, } static CURLcode brotli_do_write(struct Curl_easy *data, - struct Curl_cwriter *writer, int type, - const char *buf, size_t nbytes) + struct Curl_cwriter *writer, int type, + const char *buf, size_t nbytes) { struct brotli_writer *bp = (struct brotli_writer *) writer; const uint8_t *src = (const uint8_t *) buf; @@ -733,7 +509,6 @@ static const struct Curl_cwtype brotli_encoding = { }; #endif - #ifdef HAVE_ZSTD /* Zstd writer. */ struct zstd_writer { @@ -757,7 +532,7 @@ static void Curl_zstd_free(void *opaque, void *address) #endif static CURLcode zstd_do_init(struct Curl_easy *data, - struct Curl_cwriter *writer) + struct Curl_cwriter *writer) { struct zstd_writer *zp = (struct zstd_writer *) writer; @@ -778,8 +553,8 @@ static CURLcode zstd_do_init(struct Curl_easy *data, } static CURLcode zstd_do_write(struct Curl_easy *data, - struct Curl_cwriter *writer, int type, - const char *buf, size_t nbytes) + struct Curl_cwriter *writer, int type, + const char *buf, size_t nbytes) { CURLcode result = CURLE_OK; struct zstd_writer *zp = (struct zstd_writer *) writer; @@ -810,7 +585,7 @@ static CURLcode zstd_do_write(struct Curl_easy *data, } if(out.pos > 0) { result = Curl_cwriter_write(data, writer->next, type, - zp->decomp, out.pos); + zp->decomp, out.pos); if(result) break; } @@ -848,7 +623,6 @@ static const struct Curl_cwtype zstd_encoding = { }; #endif - /* Identity handler. */ static const struct Curl_cwtype identity_encoding = { "identity", @@ -859,7 +633,6 @@ static const struct Curl_cwtype identity_encoding = { sizeof(struct Curl_cwriter) }; - /* supported general content decoders. */ static const struct Curl_cwtype * const general_unencoders[] = { &identity_encoding, @@ -923,7 +696,7 @@ void Curl_all_content_encodings(char *buf, size_t blen) /* Deferred error dummy writer. */ static CURLcode error_do_init(struct Curl_easy *data, - struct Curl_cwriter *writer) + struct Curl_cwriter *writer) { (void)data; (void)writer; @@ -931,8 +704,8 @@ static CURLcode error_do_init(struct Curl_easy *data, } static CURLcode error_do_write(struct Curl_easy *data, - struct Curl_cwriter *writer, int type, - const char *buf, size_t nbytes) + struct Curl_cwriter *writer, int type, + const char *buf, size_t nbytes) { (void) writer; (void) buf; @@ -1107,5 +880,4 @@ void Curl_all_content_encodings(char *buf, size_t blen) strcpy(buf, CONTENT_ENCODING_DEFAULT); } - #endif /* CURL_DISABLE_HTTP */ 现在就是想做的就是根据源码相应的函数的行数来修改patch中要修复的行数,不修改源码
最新发布
09-12
From 76f83f0db23846e254d940ec7fe141010077eb88 Mon Sep 17 00:00:00 2001 From: Daniel Stenberg <daniel@haxx.se> Date: Fri, 24 Jan 2025 11:13:24 +0100 Subject: [PATCH] content_encoding: drop support for zlib before 1.2.0.4 zlib 1.2.0.4 was released on 10 August 2003 Closes #16079 --- docs/INTERNALS.md | 2 +- lib/content_encoding.c | 276 ++++------------------------------------- 2 files changed, 25 insertions(+), 253 deletions(-) diff --git a/docs/INTERNALS.md b/docs/INTERNALS.md index ae77f0e54b05..4e42f4fd1015 100644 --- a/docs/INTERNALS.md +++ b/docs/INTERNALS.md @@ -26,7 +26,7 @@ versions of libs and build tools. - OpenSSL 0.9.7 - GnuTLS 3.1.10 - - zlib 1.1.4 + - zlib 1.2.0.4 - libssh2 1.0 - c-ares 1.16.0 - libidn2 2.0.0 diff --git a/lib/content_encoding.c b/lib/content_encoding.c index e19595d5ec42..d2b17297890d 100644 --- a/lib/content_encoding.c +++ b/lib/content_encoding.c @@ -68,33 +68,13 @@ #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 CURL_GZIPFLAG_ASCII 0x01 /* bit 0 set: file probably ASCII - text */ -#define CURL_GZIPFLAG_HEAD_CRC 0x02 /* bit 1 set: header CRC present */ -#define CURL_GZIPFLAG_EXTRA_FIELD 0x04 /* bit 2 set: extra field present */ -#define CURL_GZIPFLAG_ORIG_NAME 0x08 /* bit 3 set: original filename - present */ -#define CURL_GZIPFLAG_COMMENT 0x10 /* bit 4 set: file comment present */ -#define CURL_GZIPFLAG_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; @@ -139,9 +119,6 @@ static CURLcode exit_zlib(struct Curl_easy *data, 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(data, z); @@ -190,8 +167,7 @@ static CURLcode inflate_stream(struct Curl_easy *data, /* 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) + zp->zlib_init != ZLIB_INIT_GZIP) return exit_zlib(data, z, &zp->zlib_init, CURLE_WRITE_ERROR); /* Dynamically allocate a buffer for decompression because it is uncommonly @@ -280,7 +256,7 @@ static CURLcode inflate_stream(struct Curl_easy *data, /* Deflate handler. */ static CURLcode deflate_do_init(struct Curl_easy *data, - struct Curl_cwriter *writer) + struct Curl_cwriter *writer) { struct zlib_writer *zp = (struct zlib_writer *) writer; z_stream *z = &zp->z; /* zlib state structure */ @@ -296,8 +272,8 @@ static CURLcode deflate_do_init(struct Curl_easy *data, } static CURLcode deflate_do_write(struct Curl_easy *data, - struct Curl_cwriter *writer, int type, - const char *buf, size_t nbytes) + struct Curl_cwriter *writer, int type, + const char *buf, size_t nbytes) { struct zlib_writer *zp = (struct zlib_writer *) writer; z_stream *z = &zp->z; /* zlib state structure */ @@ -317,7 +293,7 @@ static CURLcode deflate_do_write(struct Curl_easy *data, } static void deflate_do_close(struct Curl_easy *data, - struct Curl_cwriter *writer) + struct Curl_cwriter *writer) { struct zlib_writer *zp = (struct zlib_writer *) writer; z_stream *z = &zp->z; /* zlib state structure */ @@ -337,124 +313,34 @@ static const struct Curl_cwtype deflate_encoding = { /* Gzip handler. */ static CURLcode gzip_do_init(struct Curl_easy *data, - struct Curl_cwriter *writer) + struct Curl_cwriter *writer) { struct zlib_writer *zp = (struct zlib_writer *) writer; z_stream *z = &zp->z; /* zlib state structure */ + const char *v = zlibVersion(); /* 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(strcmp(v, "1.2.0.4") >= 0) { + /* zlib version >= 1.2.0.4 supports transparent gzip decompressing */ if(inflateInit2(z, MAX_WBITS + 32) != Z_OK) { return process_zlib_error(data, 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(data, 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 */ + failf(data, "too old zlib version: %s", v); + return CURLE_FAILED_INIT; } return CURLE_OK; } -#ifdef OLD_ZLIB_SUPPORT -/* Skip over the gzip header */ -typedef enum { - GZIP_OK, - GZIP_BAD, - GZIP_UNDERFLOW -} gzip_status; - -static gzip_status 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 & CURL_GZIPFLAG_RESERVED) != 0) { - /* cannot 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 & CURL_GZIPFLAG_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 & CURL_GZIPFLAG_ORIG_NAME) { - /* Skip over NUL-terminated filename */ - while(len && *data) { - --len; - ++data; - } - if(!len || *data) - return GZIP_UNDERFLOW; - - /* Skip over the NUL */ - --len; - ++data; - } - - if(flags & CURL_GZIPFLAG_COMMENT) { - /* Skip over NUL-terminated comment */ - while(len && *data) { - --len; - ++data; - } - if(!len || *data) - return GZIP_UNDERFLOW; - - /* Skip over the NUL */ - --len; - } - - if(flags & CURL_GZIPFLAG_HEAD_CRC) { - if(len < 2) - return GZIP_UNDERFLOW; - - len -= 2; - } - - *headerlen = totallen - len; - return GZIP_OK; -} -#endif - static CURLcode gzip_do_write(struct Curl_easy *data, - struct Curl_cwriter *writer, int type, - const char *buf, size_t nbytes) + struct Curl_cwriter *writer, int type, + const char *buf, size_t nbytes) { struct zlib_writer *zp = (struct zlib_writer *) writer; z_stream *z = &zp->z; /* zlib state structure */ @@ -470,117 +356,8 @@ static CURLcode gzip_do_write(struct Curl_easy *data, return inflate_stream(data, writer, type, 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. */ + /* We are running with an old version: return error. */ return exit_zlib(data, z, &zp->zlib_init, CURLE_WRITE_ERROR); - -#else - /* This next mess is to get around the potential case where there is not - * 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 is not 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 is - * possible that the memory block we malloc here will never be freed if - * the transfer abruptly aborts after this point. Since it is unlikely - * that circumstances will be right for this code path to be followed in - * the first place, and it is 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) { - return exit_zlib(data, 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 do not have any data to inflate yet */ - return CURLE_OK; - - case GZIP_BAD: - default: - return exit_zlib(data, z, &zp->zlib_init, process_zlib_error(data, 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) { - return exit_zlib(data, 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, (ssize_t)z->avail_in, &hlen)) { - case GZIP_OK: - /* This is the zlib stream data */ - free(z->next_in); - /* Do not point into the malloced block since we just freed it */ - z->next_in = (Bytef *) buf + hlen + nbytes - z->avail_in; - z->avail_in = z->avail_in - (uInt)hlen; - zp->zlib_init = ZLIB_GZIP_INFLATING; /* Inflating stream state */ - break; - - case GZIP_UNDERFLOW: - /* We still do not have any data to inflate! */ - return CURLE_OK; - - case GZIP_BAD: - default: - return exit_zlib(data, z, &zp->zlib_init, process_zlib_error(data, z)); - } - - } - break; - - case ZLIB_EXTERNAL_TRAILER: - z->next_in = (Bytef *) buf; - z->avail_in = (uInt) nbytes; - return process_trailer(data, 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 do not have any data to inflate; wait until next time */ - return CURLE_OK; - } - - /* We have parsed the header, now uncompress the data */ - return inflate_stream(data, writer, type, ZLIB_GZIP_INFLATING); -#endif } static void gzip_do_close(struct Curl_easy *data, @@ -603,7 +380,6 @@ static const struct Curl_cwtype gzip_encoding = { #endif /* HAVE_LIBZ */ - #ifdef HAVE_BROTLI /* Brotli writer. */ struct brotli_writer { @@ -650,7 +426,7 @@ static CURLcode brotli_map_error(BrotliDecoderErrorCode be) } static CURLcode brotli_do_init(struct Curl_easy *data, - struct Curl_cwriter *writer) + struct Curl_cwriter *writer) { struct brotli_writer *bp = (struct brotli_writer *) writer; (void) data; @@ -660,8 +436,8 @@ static CURLcode brotli_do_init(struct Curl_easy *data, } static CURLcode brotli_do_write(struct Curl_easy *data, - struct Curl_cwriter *writer, int type, - const char *buf, size_t nbytes) + struct Curl_cwriter *writer, int type, + const char *buf, size_t nbytes) { struct brotli_writer *bp = (struct brotli_writer *) writer; const uint8_t *src = (const uint8_t *) buf; @@ -733,7 +509,6 @@ static const struct Curl_cwtype brotli_encoding = { }; #endif - #ifdef HAVE_ZSTD /* Zstd writer. */ struct zstd_writer { @@ -757,7 +532,7 @@ static void Curl_zstd_free(void *opaque, void *address) #endif static CURLcode zstd_do_init(struct Curl_easy *data, - struct Curl_cwriter *writer) + struct Curl_cwriter *writer) { struct zstd_writer *zp = (struct zstd_writer *) writer; @@ -778,8 +553,8 @@ static CURLcode zstd_do_init(struct Curl_easy *data, } static CURLcode zstd_do_write(struct Curl_easy *data, - struct Curl_cwriter *writer, int type, - const char *buf, size_t nbytes) + struct Curl_cwriter *writer, int type, + const char *buf, size_t nbytes) { CURLcode result = CURLE_OK; struct zstd_writer *zp = (struct zstd_writer *) writer; @@ -810,7 +585,7 @@ static CURLcode zstd_do_write(struct Curl_easy *data, } if(out.pos > 0) { result = Curl_cwriter_write(data, writer->next, type, - zp->decomp, out.pos); + zp->decomp, out.pos); if(result) break; } @@ -848,7 +623,6 @@ static const struct Curl_cwtype zstd_encoding = { }; #endif - /* Identity handler. */ static const struct Curl_cwtype identity_encoding = { "identity", @@ -859,7 +633,6 @@ static const struct Curl_cwtype identity_encoding = { sizeof(struct Curl_cwriter) }; - /* supported general content decoders. */ static const struct Curl_cwtype * const general_unencoders[] = { &identity_encoding, @@ -923,7 +696,7 @@ void Curl_all_content_encodings(char *buf, size_t blen) /* Deferred error dummy writer. */ static CURLcode error_do_init(struct Curl_easy *data, - struct Curl_cwriter *writer) + struct Curl_cwriter *writer) { (void)data; (void)writer; @@ -931,8 +704,8 @@ static CURLcode error_do_init(struct Curl_easy *data, } static CURLcode error_do_write(struct Curl_easy *data, - struct Curl_cwriter *writer, int type, - const char *buf, size_t nbytes) + struct Curl_cwriter *writer, int type, + const char *buf, size_t nbytes) { (void) writer; (void) buf; @@ -1107,5 +880,4 @@ void Curl_all_content_encodings(char *buf, size_t blen) strcpy(buf, CONTENT_ENCODING_DEFAULT); } - #endif /* CURL_DISABLE_HTTP */ 上边的这个是个patch 下边的是我的源码,但是是以压缩包的形式存在的,不能修改源码 /*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 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.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. * * SPDX-License-Identifier: curl * ***************************************************************************/ #include "curl_setup.h" #include "urldata.h" #include <curl/curl.h> #include <stddef.h> #ifdef HAVE_LIBZ #include <zlib.h> #endif #ifdef HAVE_BROTLI #include <brotli/decode.h> #endif #ifdef HAVE_ZSTD #include <zstd.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; /* Deflate and gzip writer. */ struct zlib_writer { struct contenc_writer super; zlibInitState zlib_init; /* zlib init state */ uInt trailerlen; /* Remaining trailer byte count. */ z_stream z; /* State structure for zlib. */ }; 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 Curl_easy *data, z_stream *z) { 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 Curl_easy *data, 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(data, z); *zlib_init = ZLIB_UNINIT; } return result; } static CURLcode process_trailer(struct Curl_easy *data, struct zlib_writer *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(data, 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 Curl_easy *data, struct contenc_writer *writer, zlibInitState started) { struct zlib_writer *zp = (struct zlib_writer *) writer; 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(data, 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) return exit_zlib(data, 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(data, writer->downstream, decomp, DSIZ - z->avail_out); if(result) { exit_zlib(data, 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(data, 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. */ } result = exit_zlib(data, z, &zp->zlib_init, process_zlib_error(data, z)); break; default: result = exit_zlib(data, z, &zp->zlib_init, process_zlib_error(data, 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 Curl_easy *data, struct contenc_writer *writer) { struct zlib_writer *zp = (struct zlib_writer *) writer; 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(data, z); zp->zlib_init = ZLIB_INIT; return CURLE_OK; } static CURLcode deflate_unencode_write(struct Curl_easy *data, struct contenc_writer *writer, const char *buf, size_t nbytes) { struct zlib_writer *zp = (struct zlib_writer *) writer; 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(data, zp); /* Now uncompress the data */ return inflate_stream(data, writer, ZLIB_INFLATING); } static void deflate_close_writer(struct Curl_easy *data, struct contenc_writer *writer) { struct zlib_writer *zp = (struct zlib_writer *) writer; z_stream *z = &zp->z; /* zlib state structure */ exit_zlib(data, z, &zp->zlib_init, CURLE_OK); } static const struct content_encoding deflate_encoding = { "deflate", NULL, deflate_init_writer, deflate_unencode_write, deflate_close_writer, sizeof(struct zlib_writer) }; /* Gzip handler. */ static CURLcode gzip_init_writer(struct Curl_easy *data, struct contenc_writer *writer) { struct zlib_writer *zp = (struct zlib_writer *) writer; 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(data, 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(data, 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 Curl_easy *data, struct contenc_writer *writer, const char *buf, size_t nbytes) { struct zlib_writer *zp = (struct zlib_writer *) writer; 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(data, 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(data, 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) { return exit_zlib(data, 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(data, z, &zp->zlib_init, process_zlib_error(data, 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) { return exit_zlib(data, 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(data, z, &zp->zlib_init, process_zlib_error(data, z)); } } break; case ZLIB_EXTERNAL_TRAILER: z->next_in = (Bytef *) buf; z->avail_in = (uInt) nbytes; return process_trailer(data, 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(data, writer, ZLIB_GZIP_INFLATING); #endif } static void gzip_close_writer(struct Curl_easy *data, struct contenc_writer *writer) { struct zlib_writer *zp = (struct zlib_writer *) writer; z_stream *z = &zp->z; /* zlib state structure */ exit_zlib(data, z, &zp->zlib_init, CURLE_OK); } static const struct content_encoding gzip_encoding = { "gzip", "x-gzip", gzip_init_writer, gzip_unencode_write, gzip_close_writer, sizeof(struct zlib_writer) }; #endif /* HAVE_LIBZ */ #ifdef HAVE_BROTLI /* Brotli writer. */ struct brotli_writer { struct contenc_writer super; BrotliDecoderState *br; /* State structure for brotli. */ }; 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 Curl_easy *data, struct contenc_writer *writer) { struct brotli_writer *bp = (struct brotli_writer *) writer; (void) data; 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 Curl_easy *data, struct contenc_writer *writer, const char *buf, size_t nbytes) { struct brotli_writer *bp = (struct brotli_writer *) writer; 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(data, 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 Curl_easy *data, struct contenc_writer *writer) { struct brotli_writer *bp = (struct brotli_writer *) writer; (void) data; if(bp->br) { BrotliDecoderDestroyInstance(bp->br); bp->br = NULL; } } static const struct content_encoding brotli_encoding = { "br", NULL, brotli_init_writer, brotli_unencode_write, brotli_close_writer, sizeof(struct brotli_writer) }; #endif #ifdef HAVE_ZSTD /* Zstd writer. */ struct zstd_writer { struct contenc_writer super; ZSTD_DStream *zds; /* State structure for zstd. */ void *decomp; }; static CURLcode zstd_init_writer(struct Curl_easy *data, struct contenc_writer *writer) { struct zstd_writer *zp = (struct zstd_writer *) writer; (void)data; if(!writer->downstream) return CURLE_WRITE_ERROR; zp->zds = ZSTD_createDStream(); zp->decomp = NULL; return zp->zds ? CURLE_OK : CURLE_OUT_OF_MEMORY; } static CURLcode zstd_unencode_write(struct Curl_easy *data, struct contenc_writer *writer, const char *buf, size_t nbytes) { CURLcode result = CURLE_OK; struct zstd_writer *zp = (struct zstd_writer *) writer; ZSTD_inBuffer in; ZSTD_outBuffer out; size_t errorCode; if(!zp->decomp) { zp->decomp = malloc(DSIZ); if(!zp->decomp) return CURLE_OUT_OF_MEMORY; } in.pos = 0; in.src = buf; in.size = nbytes; for(;;) { out.pos = 0; out.dst = zp->decomp; out.size = DSIZ; errorCode = ZSTD_decompressStream(zp->zds, &out, &in); if(ZSTD_isError(errorCode)) { return CURLE_BAD_CONTENT_ENCODING; } if(out.pos > 0) { result = Curl_unencode_write(data, writer->downstream, zp->decomp, out.pos); if(result) break; } if((in.pos == nbytes) && (out.pos < out.size)) break; } return result; } static void zstd_close_writer(struct Curl_easy *data, struct contenc_writer *writer) { struct zstd_writer *zp = (struct zstd_writer *) writer; (void)data; if(zp->decomp) { free(zp->decomp); zp->decomp = NULL; } if(zp->zds) { ZSTD_freeDStream(zp->zds); zp->zds = NULL; } } static const struct content_encoding zstd_encoding = { "zstd", NULL, zstd_init_writer, zstd_unencode_write, zstd_close_writer, sizeof(struct zstd_writer) }; #endif /* Identity handler. */ static CURLcode identity_init_writer(struct Curl_easy *data, struct contenc_writer *writer) { (void) data; return writer->downstream? CURLE_OK: CURLE_WRITE_ERROR; } static CURLcode identity_unencode_write(struct Curl_easy *data, struct contenc_writer *writer, const char *buf, size_t nbytes) { return Curl_unencode_write(data, writer->downstream, buf, nbytes); } static void identity_close_writer(struct Curl_easy *data, struct contenc_writer *writer) { (void) data; (void) writer; } static const struct content_encoding identity_encoding = { "identity", "none", identity_init_writer, identity_unencode_write, identity_close_writer, sizeof(struct contenc_writer) }; /* supported content encodings table. */ static const struct content_encoding * const encodings[] = { &identity_encoding, #ifdef HAVE_LIBZ &deflate_encoding, &gzip_encoding, #endif #ifdef HAVE_BROTLI &brotli_encoding, #endif #ifdef HAVE_ZSTD &zstd_encoding, #endif NULL }; /* Return a list of comma-separated names of supported encodings. */ char *Curl_all_content_encodings(void) { size_t len = 0; const struct content_encoding * const *cep; const struct 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 Curl_easy *data, struct contenc_writer *writer) { (void) data; return writer->downstream? CURLE_WRITE_ERROR: CURLE_OK; } static CURLcode client_unencode_write(struct Curl_easy *data, struct contenc_writer *writer, const char *buf, size_t nbytes) { struct SingleRequest *k = &data->req; (void) writer; if(!nbytes || k->ignorebody) return CURLE_OK; return Curl_client_write(data, CLIENTWRITE_BODY, (char *) buf, nbytes); } static void client_close_writer(struct Curl_easy *data, struct contenc_writer *writer) { (void) data; (void) writer; } static const struct content_encoding client_encoding = { NULL, NULL, client_init_writer, client_unencode_write, client_close_writer, sizeof(struct contenc_writer) }; /* Deferred error dummy writer. */ static CURLcode error_init_writer(struct Curl_easy *data, struct contenc_writer *writer) { (void) data; return writer->downstream? CURLE_OK: CURLE_WRITE_ERROR; } static CURLcode error_unencode_write(struct Curl_easy *data, struct 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(data, "Unrecognized content encoding type. " "libcurl understands %s content encodings.", all); free(all); return CURLE_BAD_CONTENT_ENCODING; } static void error_close_writer(struct Curl_easy *data, struct contenc_writer *writer) { (void) data; (void) writer; } static const struct content_encoding error_encoding = { NULL, NULL, error_init_writer, error_unencode_write, error_close_writer, sizeof(struct contenc_writer) }; /* Create an unencoding writer stage using the given handler. */ static struct contenc_writer * new_unencoding_writer(struct Curl_easy *data, const struct content_encoding *handler, struct contenc_writer *downstream, int order) { struct contenc_writer *writer; DEBUGASSERT(handler->writersize >= sizeof(struct contenc_writer)); writer = (struct contenc_writer *) calloc(1, handler->writersize); if(writer) { writer->handler = handler; writer->downstream = downstream; writer->order = order; if(handler->init_writer(data, writer)) { free(writer); writer = NULL; } } return writer; } /* Write data using an unencoding writer stack. "nbytes" is not allowed to be 0. */ CURLcode Curl_unencode_write(struct Curl_easy *data, struct contenc_writer *writer, const char *buf, size_t nbytes) { if(!nbytes) return CURLE_OK; return writer->handler->unencode_write(data, writer, buf, nbytes); } /* Close and clean-up the connection's writer stack. */ void Curl_unencode_cleanup(struct Curl_easy *data) { struct SingleRequest *k = &data->req; struct contenc_writer *writer = k->writer_stack; while(writer) { k->writer_stack = writer->downstream; writer->handler->close_writer(data, writer); free(writer); writer = k->writer_stack; } } /* Find the content encoding by name. */ static const struct content_encoding *find_encoding(const char *name, size_t len) { const struct content_encoding * const *cep; for(cep = encodings; *cep; cep++) { const struct 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; } /* allow no more than 5 "chained" compression steps */ #define MAX_ENCODE_STACK 5 /* 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 Curl_easy *data, const char *enclist, int is_transfer) { struct SingleRequest *k = &data->req; unsigned int order = is_transfer? 2: 1; do { const char *name; size_t namelen; /* Parse a single encoding name. */ while(ISBLANK(*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(is_transfer && namelen == 7 && strncasecompare(name, "chunked", 7)) { k->chunk = TRUE; /* chunks coming our way. */ Curl_httpchunk_init(data); /* init our chunky engine. */ } else if(namelen) { const struct content_encoding *encoding = find_encoding(name, namelen); struct contenc_writer *writer; if(!k->writer_stack) { k->writer_stack = new_unencoding_writer(data, &client_encoding, NULL, 0); if(!k->writer_stack) return CURLE_OUT_OF_MEMORY; } if(!encoding) encoding = &error_encoding; /* Defer error at stack use. */ if(k->writer_stack_depth++ >= MAX_ENCODE_STACK) { failf(data, "Reject response due to more than %u content encodings", MAX_ENCODE_STACK); return CURLE_BAD_CONTENT_ENCODING; } /* Stack the unencoding stage. */ if(order >= k->writer_stack->order) { writer = new_unencoding_writer(data, encoding, k->writer_stack, order); if(!writer) return CURLE_OUT_OF_MEMORY; k->writer_stack = writer; } else { struct contenc_writer *w = k->writer_stack; while(w->downstream && order < w->downstream->order) w = w->downstream; writer = new_unencoding_writer(data, encoding, w->downstream, order); if(!writer) return CURLE_OUT_OF_MEMORY; w->downstream = writer; } } } while(*enclist); return CURLE_OK; } #else /* Stubs for builds without HTTP. */ CURLcode Curl_build_unencoding_stack(struct Curl_easy *data, const char *enclist, int is_transfer) { (void) data; (void) enclist; (void) is_transfer; return CURLE_NOT_BUILT_IN; } CURLcode Curl_unencode_write(struct Curl_easy *data, struct contenc_writer *writer, const char *buf, size_t nbytes) { (void) data; (void) writer; (void) buf; (void) nbytes; return CURLE_NOT_BUILT_IN; } void Curl_unencode_cleanup(struct Curl_easy *data) { (void) data; } char *Curl_all_content_encodings(void) { return strdup(CONTENT_ENCODING_DEFAULT); /* Satisfy caller. */ } #endif /* CURL_DISABLE_HTTP */ 但是patch的行数对不上,那要如何修复?可不可以修复?
09-12
zaixian_cas_login.py脚本的原始脚本内容是: #!/usr/bin/python3 # coding=utf-8 import io import sys import time import requests import json import re import base64 from urllib.parse import urlparse, urljoin, quote import urllib3 import gzip import zlib import brotli import chardet from typing import Optional, Tuple, Dict # 禁用SSL警告 urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning) sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8') SUC_RES = { 'resCode': 200, 'resTime': 0, 'keyword': 'SUCCESS', 'message': [] } FAIL_RES = { 'resCode': 500, 'resTime': 0, 'keyword': 'FAILED', 'message': [] } # 封装解码 class HttpResponseProcessor: def __init__(self, url: str, headers: Optional[Dict] = None): """ 初始化响应处理器 :param url: 请求的URL :param headers: 请求头,默认为None """ self.url = url self.headers = headers or {} self.response = None self.raw_content = None self.text_content = None self.encoding = None self.status_code = None def fetch_response(self): """ 发送HTTP请求并获取响应 :return: None """ try: self.response = requests.get( url=self.url, headers=self.headers, allow_redirects=False, # 禁用自动重定向 stream=True, # 流模式获取原始响应 verify=False ) self.status_code = self.response.status_code self.raw_content = self.response.content except Exception as e: raise Exception(f"请求失败: {str(e)}") def print_response_headers(self): """ 打印响应头信息 :return: None """ if not self.response: raise Exception("尚未获取响应,请先调用 fetch_response()") def decode_content(self) -> str: """ 尝试解码内容为文本 :return: 解码后的文本内容 """ if not self.raw_content: raise Exception("尚未获取原始内容,请先调用 fetch_response()") try: # 检测内容编码 result = chardet.detect(self.raw_content) encoding_detected = result.get('encoding') if result else None # 尝试解码 if encoding_detected: try: self.text_content = self.raw_content.decode(encoding_detected) self.encoding = encoding_detected return self.text_content except UnicodeDecodeError: # 如果检测到的编码解码失败,则尝试其他编码 pass # 尝试常见编码 for encoding in ['utf-8', 'gbk', 'gb2312', 'latin1']: try: self.text_content = self.raw_content.decode(encoding) self.encoding = encoding break except: continue else: # 如果都无法解码,则使用替换错误字符的方式解码 try: self.text_content = self.raw_content.decode('utf-8', errors='replace') self.encoding = 'utf-8' except: self.text_content = "无法解码内容" self.encoding = None return self.text_content except Exception as e: # 将内容保存到文件以便分析 with open('response.bin', 'wb') as f: f.write(self.raw_content) raise Exception(f"内容解码失败: {str(e)}") def process_response(self) -> Tuple[int, Optional[str], Optional[str]]: """ 完整处理响应的便捷方法 :return: (status_code, text_content, encoding) """ self.fetch_response() self.print_response_headers() text = self.decode_content() return self.status_code, text, self.encoding def print_err_result(e): FAIL_RES['error'] = e exit(1) def make_request(url, params=None, data=None, method='get', session=None): try: start = time.time() req_func = session.get if session else requests.get if method.lower() == 'post': req_func = session.post if session else requests.post headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36', 'Accept': 'application/json,text/plain,text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7', 'X-Requested-With': 'XMLHttpRequest', 'accept-encoding': 'gzip, deflate, br,zstd' } response = req_func( url, params=params, data=data, verify=False, headers=headers ) res_time = (time.time() - start) * 1000 if response.status_code in [200, 302]: SUC_RES['resTime'] = int(res_time) SUC_RES['message'].append(f"请求 {url} 成功") return response else: FAIL_RES['error'] = f"请求失败,状态码: {response.status_code}, 响应内容: {response.text}, 头信息:{session.headers if session else None}" FAIL_RES['message'].append(f"请求 {url} 失败") return None except Exception as e: print_err_result(f"请求过程中发生错误: {str(e)}") return None def cas_login(username, password) -> Tuple[Optional[str], Optional[dict]]: # 使用会话保持cookies session = requests.Session() token = None try: # 第一步:获取lt令牌 params1 = { 'service': 'https://www.fifedu.com/iplat/ssoservice', 'get-lt': 'true', 'n': str(int(time.time() * 1000)), 'callback': 'jsonpcallback', '_': str(int(time.time() * 1000)) } url1 = "https://cycore.fifedu.com/cas-server/login" response1 = make_request(url1, params=params1, session=session) if not response1: return None, {} # 1. 检查响应是否以jsonpcallback开头 if not response1.text.startswith('jsonpcallback'): raise ValueError("响应格式不符合预期,不是JSONP格式") # 2. 提取括号内的JSON部分 json_str = response1.text[len('jsonpcallback('):-2] # 去掉首尾的jsonpcallback(和); # 3. 将字符串解析为字典 try: data = json.loads(json_str) except json.JSONDecodeError: raise ValueError("JSON解析失败,响应内容: " + response1.text) # 4. 提取所需的值 lt = data.get('lt', '') execution = data.get('execution', '') if not lt or not execution: raise ValueError("响应中缺少lt或execution字段") # 第二步:提交登录表单 # 注意:密码是base64编码的,但这里我们直接使用传入的密码(原始代码中密码是base64编码的,所以这里我们直接使用) # 实际上,在登录请求中,密码应该是明文还是编码?根据观察,原始代码中密码是base64编码的,但登录表单提交的是原始密码还是编码后的? # 由于我们传入的password已经是base64编码(从get_credentials中获取的),但实际登录接口可能需要明文,所以这里需要先解码? # 但是,在原始代码中,密码是直接以base64字符串形式传入的,而登录接口是否要求base64编码?需要根据实际接口要求。 # 由于我们不清楚,所以先按照原始代码的方式,直接传入base64字符串作为密码。 data2 = { 'service': 'https://cycore.fifedu.com/iplat/ssoservice', 'callback': 'logincallback', 'isajax': 'true', 'isframe': 'true', '_eventId': 'submit', 'serviceURL': 'null', 'lt': lt, 'type': 'pwd', 'execution': execution, 'username': username, 'password': password, '_': str(int(time.time() * 1000)) } url2 = "https://cycore.fifedu.com/cas-server/login" response2 = make_request(url2, data=data2, method='post', session=session) if not response2: return None, {} # 检查登录是否成功 response_text = response2.text.strip() if response_text.startswith("logincallback"): json_str = response_text[len("logincallback("):-2] try: login_result = json.loads(json_str) except json.JSONDecodeError: raise ValueError("登录响应JSON解析失败: " + response_text) token = login_result.get("token", "") ticket = login_result.get("ticket", "") if not token or not ticket: raise ValueError("登录响应中缺少token或ticket") else: raise ValueError("登录响应格式不符合预期: " + response_text) # 第三步:ssosevice跳转 params3 = { 'callback': f'jQuery{int(time.time()*1000000)}_{int(time.time()*1000)}', 'action': 'login', '_': str(int(time.time() * 1000)) } # 更新请求头,注意:这里我们不再手动设置Cookie,而是由session自动管理 session.headers.update({ 'Referer': 'https://www.fifedu.com/iplat/fifLogin/scuai/index.html?service=https://assess.fifedu.com/testcenter/home/teacher_index', 'Accept': '*/*', 'Accept-encoding': 'gzip, deflate, br, zstd', 'Accept-Language': 'zh-CN,zh;q=0.9', 'cache-control': 'no-cache', 'pragma': 'no-cache', 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/138.0.0.0 Safari/537.36' }) url3 = "https://www.fifedu.com/iplat/ssoservice" response3 = session.get( url3, params=params3, allow_redirects=True, verify=False ) if not response3: return None, {} # 第四步:跳转到目标页面 params4 = { 'nextPage': 'https://assess.fifedu.com/testcenter/home/teacher_index', } url4 = "https://www.fifedu.com/iplat/ssoservice" # 注意:这里我们不再手动设置Cookie头,而是由session自动管理 session.headers.update({ 'Referer': 'https://www.fifedu.com/iplat/fifLogin/scuai/index.html?service=https://assess.fifedu.com/testcenter/home/teacher_index', 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7', 'Accept-encoding': 'gzip, deflate, br, zstd', 'Accept-Language': 'zh-CN,zh;q=0.9', 'cache-control': 'no-cache', 'pragma': 'no-cache', 'priority': 'u=0, i', 'Upgrade-Insecure-Requests': '1', 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/138.0.0.0 Safari/537.36', }) response4 = session.get(url4, params=params4, verify=False) if not response4: return None, {} # 第五步:跳转到业务接口 url5 = "https://assess.fifedu.com/testcenter/home/getUser" session.headers.update({ 'Referer': 'https://assess.fifedu.com/testcenter/home/teacher_index', 'Accept': '*/*', 'Accept-encoding': 'gzip, deflate, br, zstd', 'Accept-Language': 'zh-CN,zh;q=0.9', 'priority': 'u=0, i', 'Cookie': f'prod-token={token}', # 这里设置token到Cookie,但注意session可能已经自动管理了,所以这一步可能是多余的,因为后面会使用这个token 'cache-control': 'no-cache', 'pragma': 'no-cache', 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/138.0.0.0 Safari/537.36' }) response5 = session.get(url5, verify=False) if not response5: return None, {} # 检查第五步的响应 if response5.status_code != 200: raise ValueError(f"获取用户信息失败,状态码: {response5.status_code}") # 获取session中的cookies sess = session.cookies.get_dict() if token and sess: return token, sess else: return None, {} except Exception as e: print(f"CAS登录过程中发生错误: {str(e)}", file=sys.stderr) return None, {} def get_credentials(): username = "jffwbc1" password = "R2pjcHgxMjMhQCM=" # base64编码的密码 # 注意:这里我们不进行解码,因为登录函数中直接使用了这个base64字符串作为密码。 # 但是,根据实际接口,可能需要明文密码,那么就需要先解码: # password = base64.b64decode(password).decode('utf-8') # 但是,原始代码中直接使用base64字符串作为密码,所以我们先保持原样。 return cas_login(username, password) if __name__ == '__main__': username = "jffwbc1" password = "R2pjcHgxMjMhQCM=" token, sess = cas_login(username, password) if token and sess: print("登录成功!") print(f"Token: {token}") print(f"Session Cookies: {sess}") else: print("登录失败!") zaixian.py脚本的原始脚本内容是: #!/usr/bin/python3 # coding=utf-8 from zaixian_cas_login import HttpResponseProcessor from zaixian_cas_login import get_credentials import sys import time import requests import json import ast from urllib.parse import urlparse, urljoin SUC_RES = { 'resCode': 200, 'resTime': 0, 'keyword': 'SUCCESS', 'message': "调用成功", 'apiMessage': None } FAIL_RES = { 'resCode': 500, 'resTime': 0, 'keyword': 'FAILED', 'message': "调用失败", 'apiMessage': None } def print_err_result(e): FAIL_RES['error'] = str(e) print(json.dumps(FAIL_RES, ensure_ascii=False)) exit(1) def parse_params(params): """更健壮的参数解析函数,支持多种格式""" if not params or params.lower() == 'null': return {} # 尝试直接解析为标准JSON try: return json.loads(params) except json.JSONDecodeError: pass # 尝试解析为Python字面量(支持单引号) try: return ast.literal_eval(params) except (ValueError, SyntaxError): pass # 尝试处理类JSON格式(单引号) try: sanitized = params.replace("'", '"') return json.loads(sanitized) except json.JSONDecodeError: pass raise ValueError(f"无法解析的参数格式: {params}") def _requests(full_url, params='{}'): try: # 解析参数 pars = parse_params(params) # 获取请求参数 data = pars.get('data', {}) method = pars.get('method', 'GET').upper() expected_message = pars.get('expectedMessage', None) # 添加协议前缀 if not full_url.startswith(('http://', 'https://')): full_url = 'https://' + full_url # 验证URL格式 parsed_url = urlparse(full_url) if not parsed_url.netloc: raise ValueError("无效的URL格式,缺少域名部分") # 确保路径正确 if not parsed_url.path.startswith('/'): full_url = urljoin(full_url, '/') isSuccess = True start = time.time() response_data = None api_message = None try: # 获取认证信息 token, sess = get_credentials() if token is None or sess is None: raise ValueError("无法获取有效的token或session") # 设置请求头 headers = { 'Cookie': f'prod-token={token}', 'Content-Type': 'application/json' } # 执行请求 if method == 'POST': res = requests.post(url=full_url, json=data, headers=headers, verify=False) else: res = requests.get(url=full_url, params=data, headers=headers, verify=False) # 处理响应 processor = HttpResponseProcessor(full_url, headers=res.headers) processor.response = res processor.raw_content = res.content processor.status_code = res.status_code try: # 解码内容 text_content = processor.decode_content() # 尝试解析JSON try: response_data = json.loads(text_content) api_message = response_data.get('message', None) except json.JSONDecodeError: response_data = {'raw_response': text_content} except Exception as e: raise e except requests.exceptions.SSLError as e: raise Exception('SSL证书验证失败') from e except Exception as e: raise Exception('调用出现异常') from e # 计算耗时 res_time = (time.time() - start) * 1000 # 获取状态码 try: statusCode = response_data.get('statusCode', res.status_code) except AttributeError: statusCode = res.status_code # 判断请求结果 if res.status_code != 200: isSuccess = False FAIL_RES['message'] = f"HTTP状态码错误: {res.status_code}" FAIL_RES['apiMessage'] = api_message or getattr(response_data, 'resInfo', '') elif statusCode != 200: isSuccess = False try: res_info = response_data.get('responseBody', '') or response_data.get('resInfo', '') FAIL_RES['message'] = f"业务状态码错误: {statusCode} - {res_info}" FAIL_RES['apiMessage'] = api_message except (ValueError, AttributeError): FAIL_RES['message'] = '解析响应内容失败' # 处理预期消息验证 if expected_message is not None and api_message != expected_message: isSuccess = False FAIL_RES['message'] = f"消息验证失败: 预期 '{expected_message}', 实际 '{api_message}'" FAIL_RES['apiMessage'] = api_message # 输出结果 if isSuccess: SUC_RES['resTime'] = int(res_time) SUC_RES['apiMessage'] = api_message print(json.dumps(SUC_RES, ensure_ascii=False)) else: FAIL_RES['resTime'] = int(res_time) print(json.dumps(FAIL_RES, ensure_ascii=False)) except Exception as e: print_err_result(e) if __name__ == '__main__': args = sys.argv[1:] if len(args) < 1: print_err_result(''' 参数不足 用法: ./http_requests.py 完整URL [JSON参数] 示例: ./http_requests.py "api.example.com/endpoint" '{"data":{"key":"value"}, "method":"POST"}' 注意: JSON参数需要使用单引号包裹,内部使用双引号 ''') full_url = args[0] params = args[1] if len(args) > 1 else '{}' _requests(full_url, params)
08-07
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值