xref: /lighttpd1.4/src/http_chunk.c (revision 4933a225)
1 /*
2  * http_chunk - append response to chunkqueue, possibly in "chunked" encoding
3  *
4  * Fully-rewritten from original
5  * Copyright(c) 2019 Glenn Strauss gstrauss()gluelogic.com  All rights reserved
6  * License: BSD 3-clause (same as lighttpd)
7  */
8 #include "first.h"
9 
10 #include "http_chunk.h"
11 #include "base.h"
12 #include "chunk.h"
13 #include "stat_cache.h"
14 #include "fdevent.h"
15 #include "log.h"
16 
17 #include <sys/types.h>
18 #include <sys/stat.h>
19 
20 #include <stdlib.h>
21 #include <unistd.h>
22 
23 #include <errno.h>
24 #include <string.h>
25 
26 static void http_chunk_len_append(chunkqueue * const cq, uintmax_t len) {
27     char buf[24]; /* 64-bit (8 bytes) is 16 hex chars (+2 \r\n, +1 \0 = 19) */
28   #if 0
29     buffer b = { buf, 0, sizeof(buf) };
30     buffer_append_uint_hex(&b, len);
31     buffer_append_string_len(&b, CONST_STR_LEN("\r\n"));
32     chunkqueue_append_mem(cq, b.ptr, b.used-1);
33   #else
34     int i = (int)(sizeof(buf));
35     buf[--i] = '\n';
36     buf[--i] = '\r';
37     do { buf[--i] = "0123456789abcdef"[len & 0x0F]; } while (len >>= 4);
38     chunkqueue_append_mem(cq, buf+i, sizeof(buf)-i);
39   #endif
40 }
41 
42 static int http_chunk_len_append_tempfile(chunkqueue * const cq, uintmax_t len, log_error_st * const errh) {
43     char buf[24]; /* 64-bit (8 bytes) is 16 hex chars (+2 \r\n, +1 \0 = 19) */
44   #if 0
45     buffer b = { buf, 0, sizeof(buf) };
46     buffer_append_uint_hex(&b, len);
47     buffer_append_string_len(&b, CONST_STR_LEN("\r\n"));
48     return chunkqueue_append_mem_to_tempfile(cq, b.ptr, b.used-1, errh);
49   #else
50     int i = (int)(sizeof(buf));
51     buf[--i] = '\n';
52     buf[--i] = '\r';
53     do { buf[--i] = "0123456789abcdef"[len & 0x0F]; } while (len >>= 4);
54     return chunkqueue_append_mem_to_tempfile(cq, buf+i, sizeof(buf)-i, errh);
55   #endif
56 }
57 
58 static int http_chunk_append_file_open_fstat(const request_st * const r, const buffer * const fn, struct stat * const st) {
59     return
60       (r->conf.follow_symlink
61        || !stat_cache_path_contains_symlink(fn, r->conf.errh))
62         ? stat_cache_open_rdonly_fstat(fn, st, r->conf.follow_symlink)
63         : -1;
64 }
65 
66 static int http_chunk_append_read_fd_range(request_st * const r, const buffer * const fn, const int fd, off_t offset, off_t len) {
67     /* note: this routine should not be used for range requests
68      * unless the total size of ranges requested is small */
69     /* note: future: could read into existing MEM_CHUNK in cq->last if
70      * there is sufficient space, but would need to adjust for existing
71      * offset in for cq->bytes_in in chunkqueue_append_buffer_commit() */
72     UNUSED(fn);
73 
74     chunkqueue * const cq = &r->write_queue;
75 
76     if (r->resp_send_chunked)
77         http_chunk_len_append(cq, (uintmax_t)len);
78 
79     if (-1 == lseek(fd, offset, SEEK_SET)) return -1;
80     buffer * const b = chunkqueue_append_buffer_open_sz(cq, len+2+1);
81     ssize_t rd;
82     offset = 0;
83     do {
84         rd = read(fd, b->ptr+offset, len-offset);
85     } while (rd > 0 ? (offset += rd, len -= rd) : errno == EINTR);
86     buffer_commit(b, offset);
87 
88     if (r->resp_send_chunked)
89         buffer_append_string_len(b, CONST_STR_LEN("\r\n"));
90 
91     chunkqueue_append_buffer_commit(cq);
92     return (rd >= 0) ? 0 : -1;
93 }
94 
95 void http_chunk_append_file_ref_range(request_st * const r, stat_cache_entry * const sce, const off_t offset, const off_t len) {
96     chunkqueue * const cq = &r->write_queue;
97 
98     if (r->resp_send_chunked)
99         http_chunk_len_append(cq, (uintmax_t)len);
100 
101     const buffer * const fn = &sce->name;
102     const int fd = sce->fd;
103     chunkqueue_append_file_fd(cq, fn, fd, offset, len);
104     if (fd >= 0) {
105         chunk * const d = cq->last;
106         d->file.ref = sce;
107         d->file.refchg = stat_cache_entry_refchg;
108         stat_cache_entry_refchg(sce, 1);
109     }
110 
111     if (r->resp_send_chunked)
112         chunkqueue_append_mem(cq, CONST_STR_LEN("\r\n"));
113 }
114 
115 void http_chunk_append_file_fd_range(request_st * const r, const buffer * const fn, const int fd, const off_t offset, const off_t len) {
116     chunkqueue * const cq = &r->write_queue;
117 
118     if (r->resp_send_chunked)
119         http_chunk_len_append(cq, (uintmax_t)len);
120 
121     chunkqueue_append_file_fd(cq, fn, fd, offset, len);
122 
123     if (r->resp_send_chunked)
124         chunkqueue_append_mem(cq, CONST_STR_LEN("\r\n"));
125 }
126 
127 int http_chunk_append_file_range(request_st * const r, const buffer * const fn, const off_t offset, off_t len) {
128     struct stat st;
129     const int fd = http_chunk_append_file_open_fstat(r, fn, &st);
130     if (fd < 0) return -1;
131 
132     if (-1 == len) {
133         if (offset >= st.st_size) {
134             close(fd);
135             return (offset == st.st_size) ? 0 : -1;
136         }
137         len = st.st_size - offset;
138     }
139     else if (st.st_size - offset < len) {
140         close(fd);
141         return -1;
142     }
143 
144     http_chunk_append_file_fd_range(r, fn, fd, offset, len);
145     return 0;
146 }
147 
148 int http_chunk_append_file(request_st * const r, const buffer * const fn) {
149     struct stat st;
150     const int fd = http_chunk_append_file_open_fstat(r, fn, &st);
151     if (fd < 0) return -1;
152     http_chunk_append_file_fd(r, fn, fd, st.st_size);
153     return 0;
154 }
155 
156 int http_chunk_append_file_fd(request_st * const r, const buffer * const fn, const int fd, const off_t sz) {
157     if (sz > 32768 || !r->resp_send_chunked) {
158         http_chunk_append_file_fd_range(r, fn, fd, 0, sz);
159         return 0;
160     }
161 
162     /*(read small files into memory)*/
163     int rc = (0 != sz) ? http_chunk_append_read_fd_range(r,fn,fd,0,sz) : 0;
164     close(fd);
165     return rc;
166 }
167 
168 int http_chunk_append_file_ref(request_st * const r, stat_cache_entry * const sce) {
169     const off_t sz = sce->st.st_size;
170     if (sz > 32768 || !r->resp_send_chunked) {
171         http_chunk_append_file_ref_range(r, sce, 0, sz);
172         return 0;
173     }
174 
175     /*(read small files into memory)*/
176     const buffer * const fn = &sce->name;
177     const int fd = sce->fd;
178     int rc = (0 != sz) ? http_chunk_append_read_fd_range(r,fn,fd,0,sz) : 0;
179     return rc;
180 }
181 
182 static int http_chunk_append_to_tempfile(request_st * const r, const char * const mem, const size_t len) {
183     chunkqueue * const cq = &r->write_queue;
184     log_error_st * const errh = r->conf.errh;
185 
186     if (r->resp_send_chunked
187         && 0 != http_chunk_len_append_tempfile(cq, len, errh))
188         return -1;
189 
190     if (0 != chunkqueue_append_mem_to_tempfile(cq, mem, len, errh))
191         return -1;
192 
193     if (r->resp_send_chunked
194         && 0 !=
195            chunkqueue_append_mem_to_tempfile(cq, CONST_STR_LEN("\r\n"), errh))
196         return -1;
197 
198     return 0;
199 }
200 
201 static int http_chunk_append_cq_to_tempfile(request_st * const r, chunkqueue * const src, const size_t len) {
202     chunkqueue * const cq = &r->write_queue;
203     log_error_st * const errh = r->conf.errh;
204 
205     if (r->resp_send_chunked
206         && 0 != http_chunk_len_append_tempfile(cq, len, errh))
207         return -1;
208 
209     if (0 != chunkqueue_steal_with_tempfiles(cq, src, len, errh))
210         return -1;
211 
212     if (r->resp_send_chunked
213         && 0 !=
214            chunkqueue_append_mem_to_tempfile(cq, CONST_STR_LEN("\r\n"), errh))
215         return -1;
216 
217     return 0;
218 }
219 
220 __attribute_pure__
221 static int http_chunk_uses_tempfile(const request_st * const r, const chunkqueue * const cq, const size_t len) {
222 
223     /* current usage does not append_mem or append_buffer after appending
224      * file, so not checking if users of this interface have appended large
225      * (references to) files to chunkqueue, which would not be in memory
226      * (but included in calculation for whether or not to use temp file) */
227 
228     /*(allow slightly larger mem use if FDEVENT_STREAM_RESPONSE_BUFMIN
229      * to reduce creation of temp files when backend producer will be
230      * blocked until more data is sent to network to client)*/
231 
232     const chunk * const c = cq->last;
233     return
234       ((c && c->type == FILE_CHUNK && c->file.is_temp)
235        || chunkqueue_length(cq) + len
236           > ((r->conf.stream_response_body & FDEVENT_STREAM_RESPONSE_BUFMIN)
237              ? 128*1024
238              :  64*1024));
239 }
240 
241 int http_chunk_append_buffer(request_st * const r, buffer * const mem) {
242     size_t len = buffer_string_length(mem);
243     if (0 == len) return 0;
244 
245     chunkqueue * const cq = &r->write_queue;
246 
247     if (http_chunk_uses_tempfile(r, cq, len))
248         return http_chunk_append_to_tempfile(r, mem->ptr, len);
249 
250     if (r->resp_send_chunked)
251         http_chunk_len_append(cq, len);
252 
253     /*(chunkqueue_append_buffer() might steal buffer contents)*/
254     chunkqueue_append_buffer(cq, mem);
255 
256     if (r->resp_send_chunked)
257         chunkqueue_append_mem(cq, CONST_STR_LEN("\r\n"));
258 
259     return 0;
260 }
261 
262 int http_chunk_append_mem(request_st * const r, const char * const mem, const size_t len) {
263     if (0 == len) return 0;
264     force_assert(NULL != mem);
265 
266     chunkqueue * const cq = &r->write_queue;
267 
268     if (http_chunk_uses_tempfile(r, cq, len))
269         return http_chunk_append_to_tempfile(r, mem, len);
270 
271     if (r->resp_send_chunked)
272         http_chunk_len_append(cq, len);
273 
274     chunkqueue_append_mem(cq, mem, len);
275 
276     if (r->resp_send_chunked)
277         chunkqueue_append_mem(cq, CONST_STR_LEN("\r\n"));
278 
279     return 0;
280 }
281 
282 int http_chunk_transfer_cqlen(request_st * const r, chunkqueue * const src, const size_t len) {
283     if (0 == len) return 0;
284 
285     chunkqueue * const cq = &r->write_queue;
286 
287     if (http_chunk_uses_tempfile(r, cq, len))
288         return http_chunk_append_cq_to_tempfile(r, src, len);
289 
290     if (r->resp_send_chunked)
291         http_chunk_len_append(cq, len);
292 
293     chunkqueue_steal(cq, src, len);
294 
295     if (r->resp_send_chunked)
296         chunkqueue_append_mem(cq, CONST_STR_LEN("\r\n"));
297 
298     return 0;
299 }
300 
301 void http_chunk_close(request_st * const r) {
302     if (!r->resp_send_chunked) return;
303 
304     if (r->gw_dechunk && !buffer_string_is_empty(&r->gw_dechunk->b)) {
305         /* XXX: trailers passed through; no sanity check currently done */
306         chunkqueue_append_buffer(&r->write_queue, &r->gw_dechunk->b);
307         if (!r->gw_dechunk->done)
308             r->keep_alive = 0;
309     }
310     else
311         chunkqueue_append_mem(&r->write_queue, CONST_STR_LEN("0\r\n\r\n"));
312 }
313 
314 static int
315 http_chunk_decode_append_data (request_st * const r, const char *mem, off_t len)
316 {
317     /*(silently discard data, if any, after final \r\n)*/
318     if (r->gw_dechunk->done) return 0;
319 
320     buffer * const h = &r->gw_dechunk->b;
321     off_t te_chunked = r->gw_dechunk->gw_chunked;
322     while (len) {
323         if (0 == te_chunked) {
324             const char *p = strchr(mem, '\n');
325             /*(likely better ways to handle chunked header crossing chunkqueue
326              * chunks, but this situation is not expected to occur frequently)*/
327             if (NULL == p) { /* incomplete HTTP chunked header line */
328                 uint32_t hlen = buffer_string_length(h);
329                 if ((off_t)(1024 - hlen) < len) {
330                     log_error(r->conf.errh, __FILE__, __LINE__,
331                       "chunked header line too long");
332                     return -1;
333                 }
334                 buffer_append_string_len(h, mem, len);
335                 break;
336             }
337 
338             off_t hsz = ++p - mem;
339             unsigned char *s = (unsigned char *)mem;
340             if (!buffer_string_is_empty(h)) {
341                 uint32_t hlen = buffer_string_length(h);
342                 if (NULL == memchr(h->ptr, '\n', hlen)) {
343                     if ((off_t)(1024 - hlen) < hsz) {
344                         log_error(r->conf.errh, __FILE__, __LINE__,
345                           "chunked header line too long");
346                         return -1;
347                     }
348                     buffer_append_string_len(h, mem, hsz);
349                 }
350                 s = (unsigned char *)h->ptr;
351             }
352             for (unsigned char u; (u=(unsigned char)hex2int(*s))!=0xFF; ++s) {
353                 if (te_chunked > (off_t)(1uLL<<(8*sizeof(off_t)-5))-1-2) {
354                     log_error(r->conf.errh, __FILE__, __LINE__,
355                       "chunked data size too large");
356                     return -1;
357                 }
358                 te_chunked <<= 4;
359                 te_chunked |= u;
360             }
361             if ((char *)s == mem || (char *)s == h->ptr) return -1; /*(no hex)*/
362             while (*s == ' ' || *s == '\t') ++s;
363             if (*s != '\r' && *s != ';') { /*(not strictly checking \r\n)*/
364                 log_error(r->conf.errh, __FILE__, __LINE__,
365                   "chunked header invalid chars");
366                 return -1;
367             }
368 
369             if (0 == te_chunked) {
370                 /* do not consume final chunked header until
371                  * (optional) trailers received along with
372                  * request-ending blank line "\r\n" */
373                 if (len - hsz == 2 && p[0] == '\r' && p[1] == '\n') {
374                     /* common case with no trailers; final \r\n received */
375                     /*(silently discard data, if any, after final \r\n)*/
376                   #if 0 /*(avoid allocation for common case; users must check)*/
377                     if (buffer_is_empty(h))
378                         buffer_copy_string_len(h, CONST_STR_LEN("0\r\n\r\n"));
379                   #else
380                     buffer_clear(h);
381                   #endif
382                     r->gw_dechunk->done = r->http_status;
383                     break;
384                 }
385 
386                 /* accumulate trailers and check for end of trailers */
387                 /* XXX: reuse r->conf.max_request_field_size
388                  *      or have separate limit? */
389                 uint32_t hlen = buffer_string_length(h);
390                 if ((off_t)(r->conf.max_request_field_size - hlen) < hsz) {
391                     /* truncate excessively long trailers */
392                     r->gw_dechunk->done = r->http_status;
393                     hsz = (off_t)(r->conf.max_request_field_size - hlen);
394                     buffer_append_string_len(h, mem, hsz);
395                     p = strrchr(h->ptr, '\n');
396                     if (NULL != p)
397                         buffer_string_set_length(h, p + 1 - h->ptr);
398                     else { /*(should not happen)*/
399                         buffer_clear(h);
400                         buffer_append_string_len(h, CONST_STR_LEN("0\r\n"));
401                     }
402                     buffer_append_string_len(h, CONST_STR_LEN("\r\n"));
403                     break;
404                 }
405                 buffer_append_string_len(h, mem, hsz);
406                 hlen += (uint32_t)hsz; /* uint32_t fits in (buffer *) */
407                 if (hlen < 4) break;
408                 p = h->ptr + hlen - 4;
409                 if (p[0]=='\r'&&p[1]=='\n'&&p[2]=='\r'&&p[3]=='\n')
410                     r->gw_dechunk->done = r->http_status;
411                 else if ((p = strstr(h->ptr, "\r\n\r\n"))) {
412                     r->gw_dechunk->done = r->http_status;
413                     /*(silently discard data, if any, after final \r\n)*/
414                     buffer_string_set_length(h, (uint32_t)(p+4-h->ptr));
415                 }
416                 break;
417             }
418 
419             mem += hsz;
420             len -= hsz;
421 
422             te_chunked += 2; /*(for trailing "\r\n" after chunked data)*/
423         }
424 
425         if (te_chunked >= 2) {
426             off_t clen = te_chunked - 2;
427             if (clen > len) clen = len;
428             if (0 != http_chunk_append_mem(r, mem, clen))
429                 return -1;
430             mem += clen;
431             len -= clen;
432             te_chunked -= clen;
433             if (te_chunked == 2) {
434                 if (len >= 2) {
435                     if (mem[0] != '\r' || mem[1] != '\n') return -1;
436                     mem += 2;
437                     len -= 2;
438                     te_chunked = 0;
439                 }
440                 else if (len == 1 && mem[0] != '\r') return -1;
441             }
442         }
443         else if (1 == te_chunked) {
444             /* finish reading chunk block "\r\n" */
445             if (mem[0] != '\n') return -1;
446             ++mem;
447             --len;
448             te_chunked = 0;
449         }
450     }
451     r->gw_dechunk->gw_chunked = te_chunked;
452     return 0;
453 }
454 
455 int http_chunk_decode_append_buffer(request_st * const r, buffer * const mem)
456 {
457     /*(called by funcs receiving data from backends, which might be chunked)*/
458     /*(separate from http_chunk_append_buffer() called by numerous others)*/
459     if (!r->resp_decode_chunked)
460         return http_chunk_append_buffer(r, mem);
461 
462     /* no need to decode chunked to immediately re-encode chunked,
463      * though would be more robust to still validate chunk lengths sent
464      * (or else we might wait for keep-alive while client waits for final chunk)
465      * Before finishing response/stream, we *are not* checking if we got final
466      * chunk of chunked encoding from backend.  If we were, we could consider
467      * closing HTTP/1.0 and HTTP/1.1 connections (no keep-alive), and in HTTP/2
468      * we could consider sending RST_STREAM error.  http_chunk_close() would
469      * only handle case of streaming chunked to client */
470     if (r->resp_send_chunked) {
471         r->resp_send_chunked = 0;
472         int rc = http_chunk_append_buffer(r, mem); /* might append to tmpfile */
473         r->resp_send_chunked = 1;
474         return rc;
475     }
476 
477     /* might avoid copy by transferring buffer if buffer is all data that is
478      * part of large chunked block, but choosing to *not* expand that out here*/
479     return http_chunk_decode_append_data(r, CONST_BUF_LEN(mem));
480 }
481 
482 int http_chunk_decode_append_mem(request_st * const r, const char * const mem, const size_t len)
483 {
484     /*(called by funcs receiving data from backends, which might be chunked)*/
485     /*(separate from http_chunk_append_mem() called by numerous others)*/
486     if (!r->resp_decode_chunked)
487         return http_chunk_append_mem(r, mem, len);
488 
489     /* no need to decode chunked to immediately re-encode chunked,
490      * though would be more robust to still validate chunk lengths sent
491      * (or else we might wait for keep-alive while client waits for final chunk)
492      * Before finishing response/stream, we *are not* checking if we got final
493      * chunk of chunked encoding from backend.  If we were, we could consider
494      * closing HTTP/1.0 and HTTP/1.1 connections (no keep-alive), and in HTTP/2
495      * we could consider sending RST_STREAM error.  http_chunk_close() would
496      * only handle case of streaming chunked to client */
497     if (r->resp_send_chunked) {
498         r->resp_send_chunked = 0;
499         int rc = http_chunk_append_mem(r, mem, len); /*might append to tmpfile*/
500         r->resp_send_chunked = 1;
501         return rc;
502     }
503 
504     return http_chunk_decode_append_data(r, mem, (off_t)len);
505 }
506