1 /* Copyright 2002-2004 Justin Erenkrantz and Greg Stein
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
7 * http://www.apache.org/licenses/LICENSE-2.0
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
16 #include <apr_pools.h>
19 #include "serf_bucket_util.h"
21 /* Older versions of APR do not have this macro. */
23 #define REQUESTED_MAX APR_SIZE_MAX
25 #define REQUESTED_MAX (~((apr_size_t)0))
30 serf_bucket_t *stream;
31 apr_uint64_t remaining;
34 serf_bucket_t *serf_bucket_response_body_create(
35 serf_bucket_t *stream, apr_uint64_t len, serf_bucket_alloc_t *allocator)
39 ctx = serf_bucket_mem_alloc(allocator, sizeof(*ctx));
43 return serf_bucket_create(&serf_bucket_type_response_body, allocator, ctx);
46 static apr_status_t serf_response_body_read(serf_bucket_t *bucket,
51 body_context_t *ctx = bucket->data;
54 if (!ctx->remaining) {
59 if (requested == SERF_READ_ALL_AVAIL || requested > ctx->remaining) {
60 if (ctx->remaining <= REQUESTED_MAX) {
61 requested = (apr_size_t) ctx->remaining;
63 requested = REQUESTED_MAX;
67 status = serf_bucket_read(ctx->stream, requested, data, len);
69 if (!SERF_BUCKET_READ_ERROR(status)) {
70 ctx->remaining -= *len;
73 if (APR_STATUS_IS_EOF(status) && ctx->remaining > 0) {
74 /* The server sent less data than expected. */
75 status = SERF_ERROR_TRUNCATED_HTTP_RESPONSE;
81 static apr_status_t serf_response_body_readline(serf_bucket_t *bucket,
82 int acceptable, int *found,
86 body_context_t *ctx = bucket->data;
89 if (!ctx->remaining) {
94 status = serf_bucket_readline(ctx->stream, acceptable, found, data, len);
96 if (!SERF_BUCKET_READ_ERROR(status)) {
97 ctx->remaining -= *len;
100 if (APR_STATUS_IS_EOF(status) && ctx->remaining > 0) {
101 /* The server sent less data than expected. */
102 status = SERF_ERROR_TRUNCATED_HTTP_RESPONSE;
108 static apr_status_t serf_response_body_peek(serf_bucket_t *bucket,
112 body_context_t *ctx = bucket->data;
114 return serf_bucket_peek(ctx->stream, data, len);
117 static void serf_response_body_destroy(serf_bucket_t *bucket)
119 body_context_t *ctx = bucket->data;
121 serf_bucket_destroy(ctx->stream);
123 serf_default_destroy_and_data(bucket);
126 const serf_bucket_type_t serf_bucket_type_response_body = {
128 serf_response_body_read,
129 serf_response_body_readline,
130 serf_default_read_iovec,
131 serf_default_read_for_sendfile,
132 serf_default_read_bucket,
133 serf_response_body_peek,
134 serf_response_body_destroy,