1 /* http.c - HTTP protocol handler
2 * Copyright (C) 1999 Free Software Foundation, Inc.
4 * This file is part of GnuPG.
6 * GnuPG is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 2 of the License, or
9 * (at your option) any later version.
11 * GnuPG is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License
17 * along with this program; if not, write to the Free Software
18 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA
29 #include <sys/types.h>
30 #include <sys/socket.h>
32 #include <arpa/inet.h>
33 #include <netinet/in.h>
42 #define MAX_LINELEN 20000 /* max. length of a HTTP line */
43 #define VALID_URI_CHARS "abcdefghijklmnopqrstuvwxyz" \
44 "ABCDEFGHIJKLMNOPQRSTUVWXYZ" \
46 "!\"#$%&'()*+,-./:;<=>?[\\]^_{|}~"
49 #define EAGAIN EWOULDBLOCK
52 static int parse_uri( PARSED_URI *ret_uri, const char *uri );
53 static void release_parsed_uri( PARSED_URI uri );
54 static int do_parse_uri( PARSED_URI uri, int only_local_part );
55 static int remove_escapes( byte *string );
56 static int insert_escapes( byte *buffer, const byte *string,
57 const byte *special );
58 static URI_TUPLE parse_tuple( byte *string );
59 static int send_request( HTTP_HD hd );
60 static byte *build_rel_path( PARSED_URI uri );
61 static int parse_response( HTTP_HD hd );
63 static int connect_server( const char *server, ushort port );
64 static int write_server( int sock, const char *data, size_t length );
68 http_open( HTTP_HD hd, HTTP_REQ_TYPE reqtype, const char *url,
73 if( flags || !(reqtype == HTTP_REQ_GET || reqtype == HTTP_REQ_POST) )
74 return G10ERR_INV_ARG;
76 /* initialize the handle */
77 memset( hd, 0, sizeof *hd );
80 hd->req_type = reqtype;
82 rc = parse_uri( &hd->uri, url );
84 rc = send_request( hd );
86 hd->fp_write = iobuf_fdopen( hd->sock , "w" );
93 if( !hd->fp_read && !hd->fp_write && hd->sock != -1 )
95 iobuf_close( hd->fp_read );
96 iobuf_close( hd->fp_write);
97 release_parsed_uri( hd->uri );
105 http_start_data( HTTP_HD hd )
108 iobuf_put( hd->fp_write, '\n' );
115 http_wait_response( HTTP_HD hd, unsigned int *ret_status )
119 http_start_data( hd ); /* make sure that we are in the data */
120 iobuf_flush( hd->fp_write );
122 hd->sock = dup( hd->sock );
124 return G10ERR_GENERAL;
125 iobuf_close( hd->fp_write );
127 shutdown( hd->sock, 1 );
130 hd->fp_read = iobuf_fdopen( hd->sock , "r" );
132 return G10ERR_GENERAL;
134 rc = parse_response( hd );
135 if( !rc && ret_status )
136 *ret_status = hd->status_code;
143 http_open_document( HTTP_HD hd, const char *document, unsigned int flags )
148 return G10ERR_INV_ARG;
150 rc = http_open( hd, HTTP_REQ_GET, document, 0 );
154 rc = http_wait_response( hd, NULL );
165 http_close( HTTP_HD hd )
167 if( !hd || !hd->initialized )
169 if( !hd->fp_read && !hd->fp_write && hd->sock != -1 )
171 iobuf_close( hd->fp_read );
172 iobuf_close( hd->fp_write );
173 release_parsed_uri( hd->uri );
174 m_free( hd->buffer );
181 * Parse an URI and put the result into the newly allocated ret_uri.
182 * The caller must always use release_parsed_uri to releases the
183 * resources (even on an error).
186 parse_uri( PARSED_URI *ret_uri, const char *uri )
188 *ret_uri = m_alloc_clear( sizeof(**ret_uri) + strlen(uri) );
189 strcpy( (*ret_uri)->buffer, uri );
190 return do_parse_uri( *ret_uri, 0 );
194 release_parsed_uri( PARSED_URI uri )
200 for( r = uri->query; r; r = r2 ) {
209 do_parse_uri( PARSED_URI uri, int only_local_part )
216 n = strlen( uri->buffer );
217 /* initialize all fields to an empty string or an empty list */
218 uri->scheme = uri->host = uri->path = p + n;
220 uri->params = uri->query = NULL;
222 /* a quick validity check */
223 if( strspn( p, VALID_URI_CHARS) != n )
224 return G10ERR_BAD_URI; /* invalid characters found */
226 if( !only_local_part ) {
227 /* find the scheme */
228 if( !(p2 = strchr( p, ':' ) ) || p2 == p )
229 return G10ERR_BAD_URI; /* No scheme */
233 if( !strcmp( uri->scheme, "http" ) )
235 else if( !strcmp( uri->scheme, "x-hkp" ) ) /* same as HTTP */
238 return G10ERR_INVALID_URI; /* Unsupported scheme */
242 /* find the hostname */
244 return G10ERR_INVALID_URI; /* does not start with a slash */
247 if( *p == '/' ) { /* there seems to be a hostname */
249 if( (p2 = strchr(p, '/')) )
253 if( (p3=strchr( p, ':' )) ) {
255 uri->port = atoi( p3 );
260 if( (n = remove_escapes( uri->host )) < 0 )
261 return G10ERR_BAD_URI;
262 if( n != strlen( p ) )
263 return G10ERR_BAD_URI; /* hostname with a Nul in it */
266 } /* end global URI part */
268 /* parse the pathname part */
269 if( !p || !*p ) /* we don't have a path */
270 return 0; /* and this is okay */
272 /* fixme: here we have to check params */
274 /* do we have a query part */
275 if( (p2 = strchr( p, '?' )) )
279 if( (n = remove_escapes( p )) < 0 )
280 return G10ERR_BAD_URI;
281 if( n != strlen( p ) )
282 return G10ERR_BAD_URI; /* path with a Nul in it */
285 if( !p || !*p ) /* we don't have a query string */
288 /* now parse the query string */
293 if( (p2 = strchr( p, '&' )) )
295 if( !(elem = parse_tuple( p )) )
296 return G10ERR_BAD_URI;
311 * Remove all %xx escapes; this is done inplace.
312 * Returns: new length of the string.
315 remove_escapes( byte *string )
320 for(p=s=string; *s ; s++ ) {
322 if( s[1] && s[2] && isxdigit(s[1]) && isxdigit(s[2]) ) {
324 *p = *s >= '0' && *s <= '9' ? *s - '0' :
325 *s >= 'A' && *s <= 'F' ? *s - 'A' + 10 : *s - 'a' + 10 ;
328 *p |= *s >= '0' && *s <= '9' ? *s - '0' :
329 *s >= 'A' && *s <= 'F' ? *s - 'A' + 10 : *s - 'a' + 10 ;
341 return -1; /* bad URI */
350 *p = 0; /* always keep a string terminator */
356 insert_escapes( byte *buffer, const byte *string, const byte *special )
360 for( ; *string; string++ ) {
361 if( strchr( VALID_URI_CHARS, *string )
362 && !strchr( special, *string ) ) {
369 sprintf( buffer, "%02X", *string );
383 parse_tuple( byte *string )
390 if( (p2 = strchr( p, '=' )) )
392 if( (n = remove_escapes( p )) < 0 )
393 return NULL; /* bad URI */
394 if( n != strlen( p ) )
395 return NULL; /* name with a Nul in it */
396 tuple = m_alloc_clear( sizeof *tuple );
399 /* we have only the name, so we assume an empty value string */
400 tuple->value = p + strlen(p);
403 else { /* name and value */
404 if( (n = remove_escapes( p2 )) < 0 ) {
406 return NULL; /* bad URI */
416 * Send a HTTP request to the server
417 * Returns 0 if the request was successful
420 send_request( HTTP_HD hd )
427 server = *hd->uri->host? hd->uri->host : "localhost";
428 port = hd->uri->port? hd->uri->port : 80;
430 hd->sock = connect_server( server, port );
432 return G10ERR_NETWORK;
434 p = build_rel_path( hd->uri );
435 request = m_alloc( strlen(p) + 20 );
436 sprintf( request, "%s %s%s HTTP/1.0\r\n",
437 hd->req_type == HTTP_REQ_GET ? "GET" :
438 hd->req_type == HTTP_REQ_HEAD? "HEAD":
439 hd->req_type == HTTP_REQ_POST? "POST": "OOPS",
440 *p == '/'? "":"/", p );
443 rc = write_server( hd->sock, request, strlen(request) );
453 * Build the relative path from the parsed URI.
454 * Minimal implementation.
457 build_rel_path( PARSED_URI uri )
463 /* count the needed space */
464 n = insert_escapes( NULL, uri->path, "%;?&" );
465 /* fixme: add params */
466 for( r=uri->query; r; r = r->next ) {
468 n += insert_escapes( NULL, r->name, "%;?&=" );
470 n += insert_escapes( NULL, r->value, "%;?&=" );
474 /* now allocate and copy */
475 p = rel_path = m_alloc( n );
476 n = insert_escapes( p, uri->path, "%;?&" );
478 /* fixme: add params */
479 for( r=uri->query; r; r = r->next ) {
480 *p++ = r == uri->query? '?':'&';
481 n = insert_escapes( p, r->name, "%;?&=" );
484 /* fixme: use valuelen */
485 n = insert_escapes( p, r->value, "%;?&=" );
494 /***********************
495 * Parse the response from a server.
496 * Returns: errorcode and sets some fileds in the handle
499 parse_response( HTTP_HD hd )
502 unsigned maxlen, len;
504 /* Wait for the status line */
506 maxlen = MAX_LINELEN;
507 len = iobuf_read_line( hd->fp_read, &hd->buffer,
508 &hd->buffer_size, &maxlen );
511 return -1; /* line has been truncated */
516 if( (p = strchr( line, '/')) )
518 if( !p || strcmp( line, "HTTP" ) )
519 return 0; /* assume http 0.9 */
521 if( (p2 = strpbrk( p, " \t" ) ) ) {
523 p2 += strspn( p2, " \t" );
526 return 0; /* assume http 0.9 */
528 /* fixme: add HTTP version number check here */
529 if( (p2 = strpbrk( p, " \t" ) ) )
531 if( !isdigit(p[0]) || !isdigit(p[1]) || !isdigit(p[2]) || p[3] ) {
532 /* malformed HTTP statuscode - assume HTTP 0.9 */
534 hd->status_code = 200;
537 hd->status_code = atoi( p );
539 /* skip all the header lines and wait for the empty line */
541 maxlen = MAX_LINELEN;
542 len = iobuf_read_line( hd->fp_read, &hd->buffer,
543 &hd->buffer_size, &maxlen );
545 /* we ignore truncated lines */
548 /* time lineendings */
549 if( (*line == '\r' && line[1] == '\n') || *line == '\n' )
551 } while( len && *line );
560 struct sockaddr_in mya;
561 struct sockaddr_in peer;
567 if( (fd=socket(AF_INET,SOCK_STREAM, 0)) == -1 ) {
568 log_error("socket() failed: %s\n", strerror(errno));
572 if( setsockopt( fd, SOL_SOCKET, SO_REUSEADDR, (byte*)&i, sizeof(i) ) )
573 log_info("setsockopt(SO_REUSEADDR) failed: %s\n", strerror(errno) );
575 mya.sin_family=AF_INET;
576 memset(&mya.sin_addr, 0, sizeof(mya.sin_addr));
577 mya.sin_port=htons(11371);
579 if( bind( fd, (struct sockaddr *)&mya, sizeof(mya)) ) {
580 log_error("bind to port 11371 failed: %s\n", strerror(errno) );
585 if( listen( fd, 5 ) ) {
586 log_error("listen failed: %s\n", strerror(errno) );
595 if( select( fd+1, &rfds, NULL, NULL, NULL) <= 0 )
596 continue; /* ignore any errors */
598 if( !FD_ISSET( fd, &rfds ) )
601 addrlen = sizeof peer;
602 client = accept( fd, (struct sockaddr *)&peer, &addrlen);
606 log_info("connect from %s\n", inet_ntoa( peer.sin_addr ) );
614 fp = fdopen( client , "r" );
615 while( (c=getc(fp)) != EOF )
631 connect_server( const char *server, ushort port )
633 struct sockaddr_in addr;
634 struct hostent *host;
637 addr.sin_family = AF_INET;
638 addr.sin_port = htons(port);
639 host = gethostbyname((char*)server);
643 addr.sin_addr = *(struct in_addr*)host->h_addr;
645 sd = socket(AF_INET, SOCK_STREAM, 0);
649 if( connect( sd, (struct sockaddr *)&addr, sizeof addr) == -1 ) {
659 write_server( int sock, const char *data, size_t length )
665 nwritten = write( sock, data, nleft );
666 if( nwritten == -1 ) {
669 if( errno == EAGAIN ) {
674 select(0, NULL, NULL, NULL, &tv);
677 log_info("write failed: %s\n", strerror(errno));
678 return G10ERR_NETWORK;
688 /**** Test code ****/
692 main(int argc, char **argv)
697 struct http_context hd;
700 log_set_name("http-test");
707 fprintf(stderr,"usage: http-test uri\n");
712 rc = parse_uri( &uri, *argv );
714 log_error("`%s': %s\n", *argv, g10_errstr(rc));
715 release_parsed_uri( uri );
719 printf("Scheme: %s\n", uri->scheme );
720 printf("Host : %s\n", uri->host );
721 printf("Port : %u\n", uri->port );
722 printf("Path : %s\n", uri->path );
723 for( r=uri->params; r; r = r->next ) {
724 printf("Params: %s=%s", r->name, r->value );
725 if( strlen( r->value ) != r->valuelen )
726 printf(" [real length=%d]", (int)r->valuelen );
729 for( r=uri->query; r; r = r->next ) {
730 printf("Query : %s=%s", r->name, r->value );
731 if( strlen( r->value ) != r->valuelen )
732 printf(" [real length=%d]", (int)r->valuelen );
735 release_parsed_uri( uri ); uri = NULL;
737 rc = http_open_document( &hd, *argv, 0 );
739 log_error("can't get `%s': %s\n", *argv, g10_errstr(rc));
742 log_info("open_http_document succeeded; status=%u\n", hd.status_code );
743 while( (c=iobuf_get( hd.fp_read)) != -1 )