Define local strcasecmp funcs
[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_lookup(const Z_HTTP_Header *hp, const char *n)
223 {
224     for (; hp; hp = hp->next)
225         if (!yaz_strcasecmp(hp->name, n))
226             return hp->value;
227     return 0;
228 }
229
230
231 Z_GDU *z_get_HTTP_Request(ODR o)
232 {
233     Z_GDU *p = (Z_GDU *) odr_malloc(o, sizeof(*p));
234     Z_HTTP_Request *hreq;
235
236     p->which = Z_GDU_HTTP_Request;
237     p->u.HTTP_Request = (Z_HTTP_Request *) odr_malloc(o, sizeof(*hreq));
238     hreq = p->u.HTTP_Request;
239     hreq->headers = 0;
240     hreq->content_len = 0;
241     hreq->content_buf = 0;
242     hreq->version = "1.1";
243     hreq->method = "POST";
244     hreq->path = "/";
245     z_HTTP_header_add(o, &hreq->headers, "User-Agent", "YAZ/" YAZ_VERSION);
246     return p;
247 }
248
249
250 Z_GDU *z_get_HTTP_Request_host_path(ODR odr,
251                                     const char *host,
252                                     const char *path)
253 {
254     Z_GDU *p = z_get_HTTP_Request(odr);
255
256     p->u.HTTP_Request->path = odr_strdup(odr, path);
257
258     if (host)
259     {
260         const char *cp0 = strstr(host, "://");
261         const char *cp1 = 0;
262         if (cp0)
263             cp0 = cp0+3;
264         else
265             cp0 = host;
266
267         cp1 = strchr(cp0, '/');
268         if (!cp1)
269             cp1 = cp0+strlen(cp0);
270
271         if (cp0 && cp1)
272         {
273             char *h = (char*) odr_malloc(odr, cp1 - cp0 + 1);
274             memcpy (h, cp0, cp1 - cp0);
275             h[cp1-cp0] = '\0';
276             z_HTTP_header_add(odr, &p->u.HTTP_Request->headers,
277                               "Host", h);
278         }
279     }
280     return p;
281 }
282
283 Z_GDU *z_get_HTTP_Request_uri(ODR odr, const char *uri, const char *args,
284                               int use_full_uri)
285 {
286     Z_GDU *p = z_get_HTTP_Request(odr);
287     const char *cp0 = strstr(uri, "://");
288     const char *cp1 = 0;
289     if (cp0)
290         cp0 = cp0+3;
291     else
292         cp0 = uri;
293
294     cp1 = strchr(cp0, '/');
295     if (!cp1)
296         cp1 = cp0+strlen(cp0);
297
298     if (cp0 && cp1)
299     {
300         char *h = (char*) odr_malloc(odr, cp1 - cp0 + 1);
301         memcpy (h, cp0, cp1 - cp0);
302         h[cp1-cp0] = '\0';
303         z_HTTP_header_add(odr, &p->u.HTTP_Request->headers,
304                           "Host", h);
305     }
306
307     if (!args)
308     {
309         if (*cp1)
310             args = cp1 + 1;
311         else
312             args = "";
313     }
314     p->u.HTTP_Request->path = odr_malloc(odr, cp1 - uri + strlen(args) + 2);
315     if (use_full_uri)
316     {
317         memcpy(p->u.HTTP_Request->path, uri, cp1 - uri);
318         strcpy(p->u.HTTP_Request->path + (cp1 - uri), "/");
319     }
320     else
321         strcpy(p->u.HTTP_Request->path, "/");
322     strcat(p->u.HTTP_Request->path, args);
323     return p;
324 }
325
326 Z_GDU *z_get_HTTP_Response(ODR o, int code)
327 {
328     Z_GDU *p = (Z_GDU *) odr_malloc(o, sizeof(*p));
329     Z_HTTP_Response *hres;
330
331     p->which = Z_GDU_HTTP_Response;
332     p->u.HTTP_Response = (Z_HTTP_Response *) odr_malloc(o, sizeof(*hres));
333     hres = p->u.HTTP_Response;
334     hres->headers = 0;
335     hres->content_len = 0;
336     hres->content_buf = 0;
337     hres->code = code;
338     hres->version = "1.1";
339     z_HTTP_header_add(o, &hres->headers, "Server",
340                       "YAZ/" YAZ_VERSION);
341     if (code != 200)
342     {
343         hres->content_buf = (char*) odr_malloc(o, 400);
344         sprintf(hres->content_buf,
345                 "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\""
346                 " \"http://www.w3.org/TR/html4/strict.dtd\">\n"
347                 "<HTML>\n"
348                 " <HEAD>\n"
349                 "  <TITLE>YAZ " YAZ_VERSION "</TITLE>\n"
350                 " </HEAD>\n"
351                 " <BODY>\n"
352                 "  <P><A HREF=\"http://www.indexdata.com/yaz/\">YAZ</A> "
353                 YAZ_VERSION "</P>\n"
354                 "  <P>Error: %d</P>\n"
355                 "  <P>Description: %.50s</P>\n"
356                 " </BODY>\n"
357                 "</HTML>\n",
358                 code, z_HTTP_errmsg(code));
359         hres->content_len = strlen(hres->content_buf);
360         z_HTTP_header_add(o, &hres->headers, "Content-Type", "text/html");
361     }
362     return p;
363 }
364
365 const char *z_HTTP_errmsg(int code)
366 {
367     switch (code)
368     {
369     case 100:
370         return "Continue";
371     case 101:
372         return "Switching Protocols";
373     case 200:
374         return "OK";
375     case 201:
376         return "Created";
377     case 202:
378         return "Accepted";
379     case 203:
380         return "Non-Authoritative Information";
381     case 204:
382         return "No Content";
383     case 205:
384         return "Reset Content";
385     case 206:
386         return "Partial Content";
387     case 300:
388         return "Multiple Choices";
389     case 301:
390         return "Moved Permenently";
391     case 302:
392         return "Found";
393     case 303:
394         return "See Other";
395     case 304:
396         return "Not Modified";
397     case 305:
398         return "Use Proxy";
399     case 307:
400         return "Temporary Redirect";
401     case 400:
402         return "Bad Request";
403     case 404:
404         return "Not Found";
405     case 405:
406         return "Method Not Allowed";
407     case 406:
408         return "Not Acceptable";
409     case 407:
410         return "Proxy Authentication Required";
411     case 408:
412         return "Request Timeout";
413     case 409:
414         return "Conflict";
415     case 410:
416         return "Gone";
417     case 411:
418         return "Length Required";
419     case 412:
420         return "Precondition Failed";
421     case 413:
422         return "Request Entity Too Large";
423     case 414:
424         return "Request-URI Too Long";
425     case 415:
426         return "Unsupported Media Type";
427     case 416:
428         return "Requested Range Not Satisfiable";
429     case 417:
430         return "Expectation Failed";
431     case 500:
432         return "Internal Error";
433     case 501:
434         return "Not Implemented";
435     case 502:
436         return "Bad Gateway";
437     case 503:
438         return "Service Unavailable";
439     case 504:
440         return "Gateway Timeout";
441     case 505:
442         return "HTTP Version Not Supported";
443     default:
444         return "Unknown Error";
445     }
446 }
447
448 int yaz_decode_http_response(ODR o, Z_HTTP_Response **hr_p)
449 {
450     int i, po;
451     Z_HTTP_Response *hr = (Z_HTTP_Response *) odr_malloc(o, sizeof(*hr));
452
453     *hr_p = hr;
454     hr->content_buf = 0;
455     hr->content_len = 0;
456
457     po = i = 5;
458     while (i < o->size-2 && !strchr(" \r\n", o->buf[i]))
459         i++;
460     hr->version = (char *) odr_malloc(o, i - po + 1);
461     if (i - po)
462         memcpy(hr->version, o->buf + po, i - po);
463     hr->version[i-po] = 0;
464     if (o->buf[i] != ' ')
465     {
466         o->error = OHTTP;
467         return 0;
468     }
469     i++;
470     hr->code = 0;
471     while (i < o->size-2 && o->buf[i] >= '0' && o->buf[i] <= '9')
472     {
473         hr->code = hr->code*10 + (o->buf[i] - '0');
474         i++;
475     }
476     while (i < o->size-1 && o->buf[i] != '\n')
477         i++;
478     return decode_headers_content(o, i, &hr->headers,
479                                   &hr->content_buf, &hr->content_len);
480 }
481
482 int yaz_decode_http_request(ODR o, Z_HTTP_Request **hr_p)
483 {
484     int i, po;
485     Z_HTTP_Request *hr = (Z_HTTP_Request *) odr_malloc(o, sizeof(*hr));
486
487     *hr_p = hr;
488
489     /* method .. */
490     for (i = 0; o->buf[i] != ' '; i++)
491         if (i >= o->size-5 || i > 30)
492         {
493             o->error = OHTTP;
494             return 0;
495         }
496     hr->method = (char *) odr_malloc(o, i+1);
497     memcpy (hr->method, o->buf, i);
498     hr->method[i] = '\0';
499     /* path */
500     po = i+1;
501     for (i = po; o->buf[i] != ' '; i++)
502         if (i >= o->size-5)
503         {
504             o->error = OHTTP;
505             return 0;
506         }
507     hr->path = (char *) odr_malloc(o, i - po + 1);
508     memcpy (hr->path, o->buf+po, i - po);
509     hr->path[i - po] = '\0';
510     /* HTTP version */
511     i++;
512     if (i > o->size-5 || memcmp(o->buf+i, "HTTP/", 5))
513     {
514         o->error = OHTTP;
515         return 0;
516     }
517     i+= 5;
518     po = i;
519     while (i < o->size && !strchr("\r\n", o->buf[i]))
520         i++;
521     hr->version = (char *) odr_malloc(o, i - po + 1);
522     memcpy(hr->version, o->buf + po, i - po);
523     hr->version[i - po] = '\0';
524     /* headers */
525     if (i < o->size-1 && o->buf[i] == '\r')
526         i++;
527     if (o->buf[i] != '\n')
528     {
529         o->error = OHTTP;
530         return 0;
531     }
532     return decode_headers_content(o, i, &hr->headers,
533                                   &hr->content_buf, &hr->content_len);
534 }
535
536 static void dump_http_package(ODR o, const char *buf, size_t len)
537 {
538     int i;
539     for (i = 0; ; i++)
540     {
541         if (i == len)
542         {
543             odr_printf(o, "%.*s\n", i, buf);
544             break;
545         }
546         else if (i > 8192)
547         {
548             odr_printf(o, "%.*s\n", i, buf);
549             odr_printf(o, "(truncated\n", (long) len);
550             break;
551         }
552         else if (buf[i] == 0)
553         {
554             odr_printf(o, "%.*s\n", i, buf);
555             odr_printf(o, "(binary data)\n", (long) len);
556             break;
557         }
558     }
559 }
560
561 int yaz_encode_http_response(ODR o, Z_HTTP_Response *hr)
562 {
563     char sbuf[80];
564     Z_HTTP_Header *h;
565     int top0 = o->top;
566
567     sprintf(sbuf, "HTTP/%s %d %s\r\n", hr->version,
568             hr->code,
569             z_HTTP_errmsg(hr->code));
570     odr_write2(o, sbuf, strlen(sbuf));
571     /* use content_len for Content-Length */
572     sprintf(sbuf, "Content-Length: %d\r\n", hr->content_len);
573     odr_write2(o, sbuf, strlen(sbuf));
574     for (h = hr->headers; h; h = h->next)
575     {
576         if (yaz_strcasecmp(h->name, "Content-Length")
577             && yaz_strcasecmp(h->name, "Transfer-Encoding"))
578         {   /* skip Content-Length if given. content_len rules */
579             odr_write2(o, h->name, strlen(h->name));
580             odr_write2(o, ": ", 2);
581             odr_write2(o, h->value, strlen(h->value));
582             odr_write2(o, "\r\n", 2);
583         }
584     }
585     odr_write(o, (unsigned char *) "\r\n", 2);
586     if (hr->content_buf)
587         odr_write2(o, hr->content_buf, hr->content_len);
588     if (o->direction == ODR_PRINT)
589     {
590         odr_printf(o, "-- HTTP response:\n");
591         dump_http_package(o, (const char *) o->buf + top0, o->top - top0);
592         odr_printf(o, "--\n");
593     }
594     return 1;
595 }
596
597 int yaz_encode_http_request(ODR o, Z_HTTP_Request *hr)
598 {
599     Z_HTTP_Header *h;
600     int top0 = o->top;
601
602     odr_write2(o, hr->method, strlen(hr->method));
603     odr_write2(o, " ", 1);
604     odr_write2(o, hr->path, strlen(hr->path));
605     odr_write2(o, " HTTP/", 6);
606     odr_write2(o, hr->version, strlen(hr->version));
607     odr_write2(o, "\r\n", 2);
608     if (hr->content_len &&
609         !z_HTTP_header_lookup(hr->headers,
610                               "Content-Length"))
611     {
612         char lstr[60];
613         sprintf(lstr, "Content-Length: %d\r\n",
614                 hr->content_len);
615         odr_write2(o, lstr, strlen(lstr));
616     }
617     for (h = hr->headers; h; h = h->next)
618     {
619         odr_write2(o, h->name, strlen(h->name));
620         odr_write2(o, ": ", 2);
621         odr_write2(o, h->value, strlen(h->value));
622         odr_write2(o, "\r\n", 2);
623     }
624     odr_write2(o, "\r\n", 2);
625     if (hr->content_buf)
626         odr_write2(o, hr->content_buf, hr->content_len);
627     if (o->direction == ODR_PRINT)
628     {
629         odr_printf(o, "-- HTTP request:\n");
630         dump_http_package(o, (const char *) o->buf + top0, o->top - top0);
631         odr_printf(o, "--\n");
632     }
633     return 1;
634 }
635
636 /*
637  * Local variables:
638  * c-basic-offset: 4
639  * c-file-style: "Stroustrup"
640  * indent-tabs-mode: nil
641  * End:
642  * vim: shiftwidth=4 tabstop=8 expandtab
643  */
644