]> mj.ucw.cz Git - netgrind.git/blob - netgrind/http.c
b90c89382d7650447543b08c0b4a5edcf1bed6df
[netgrind.git] / netgrind / http.c
1 /*
2  *      Netgrind -- HTTP Analyser
3  *
4  *      (c) 2003 Martin Mares <mj@ucw.cz>
5  *
6  *      This software may be freely distributed and used according to the terms
7  *      of the GNU General Public License.
8  */
9
10 #undef LOCAL_DEBUG
11
12 #include "lib/lib.h"
13 #include "lib/pools.h"
14 #include "netgrind/pkt.h"
15 #include "netgrind/netgrind.h"
16
17 #include <stdio.h>
18 #include <stdlib.h>
19 #include <string.h>
20 #include <alloca.h>
21 #include <netinet/in.h>
22
23 #define MAXLINE 4096
24
25 struct http_header {
26   node n;
27   byte *name, *value;
28   byte buf[1];
29 };
30
31 struct http_state {
32   enum {
33     HTTP_IDLE,                  /* initialized, waiting for request */
34     HTTP_ERROR,                 /* protocol error, ignoring everything else */
35     HTTP_CUT,                   /* unexpected EOF in one direction, ignoring everything else */
36     HTTP_REQUEST,               /* parsing request */
37     HTTP_BODY_CHUNKED,          /* receiving body: chunked encoding */
38     HTTP_BODY_LENGTH,           /* receiving body: length given */
39     HTTP_BODY_INF,              /* receiving body: till EOF */
40     HTTP_RESPONSE,              /* parsing response */
41     HTTP_DONE,                  /* transaction finished, logging it */
42     HTTP_CONNECT,               /* inside CONNECT transaction */
43   } state;
44   byte *error;
45   u64 req_start_time, resp_start_time;
46   uns id;
47   struct mempool *pool;
48   list tx_queue, rx_queue;
49   byte *req_line, *resp_line;
50   list req_headers, resp_headers;
51   byte line[MAXLINE];
52   uns line_len;
53   uns body_len;
54   uns body_trailer;
55   list *body_queue;
56   uns body_end_state;
57   uns body_total_size;
58   uns req_counter;
59 };
60
61 static void http_open(struct flow *f, u64 when)
62 {
63   static int http_counter;
64   struct http_state *s = xmalloc_zero(sizeof(*s));
65   f->appl_data = s;
66   s->id = http_counter++;
67   DBG("HTTP: %d NEW %d.%d.%d.%d:%d -> %d.%d.%d.%d:%d\n", s->id,
68       IPQUAD(f->saddr), ntohs(f->sport), IPQUAD(f->daddr), ntohs(f->dport));
69   list_init(&s->tx_queue);
70   list_init(&s->rx_queue);
71   s->req_start_time = when;
72 }
73
74 static byte *http_lookup_hdr(list *l, byte *name)
75 {
76   struct http_header *h;
77   WALK_LIST(h, *l)
78     if (!strcasecmp(h->name, name))
79       return h->value;
80   return NULL;
81 }
82
83 static uns find_token(byte *hay, byte *needle)
84 {
85   if (!hay)
86     return 0;
87   while (*hay)
88     {
89       if (*hay == ' ' || *hay == '\t' || *hay == ',')
90         hay++;
91       else
92         {
93           byte *h = hay;
94           while (*hay && *hay != ',' && *hay != ' ' && *hay != '\t')
95             hay++;
96           uns old = *hay;
97           *hay = 0;
98           uns found = !strcasecmp(h, needle);
99           *hay = old;
100           if (found)
101             return 1;
102         }
103     }
104   return 0;
105 }
106
107 static void http_report(struct flow *f, struct http_state *s, u64 when, byte *reason)
108 {
109   byte *method, *url, *x, *y, *stat;
110   static uns http_counter;
111
112   if (!(method = s->req_line))
113     return;
114
115   /* Analyse request line */
116   url = method;
117   while (*url && *url != ' ')
118     url++;
119   while (*url == ' ')
120     *url++ = 0;
121   x = url;
122   while (*x != ' ')
123     x++;
124   *x = 0;
125
126   /* Analyse response line */
127   if (stat = s->resp_line)
128     {
129       while (*stat && *stat != ' ')
130         stat++;
131       while (*stat == ' ')
132         stat++;
133       x = stat;
134       while (*x && *x != ' ')
135         x++;
136       *x = 0;
137     }
138   else
139     stat = "";
140   if (!reason)
141     reason = stat[0] ? stat : (byte*)"???";
142
143   /* Reconstruct full URL */
144   if (!strstr(url, "://") && strcasecmp(method, "CONNECT"))
145     {
146       if (!(x = http_lookup_hdr(&s->req_headers, "Host:")))
147         x = "???";
148       y = url;
149       url = alloca(7 + strlen(x) + strlen(y) + 1);
150       sprintf(url, "http://%s%s", x, y);
151     }
152   char *ffor = http_lookup_hdr(&s->req_headers, "X-Forwarded-For:");
153
154   /* Find out cacheability */
155   byte *rq_pragma = http_lookup_hdr(&s->req_headers, "Pragma:");
156   byte *rp_pragma = http_lookup_hdr(&s->resp_headers, "Pragma:");
157   byte *rq_cc = http_lookup_hdr(&s->req_headers, "Cache-control:");
158   byte *rp_cc = http_lookup_hdr(&s->resp_headers, "Cache-control:");
159   byte *rp_cache = http_lookup_hdr(&s->resp_headers, "X-Cache:");
160   uns rq_cflag, rp_cflag, rp_hit;
161   if (find_token(rq_pragma, "no-cache") || find_token(rq_cc, "no-cache"))
162     rq_cflag = 'N';
163   else if (find_token(rq_cc, "max-age=0") || find_token(rq_cc, "must-revalidate"))
164     rq_cflag = 'R';
165   else
166     rq_cflag = '.';
167   if (find_token(rp_pragma, "no-cache") || find_token(rp_cc, "no-cache"))
168     rp_cflag = 'N';
169   else if (find_token(rp_cc, "private"))
170     rp_cflag = 'P';
171   else if (find_token(rp_cc, "no-store"))
172     rp_cflag = 'S';
173   else if (find_token(rp_cc, "must-revalidate"))
174     rp_cflag = 'R';
175   else
176     rp_cflag = '.';
177   if (!rp_cache)
178     rp_hit = '.';
179   else if (!strncmp(rp_cache, "HIT ", 4))
180     rp_hit = '+';
181   else if (!strncmp(rp_cache, "MISS ", 5))
182     rp_hit = '-';
183   else
184     rp_hit = '?';
185
186   byte stamp[TIMESTAMP_LEN], src[22], dst[22];
187   sprintf(src, "%d.%d.%d.%d:%d", IPQUAD(f->saddr), ntohs(f->sport));
188   sprintf(dst, "%d.%d.%d.%d:%d", IPQUAD(f->daddr), ntohs(f->dport));
189   format_timestamp(stamp, s->req_start_time);
190   u64 ttotal = when - s->req_start_time;
191   u64 tresp = (s->resp_line ? (s->resp_start_time - s->req_start_time) : 0);
192   if (!http_counter++)
193     printf("# timestamp             source                destination           forwarded-for   res cac que   length total time  wait time method URL\n");
194          /* 2003-06-06 22:53:38.642 81.27.194.19:1175     205.217.153.53:80     123.123.123.123 200 ...   0    14030      0.957      0.444 GET http://... */
195   printf("%s %-21s %-21s %-15s %-3s %c%c%c %3d %8d %6d.%03d %6d.%03d %s %s\n",
196          stamp, src, dst, (ffor ? : "-"), reason,
197          rq_cflag, rp_cflag, rp_hit,
198          s->req_counter,
199          s->body_total_size,
200          (uns)(ttotal/1000000), (uns)(ttotal%1000000)/1000,
201          (uns)(tresp/1000000), (uns)(tresp%1000000)/1000,
202          method, url);
203
204   s->req_counter++;
205 }
206
207 static void http_close(struct flow *f, int cause, u64 when)
208 {
209   struct http_state *s = f->appl_data;
210   DBG("HTTP: %d CLOSE in state %d (cause %d)\n", s->id, s->state, cause);
211   if (cause != CAUSE_CLOSE)
212     {
213       if (s->state != HTTP_IDLE)
214         {
215           byte buf[16];
216           sprintf(buf, "T%s", flow_cause_names_short[cause]);
217           http_report(f, s, when, buf);
218         }
219     }
220   else
221     switch (s->state)
222       {
223       case HTTP_ERROR:
224         http_report(f, s, when, "ERR");
225         break;
226       case HTTP_CUT:
227         http_report(f, s, when, "CUT");
228         break;
229       case HTTP_CONNECT:
230         http_report(f, s, when, "FIN");
231         break;
232       }
233   pkt_flush_queue(&s->rx_queue);
234   pkt_flush_queue(&s->tx_queue);
235   if (s->pool)
236     mp_delete(s->pool);
237   xfree(s);
238 }
239
240 static struct http_header *http_get_line(struct http_state *s, list *l)
241 {
242   for(;;)
243     {
244       struct pkt *p = list_head(l);
245       if (!p)
246         return NULL;
247       while (p->data < p->stop)
248         {
249           uns c = *p->data++;
250           if (c == '\r')
251             ;
252           else if (c == '\n')
253             {
254               struct http_header *h = mp_alloc(s->pool, sizeof(*h) + s->line_len);
255               memcpy(h->buf, s->line, s->line_len);
256               h->buf[s->line_len] = 0;
257               h->name = h->value = NULL;
258               s->line_len = 0;
259               return h;
260             }
261           else if (s->line_len >= MAXLINE-1)
262             {
263               DBG("HTTP: Line too long!\n");
264               s->state = HTTP_ERROR;
265               return NULL;
266             }
267           else
268             s->line[s->line_len++] = c;
269         }
270       list_remove(&p->n);
271       pkt_free(p);
272     }
273 }
274
275 static int http_skip_body_bytes(struct http_state *s)
276 {
277   for(;;)
278     {
279       struct pkt *p = list_head(s->body_queue);
280       if (!p)
281         return 0;
282       uns avail = pkt_len(p);
283       uns want = s->body_len;
284       uns go = MIN(avail, want);
285       p->data += go;
286       s->body_len -= go;
287       s->body_total_size += go;
288       if (!s->body_len)
289         return 1;
290       if (!pkt_len(p))
291         {
292           list_remove(&p->n);
293           pkt_free(p);
294         }
295     }
296 }
297
298 static int http_have_input(list *l)
299 {
300   for(;;)
301     {
302       struct pkt *p = list_head(l);
303       if (!p)
304         return 0;
305       if (pkt_len(p))
306         return 1;
307       list_remove(&p->n);
308       pkt_free(p);
309     }
310 }
311
312 static void http_init_xact(struct http_state *s)
313 {
314   list_init(&s->req_headers);
315   list_init(&s->resp_headers);
316   if (s->pool)
317     mp_flush(s->pool);
318   else
319     s->pool = mp_new(4096);
320   s->req_line = s->resp_line = NULL;
321   s->line_len = 0;
322   s->body_total_size = 0;
323 }
324
325 static void http_parse_hdr(list *l, struct http_header *h)
326 {
327   byte *x = h->buf;
328   h->name = x;
329   while (*x && *x != ' ' && *x != '\t')
330     x++;
331   while (*x == ' ' || *x == '\t')
332     *x++ = 0;
333   h->value = x;
334   list_add_tail(l, &h->n);
335 }
336
337 static int http_ask_body(struct http_state *s, list *hdr)
338 {
339   byte *x;
340   if (x = http_lookup_hdr(hdr, "Transfer-Encoding:"))
341     {
342       DBG("\tBody encoding: %s\n", x);
343       if (!strcasecmp(x, "chunked"))
344         {
345           s->state = HTTP_BODY_CHUNKED;
346           s->body_len = 0;
347           s->body_trailer = 0;
348         }
349       else
350         s->state = HTTP_ERROR;
351     }
352   else if (x = http_lookup_hdr(hdr, "Content-Length:"))
353     {
354       s->body_len = atol(x);
355       DBG("\tBody length: %d\n", s->body_len);
356       s->state = HTTP_BODY_LENGTH;
357     }
358   else
359     return 0;
360   return 1;
361 }
362
363 static void http_parse_req(struct http_state *s)
364 {
365   if (!strstr(s->req_line, " HTTP/1"))
366     {
367       DBG("\tNot a HTTP/1.x request!\n");
368       s->state = HTTP_ERROR;
369     }
370   else if (http_ask_body(s, &s->req_headers))
371     ;
372   else if (!strncasecmp(s->req_line, "POST ", 4))
373     {
374       DBG("\tPOST with no request body, that smells!\n");
375       s->state = HTTP_BODY_INF;
376     }
377   else
378     {
379       DBG("\tNo request body, awaiting reply\n");
380       s->state = HTTP_RESPONSE;
381     }
382   s->body_queue = &s->tx_queue;
383   s->body_end_state = HTTP_RESPONSE;
384 }
385
386 static void http_parse_resp(struct http_state *s)
387 {
388   if (!strncasecmp(s->req_line, "HEAD ", 5))
389     {
390       DBG("\tHEAD has no body :)\n");
391       s->state = HTTP_DONE;
392     }
393   else if (http_ask_body(s, &s->resp_headers))
394     ;
395   else if (!strncasecmp(s->req_line, "GET ", 4) && strstr(s->resp_line, " 200 "))
396     {
397       DBG("\tGET with no response body, that smells!\n");
398       s->state = HTTP_BODY_INF;
399     }
400   else
401     {
402       DBG("\tNo response body\n");
403       s->state = HTTP_DONE;
404     }
405   s->body_queue = &s->rx_queue;
406   s->body_end_state = HTTP_DONE;
407 }
408
409 static void http_input(struct flow *f, int dir, struct pkt *p)
410 {
411   struct http_state *s = f->appl_data;
412   struct http_header *h;
413   int fin_tx = (f->pipe[0].state == FLOW_FINISHED);
414   int fin_rx = (f->pipe[1].state == FLOW_FINISHED);
415
416   // DBG("dir=%d txf=%d rxf=%d len=%d\n", dir, fin_tx, fin_rx, pkt_len(p));
417   if (s->state == HTTP_ERROR || s->state == HTTP_CUT)
418     {
419       DBG("HTTP: %d DROPPING INPUT\n", s->id);
420       pkt_free(p);
421       return;
422     }
423   if (pkt_len(p))
424     list_add_tail((dir ? &s->tx_queue : &s->rx_queue), &p->n);
425   for(;;)
426     {
427       DBG("HTTP: %d STATE %d\n", s->id, s->state);
428       switch (s->state)
429         {
430         case HTTP_IDLE:
431           if (fin_tx || !http_have_input(&s->tx_queue))
432             return;
433           s->state = HTTP_REQUEST;
434           http_init_xact(s);
435           if (!s->req_start_time)
436             s->req_start_time = p->timestamp;
437           break;
438         case HTTP_REQUEST:
439           if (fin_tx || fin_rx)
440             goto cut;
441           if (!(h = http_get_line(s, &s->tx_queue)))
442             return;
443           DBG("\t>> %s\n", h->buf);
444           if (!s->req_line)
445             {
446               if (!h->buf[0])
447                 goto err;
448               s->req_line = h->buf;
449             }
450           else if (h->buf[0])
451             http_parse_hdr(&s->req_headers, h);
452           else
453             http_parse_req(s);
454           break;
455         case HTTP_BODY_LENGTH:
456           if (fin_rx)
457             goto cut;
458           if (!http_skip_body_bytes(s))
459             return;
460           DBG("\tEnd of body\n");
461           s->state = s->body_end_state;
462           break;
463         case HTTP_BODY_CHUNKED:
464           if (fin_rx)
465             goto cut;
466           if (s->body_len)
467             {
468               if (!http_skip_body_bytes(s))
469                 return;
470             }
471           else if (s->body_trailer)
472             {
473               if (!(h = http_get_line(s, s->body_queue)))
474                 return;
475               if (!h->buf[0])
476                 {
477                   DBG("\tEnd of chunk-encoded body\n");
478                   s->state = s->body_end_state;
479                 }
480             }
481           else
482             {
483               if (!(h = http_get_line(s, s->body_queue)))
484                 return;
485               if (sscanf(h->buf, "%x", &s->body_len) != 1)
486                 goto err;
487               if (s->body_len)
488                 s->body_len += 2; /* extra CRLF */
489               else                /* last chunk */
490                 s->body_trailer = 1;
491             }
492           break;
493         case HTTP_BODY_INF:
494           s->body_len = ~0U;
495           http_skip_body_bytes(s);
496           if (fin_rx)
497             {
498               DBG("\tEnd of FIN-delimited body\n");
499               s->state = s->body_end_state;
500             }
501           else
502             return;
503           break;
504         case HTTP_RESPONSE:
505           if (fin_rx)
506             goto cut;
507           if (!(h = http_get_line(s, &s->rx_queue)))
508             return;
509           DBG("\t<< %s\n", h->buf);
510           if (!s->resp_line)
511             {
512               if (!h->buf[0])
513                 goto err;
514               s->resp_line = h->buf;
515               s->resp_start_time = p->timestamp;
516             }
517           else if (h->buf[0])
518             http_parse_hdr(&s->resp_headers, h);
519           else
520             http_parse_resp(s);
521           break;
522         case HTTP_DONE:
523           DBG("\tTransaction finished.\n");
524           if (!strncasecmp(s->req_line, "CONNECT ", 8))
525             {
526               s->state = HTTP_CONNECT;
527               return;
528             }
529           http_report(f, s, p->timestamp, NULL);
530           s->state = HTTP_IDLE;
531           s->req_start_time = 0;
532           break;
533         case HTTP_CONNECT:
534           s->body_len = ~0U;
535           s->body_queue = &s->rx_queue;
536           http_skip_body_bytes(s);
537           s->body_len = ~0U;
538           s->body_queue = &s->tx_queue;
539           http_skip_body_bytes(s);
540           return;
541         case HTTP_ERROR:
542         case HTTP_CUT:
543           return;
544         default:
545           ASSERT(0);
546         }
547     }
548
549  err:
550   DBG("HTTP: %d ERROR: PROTOCOL VIOLATION\n", s->id);
551   s->state = HTTP_ERROR;
552   return;
553
554  cut:
555   DBG("HTTP: %d ERROR: UNEXPECTED EOF\n", s->id);
556   s->state = HTTP_CUT;
557 }
558
559 struct appl_hooks appl_http = {
560   .open = http_open,
561   .input = http_input,
562   .close = http_close
563 };