root/src/noit_http.c

Revision 6298e33b2e6517913907fa76bd9af5a1ea28b922, 33.0 kB (checked in by Theo Schlossnagle <jesus@omniti.com>, 5 years ago)

fix the request fetching stuff

  • Property mode set to 100644
Line 
1 /*
2  * Copyright (c) 2007, OmniTI Computer Consulting, Inc.
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions are
7  * met:
8  *
9  *     * Redistributions of source code must retain the above copyright
10  *       notice, this list of conditions and the following disclaimer.
11  *     * Redistributions in binary form must reproduce the above
12  *       copyright notice, this list of conditions and the following
13  *       disclaimer in the documentation and/or other materials provided
14  *       with the distribution.
15  *     * Neither the name OmniTI Computer Consulting, Inc. nor the names
16  *       of its contributors may be used to endorse or promote products
17  *       derived from this software without specific prior written
18  *       permission.
19  *
20  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
21  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
22  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
23  * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
24  * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
25  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
26  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
27  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
28  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
29  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
30  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
31  */
32
33 #include "noit_defines.h"
34 #include "noit_http.h"
35 #include "utils/noit_str.h"
36
37 #include <errno.h>
38 #include <ctype.h>
39 #include <assert.h>
40 #include <zlib.h>
41 #include <libxml/tree.h>
42
43 #define REQ_PAT "\r\n\r\n"
44 #define REQ_PATSIZE 4
45 #define HEADER_CONTENT_LENGTH "content-length"
46 #define HEADER_EXPECT "expect"
47
48 #define CTX_ADD_HEADER(a,b) \
49     noit_hash_replace(&ctx->res.headers, \
50                       strdup(a), strlen(a), strdup(b), free, free)
51 static const char _hexchars[16] =
52   {'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'};
53
54 struct bchain *bchain_alloc(size_t size) {
55   struct bchain *n;
56   n = malloc(size + ((void *)n->buff - (void *)n));
57   if(!n) return NULL;
58   n->prev = n->next = NULL;
59   n->start = n->size = 0;
60   n->allocd = size;
61   return n;
62 }
63 #define RELEASE_BCHAIN(a) do { \
64   while(a) { \
65     struct bchain *__b; \
66     __b = a; \
67     a = __b->next; \
68     bchain_free(__b); \
69   } \
70 } while(0)
71 struct bchain *bchain_from_data(const void *d, size_t size) {
72   struct bchain *n;
73   n = bchain_alloc(size);
74   if(!n) return NULL;
75   memcpy(n->buff, d, size);
76   n->size = size;
77   return n;
78 }
79 void bchain_free(struct bchain *b) {
80   free(b);
81 }
82
83 static noit_http_method
84 _method_enum(const char *s) {
85   switch(*s) {
86    case 'G':
87     if(!strcasecmp(s, "GET")) return NOIT_HTTP_GET;
88     break;
89    case 'H':
90     if(!strcasecmp(s, "HEAD")) return NOIT_HTTP_HEAD;
91     break;
92    case 'P':
93     if(!strcasecmp(s, "POST")) return NOIT_HTTP_POST;
94     break;
95    default:
96     break;
97   }
98   return NOIT_HTTP_OTHER;
99 }
100 static noit_http_protocol
101 _protocol_enum(const char *s) {
102   if(!strcasecmp(s, "HTTP/1.1")) return NOIT_HTTP11;
103   if(!strcasecmp(s, "HTTP/1.0")) return NOIT_HTTP10;
104   return NOIT_HTTP09;
105 }
106 static noit_boolean
107 _fixup_bchain(struct bchain *b) {
108   /* make sure lines (CRLF terminated) don't cross chain boundaries */
109   while(b) {
110     struct bchain *f;
111     int start_in_b, end_in_f;
112     size_t new_size;
113     const char *str_in_f;
114
115     start_in_b = b->start;
116     if(b->size > 2) {
117       if(memcmp(b->buff + b->start + b->size - 2, "\r\n", 2) == 0) {
118         b = b->next;
119         continue;
120       }
121       start_in_b = b->start + b->size - 3; /* we already checked -2 */
122       while(start_in_b >= b->start) {
123         if(memcmp(b->buff + start_in_b, "\r\n", 2) == 0) {
124           start_in_b += 2;
125           break;
126         }
127       }
128     }
129
130     /* start_in_b points to the beginning of the string we need to build
131      * into a new buffer.
132      */
133     f = b->next;
134     if(!f) return noit_false; /* Nothing left, can't complete the line */
135     str_in_f = strnstrn("\r\n", 2, f->buff + f->start, f->size);
136     if(!str_in_f) return noit_false; /* nothing in next chain -- too long */
137     str_in_f += 2;
138     end_in_f = (str_in_f - f->buff - f->start);
139     new_size = end_in_f + (b->start + b->size - start_in_b);
140     if(new_size > DEFAULT_BCHAINSIZE) return noit_false; /* string too long */
141     f = bchain_alloc(new_size);
142     f->prev = b;
143     f->next = b->next;
144     f->start = 0;
145     f->size = new_size;
146     memcpy(f->buff, b->buff + start_in_b, b->start + b->size - start_in_b);
147     memcpy(f->buff + b->start + b->size - start_in_b,
148            f->buff + f->start, end_in_f);
149     f->next->prev = f;
150     f->prev->next = f;
151     f->prev->size -= start_in_b - b->start;
152     f->next->size -= end_in_f;
153     f->next->start += end_in_f;
154     b = f->next; /* skip f, we know it is right */
155   }
156   return noit_true;
157 }
158 static noit_boolean
159 _extract_header(char *l, const char **n, const char **v) {
160   *n = NULL;
161   if(*l == ' ' || *l == '\t') {
162     while(*l == ' ' || *l == '\t') l++;
163     *v = l;
164     return noit_true;
165   }
166   *n = l;
167   while(*l != ':' && *l) { *l = tolower(*l); l++; }
168   if(!*l) return noit_false;
169   *v = l+1;
170   /* Right trim the name */
171   *l-- = '\0';
172   while(*l == ' ' || *l == '\t') *l-- = '\0';
173   while(**v == ' ' || **v == '\t') (*v)++;
174   return noit_true;
175 }
176 static int
177 _http_perform_write(noit_http_session_ctx *ctx, int *mask) {
178   int len, tlen = 0;
179   struct bchain **head, *b;
180  choose_bucket:
181   head = ctx->res.leader ? &ctx->res.leader : &ctx->res.output_raw;
182   b = *head;
183
184   if(!ctx->conn.e) return 0;
185 #if 0
186   if(ctx->res.output_started == noit_false) return EVENTER_EXCEPTION;
187 #endif
188   if(!b) {
189     if(ctx->res.closed) ctx->res.complete = noit_true;
190     *mask = EVENTER_EXCEPTION;
191     return tlen;
192   }
193
194   if(ctx->res.output_raw_offset >= b->size) {
195     *head = b->next;
196     bchain_free(b);
197     b = *head;
198     if(b) b->prev = NULL;
199     ctx->res.output_raw_offset = 0;
200     goto choose_bucket;
201   }
202
203   len = ctx->conn.e->opset->
204           write(ctx->conn.e->fd,
205                 b->buff + b->start + ctx->res.output_raw_offset,
206                 b->size - ctx->res.output_raw_offset,
207                 mask, ctx->conn.e);
208   if(len == -1 && errno == EAGAIN) {
209     *mask |= EVENTER_EXCEPTION;
210     return tlen;
211   }
212   if(len == -1) {
213     /* socket error */
214     ctx->conn.e->opset->close(ctx->conn.e->fd, mask, ctx->conn.e);
215     ctx->conn.e = NULL;
216     return -1;
217   }
218   ctx->res.output_raw_offset += len;
219   tlen += len;
220   goto choose_bucket;
221 }
222 static noit_boolean
223 noit_http_request_finalize_headers(noit_http_request *req, noit_boolean *err) {
224   int start;
225   void *vval;
226   const char *mstr, *last_name = NULL;
227   struct bchain *b;
228
229   if(req->state != NOIT_HTTP_REQ_HEADERS) return noit_false;
230   if(!req->current_input) req->current_input = req->first_input;
231   if(!req->current_input) return noit_false;
232  restart:
233   while(req->current_input->prev &&
234         (req->current_offset < (req->current_input->start + REQ_PATSIZE - 1))) {
235     int inset;
236     /* cross bucket */
237     if(req->current_input == req->last_input &&
238        req->current_offset >= (req->last_input->start + req->last_input->size))
239       return noit_false;
240     req->current_offset++;
241     inset = req->current_offset - req->current_input->start;
242     if(memcmp(req->current_input->buff + req->current_input->start,
243               REQ_PAT + (REQ_PATSIZE - inset), inset) == 0 &&
244        memcmp(req->current_input->prev->buff +
245                 req->current_input->prev->start +
246                 req->current_input->prev->size - REQ_PATSIZE + inset,
247               REQ_PAT + inset,
248               REQ_PATSIZE - inset) == 0) goto match;
249   }
250   start = MAX(req->current_offset - REQ_PATSIZE, req->current_input->start);
251   mstr = strnstrn(REQ_PAT, REQ_PATSIZE,
252                   req->current_input->buff + start,
253                   req->current_input->size -
254                     (start - req->current_input->start));
255   if(!mstr && req->current_input->next) {
256     req->current_input = req->current_input->next;
257     req->current_offset = req->current_input->start;
258     goto restart;
259   }
260   if(!mstr) return noit_false;
261   req->current_offset = mstr - req->current_input->buff + REQ_PATSIZE;
262  match:
263   req->current_request_chain = req->first_input;
264   noitL(noit_debug, " noit_http_request_finalize : match(%d in %d)\n",
265         req->current_offset - req->current_input->start,
266         req->current_input->size);
267   if(req->current_offset <
268      req->current_input->start + req->current_input->size) {
269     /* There are left-overs */
270     int lsize = req->current_input->size - req->current_offset;
271     noitL(noit_debug, " noit_http_request_finalize -- leftovers: %d\n", lsize);
272     req->first_input = bchain_alloc(lsize);
273     req->first_input->prev = NULL;
274     req->first_input->next = req->current_input->next;
275     req->first_input->start = 0;
276     req->first_input->size = lsize;
277     memcpy(req->first_input->buff,
278            req->current_input->buff + req->current_offset,
279            req->first_input->size);
280     if(req->last_input == req->current_input)
281       req->last_input = req->first_input;
282     else
283       bchain_free(req->current_input);
284   }
285   else {
286     req->first_input = req->last_input = NULL;
287   }
288   req->current_input = NULL;
289   req->current_offset = 0;
290
291   /* Now we need to dissect the current_request_chain into an HTTP request */
292   /* First step: make sure that no line crosses a chain boundary by
293    * inserting new chains as necessary.
294    */
295   if(!_fixup_bchain(req->current_request_chain)) {
296     *err = noit_true;
297     return noit_false;
298   }
299   /* Second step is to parse out the request itself */
300   for(b = req->current_request_chain; b; b = b->next) {
301     char *curr_str, *next_str;
302     b->buff[b->start + b->size - 2] = '\0';
303     curr_str = b->buff + b->start;
304     do {
305       next_str = strstr(curr_str, "\r\n");
306       if(next_str) {
307         *((char *)next_str) = '\0';
308         next_str += 2;
309       }
310       if(req->method_str && *curr_str == '\0')
311         break; /* our CRLFCRLF... end of req */
312 #define FAIL do { *err = noit_true; return noit_false; } while(0)
313       if(!req->method_str) { /* request line */
314         req->method_str = (char *)curr_str;
315         req->uri_str = strchr(curr_str, ' ');
316         if(!req->uri_str) FAIL;
317         *(req->uri_str) = '\0';
318         req->uri_str++;
319         req->protocol_str = strchr(req->uri_str, ' ');
320         if(!req->protocol_str) FAIL;
321         *(req->protocol_str) = '\0';
322         req->protocol_str++;
323         req->method = _method_enum(req->method_str);
324         req->protocol = _protocol_enum(req->protocol_str);
325         if(req->protocol == NOIT_HTTP11) req->opts |= NOIT_HTTP_CHUNKED;
326       }
327       else { /* request headers */
328         const char *name, *value;
329         if(_extract_header(curr_str, &name, &value) == noit_false) FAIL;
330         if(!name && !last_name) FAIL;
331         if(!strcmp(name ? name : last_name, "accept-encoding")) {
332           if(strstr(value, "gzip")) req->opts |= NOIT_HTTP_GZIP;
333           if(strstr(value, "deflate")) req->opts |= NOIT_HTTP_DEFLATE;
334         }
335         if(name)
336           noit_hash_replace(&req->headers, name, strlen(name), (void *)value,
337                             NULL, NULL);
338         else {
339           struct bchain *b;
340           const char *prefix = NULL;
341           int l1, l2;
342           noit_hash_retr_str(&req->headers, last_name, strlen(last_name),
343                              &prefix);
344           if(!prefix) FAIL;
345           l1 = strlen(prefix);
346           l2 = strlen(value);
347           b = bchain_alloc(l1 + l2 + 2);
348           b->next = req->current_request_chain;
349           b->next->prev = b;
350           req->current_request_chain = b;
351           b->size = l1 + l2 + 2;
352           memcpy(b->buff, prefix, l1);
353           b->buff[l1] = ' ';
354           memcpy(b->buff + l1 + 1, value, l2);
355           b->buff[l1 + 1 + l2] = '\0';
356           noit_hash_replace(&req->headers, last_name, strlen(last_name),
357                             b->buff, NULL, NULL);
358         }
359         if(name) last_name = name;
360       }
361       curr_str = next_str;
362     } while(next_str);
363   }
364
365   /* headers are done... we could need to read a payload */
366   if(noit_hash_retrieve(&req->headers,
367                         HEADER_CONTENT_LENGTH,
368                         sizeof(HEADER_CONTENT_LENGTH)-1, &vval)) {
369     const char *val = vval;
370     req->has_payload = noit_true;
371     req->content_length = strtoll(val, NULL, 10);
372   }
373   if(noit_hash_retrieve(&req->headers, HEADER_EXPECT,
374                         sizeof(HEADER_EXPECT)-1, &vval)) {
375     const char *val = vval;
376     if(strncmp(val, "100-", 4) || /* Bad expect header */
377        req->has_payload == noit_false) /* expect, but no content length */
378       FAIL;
379     /* We need to tell the client to "go-ahead" -- HTTP sucks */
380     req->state = NOIT_HTTP_REQ_EXPECT;
381     return noit_false;
382   }
383   if(req->content_length > 0) {
384     /* switch modes... let's go read the payload */
385     req->state = NOIT_HTTP_REQ_PAYLOAD;
386     return noit_false;
387   }
388
389   req->complete = noit_true;
390   return noit_true;
391 }
392 static noit_boolean
393 noit_http_request_finalize_payload(noit_http_request *req, noit_boolean *err) {
394   req->complete = noit_true;
395   return noit_true;
396 }
397 static noit_boolean
398 noit_http_request_finalize(noit_http_request *req, noit_boolean *err) {
399   if(req->state == NOIT_HTTP_REQ_HEADERS)
400     if(noit_http_request_finalize_headers(req, err)) return noit_true;
401   if(req->state == NOIT_HTTP_REQ_EXPECT) return noit_false;
402   if(req->state == NOIT_HTTP_REQ_PAYLOAD)
403     if(noit_http_request_finalize_payload(req, err)) return noit_true;
404   return noit_false;
405 }
406 int
407 noit_http_complete_request(noit_http_session_ctx *ctx, int mask) {
408   struct bchain *in;
409   noit_boolean rv, err = noit_false;
410
411   if(mask & EVENTER_EXCEPTION) {
412    full_error:
413     ctx->conn.e->opset->close(ctx->conn.e->fd, &mask, ctx->conn.e);
414     ctx->conn.e = NULL;
415     return 0;
416   }
417   if(ctx->req.complete == noit_true) return EVENTER_EXCEPTION;
418
419   /* We could have a complete request in the tail of a previous request */
420   rv = noit_http_request_finalize(&ctx->req, &err);
421   if(rv == noit_true) return EVENTER_WRITE | EVENTER_EXCEPTION;
422   if(err == noit_true) goto full_error;
423
424   while(1) {
425     int len;
426
427     in = ctx->req.last_input;
428     if(!in) {
429       in = ctx->req.first_input = ctx->req.last_input =
430         bchain_alloc(DEFAULT_BCHAINSIZE);
431       if(!in) goto full_error;
432     }
433     if(in->size > 0 && /* we've read something */
434        DEFAULT_BCHAINMINREAD > BCHAIN_SPACE(in) && /* we'd like read more */
435        DEFAULT_BCHAINMINREAD < DEFAULT_BCHAINSIZE) { /* and we can */
436       in->next = ctx->req.last_input =
437         bchain_alloc(DEFAULT_BCHAINSIZE);
438       in->next->prev = in;
439       in = in->next;
440       if(!in) goto full_error;
441     }
442
443     len = ctx->conn.e->opset->read(ctx->conn.e->fd,
444                                    in->buff + in->start + in->size,
445                                    in->allocd - in->size - in->start,
446                                    &mask, ctx->conn.e);
447     noitL(noit_debug, " noit_http -> read(%d) = %d\n", ctx->conn.e->fd, len);
448     if(len == -1 && errno == EAGAIN) return mask;
449     if(len <= 0) goto full_error;
450     if(len > 0) in->size += len;
451     rv = noit_http_request_finalize(&ctx->req, &err);
452     if(len == -1 || err == noit_true) goto full_error;
453     if(ctx->req.state == NOIT_HTTP_REQ_EXPECT) {
454       const char *expect;
455       ctx->req.state = NOIT_HTTP_REQ_PAYLOAD;
456       assert(ctx->res.leader == NULL);
457       expect = "HTTP/1.1 100 Continue\r\n\r\n";
458       ctx->res.leader = bchain_from_data(expect, strlen(expect));
459       _http_perform_write(ctx, &mask);
460       if(ctx->res.leader != NULL) return mask;
461     }
462     if(rv == noit_true) return mask | EVENTER_WRITE | EVENTER_EXCEPTION;
463   }
464   return EVENTER_READ | EVENTER_EXCEPTION;
465 }
466 noit_boolean
467 noit_http_session_prime_input(noit_http_session_ctx *ctx,
468                               const void *data, size_t len) {
469   if(ctx->req.first_input != NULL) return noit_false;
470   if(len > DEFAULT_BCHAINSIZE) return noit_false;
471   ctx->req.first_input = ctx->req.last_input =
472       bchain_alloc(DEFAULT_BCHAINSIZE);
473   memcpy(ctx->req.first_input->buff, data, len);
474   ctx->req.first_input->size = len;
475   return noit_true;
476 }
477
478 void
479 noit_http_request_release(noit_http_session_ctx *ctx) {
480   noit_hash_destroy(&ctx->req.headers, NULL, NULL);
481   /* If we expected a payload, we expect a trailing \r\n */
482   if(ctx->req.has_payload) {
483     int drained, mask;
484     ctx->drainage = ctx->req.content_length - ctx->req.content_length_read;
485     /* best effort, we'll drain it before the next request anyway */
486     drained = noit_http_session_req_consume(ctx, NULL, ctx->drainage, &mask);
487     ctx->drainage -= drained;
488   }
489   RELEASE_BCHAIN(ctx->req.current_request_chain);
490   memset(&ctx->req, 0, sizeof(ctx->req));
491 }
492 void
493 noit_http_response_release(noit_http_session_ctx *ctx) {
494   noit_hash_destroy(&ctx->res.headers, free, free);
495   if(ctx->res.status_reason) free(ctx->res.status_reason);
496   RELEASE_BCHAIN(ctx->res.leader);
497   RELEASE_BCHAIN(ctx->res.output);
498   RELEASE_BCHAIN(ctx->res.output_raw);
499   memset(&ctx->res, 0, sizeof(ctx->res));
500 }
501 void
502 noit_http_ctx_session_release(noit_http_session_ctx *ctx) {
503   if(noit_atomic_dec32(&ctx->ref_cnt) == 0) {
504     noit_http_request_release(ctx);
505     noit_http_response_release(ctx);
506     free(ctx);
507   }
508 }
509 int
510 noit_http_session_req_consume(noit_http_session_ctx *ctx,
511                               void *buf, size_t len, int *mask) {
512   size_t bytes_read = 0;
513   /* We attempt to consume from the first_input */
514   struct bchain *in, *tofree;
515   noitL(noit_debug, " ... noit_http_session_req_consume(%d) %d of %d\n",
516         ctx->conn.e->fd, len,
517         ctx->req.content_length - ctx->req.content_length_read);
518   len = MIN(len, ctx->req.content_length - ctx->req.content_length_read);
519   while(bytes_read < len) {
520     int crlen = 0;
521     in = ctx->req.first_input;
522     while(in && bytes_read < len) {
523       int partial_len = MIN(in->size, len - bytes_read);
524       if(buf) memcpy(buf+bytes_read, in->buff+in->start, partial_len);
525       bytes_read += partial_len;
526       ctx->req.content_length_read += partial_len;
527       noitL(noit_debug, " ... filling %d bytes (read through %d/%d)\n",
528             bytes_read, ctx->req.content_length_read, ctx->req.content_length);
529       in->start += partial_len;
530       in->size -= partial_len;
531       if(in->size == 0) {
532         tofree = in;
533         ctx->req.first_input = in = in->next;
534         tofree->next = NULL;
535         RELEASE_BCHAIN(tofree);
536         if(in == NULL) {
537           ctx->req.last_input = NULL;
538           noitL(noit_debug, " ... noit_http_session_req_consume = %d\n",
539                 bytes_read);
540           return bytes_read;
541         }
542       }
543     }
544     while(bytes_read + crlen < len) {
545       int rlen;
546       in = ctx->req.last_input;
547       if(!in)
548         in = ctx->req.first_input = ctx->req.last_input =
549             bchain_alloc(DEFAULT_BCHAINSIZE);
550       else if(in->start + in->size >= in->allocd) {
551         in->next = bchain_alloc(DEFAULT_BCHAINSIZE);
552         in = ctx->req.last_input = in->next;
553       }
554       /* pull next chunk */
555       rlen = ctx->conn.e->opset->read(ctx->conn.e->fd,
556                                       in->buff + in->start + in->size,
557                                       in->allocd - in->size - in->start,
558                                       mask, ctx->conn.e);
559       noitL(noit_debug, " noit_http -> read(%d) = %d\n", ctx->conn.e->fd, rlen);
560       if(rlen == -1 && errno == EAGAIN) {
561         /* We'd block to read more, but we have data,
562          * so do a short read */
563         if(ctx->req.first_input->size) break;
564         /* We've got nothing... */
565         noitL(noit_debug, " ... noit_http_session_req_consume = -1 (EAGAIN)\n");
566         return -1;
567       }
568       if(rlen <= 0) {
569         noitL(noit_debug, " ... noit_http_session_req_consume = -1 (error)\n");
570         return -1;
571       }
572       in->size += rlen;
573       crlen += rlen;
574     }
575   }
576   /* NOT REACHED */
577   return bytes_read;
578 }
579 int
580 noit_http_session_drive(eventer_t e, int origmask, void *closure,
581                         struct timeval *now) {
582   noit_http_session_ctx *ctx = closure;
583   int rv = 0;
584   int mask = origmask;
585
586   /* Drainage -- this is as nasty as it sounds
587    * The last request could have unread upload content, we would have
588    * noted that in noit_http_request_release.
589    */
590   noitL(noit_debug, " -> noit_http_session_drive(%d) [%x]\n", e->fd, origmask);
591   while(ctx->drainage > 0) {
592     int len;
593     noitL(noit_debug, "   ... draining last request(%d)\n", e->fd);
594     len = noit_http_session_req_consume(ctx, NULL, ctx->drainage, &mask);
595     if(len == -1 && errno == EAGAIN) {
596       noitL(noit_debug, " <- noit_http_session_drive(%d) [%x]\n", e->fd, mask);
597       return mask;
598     }
599     if(len <= 0) goto abort_drive;
600     ctx->drainage -= len;
601   }
602
603  next_req:
604   if(ctx->req.complete != noit_true) {
605     int maybe_write_mask;
606     noitL(noit_debug, "   -> noit_http_complete_request(%d)\n", e->fd);
607     mask = noit_http_complete_request(ctx, origmask);
608     noitL(noit_debug, "   <- noit_http_complete_request(%d) = %d\n",
609           e->fd, mask);
610     _http_perform_write(ctx, &maybe_write_mask);
611     if(ctx->conn.e == NULL) goto release;
612     if(ctx->req.complete != noit_true) {
613       noitL(noit_debug, " <- noit_http_session_drive(%d) [%x]\n", e->fd,
614             mask|maybe_write_mask);
615       return mask | maybe_write_mask;
616     }
617   }
618
619   /* only dispatch if the response is not complete */
620   if(ctx->res.complete == noit_false) {
621     noitL(noit_debug, "   -> dispatch(%d)\n", e->fd);
622     rv = ctx->dispatcher(ctx);
623     noitL(noit_debug, "   <- dispatch(%d) = %d\n", e->fd, rv);
624   }
625
626   _http_perform_write(ctx, &mask);
627   if(ctx->res.complete == noit_true &&
628      ctx->conn.e &&
629      ctx->conn.needs_close == noit_true) {
630    abort_drive:
631     ctx->conn.e->opset->close(ctx->conn.e->fd, &mask, ctx->conn.e);
632     ctx->conn.e = NULL;
633     goto release;
634     return 0;
635   }
636   if(ctx->res.complete == noit_true) {
637     noit_http_request_release(ctx);
638     noit_http_response_release(ctx);
639   }
640   if(ctx->req.complete == noit_false) goto next_req;
641   if(ctx->conn.e) {
642     noitL(noit_debug, " <- noit_http_session_drive(%d) [%x]\n", e->fd, mask|rv);
643     return mask | rv;
644   }
645   noitL(noit_debug, " <- noit_http_session_drive(%d) [%x]\n", e->fd, 0);
646   return 0;
647  release:
648   noit_http_ctx_session_release(ctx);
649   noitL(noit_debug, " <- noit_http_session_drive(%d) [%x]\n", e->fd, 0);
650   return 0;
651 }
652
653 noit_http_session_ctx *
654 noit_http_session_ctx_new(noit_http_dispatch_func f, void *c, eventer_t e) {
655   noit_http_session_ctx *ctx;
656   ctx = calloc(1, sizeof(*ctx));
657   ctx->ref_cnt = 1;
658   ctx->req.complete = noit_false;
659   ctx->conn.e = e;
660   ctx->dispatcher = f;
661   ctx->dispatcher_closure = c;
662   ctx->drive = noit_http_session_drive;
663   return ctx;
664 }
665
666 noit_boolean
667 noit_http_response_status_set(noit_http_session_ctx *ctx,
668                               int code, const char *reason) {
669   if(ctx->res.output_started == noit_true) return noit_false;
670   ctx->res.protocol = ctx->req.protocol;
671   if(code < 100 || code > 999) return noit_false;
672   ctx->res.status_code = code;
673   if(ctx->res.status_reason) free(ctx->res.status_reason);
674   ctx->res.status_reason = strdup(reason);
675   return noit_true;
676 }
677 noit_boolean
678 noit_http_response_header_set(noit_http_session_ctx *ctx,
679                               const char *name, const char *value) {
680   if(ctx->res.output_started == noit_true) return noit_false;
681   noit_hash_replace(&ctx->res.headers, strdup(name), strlen(name),
682                     strdup(value), free, free);
683   return noit_true;
684 }
685 noit_boolean
686 noit_http_response_option_set(noit_http_session_ctx *ctx, u_int32_t opt) {
687   if(ctx->res.output_started == noit_true) return noit_false;
688   /* transfer and content encodings only allowed in HTTP/1.1 */
689   if(ctx->res.protocol != NOIT_HTTP11 &&
690      (opt & NOIT_HTTP_CHUNKED))
691     return noit_false;
692   if(ctx->res.protocol != NOIT_HTTP11 &&
693      (opt & (NOIT_HTTP_GZIP | NOIT_HTTP_DEFLATE)))
694     return noit_false;
695   if(((ctx->res.output_options | opt) &
696       (NOIT_HTTP_GZIP | NOIT_HTTP_DEFLATE)) ==
697         (NOIT_HTTP_GZIP | NOIT_HTTP_DEFLATE))
698     return noit_false;
699
700   /* Check out "accept" set */
701   if(!(opt & ctx->req.opts)) return noit_false;
702
703   ctx->res.output_options |= opt;
704   if(ctx->res.output_options & NOIT_HTTP_CHUNKED)
705     CTX_ADD_HEADER("Transfer-Encoding", "chunked");
706   if(ctx->res.output_options & (NOIT_HTTP_GZIP | NOIT_HTTP_DEFLATE)) {
707     CTX_ADD_HEADER("Vary", "Accept-Encoding");
708     if(ctx->res.output_options & NOIT_HTTP_GZIP)
709       CTX_ADD_HEADER("Content-Encoding", "gzip");
710     else if(ctx->res.output_options & NOIT_HTTP_DEFLATE)
711       CTX_ADD_HEADER("Content-Encoding", "deflate");
712   }
713   if(ctx->res.output_options & NOIT_HTTP_CLOSE) {
714     CTX_ADD_HEADER("Connection", "close");
715     ctx->conn.needs_close = noit_true;
716   }
717   return noit_true;
718 }
719 noit_boolean
720 noit_http_response_append(noit_http_session_ctx *ctx,
721                           const void *b, size_t l) {
722   struct bchain *o;
723   int boff = 0;
724   if(ctx->res.closed == noit_true) return noit_false;
725   if(ctx->res.output_started == noit_true &&
726      !(ctx->res.output_options & (NOIT_HTTP_CLOSE | NOIT_HTTP_CHUNKED)))
727     return noit_false;
728   if(!ctx->res.output)
729     assert(ctx->res.output = bchain_alloc(DEFAULT_BCHAINSIZE));
730   o = ctx->res.output;
731   while(o->next) o = o->next;
732   while(l > 0) {
733     if(o->allocd == o->start + o->size) {
734       /* Filled up, need another */
735       o->next = bchain_alloc(DEFAULT_BCHAINSIZE);
736       o->next->prev = o->next;
737       o = o->next;
738     }
739     if(o->allocd > o->start + o->size) {
740       int tocopy = MIN(l, o->allocd - o->start - o->size);
741       memcpy(o->buff + o->start + o->size, (const char *)b + boff, tocopy);
742       o->size += tocopy;
743       boff += tocopy;
744       l -= tocopy;
745     }
746   }
747   return noit_true;
748 }
749 noit_boolean
750 noit_http_response_append_bchain(noit_http_session_ctx *ctx,
751                                  struct bchain *b) {
752   struct bchain *o;
753   if(ctx->res.closed == noit_true) return noit_false;
754   if(ctx->res.output_started == noit_true &&
755      !(ctx->res.output_options & (NOIT_HTTP_CHUNKED | NOIT_HTTP_CLOSE)))
756     return noit_false;
757   if(!ctx->res.output)
758     ctx->res.output = b;
759   else {
760     o = ctx->res.output;
761     while(o->next) o = o->next;
762     o->next = b;
763     b->prev = o;
764   }
765   return noit_true;
766 }
767 static int
768 _http_construct_leader(noit_http_session_ctx *ctx) {
769   int len = 0, tlen;
770   struct bchain *b;
771   const char *protocol_str;
772   const char *key, *value;
773   int klen;
774   noit_hash_iter iter = NOIT_HASH_ITER_ZERO;
775
776   assert(!ctx->res.leader);
777   ctx->res.leader = b = bchain_alloc(DEFAULT_BCHAINSIZE);
778
779   protocol_str = ctx->res.protocol == NOIT_HTTP11 ?
780                    "HTTP/1.1" :
781                    (ctx->res.protocol == NOIT_HTTP10 ?
782                      "HTTP/1.0" :
783                      "HTTP/0.9");
784   tlen = snprintf(b->buff, b->allocd, "%s %03d %s\r\n",
785                   protocol_str, ctx->res.status_code, ctx->res.status_reason);
786   if(tlen < 0) return -1;
787   len = b->size = tlen;
788
789 #define CTX_LEADER_APPEND(s, slen) do { \
790   if(b->size + slen > DEFAULT_BCHAINSIZE) { \
791     b->next = bchain_alloc(DEFAULT_BCHAINSIZE); \
792     assert(b->next); \
793     b->next->prev = b; \
794     b = b->next; \
795   } \
796   assert(DEFAULT_BCHAINSIZE >= b->size + slen); \
797   memcpy(b->buff + b->start + b->size, s, slen); \
798   b->size += slen; \
799 } while(0)
800   while(noit_hash_next_str(&ctx->res.headers, &iter,
801                            &key, &klen, &value)) {
802     int vlen = strlen(value);
803     CTX_LEADER_APPEND(key, klen);
804     CTX_LEADER_APPEND(": ", 2);
805     CTX_LEADER_APPEND(value, vlen);
806     CTX_LEADER_APPEND("\r\n", 2);
807   }
808   CTX_LEADER_APPEND("\r\n", 2);
809   return len;
810 }
811 /* memgzip */
812 static int memgzip2(Bytef *dest, uLongf *destLen,
813                     const Bytef *source, uLong sourceLen, int level) {
814     z_stream stream;
815     int err;
816
817     memset(&stream, 0, sizeof(stream));
818     stream.next_in = (Bytef*)source;
819     stream.avail_in = (uInt)sourceLen;
820     stream.next_out = dest;
821     stream.avail_out = (uInt)*destLen;
822     if ((uLong)stream.avail_out != *destLen) return Z_BUF_ERROR;
823
824     err = deflateInit2(&stream, level, Z_DEFLATED, 15+16, 8,
825                        Z_DEFAULT_STRATEGY);
826     if (err != Z_OK) return err;
827
828     err = deflate(&stream, Z_FINISH);
829     if (err != Z_STREAM_END) {
830         deflateEnd(&stream);
831         return err == Z_OK ? Z_BUF_ERROR : err;
832     }
833     *destLen = stream.total_out;
834
835     err = deflateEnd(&stream);
836     return err;
837 }
838 static noit_boolean
839 _http_encode_chain(struct bchain *out, struct bchain *in, int opts) {
840   /* implement gzip and deflate! */
841   if(opts & NOIT_HTTP_GZIP) {
842     uLongf olen;
843     olen = out->allocd - out->start;
844     if(Z_OK != memgzip2((Bytef *)(out->buff + out->start), &olen,
845                         (Bytef *)(in->buff + in->start), (uLong)in->size,
846                         9)) {
847       noitL(noit_error, "zlib compress2 error\n");
848       return noit_false;
849     }
850     out->size += olen;
851   }
852   else if(opts & NOIT_HTTP_DEFLATE) {
853     uLongf olen;
854     olen = out->allocd - out->start;
855     if(Z_OK != compress2((Bytef *)(out->buff + out->start), &olen,
856                          (Bytef *)(in->buff + in->start), (uLong)in->size,
857                          9)) {
858       noitL(noit_error, "zlib compress2 error\n");
859       return noit_false;
860     }
861     out->size += olen;
862   }
863   else {
864     if(in->size > out->allocd - out->start) return noit_false;
865     memcpy(out->buff + out->start, in->buff + in->start, in->size);
866     out->size += in->size;
867   }
868   return noit_true;
869 }
870 struct bchain *
871 noit_http_process_output_bchain(noit_http_session_ctx *ctx,
872                                 struct bchain *in) {
873   struct bchain *out;
874   int ilen, maxlen = in->size, hexlen;
875   int opts = ctx->res.output_options;
876
877   /* a chunked header looks like: hex*\r\ndata\r\n */
878   /* let's assume that content never gets "larger" */
879   if(opts & NOIT_HTTP_GZIP) maxlen = deflateBound(NULL, in->size);
880   else if(opts & NOIT_HTTP_DEFLATE) maxlen = compressBound(in->size);
881
882   /* So, the link size is the len(data) + 4 + ceil(log(len(data))/log(16)) */
883   ilen = maxlen;
884   hexlen = 0;
885   while(ilen) { ilen >>= 4; hexlen++; }
886   if(hexlen == 0) hexlen = 1;
887
888   out = bchain_alloc(hexlen + 4 + maxlen);
889   /* if we're chunked, let's give outselved hexlen + 2 prefix space */
890   if(opts & NOIT_HTTP_CHUNKED) out->start = hexlen + 2;
891   if(_http_encode_chain(out, in, opts) == noit_false) {
892     free(out);
893     return NULL;
894   }
895   /* Too long! Out "larger" assumption is bad */
896   if(opts & NOIT_HTTP_CHUNKED) {
897     ilen = out->size;
898     assert(out->start+out->size+2 <= out->allocd);
899     out->buff[out->start + out->size++] = '\r';
900     out->buff[out->start + out->size++] = '\n';
901     out->start = 0;
902     /* terminate */
903     out->size += 2;
904     out->buff[hexlen] = '\r';
905     out->buff[hexlen+1] = '\n';
906     /* backfill */
907     out->size += hexlen;
908     while(hexlen > 0) {
909       out->buff[hexlen - 1] = _hexchars[ilen & 0xf];
910       ilen >>= 4;
911       hexlen--;
912     }
913     while(out->buff[out->start] == '0') {
914       out->start++;
915       out->size--;
916     }
917   }
918   return out;
919 }
920 noit_boolean
921 noit_http_response_flush(noit_http_session_ctx *ctx, noit_boolean final) {
922   struct bchain *o, *r;
923   int mask;
924
925   if(ctx->res.closed == noit_true) return noit_false;
926   if(ctx->res.output_started == noit_false) {
927     _http_construct_leader(ctx);
928     ctx->res.output_started = noit_true;
929   }
930   /* encode output to output_raw */
931   r = ctx->res.output_raw;
932   while(r && r->next) r = r->next;
933   /* r is the last raw output link */
934   o = ctx->res.output;
935   /* o is the first output link to process */
936   while(o) {
937     struct bchain *tofree, *n;
938     n = noit_http_process_output_bchain(ctx, o);
939     if(!n) {
940       /* Bad, response stops here! */
941       noitL(noit_error, "noit_http_process_output_bchain: NULL\n");
942       while(o) { tofree = o; o = o->next; free(tofree); }
943       final = noit_true;
944       break;
945     }
946     if(r) {
947       r->next = n;
948       n->prev = r;
949       r = n;
950     }
951     else {
952       r = ctx->res.output_raw = n;
953     }
954     tofree = o; o = o->next; free(tofree); /* advance and free */
955   }
956   ctx->res.output = NULL;
957   if(final) {
958     struct bchain *n;
959     ctx->res.closed = noit_true;
960     if(ctx->res.output_options & NOIT_HTTP_CHUNKED)
961       n = bchain_from_data("0\r\n\r\n", 5);
962     else
963       n = bchain_from_data("\r\n", 2);
964     if(r) {
965       r->next = n;
966       n->prev = r;
967       r = n;
968     }
969     else {
970       r = ctx->res.output_raw = n;
971     }
972   }
973
974   _http_perform_write(ctx, &mask);
975   if(ctx->conn.e) {
976     eventer_update(ctx->conn.e, mask);
977   }
978   /* If the write fails completely, the event will be closed, freed and NULL */
979   return ctx->conn.e ? noit_true : noit_false;
980 }
981 noit_boolean
982 noit_http_response_end(noit_http_session_ctx *ctx) {
983   if(!noit_http_response_flush(ctx, noit_true)) return noit_false;
984   return noit_true;
985 }
986
987
988 /* Helper functions */
989
990 static int
991 noit_http_write_xml(void *vctx, const char *buffer, int len) {
992   if(noit_http_response_append((noit_http_session_ctx *)vctx, buffer, len))
993     return len;
994   return -1;
995 }
996 static int
997 noit_http_close_xml(void *vctx) {
998   noit_http_response_end((noit_http_session_ctx *)vctx);
999   return 0;
1000 }
1001 void
1002 noit_http_response_xml(noit_http_session_ctx *ctx, xmlDocPtr doc) {
1003   xmlOutputBufferPtr out;
1004   xmlCharEncodingHandlerPtr enc;
1005   enc = xmlGetCharEncodingHandler(XML_CHAR_ENCODING_UTF8);
1006   out = xmlOutputBufferCreateIO(noit_http_write_xml,
1007                                 noit_http_close_xml,
1008                                 ctx, enc);
1009   xmlSaveFormatFileTo(out, doc, "utf8", 1);
1010 }
1011
Note: See TracBrowser for help on using the browser.