Adjustments to make YAZ compile as C++ code.
[yaz-moved-to-github.git] / src / http.c
1 /*
2  * Copyright (C) 1995-2007, Index Data ApS
3  * See the file LICENSE for details.
4  *
5  * $Id: http.c,v 1.4 2007-11-30 11:44:47 adam Exp $
6  */
7
8 /**
9  * \file http.c
10  * \brief Implements HTTP decoding
11  */
12
13 #include <ctype.h>
14 #include <yaz/odr.h>
15 #include <yaz/yaz-version.h>
16 #include <yaz/yaz-iconv.h>
17 #include <yaz/zgdu.h>
18
19 #ifdef WIN32
20 #define strncasecmp _strnicmp
21 #define strcasecmp _stricmp
22 #endif
23  
24
25 /*
26  * This function's counterpart, yaz_base64decode(), is in srwutil.c.
27  * I feel bad that they're not together, but each function is only
28  * needed in one place, and those places are not together.  Maybe one
29  * day we'll move them into a new httputil.c, and declare them in a
30  * corresponding httputil.h
31  */
32 static void yaz_base64encode(const char *in, char *out)
33 {
34     static char encoding[] =
35         "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
36     unsigned char buf[3];
37     long n;
38
39     while (*in != 0) {
40         char *pad = 0;
41         buf[0] = in[0];
42         buf[1] = in[1];
43         if (in[1] == 0) {
44             buf[2] = 0;
45             pad = "==";
46         } else {
47             buf[2] = in[2];
48             if (in[2] == 0)
49                 pad = "=";
50         }
51
52         /* Treat three eight-bit numbers as on 24-bit number */
53         n = (buf[0] << 16) + (buf[1] << 8) + buf[2];
54
55         /* Write the six-bit chunks out as four encoded characters */
56         *out++ = encoding[(n >> 18) & 63];
57         *out++ = encoding[(n >> 12) & 63];
58         if (in[1] != 0)
59             *out++ = encoding[(n >> 6) & 63];
60         if (in[1] != 0 && in[2] != 0)
61             *out++ = encoding[n & 63];
62
63         if (pad != 0) {
64             while (*pad != 0)
65                 *out++ = *pad++;
66             break;
67         }
68         in += 3;
69     }
70
71     *out++ = 0;
72 }
73
74
75 static int decode_headers_content(ODR o, int off, Z_HTTP_Header **headers,
76                                   char **content_buf, int *content_len)
77 {
78     int i = off;
79     int chunked = 0;
80
81     *headers = 0;
82     while (i < o->size-1 && o->buf[i] == '\n')
83     {
84         int po;
85         i++;
86         if (o->buf[i] == '\r' && i < o->size-1 && o->buf[i+1] == '\n')
87         {
88             i++;
89             break;
90         }
91         if (o->buf[i] == '\n')
92             break;
93         for (po = i; ; i++)
94         {
95             if (i == o->size)
96             {
97                 o->error = OHTTP;
98                 return 0;
99             }
100             else if (o->buf[i] == ':')
101                 break;
102         }
103         *headers = (Z_HTTP_Header *) odr_malloc(o, sizeof(**headers));
104         (*headers)->name = (char*) odr_malloc(o, i - po + 1);
105         memcpy ((*headers)->name, o->buf + po, i - po);
106         (*headers)->name[i - po] = '\0';
107         i++;
108         while (i < o->size-1 && o->buf[i] == ' ')
109             i++;
110         for (po = i; i < o->size-1 && !strchr("\r\n", o->buf[i]); i++)
111             ;
112         
113         (*headers)->value = (char*) odr_malloc(o, i - po + 1);
114         memcpy ((*headers)->value, o->buf + po, i - po);
115         (*headers)->value[i - po] = '\0';
116         
117         if (!strcasecmp((*headers)->name, "Transfer-Encoding")
118             &&
119             !strcasecmp((*headers)->value, "chunked"))
120             chunked = 1;
121         headers = &(*headers)->next;
122         if (i < o->size-1 && o->buf[i] == '\r')
123             i++;
124     }
125     *headers = 0;
126     if (o->buf[i] != '\n')
127     {
128         o->error = OHTTP;
129         return 0;
130     }
131     i++;
132
133     if (chunked)
134     {
135         int off = 0;
136         
137         /* we know buffer will be smaller than o->size - i*/
138         *content_buf = (char*) odr_malloc(o, o->size - i);  
139         
140         while (1)
141         {
142             /* chunk length .. */
143             int chunk_len = 0;
144             for (; i  < o->size-2; i++)
145                 if (isdigit(o->buf[i]))
146                     chunk_len = chunk_len * 16 + 
147                         (o->buf[i] - '0');
148                 else if (isupper(o->buf[i]))
149                     chunk_len = chunk_len * 16 + 
150                         (o->buf[i] - ('A'-10));
151                 else if (islower(o->buf[i]))
152                     chunk_len = chunk_len * 16 + 
153                         (o->buf[i] - ('a'-10));
154                 else
155                     break;
156             /* chunk extension ... */
157             while (o->buf[i] != '\r' && o->buf[i+1] != '\n')
158             {
159                 if (i >= o->size-2)
160                 {
161                     o->error = OHTTP;
162                     return 0;
163                 }
164                 i++;
165             }
166             i += 2;  /* skip CRLF */
167             if (chunk_len == 0)
168                 break;
169             if (chunk_len < 0 || off + chunk_len > o->size)
170             {
171                 o->error = OHTTP;
172                 return 0;
173             }
174             /* copy chunk .. */
175             memcpy (*content_buf + off, o->buf + i, chunk_len);
176             i += chunk_len + 2; /* skip chunk+CRLF */
177             off += chunk_len;
178         }
179         if (!off)
180             *content_buf = 0;
181         *content_len = off;
182     }
183     else
184     {
185         if (i > o->size)
186         {
187             o->error = OHTTP;
188             return 0;
189         }
190         else if (i == o->size)
191         {
192             *content_buf = 0;
193             *content_len = 0;
194         }
195         else 
196         {
197             *content_len = o->size - i;
198             *content_buf = (char*) odr_malloc(o, *content_len + 1);
199             memcpy(*content_buf, o->buf + i, *content_len);
200             (*content_buf)[*content_len] = '\0';
201         }
202     }
203     return 1;
204 }
205
206 void z_HTTP_header_add_content_type(ODR o, Z_HTTP_Header **hp,
207                                     const char *content_type,
208                                     const char *charset)
209 {
210     const char *l = "Content-Type";
211     if (charset)
212     {
213         char *ctype = (char *)
214             odr_malloc(o, strlen(content_type)+strlen(charset) + 15);
215         sprintf(ctype, "%s; charset=%s", content_type, charset);
216         z_HTTP_header_add(o, hp, l, ctype);
217     }
218     else
219         z_HTTP_header_add(o, hp, l, content_type);
220
221 }
222
223 /*
224  * HTTP Basic authentication is described at:
225  * http://tools.ietf.org/html/rfc1945#section-11.1
226  */
227 void z_HTTP_header_add_basic_auth(ODR o, Z_HTTP_Header **hp,
228                                   const char *username, const char *password)
229 {
230     char *tmp, *buf;
231     int len;
232
233     if (username == 0)
234         return;
235
236     len = strlen(username) + strlen(password);
237     tmp = (char *) odr_malloc(o, len+2);
238     sprintf(tmp, "%s:%s", username, password);
239     buf = (char *) odr_malloc(o, (len+1) * 8/6 + 12);
240     strcpy(buf, "Basic ");
241     yaz_base64encode(tmp, &buf[strlen(buf)]);
242     z_HTTP_header_add(o, hp, "Authorization", buf);
243 }
244
245
246 void z_HTTP_header_add(ODR o, Z_HTTP_Header **hp, const char *n,
247                        const char *v)
248 {
249     while (*hp)
250         hp = &(*hp)->next;
251     *hp = (Z_HTTP_Header *) odr_malloc(o, sizeof(**hp));
252     (*hp)->name = odr_strdup(o, n);
253     (*hp)->value = odr_strdup(o, v);
254     (*hp)->next = 0;
255 }
256
257 const char *z_HTTP_header_lookup(const Z_HTTP_Header *hp, const char *n)
258 {
259     for (; hp; hp = hp->next)
260         if (!yaz_matchstr(hp->name, n))
261             return hp->value;
262     return 0;
263 }
264
265
266 Z_GDU *z_get_HTTP_Request(ODR o)
267 {
268     Z_GDU *p = (Z_GDU *) odr_malloc(o, sizeof(*p));
269     Z_HTTP_Request *hreq;
270
271     p->which = Z_GDU_HTTP_Request;
272     p->u.HTTP_Request = (Z_HTTP_Request *) odr_malloc(o, sizeof(*hreq));
273     hreq = p->u.HTTP_Request;
274     hreq->headers = 0;
275     hreq->content_len = 0;
276     hreq->content_buf = 0;
277     hreq->version = "1.1";
278     hreq->method = "POST";
279     hreq->path = "/";
280     z_HTTP_header_add(o, &hreq->headers, "User-Agent", "YAZ/" YAZ_VERSION);
281     return p;
282 }
283
284
285 Z_GDU *z_get_HTTP_Request_host_path(ODR odr,
286                                     const char *host,
287                                     const char *path)
288 {
289     Z_GDU *p = z_get_HTTP_Request(odr);
290
291     p->u.HTTP_Request->path = odr_strdup(odr, path);
292
293     if (host)
294     {
295         const char *cp0 = strstr(host, "://");
296         const char *cp1 = 0;
297         if (cp0)
298             cp0 = cp0+3;
299         else
300             cp0 = host;
301
302         cp1 = strchr(cp0, '/');
303         if (!cp1)
304             cp1 = cp0+strlen(cp0);
305
306         if (cp0 && cp1)
307         {
308             char *h = (char*) odr_malloc(odr, cp1 - cp0 + 1);
309             memcpy (h, cp0, cp1 - cp0);
310             h[cp1-cp0] = '\0';
311             z_HTTP_header_add(odr, &p->u.HTTP_Request->headers,
312                               "Host", h);
313         }
314     }
315     return p;
316 }
317
318
319 Z_GDU *z_get_HTTP_Response(ODR o, int code)
320 {
321     Z_GDU *p = (Z_GDU *) odr_malloc(o, sizeof(*p));
322     Z_HTTP_Response *hres;
323
324     p->which = Z_GDU_HTTP_Response;
325     p->u.HTTP_Response = (Z_HTTP_Response *) odr_malloc(o, sizeof(*hres));
326     hres = p->u.HTTP_Response;
327     hres->headers = 0;
328     hres->content_len = 0;
329     hres->content_buf = 0;
330     hres->code = code;
331     hres->version = "1.1";
332     z_HTTP_header_add(o, &hres->headers, "Server",
333                       "YAZ/" YAZ_VERSION);
334     if (code != 200)
335     {
336         hres->content_buf = (char*) odr_malloc(o, 400);
337         sprintf (hres->content_buf, 
338                  "<!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML 2.0//EN\">\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.dk/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  * indent-tabs-mode: nil
549  * End:
550  * vim: shiftwidth=4 tabstop=8 expandtab
551  */
552