New utility z_get_HTTP_Response_details
[yaz-moved-to-github.git] / src / http.c
1 /* This file is part of the YAZ toolkit.
2  * Copyright (C) 1995-2013 Index Data
3  * See the file LICENSE for details.
4  */
5 /**
6  * \file http.c
7  * \brief Implements HTTP decoding
8  */
9 #if HAVE_CONFIG_H
10 #include <config.h>
11 #endif
12
13 #include <yaz/odr.h>
14 #include <yaz/yaz-version.h>
15 #include <yaz/yaz-iconv.h>
16 #include <yaz/matchstr.h>
17 #include <yaz/zgdu.h>
18 #include <yaz/base64.h>
19
20 static int decode_headers_content(ODR o, int off, Z_HTTP_Header **headers,
21                                   char **content_buf, int *content_len)
22 {
23     int i = off;
24     int chunked = 0;
25
26     *headers = 0;
27     while (i < o->size-1 && o->buf[i] == '\n')
28     {
29         int po;
30         i++;
31         if (o->buf[i] == '\r' && i < o->size-1 && o->buf[i+1] == '\n')
32         {
33             i++;
34             break;
35         }
36         if (o->buf[i] == '\n')
37             break;
38         for (po = i; ; i++)
39         {
40             if (i == o->size)
41             {
42                 o->error = OHTTP;
43                 return 0;
44             }
45             else if (o->buf[i] == ':')
46                 break;
47         }
48         *headers = (Z_HTTP_Header *) odr_malloc(o, sizeof(**headers));
49         (*headers)->name = (char*) odr_malloc(o, i - po + 1);
50         memcpy ((*headers)->name, o->buf + po, i - po);
51         (*headers)->name[i - po] = '\0';
52         i++;
53         while (i < o->size-1 && o->buf[i] == ' ')
54             i++;
55         for (po = i; i < o->size-1 && !strchr("\r\n", o->buf[i]); i++)
56             ;
57
58         (*headers)->value = (char*) odr_malloc(o, i - po + 1);
59         memcpy ((*headers)->value, o->buf + po, i - po);
60         (*headers)->value[i - po] = '\0';
61
62         if (!yaz_strcasecmp((*headers)->name, "Transfer-Encoding")
63             &&
64             !yaz_strcasecmp((*headers)->value, "chunked"))
65             chunked = 1;
66         headers = &(*headers)->next;
67         if (i < o->size-1 && o->buf[i] == '\r')
68             i++;
69     }
70     *headers = 0;
71     if (o->buf[i] != '\n')
72     {
73         o->error = OHTTP;
74         return 0;
75     }
76     i++;
77
78     if (chunked)
79     {
80         int off = 0;
81
82         /* we know buffer will be smaller than o->size - i*/
83         *content_buf = (char*) odr_malloc(o, o->size - i);
84
85         while (1)
86         {
87             /* chunk length .. */
88             int chunk_len = 0;
89             for (; i  < o->size-2; i++)
90                 if (yaz_isdigit(o->buf[i]))
91                     chunk_len = chunk_len * 16 +
92                         (o->buf[i] - '0');
93                 else if (yaz_isupper(o->buf[i]))
94                     chunk_len = chunk_len * 16 +
95                         (o->buf[i] - ('A'-10));
96                 else if (yaz_islower(o->buf[i]))
97                     chunk_len = chunk_len * 16 +
98                         (o->buf[i] - ('a'-10));
99                 else
100                     break;
101             /* chunk extension ... */
102             while (o->buf[i] != '\r' && o->buf[i+1] != '\n')
103             {
104                 if (i >= o->size-2)
105                 {
106                     o->error = OHTTP;
107                     return 0;
108                 }
109                 i++;
110             }
111             i += 2;  /* skip CRLF */
112             if (chunk_len == 0)
113                 break;
114             if (chunk_len < 0 || off + chunk_len > o->size)
115             {
116                 o->error = OHTTP;
117                 return 0;
118             }
119             /* copy chunk .. */
120             memcpy (*content_buf + off, o->buf + i, chunk_len);
121             i += chunk_len + 2; /* skip chunk+CRLF */
122             off += chunk_len;
123         }
124         if (!off)
125             *content_buf = 0;
126         *content_len = off;
127     }
128     else
129     {
130         if (i > o->size)
131         {
132             o->error = OHTTP;
133             return 0;
134         }
135         else if (i == o->size)
136         {
137             *content_buf = 0;
138             *content_len = 0;
139         }
140         else
141         {
142             *content_len = o->size - i;
143             *content_buf = (char*) odr_malloc(o, *content_len + 1);
144             memcpy(*content_buf, o->buf + i, *content_len);
145             (*content_buf)[*content_len] = '\0';
146         }
147     }
148     return 1;
149 }
150
151 void z_HTTP_header_add_content_type(ODR o, Z_HTTP_Header **hp,
152                                     const char *content_type,
153                                     const char *charset)
154 {
155     const char *l = "Content-Type";
156     if (charset)
157     {
158         char *ctype = (char *)
159             odr_malloc(o, strlen(content_type)+strlen(charset) + 15);
160         sprintf(ctype, "%s; charset=%s", content_type, charset);
161         z_HTTP_header_add(o, hp, l, ctype);
162     }
163     else
164         z_HTTP_header_add(o, hp, l, content_type);
165
166 }
167
168 /*
169  * HTTP Basic authentication is described at:
170  * http://tools.ietf.org/html/rfc1945#section-11.1
171  */
172 void z_HTTP_header_add_basic_auth(ODR o, Z_HTTP_Header **hp,
173                                   const char *username, const char *password)
174 {
175     char *tmp, *buf;
176     int len;
177
178     if (username == 0)
179         return;
180     if (password == 0)
181         password = "";
182
183     len = strlen(username) + strlen(password);
184     tmp = (char *) odr_malloc(o, len+2);
185     sprintf(tmp, "%s:%s", username, password);
186     buf = (char *) odr_malloc(o, (len+1) * 8/6 + 12);
187     strcpy(buf, "Basic ");
188     yaz_base64encode(tmp, &buf[strlen(buf)]);
189     z_HTTP_header_set(o, hp, "Authorization", buf);
190 }
191
192
193 void z_HTTP_header_add(ODR o, Z_HTTP_Header **hp, const char *n,
194                        const char *v)
195 {
196     while (*hp)
197         hp = &(*hp)->next;
198     *hp = (Z_HTTP_Header *) odr_malloc(o, sizeof(**hp));
199     (*hp)->name = odr_strdup(o, n);
200     (*hp)->value = odr_strdup(o, v);
201     (*hp)->next = 0;
202 }
203
204 void z_HTTP_header_set(ODR o, Z_HTTP_Header **hp, const char *n,
205                        const char *v)
206 {
207     while (*hp)
208     {
209         if (!yaz_strcasecmp((*hp)->name, n))
210         {
211             (*hp)->value = odr_strdup(o, v);
212             return;
213         }
214         hp = &(*hp)->next;
215     }
216     *hp = (Z_HTTP_Header *) odr_malloc(o, sizeof(**hp));
217     (*hp)->name = odr_strdup(o, n);
218     (*hp)->value = odr_strdup(o, v);
219     (*hp)->next = 0;
220 }
221
222 const char *z_HTTP_header_remove(Z_HTTP_Header **hp, const char *n)
223 {
224     while (*hp)
225     {
226         if (!yaz_strcasecmp((*hp)->name, n))
227         {
228             const char *v = (*hp)->value;
229             *hp = (*hp)->next;
230             return v;
231         }
232         hp = &(*hp)->next;
233     }
234     return 0;
235 }
236
237 const char *z_HTTP_header_lookup(const Z_HTTP_Header *hp, const char *n)
238 {
239     for (; hp; hp = hp->next)
240         if (!yaz_strcasecmp(hp->name, n))
241             return hp->value;
242     return 0;
243 }
244
245
246 Z_GDU *z_get_HTTP_Request(ODR o)
247 {
248     Z_GDU *p = (Z_GDU *) odr_malloc(o, sizeof(*p));
249     Z_HTTP_Request *hreq;
250
251     p->which = Z_GDU_HTTP_Request;
252     p->u.HTTP_Request = (Z_HTTP_Request *) odr_malloc(o, sizeof(*hreq));
253     hreq = p->u.HTTP_Request;
254     hreq->headers = 0;
255     hreq->content_len = 0;
256     hreq->content_buf = 0;
257     hreq->version = "1.1";
258     hreq->method = "POST";
259     hreq->path = "/";
260     z_HTTP_header_add(o, &hreq->headers, "User-Agent", "YAZ/" YAZ_VERSION);
261     return p;
262 }
263
264
265 Z_GDU *z_get_HTTP_Request_host_path(ODR odr,
266                                     const char *host,
267                                     const char *path)
268 {
269     Z_GDU *p = z_get_HTTP_Request(odr);
270
271     p->u.HTTP_Request->path = odr_strdup(odr, path);
272
273     if (host)
274     {
275         const char *cp0 = strstr(host, "://");
276         const char *cp1 = 0;
277         if (cp0)
278             cp0 = cp0+3;
279         else
280             cp0 = host;
281
282         cp1 = strchr(cp0, '/');
283         if (!cp1)
284             cp1 = cp0+strlen(cp0);
285
286         if (cp0 && cp1)
287         {
288             char *h = (char*) odr_malloc(odr, cp1 - cp0 + 1);
289             memcpy (h, cp0, cp1 - cp0);
290             h[cp1-cp0] = '\0';
291             z_HTTP_header_add(odr, &p->u.HTTP_Request->headers,
292                               "Host", h);
293         }
294     }
295     return p;
296 }
297
298 Z_GDU *z_get_HTTP_Request_uri(ODR odr, const char *uri, const char *args,
299                               int use_full_uri)
300 {
301     Z_GDU *p = z_get_HTTP_Request(odr);
302     const char *cp0 = strstr(uri, "://");
303     const char *cp1 = 0;
304     if (cp0)
305         cp0 = cp0+3;
306     else
307         cp0 = uri;
308
309     cp1 = strchr(cp0, '/');
310     if (!cp1)
311         cp1 = cp0+strlen(cp0);
312
313     if (cp0 && cp1)
314     {
315         char *h = (char*) odr_malloc(odr, cp1 - cp0 + 1);
316         memcpy (h, cp0, cp1 - cp0);
317         h[cp1-cp0] = '\0';
318         z_HTTP_header_add(odr, &p->u.HTTP_Request->headers,
319                           "Host", h);
320     }
321
322     if (!args)
323     {
324         if (*cp1)
325             args = cp1 + 1;
326         else
327             args = "";
328     }
329     p->u.HTTP_Request->path = odr_malloc(odr, cp1 - uri + strlen(args) + 2);
330     if (use_full_uri)
331     {
332         memcpy(p->u.HTTP_Request->path, uri, cp1 - uri);
333         strcpy(p->u.HTTP_Request->path + (cp1 - uri), "/");
334     }
335     else
336         strcpy(p->u.HTTP_Request->path, "/");
337     strcat(p->u.HTTP_Request->path, args);
338     return p;
339 }
340
341 Z_GDU *z_get_HTTP_Response_details(ODR o, int code, const char *details)
342 {
343     Z_GDU *p = (Z_GDU *) odr_malloc(o, sizeof(*p));
344     Z_HTTP_Response *hres;
345
346     p->which = Z_GDU_HTTP_Response;
347     p->u.HTTP_Response = (Z_HTTP_Response *) odr_malloc(o, sizeof(*hres));
348     hres = p->u.HTTP_Response;
349     hres->headers = 0;
350     hres->content_len = 0;
351     hres->content_buf = 0;
352     hres->code = code;
353     hres->version = "1.1";
354     z_HTTP_header_add(o, &hres->headers, "Server",
355                       "YAZ/" YAZ_VERSION);
356     if (code != 200)
357     {
358         const char *http_err = z_HTTP_errmsg(code);
359         size_t sz = 400 + strlen(http_err) + (details ?
360                                               strlen(details) : 0);
361         hres->content_buf = (char*) odr_malloc(o, sz);
362         sprintf(hres->content_buf,
363                 "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\""
364                 " \"http://www.w3.org/TR/html4/strict.dtd\">\n"
365                 "<HTML>\n"
366                 " <HEAD>\n"
367                 "  <TITLE>YAZ " YAZ_VERSION "</TITLE>\n"
368                 " </HEAD>\n"
369                 " <BODY>\n"
370                 "  <P><A HREF=\"http://www.indexdata.com/yaz/\">YAZ</A> "
371                 YAZ_VERSION "</P>\n"
372                 "  <P>Error: %d</P>\n"
373                 "  <P>Description: %s</P>\n", code, http_err);
374         if (details)
375         {
376             sprintf(hres->content_buf + strlen(hres->content_buf),
377                     "<P>Details: %s</P>\n", details);
378         }
379         sprintf(hres->content_buf + strlen(hres->content_buf),
380                 " </BODY>\n"
381                 "</HTML>\n");
382         hres->content_len = strlen(hres->content_buf);
383         z_HTTP_header_add(o, &hres->headers, "Content-Type", "text/html");
384     }
385     return p;
386 }
387
388 Z_GDU *z_get_HTTP_Response(ODR o, int code)
389 {
390     return z_get_HTTP_Response_details(o, code, 0);
391 }
392
393 const char *z_HTTP_errmsg(int code)
394 {
395     switch (code)
396     {
397     case 100:
398         return "Continue";
399     case 101:
400         return "Switching Protocols";
401     case 200:
402         return "OK";
403     case 201:
404         return "Created";
405     case 202:
406         return "Accepted";
407     case 203:
408         return "Non-Authoritative Information";
409     case 204:
410         return "No Content";
411     case 205:
412         return "Reset Content";
413     case 206:
414         return "Partial Content";
415     case 300:
416         return "Multiple Choices";
417     case 301:
418         return "Moved Permenently";
419     case 302:
420         return "Found";
421     case 303:
422         return "See Other";
423     case 304:
424         return "Not Modified";
425     case 305:
426         return "Use Proxy";
427     case 307:
428         return "Temporary Redirect";
429     case 400:
430         return "Bad Request";
431     case 404:
432         return "Not Found";
433     case 405:
434         return "Method Not Allowed";
435     case 406:
436         return "Not Acceptable";
437     case 407:
438         return "Proxy Authentication Required";
439     case 408:
440         return "Request Timeout";
441     case 409:
442         return "Conflict";
443     case 410:
444         return "Gone";
445     case 411:
446         return "Length Required";
447     case 412:
448         return "Precondition Failed";
449     case 413:
450         return "Request Entity Too Large";
451     case 414:
452         return "Request-URI Too Long";
453     case 415:
454         return "Unsupported Media Type";
455     case 416:
456         return "Requested Range Not Satisfiable";
457     case 417:
458         return "Expectation Failed";
459     case 500:
460         return "Internal Error";
461     case 501:
462         return "Not Implemented";
463     case 502:
464         return "Bad Gateway";
465     case 503:
466         return "Service Unavailable";
467     case 504:
468         return "Gateway Timeout";
469     case 505:
470         return "HTTP Version Not Supported";
471     default:
472         return "Unknown Error";
473     }
474 }
475
476 int yaz_decode_http_response(ODR o, Z_HTTP_Response **hr_p)
477 {
478     int i, po;
479     Z_HTTP_Response *hr = (Z_HTTP_Response *) odr_malloc(o, sizeof(*hr));
480
481     *hr_p = hr;
482     hr->content_buf = 0;
483     hr->content_len = 0;
484
485     po = i = 5;
486     while (i < o->size-2 && !strchr(" \r\n", o->buf[i]))
487         i++;
488     hr->version = (char *) odr_malloc(o, i - po + 1);
489     if (i - po)
490         memcpy(hr->version, o->buf + po, i - po);
491     hr->version[i-po] = 0;
492     if (o->buf[i] != ' ')
493     {
494         o->error = OHTTP;
495         return 0;
496     }
497     i++;
498     hr->code = 0;
499     while (i < o->size-2 && o->buf[i] >= '0' && o->buf[i] <= '9')
500     {
501         hr->code = hr->code*10 + (o->buf[i] - '0');
502         i++;
503     }
504     while (i < o->size-1 && o->buf[i] != '\n')
505         i++;
506     return decode_headers_content(o, i, &hr->headers,
507                                   &hr->content_buf, &hr->content_len);
508 }
509
510 int yaz_decode_http_request(ODR o, Z_HTTP_Request **hr_p)
511 {
512     int i, po;
513     Z_HTTP_Request *hr = (Z_HTTP_Request *) odr_malloc(o, sizeof(*hr));
514
515     *hr_p = hr;
516
517     /* method .. */
518     for (i = 0; o->buf[i] != ' '; i++)
519         if (i >= o->size-5 || i > 30)
520         {
521             o->error = OHTTP;
522             return 0;
523         }
524     hr->method = (char *) odr_malloc(o, i+1);
525     memcpy (hr->method, o->buf, i);
526     hr->method[i] = '\0';
527     /* path */
528     po = i+1;
529     for (i = po; o->buf[i] != ' '; i++)
530         if (i >= o->size-5)
531         {
532             o->error = OHTTP;
533             return 0;
534         }
535     hr->path = (char *) odr_malloc(o, i - po + 1);
536     memcpy (hr->path, o->buf+po, i - po);
537     hr->path[i - po] = '\0';
538     /* HTTP version */
539     i++;
540     if (i > o->size-5 || memcmp(o->buf+i, "HTTP/", 5))
541     {
542         o->error = OHTTP;
543         return 0;
544     }
545     i+= 5;
546     po = i;
547     while (i < o->size && !strchr("\r\n", o->buf[i]))
548         i++;
549     hr->version = (char *) odr_malloc(o, i - po + 1);
550     memcpy(hr->version, o->buf + po, i - po);
551     hr->version[i - po] = '\0';
552     /* headers */
553     if (i < o->size-1 && o->buf[i] == '\r')
554         i++;
555     if (o->buf[i] != '\n')
556     {
557         o->error = OHTTP;
558         return 0;
559     }
560     return decode_headers_content(o, i, &hr->headers,
561                                   &hr->content_buf, &hr->content_len);
562 }
563
564 static void dump_http_package(ODR o, const char *buf, size_t len)
565 {
566     int i;
567     for (i = 0; ; i++)
568     {
569         if (i == len)
570         {
571             odr_printf(o, "%.*s\n", i, buf);
572             break;
573         }
574         else if (i > 8192)
575         {
576             odr_printf(o, "%.*s\n", i, buf);
577             odr_printf(o, "(truncated\n", (long) len);
578             break;
579         }
580         else if (buf[i] == 0)
581         {
582             odr_printf(o, "%.*s\n", i, buf);
583             odr_printf(o, "(binary data)\n", (long) len);
584             break;
585         }
586     }
587 }
588
589 int yaz_encode_http_response(ODR o, Z_HTTP_Response *hr)
590 {
591     char sbuf[80];
592     Z_HTTP_Header *h;
593     int top0 = o->top;
594
595     sprintf(sbuf, "HTTP/%s %d %s\r\n", hr->version,
596             hr->code,
597             z_HTTP_errmsg(hr->code));
598     odr_write2(o, sbuf, strlen(sbuf));
599     /* use content_len for Content-Length */
600     sprintf(sbuf, "Content-Length: %d\r\n", hr->content_len);
601     odr_write2(o, sbuf, strlen(sbuf));
602     for (h = hr->headers; h; h = h->next)
603     {
604         if (yaz_strcasecmp(h->name, "Content-Length")
605             && yaz_strcasecmp(h->name, "Transfer-Encoding"))
606         {   /* skip Content-Length if given. content_len rules */
607             odr_write2(o, h->name, strlen(h->name));
608             odr_write2(o, ": ", 2);
609             odr_write2(o, h->value, strlen(h->value));
610             odr_write2(o, "\r\n", 2);
611         }
612     }
613     odr_write(o, (unsigned char *) "\r\n", 2);
614     if (hr->content_buf)
615         odr_write2(o, hr->content_buf, hr->content_len);
616     if (o->direction == ODR_PRINT)
617     {
618         odr_printf(o, "-- HTTP response:\n");
619         dump_http_package(o, (const char *) o->buf + top0, o->top - top0);
620         odr_printf(o, "--\n");
621     }
622     return 1;
623 }
624
625 int yaz_encode_http_request(ODR o, Z_HTTP_Request *hr)
626 {
627     Z_HTTP_Header *h;
628     int top0 = o->top;
629
630     odr_write2(o, hr->method, strlen(hr->method));
631     odr_write2(o, " ", 1);
632     odr_write2(o, hr->path, strlen(hr->path));
633     odr_write2(o, " HTTP/", 6);
634     odr_write2(o, hr->version, strlen(hr->version));
635     odr_write2(o, "\r\n", 2);
636     if (hr->content_len &&
637         !z_HTTP_header_lookup(hr->headers,
638                               "Content-Length"))
639     {
640         char lstr[60];
641         sprintf(lstr, "Content-Length: %d\r\n",
642                 hr->content_len);
643         odr_write2(o, lstr, strlen(lstr));
644     }
645     for (h = hr->headers; h; h = h->next)
646     {
647         odr_write2(o, h->name, strlen(h->name));
648         odr_write2(o, ": ", 2);
649         odr_write2(o, h->value, strlen(h->value));
650         odr_write2(o, "\r\n", 2);
651     }
652     odr_write2(o, "\r\n", 2);
653     if (hr->content_buf)
654         odr_write2(o, hr->content_buf, hr->content_len);
655     if (o->direction == ODR_PRINT)
656     {
657         odr_printf(o, "-- HTTP request:\n");
658         dump_http_package(o, (const char *) o->buf + top0, o->top - top0);
659         odr_printf(o, "--\n");
660     }
661     return 1;
662 }
663
664 /*
665  * Local variables:
666  * c-basic-offset: 4
667  * c-file-style: "Stroustrup"
668  * indent-tabs-mode: nil
669  * End:
670  * vim: shiftwidth=4 tabstop=8 expandtab
671  */
672