4362c757a85d305bdf8ac67406a36808d2259572
[yaz-moved-to-github.git] / src / http.c
1 /* This file is part of the YAZ toolkit.
2  * Copyright (C) 1995-2010 Index Data
3  * See the file LICENSE for details.
4  */
5
6 /**
7  * \file http.c
8  * \brief Implements HTTP decoding
9  */
10
11 #include <ctype.h>
12 #include <yaz/odr.h>
13 #include <yaz/yaz-version.h>
14 #include <yaz/yaz-iconv.h>
15 #include <yaz/matchstr.h>
16 #include <yaz/zgdu.h>
17
18 #ifdef WIN32
19 #define strncasecmp _strnicmp
20 #define strcasecmp _stricmp
21 #endif
22  
23
24 /*
25  * This function's counterpart, yaz_base64decode(), is in srwutil.c.
26  * I feel bad that they're not together, but each function is only
27  * needed in one place, and those places are not together.  Maybe one
28  * day we'll move them into a new httputil.c, and declare them in a
29  * corresponding httputil.h
30  */
31 static void yaz_base64encode(const char *in, char *out)
32 {
33     static char encoding[] =
34         "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
35     unsigned char buf[3];
36     long n;
37
38     while (*in != 0) {
39         char *pad = 0;
40         buf[0] = in[0];
41         buf[1] = in[1];
42         if (in[1] == 0) {
43             buf[2] = 0;
44             pad = "==";
45         } else {
46             buf[2] = in[2];
47             if (in[2] == 0)
48                 pad = "=";
49         }
50
51         /* Treat three eight-bit numbers as on 24-bit number */
52         n = (buf[0] << 16) + (buf[1] << 8) + buf[2];
53
54         /* Write the six-bit chunks out as four encoded characters */
55         *out++ = encoding[(n >> 18) & 63];
56         *out++ = encoding[(n >> 12) & 63];
57         if (in[1] != 0)
58             *out++ = encoding[(n >> 6) & 63];
59         if (in[1] != 0 && in[2] != 0)
60             *out++ = encoding[n & 63];
61
62         if (pad != 0) {
63             while (*pad != 0)
64                 *out++ = *pad++;
65             break;
66         }
67         in += 3;
68     }
69
70     *out++ = 0;
71 }
72
73
74 static int decode_headers_content(ODR o, int off, Z_HTTP_Header **headers,
75                                   char **content_buf, int *content_len)
76 {
77     int i = off;
78     int chunked = 0;
79
80     *headers = 0;
81     while (i < o->size-1 && o->buf[i] == '\n')
82     {
83         int po;
84         i++;
85         if (o->buf[i] == '\r' && i < o->size-1 && o->buf[i+1] == '\n')
86         {
87             i++;
88             break;
89         }
90         if (o->buf[i] == '\n')
91             break;
92         for (po = i; ; i++)
93         {
94             if (i == o->size)
95             {
96                 o->error = OHTTP;
97                 return 0;
98             }
99             else if (o->buf[i] == ':')
100                 break;
101         }
102         *headers = (Z_HTTP_Header *) odr_malloc(o, sizeof(**headers));
103         (*headers)->name = (char*) odr_malloc(o, i - po + 1);
104         memcpy ((*headers)->name, o->buf + po, i - po);
105         (*headers)->name[i - po] = '\0';
106         i++;
107         while (i < o->size-1 && o->buf[i] == ' ')
108             i++;
109         for (po = i; i < o->size-1 && !strchr("\r\n", o->buf[i]); i++)
110             ;
111         
112         (*headers)->value = (char*) odr_malloc(o, i - po + 1);
113         memcpy ((*headers)->value, o->buf + po, i - po);
114         (*headers)->value[i - po] = '\0';
115         
116         if (!strcasecmp((*headers)->name, "Transfer-Encoding")
117             &&
118             !strcasecmp((*headers)->value, "chunked"))
119             chunked = 1;
120         headers = &(*headers)->next;
121         if (i < o->size-1 && o->buf[i] == '\r')
122             i++;
123     }
124     *headers = 0;
125     if (o->buf[i] != '\n')
126     {
127         o->error = OHTTP;
128         return 0;
129     }
130     i++;
131
132     if (chunked)
133     {
134         int off = 0;
135         
136         /* we know buffer will be smaller than o->size - i*/
137         *content_buf = (char*) odr_malloc(o, o->size - i);  
138         
139         while (1)
140         {
141             /* chunk length .. */
142             int chunk_len = 0;
143             for (; i  < o->size-2; i++)
144                 if (isdigit(o->buf[i]))
145                     chunk_len = chunk_len * 16 + 
146                         (o->buf[i] - '0');
147                 else if (isupper(o->buf[i]))
148                     chunk_len = chunk_len * 16 + 
149                         (o->buf[i] - ('A'-10));
150                 else if (islower(o->buf[i]))
151                     chunk_len = chunk_len * 16 + 
152                         (o->buf[i] - ('a'-10));
153                 else
154                     break;
155             /* chunk extension ... */
156             while (o->buf[i] != '\r' && o->buf[i+1] != '\n')
157             {
158                 if (i >= o->size-2)
159                 {
160                     o->error = OHTTP;
161                     return 0;
162                 }
163                 i++;
164             }
165             i += 2;  /* skip CRLF */
166             if (chunk_len == 0)
167                 break;
168             if (chunk_len < 0 || off + chunk_len > o->size)
169             {
170                 o->error = OHTTP;
171                 return 0;
172             }
173             /* copy chunk .. */
174             memcpy (*content_buf + off, o->buf + i, chunk_len);
175             i += chunk_len + 2; /* skip chunk+CRLF */
176             off += chunk_len;
177         }
178         if (!off)
179             *content_buf = 0;
180         *content_len = off;
181     }
182     else
183     {
184         if (i > o->size)
185         {
186             o->error = OHTTP;
187             return 0;
188         }
189         else if (i == o->size)
190         {
191             *content_buf = 0;
192             *content_len = 0;
193         }
194         else 
195         {
196             *content_len = o->size - i;
197             *content_buf = (char*) odr_malloc(o, *content_len + 1);
198             memcpy(*content_buf, o->buf + i, *content_len);
199             (*content_buf)[*content_len] = '\0';
200         }
201     }
202     return 1;
203 }
204
205 void z_HTTP_header_add_content_type(ODR o, Z_HTTP_Header **hp,
206                                     const char *content_type,
207                                     const char *charset)
208 {
209     const char *l = "Content-Type";
210     if (charset)
211     {
212         char *ctype = (char *)
213             odr_malloc(o, strlen(content_type)+strlen(charset) + 15);
214         sprintf(ctype, "%s; charset=%s", content_type, charset);
215         z_HTTP_header_add(o, hp, l, ctype);
216     }
217     else
218         z_HTTP_header_add(o, hp, l, content_type);
219
220 }
221
222 /*
223  * HTTP Basic authentication is described at:
224  * http://tools.ietf.org/html/rfc1945#section-11.1
225  */
226 void z_HTTP_header_add_basic_auth(ODR o, Z_HTTP_Header **hp,
227                                   const char *username, const char *password)
228 {
229     char *tmp, *buf;
230     int len;
231
232     if (username == 0)
233         return;
234
235     len = strlen(username) + strlen(password);
236     tmp = (char *) odr_malloc(o, len+2);
237     sprintf(tmp, "%s:%s", username, password);
238     buf = (char *) odr_malloc(o, (len+1) * 8/6 + 12);
239     strcpy(buf, "Basic ");
240     yaz_base64encode(tmp, &buf[strlen(buf)]);
241     z_HTTP_header_add(o, hp, "Authorization", buf);
242 }
243
244
245 void z_HTTP_header_add(ODR o, Z_HTTP_Header **hp, const char *n,
246                        const char *v)
247 {
248     while (*hp)
249         hp = &(*hp)->next;
250     *hp = (Z_HTTP_Header *) odr_malloc(o, sizeof(**hp));
251     (*hp)->name = odr_strdup(o, n);
252     (*hp)->value = odr_strdup(o, v);
253     (*hp)->next = 0;
254 }
255
256 const char *z_HTTP_header_lookup(const Z_HTTP_Header *hp, const char *n)
257 {
258     for (; hp; hp = hp->next)
259         if (!yaz_matchstr(hp->name, n))
260             return hp->value;
261     return 0;
262 }
263
264
265 Z_GDU *z_get_HTTP_Request(ODR o)
266 {
267     Z_GDU *p = (Z_GDU *) odr_malloc(o, sizeof(*p));
268     Z_HTTP_Request *hreq;
269
270     p->which = Z_GDU_HTTP_Request;
271     p->u.HTTP_Request = (Z_HTTP_Request *) odr_malloc(o, sizeof(*hreq));
272     hreq = p->u.HTTP_Request;
273     hreq->headers = 0;
274     hreq->content_len = 0;
275     hreq->content_buf = 0;
276     hreq->version = "1.1";
277     hreq->method = "POST";
278     hreq->path = "/";
279     z_HTTP_header_add(o, &hreq->headers, "User-Agent", "YAZ/" YAZ_VERSION);
280     return p;
281 }
282
283
284 Z_GDU *z_get_HTTP_Request_host_path(ODR odr,
285                                     const char *host,
286                                     const char *path)
287 {
288     Z_GDU *p = z_get_HTTP_Request(odr);
289
290     p->u.HTTP_Request->path = odr_strdup(odr, path);
291
292     if (host)
293     {
294         const char *cp0 = strstr(host, "://");
295         const char *cp1 = 0;
296         if (cp0)
297             cp0 = cp0+3;
298         else
299             cp0 = host;
300
301         cp1 = strchr(cp0, '/');
302         if (!cp1)
303             cp1 = cp0+strlen(cp0);
304
305         if (cp0 && cp1)
306         {
307             char *h = (char*) odr_malloc(odr, cp1 - cp0 + 1);
308             memcpy (h, cp0, cp1 - cp0);
309             h[cp1-cp0] = '\0';
310             z_HTTP_header_add(odr, &p->u.HTTP_Request->headers,
311                               "Host", h);
312         }
313     }
314     return p;
315 }
316
317
318 Z_GDU *z_get_HTTP_Response(ODR o, int code)
319 {
320     Z_GDU *p = (Z_GDU *) odr_malloc(o, sizeof(*p));
321     Z_HTTP_Response *hres;
322
323     p->which = Z_GDU_HTTP_Response;
324     p->u.HTTP_Response = (Z_HTTP_Response *) odr_malloc(o, sizeof(*hres));
325     hres = p->u.HTTP_Response;
326     hres->headers = 0;
327     hres->content_len = 0;
328     hres->content_buf = 0;
329     hres->code = code;
330     hres->version = "1.1";
331     z_HTTP_header_add(o, &hres->headers, "Server",
332                       "YAZ/" YAZ_VERSION);
333     if (code != 200)
334     {
335         hres->content_buf = (char*) odr_malloc(o, 400);
336         sprintf(hres->content_buf, 
337                 "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\""
338                 " \"http://www.w3.org/TR/html4/strict.dtd\">\n"
339                 "<HTML>\n"
340                 " <HEAD>\n"
341                 "  <TITLE>YAZ " YAZ_VERSION "</TITLE>\n"
342                 " </HEAD>\n"
343                 " <BODY>\n"
344                 "  <P><A HREF=\"http://www.indexdata.com/yaz/\">YAZ</A> " 
345                 YAZ_VERSION "</P>\n"
346                 "  <P>Error: %d</P>\n"
347                 "  <P>Description: %.50s</P>\n"
348                 " </BODY>\n"
349                 "</HTML>\n",
350                 code, z_HTTP_errmsg(code));
351         hres->content_len = strlen(hres->content_buf);
352         z_HTTP_header_add(o, &hres->headers, "Content-Type", "text/html");
353     }
354     return p;
355 }
356
357 const char *z_HTTP_errmsg(int code)
358 {
359     if (code == 200)
360         return "OK";
361     else if (code == 400)
362         return "Bad Request";
363     else if (code == 404)
364         return "Not Found";
365     else if (code == 405)
366         return "Method Not Allowed";
367     else if (code == 500)
368         return "Internal Error";
369     else
370         return "Unknown Error";
371 }
372
373 int yaz_decode_http_response(ODR o, Z_HTTP_Response **hr_p)
374 {
375     int i, po;
376     Z_HTTP_Response *hr = (Z_HTTP_Response *) odr_malloc(o, sizeof(*hr));
377     
378     *hr_p = hr;
379     hr->content_buf = 0;
380     hr->content_len = 0;
381     
382     po = i = 5;
383     while (i < o->size-2 && !strchr(" \r\n", o->buf[i]))
384         i++;
385     hr->version = (char *) odr_malloc(o, i - po + 1);
386     if (i - po)
387         memcpy(hr->version, o->buf + po, i - po);
388     hr->version[i-po] = 0;
389     if (o->buf[i] != ' ')
390     {
391         o->error = OHTTP;
392         return 0;
393     }
394     i++;
395     hr->code = 0;
396     while (i < o->size-2 && o->buf[i] >= '0' && o->buf[i] <= '9')
397     {
398         hr->code = hr->code*10 + (o->buf[i] - '0');
399         i++;
400     }
401     while (i < o->size-1 && o->buf[i] != '\n')
402         i++;
403     return decode_headers_content(o, i, &hr->headers,
404                                   &hr->content_buf, &hr->content_len);            
405 }
406
407 int yaz_decode_http_request(ODR o, Z_HTTP_Request **hr_p)
408 {
409     int i, po;
410     Z_HTTP_Request *hr = (Z_HTTP_Request *) odr_malloc(o, sizeof(*hr));
411     
412     *hr_p = hr;
413     
414     /* method .. */
415     for (i = 0; o->buf[i] != ' '; i++)
416         if (i >= o->size-5 || i > 30)
417         {
418             o->error = OHTTP;
419             return 0;
420         }
421     hr->method = (char *) odr_malloc(o, i+1);
422     memcpy (hr->method, o->buf, i);
423     hr->method[i] = '\0';
424     /* path */
425     po = i+1;
426     for (i = po; o->buf[i] != ' '; i++)
427         if (i >= o->size-5)
428         {
429             o->error = OHTTP;
430             return 0;
431         }
432     hr->path = (char *) odr_malloc(o, i - po + 1);
433     memcpy (hr->path, o->buf+po, i - po);
434     hr->path[i - po] = '\0';
435     /* HTTP version */
436     i++;
437     if (i > o->size-5 || memcmp(o->buf+i, "HTTP/", 5))
438     {
439         o->error = OHTTP;
440         return 0;
441     }
442     i+= 5;
443     po = i;
444     while (i < o->size && !strchr("\r\n", o->buf[i]))
445         i++;
446     hr->version = (char *) odr_malloc(o, i - po + 1);
447     memcpy(hr->version, o->buf + po, i - po);
448     hr->version[i - po] = '\0';
449     /* headers */
450     if (i < o->size-1 && o->buf[i] == '\r')
451         i++;
452     if (o->buf[i] != '\n')
453     {
454         o->error = OHTTP;
455         return 0;
456     }
457     return decode_headers_content(o, i, &hr->headers,
458                                   &hr->content_buf, &hr->content_len);
459 }
460
461 int yaz_encode_http_response(ODR o, Z_HTTP_Response *hr)
462 {
463     char sbuf[80];
464     Z_HTTP_Header *h;
465     int top0 = o->top;
466
467     sprintf(sbuf, "HTTP/%s %d %s\r\n", hr->version,
468             hr->code,
469             z_HTTP_errmsg(hr->code));
470     odr_write(o, (unsigned char *) sbuf, strlen(sbuf));
471     /* apply Content-Length if not already applied */
472     if (!z_HTTP_header_lookup(hr->headers,
473                               "Content-Length"))
474     {
475         char lstr[60];
476         sprintf(lstr, "Content-Length: %d\r\n",
477                 hr->content_len);
478         odr_write(o, (unsigned char *) lstr, strlen(lstr));
479     }
480     for (h = hr->headers; h; h = h->next)
481     {
482         odr_write(o, (unsigned char *) h->name, strlen(h->name));
483         odr_write(o, (unsigned char *) ": ", 2);
484         odr_write(o, (unsigned char *) h->value, strlen(h->value));
485         odr_write(o, (unsigned char *) "\r\n", 2);
486     }
487     odr_write(o, (unsigned char *) "\r\n", 2);
488     if (hr->content_buf)
489         odr_write(o, (unsigned char *) 
490                   hr->content_buf,
491                   hr->content_len);
492     if (o->direction == ODR_PRINT)
493     {
494         odr_printf(o, "-- HTTP response:\n%.*s\n", o->top - top0,
495                    o->buf + top0);
496         odr_printf(o, "-- \n");
497     }
498     return 1;
499 }
500
501 int yaz_encode_http_request(ODR o, Z_HTTP_Request *hr)
502 {
503     Z_HTTP_Header *h;
504     int top0 = o->top;
505
506     odr_write(o, (unsigned char *) hr->method,
507               strlen(hr->method));
508     odr_write(o, (unsigned char *) " ", 1);
509     odr_write(o, (unsigned char *) hr->path,
510               strlen(hr->path));
511     odr_write(o, (unsigned char *) " HTTP/", 6);
512     odr_write(o, (unsigned char *) hr->version,
513               strlen(hr->version));
514     odr_write(o, (unsigned char *) "\r\n", 2);
515     if (hr->content_len &&
516         !z_HTTP_header_lookup(hr->headers,
517                               "Content-Length"))
518     {
519         char lstr[60];
520         sprintf(lstr, "Content-Length: %d\r\n",
521                 hr->content_len);
522         odr_write(o, (unsigned char *) lstr, strlen(lstr));
523     }
524     for (h = hr->headers; h; h = h->next)
525     {
526         odr_write(o, (unsigned char *) h->name, strlen(h->name));
527         odr_write(o, (unsigned char *) ": ", 2);
528         odr_write(o, (unsigned char *) h->value, strlen(h->value));
529         odr_write(o, (unsigned char *) "\r\n", 2);
530     }
531     odr_write(o, (unsigned char *) "\r\n", 2);
532     if (hr->content_buf)
533         odr_write(o, (unsigned char *)
534                   hr->content_buf,
535                   hr->content_len);
536     if (o->direction == ODR_PRINT)
537     {
538         odr_printf(o, "-- HTTP request:\n%.*s\n", o->top - top0,
539                    o->buf + top0);
540         odr_printf(o, "-- \n");
541     }
542     return 1;
543 }
544
545 /*
546  * Local variables:
547  * c-basic-offset: 4
548  * c-file-style: "Stroustrup"
549  * indent-tabs-mode: nil
550  * End:
551  * vim: shiftwidth=4 tabstop=8 expandtab
552  */
553