summaryrefslogtreecommitdiffstats
path: root/nanohttp/nanohttp-client.c
blob: 2f79bc0f7509470bebdb9450cf7b1944359b7b58 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
/******************************************************************
*  $Id: nanohttp-client.c,v 1.26 2004/11/02 23:09:26 snowdrop Exp $
*
* CSOAP Project:  A http client/server library in C
* Copyright (C) 2003  Ferhat Ayaz
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this library; if not, write to the
* Free Software Foundation, Inc., 59 Temple Place - Suite 330,
* Boston, MA  02111-1307, USA.
*
* Email: ferhatayaz@yahoo.com
******************************************************************/
#include <nanohttp/nanohttp-client.h>


#ifdef HAVE_CONFIG_H
#include <config.h>
#endif

#include <time.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>

#ifdef MEM_DEBUG
#include <utils/alloc.h>
#endif

static 
int  httpc_send_data(httpc_conn_t *conn, const unsigned char* data, size_t size)
{
  return -1;
}

/*--------------------------------------------------
FUNCTION: httpc_init
DESC: Initialize http client connection
NOTE: This will be called from soap_client_init_args()
----------------------------------------------------*/
herror_t 
httpc_init(int argc, char *argv[])
{
	hoption_init_args(argc, argv);
	hsocket_module_init();
  return H_OK;
}


/*--------------------------------------------------
FUNCTION: httpc_destroy
DESC: Destroy the http client module
----------------------------------------------------*/
void httpc_destroy()
{
  hsocket_module_destroy();
}


/*--------------------------------------------------
FUNCTION: httpc_new
DESC: Creates a new http client connection object
You need to create at least 1 http client connection
to communicate via http.
----------------------------------------------------*/
httpc_conn_t   *
httpc_new()
{
  static int counter = 10000;
	httpc_conn_t   *res = (httpc_conn_t *) malloc(sizeof(httpc_conn_t));

	hsocket_init(&res->sock);
	res->header = NULL;
	res->version = HTTP_1_1;
	res->out = NULL;
	res->_dime_package_nr = 0;
	res->_dime_sent_bytes = 0;
	res->id = counter++;
	res->block = 0;
	return res;
}


/*--------------------------------------------------
FUNCTION: httpc_free
DESC: Free the given http client object.
----------------------------------------------------*/
void 
httpc_free(httpc_conn_t * conn)
{
	hpair_t        *tmp;

	if (conn == NULL) 
	 return;


  while (conn->header != NULL) 
  {
    tmp = conn->header;
    conn->header = conn->header->next;
    hpairnode_free(tmp);
  }

	if (conn->out != NULL)
	{
	  http_output_stream_free(conn->out);
	  conn->out = NULL;
	}

	hsocket_free(conn->sock);
	free(conn);

}


/*--------------------------------------------------
FUNCTION: httpc_set_header
DESC: Adds a new (key, value) pair to the header
or modifies the old pair if this function will
finds another pair with the same 'key' value.
----------------------------------------------------*/
int 
httpc_set_header(httpc_conn_t * conn, const char *key, const char *value)
{
	hpair_t        *p;

	if (conn == NULL) {
		log_warn1("Connection object is NULL");
		return 0;
	}
	p = conn->header;
	while (p != NULL) {
		if (p->key != NULL) {
			if (!strcmp(p->key, key)) {
				free(p->value);
				p->value = (char *) malloc(strlen(value) + 1);
				strcpy(p->value, value);
				return 1;
			}
		}
		p = p->next;
	}

	conn->header = hpairnode_new(key, value, conn->header);
	return 0;
}


/*--------------------------------------------------
FUNCTION: httpc_header_add_date
DESC: Adds the current date to the header.
----------------------------------------------------*/
static
void _httpc_set_error(httpc_conn_t *conn, int errcode, 
  const char *format, ...)
{
	va_list         ap;

  conn->errcode = errcode;

	va_start(ap, format);
	vsprintf(conn->errmsg,  format, ap);
	va_end(ap);
}

/*--------------------------------------------------
FUNCTION: httpc_header_add_date
DESC: Adds the current date to the header.
----------------------------------------------------*/
static
void 
httpc_header_add_date(httpc_conn_t * conn)
{
	char            buffer[255];
	time_t          nw;
	struct tm       stm;

	/* Set date */
	nw = time(NULL);
	localtime_r(&nw, &stm);
	strftime(buffer, 255, "%a, %d %b %y %T GMT", &stm);
	httpc_set_header(conn, HEADER_DATE, buffer);

}


/*--------------------------------------------------
FUNCTION: httpc_send_header
DESC: Sends the current header information stored
in conn through conn->sock.
----------------------------------------------------*/
herror_t 
httpc_send_header(httpc_conn_t * conn)
{
	hpair_t        *p;
	herror_t        status;
	char            buffer[1024];

	p = conn->header;
	while (p != NULL) {
		if (p->key && p->value) {
			sprintf(buffer, "%s: %s\r\n", p->key, p->value);
			status = hsocket_send(conn->sock, buffer);
			if (status != H_OK)
				return status;
		}
		p = p->next;
	}

	status = hsocket_send(conn->sock, "\r\n");
	return status;
}

/*--------------------------------------------------
FUNCTION: httpc_talk_to_server
DESC: This function is the heart of the httpc
module. It will send the request and process the
response.

Here the parameters:

method:
the request method. This can be HTTP_REQUEST_POST and
HTTP_REQUEST_GET.

conn:
the connection object (created with httpc_new())

urlstr:
the complete url in string format.
http://<host>:<port>/<context>
where <port> is not mendatory.

start_cb:
a callback function, which will be called when
the response header is completely arrives.

cb:
a callback function, which will be called everytime
when data arrives.

content_size:
size of content to send.
(only if method is HTTP_REQUEST_POST)

content:
the content data to send.
(only if method is HTTP_REQUEST_POST)

userdata:
a user define data, which will be passed to the
start_cb and cb callbacks as a parameter. This
can also be NULL.


If success, this function will return 0.
>0 otherwise.
----------------------------------------------------*/
static
herror_t 
httpc_talk_to_server(hreq_method_t method, httpc_conn_t * conn,
		     const char *urlstr)
{

	hurl_t          url;
	char            buffer[4096];
	herror_t             status;

	if (conn == NULL) {
		return herror_new(
				"httpc_talk_to_server", 
				GENERAL_INVALID_PARAM, 
				"httpc_conn_t param is NULL");
	}
	/* Build request header */
	httpc_header_add_date(conn);

	/* Create url */
	status = hurl_parse(&url, urlstr);
	if (status != H_OK) {
		log_error2("Can not parse URL '%s'", SAVE_STR(urlstr));
		return status;
	}
/* TODO (#1#): Check for HTTP protocol in URL */

	/* Set hostname  */
	httpc_set_header(conn, HEADER_HOST, url.host);

	/* Open connection */
	status = hsocket_open(&conn->sock, url.host, url.port);
	if (status != H_OK) {
		return status;
	}
	status = hsocket_block(conn->sock, conn->block);
	if (status != H_OK) {
		log_error1("Cannot make socket non-blocking");
		return status;
	}
	/* check method */
	if (method == HTTP_REQUEST_GET) {

		/* Set GET Header  */
		sprintf(buffer, "GET %s HTTP/%s\r\n",
			(url.context[0] != '\0') ? url.context : ("/"), 
			(conn->version == HTTP_1_0)?"1.0":"1.1");

	} else if (method == HTTP_REQUEST_POST) {

		/* Set POST Header  */
		sprintf(buffer, "POST %s HTTP/%s\r\n",
			(url.context[0] != '\0') ? url.context : ("/"),
			(conn->version == HTTP_1_0)?"1.0":"1.1");
	} else {

		log_error1("Unknown method type!");
		return herror_new(
				"httpc_talk_to_server", 
				GENERAL_INVALID_PARAM, 
				"hreq_method_t must be  HTTP_REQUEST_GET or HTTP_REQUEST_POST");
	}

	status = hsocket_send(conn->sock, buffer);
	if (status != H_OK) {
		log_error2("Can not send request (status:%d)", status);
		hsocket_close(conn->sock);
		return status;
	}
	/* Send Header */
	status = httpc_send_header(conn);
	if (status != H_OK) {
		log_error2("Can not send header (status:%d)", status);
		hsocket_close(conn->sock);
		return status;
	}

	return H_OK;

}

/*--------------------------------------------------
FUNCTION: httpc_get
DESC:
----------------------------------------------------*/
herror_t
httpc_get(httpc_conn_t *conn, hresponse_t** out, const char *urlstr)
{
	herror_t             status;

	status = httpc_talk_to_server(HTTP_REQUEST_GET, conn, urlstr);

	if (status != H_OK)
	{
  	return status;
	}

	status = hresponse_new_from_socket(conn->sock, out);
	if (status != H_OK)
	{
  	return status;
	}
		

	return H_OK;
}


/*--------------------------------------------------
FUNCTION: httpc_post_begin
DESC: Returns H_OK if success
----------------------------------------------------*/
herror_t httpc_post_begin(httpc_conn_t *conn, const char *url)
{
  
	herror_t             status;

	status = httpc_talk_to_server(HTTP_REQUEST_POST, conn, url);
	if (status != H_OK)
		return status;

  conn->out = http_output_stream_new(conn->sock, conn->header);

  return H_OK;
}


/*--------------------------------------------------
FUNCTION: httpc_post_begin
DESC: End a "POST" method and receive the response.
  You MUST call httpc_post_end() before!
----------------------------------------------------*/
herror_t httpc_post_end(httpc_conn_t *conn, hresponse_t** out)
{
  herror_t status;

  status = http_output_stream_flush(conn->out);

  if (status != H_OK)
  {
    return status;
  }

	status = hresponse_new_from_socket(conn->sock, out);
	if (status != H_OK)
	{
    	return status;
	}

	return H_OK;
}



/* ---------------------------------------------------
  DIME support functions httpc_dime_* function set
-----------------------------------------------------*/
/*
int httpc_dime_begin(httpc_conn_t *conn, const char *url)
{
  int status;

	httpc_set_header(conn, HEADER_CONTENT_TYPE, "application/dime");

	status = httpc_talk_to_server(HTTP_REQUEST_POST, conn, url);
	if (status != H_OK)
	 return status;

  conn->out = http_output_stream_new(conn->sock, conn->header);
	
  return H_OK;
} 

static _print_binary_ascii(int n)
{
  int i,c=0;
  char ascii[36];

  for (i=0;i<32;i++) {
    ascii[34-i-c] = (n & (1<<i))?'1':'0';
    if ((i+1)%8 == 0) {
        c++;
        ascii[i+c] = ' ';
    }
  }

  ascii[35]='\0';

  log_verbose2("%s", ascii);
}

static 
void _get_binary_ascii8(unsigned char n, char* ascii)
{
  int i;
  for (i=0;i<8;i++)
    ascii[7-i] = (n & (1<<i))?'1':'0';

  ascii[8]='\0';
}

static
void _print_binary_ascii32(unsigned char b1, unsigned char b2,
                           unsigned char b3, unsigned char b4)
{
  char ascii[4][9];
  _get_binary_ascii8(b1, ascii[0]);
  _get_binary_ascii8(b2, ascii[1]);
  _get_binary_ascii8(b3, ascii[2]);
  _get_binary_ascii8(b4, ascii[3]);

  log_verbose5("%s %s %s %s", ascii[0], ascii[1], ascii[2], ascii[3]);
}

int httpc_dime_next(httpc_conn_t* conn, long content_length, 
                    const char *content_type, const char *id,
                    const char *dime_options, int last)
{
  int status, tmp;
  byte_t header[12];

  for (tmp=0;tmp<12;tmp++)
    header[tmp]=0;

  header[0] |= DIME_VERSION_1;

  if (conn->_dime_package_nr == 0)
    header[0] |= DIME_FIRST_PACKAGE;

  if (last)
    header[0] |= DIME_LAST_PACKAGE;

  header[1] = DIME_TYPE_URI;

  tmp = strlen(dime_options);
  header[2] = tmp >> 8;
  header[3] = tmp;

  tmp = strlen(id);
  header[4] = tmp >> 8;
  header[5] = tmp;

  tmp = strlen(content_type);
  header[6] = tmp >> 8;
  header[7] = tmp;

  header[8] = (byte_t)content_length >> 24;
  header[9] = (byte_t)content_length >> 16;
  header[10] = (byte_t)content_length >> 8;
  header[11] = (byte_t)content_length;


  _print_binary_ascii32(header[0], header[1], header[2], header[3]);
  _print_binary_ascii32(header[4], header[5], header[6], header[7]);
  _print_binary_ascii32(header[8], header[9], header[10], header[11]);

	status = http_output_stream_write(conn->out, header, 12);
	if (status != H_OK)
		return status;
  
	status = http_output_stream_write(conn->out, (const byte_t*)dime_options, strlen(dime_options));
	if (status != H_OK)
		return status;
  
	status = http_output_stream_write(conn->out, (const byte_t*)id, strlen(id));
	if (status != H_OK)
		return status;
  
	status = http_output_stream_write(conn->out, (const byte_t*)content_type, strlen(content_type));
	if (status != H_OK)
		return status;
  
  return status;
}


hresponse_t* httpc_dime_end(httpc_conn_t *conn)
{
	int             status;
	hresponse_t    *res;

   Flush put stream 
  status = http_output_stream_flush(conn->out);

  if (status != H_OK)
  {
    _httpc_set_error(conn, status, "Can not flush output stream");
    return NULL;
  }

	res = hresponse_new_from_socket(conn->sock);
	if (res == NULL)
	{
  	_httpc_set_error(conn, -1, "Can not get response ");
  	return NULL;
	}
		
	return res;
}

*/
/* ---------------------------------------------------
  MIME support functions httpc_mime_* function set
-----------------------------------------------------*/

static
void _httpc_mime_get_boundary(httpc_conn_t *conn, char *dest)
{
  sprintf(dest, "---=.Part_NH_%d", conn->id);
  log_verbose2("boundary= \"%s\"", dest);
}

herror_t httpc_mime_begin(httpc_conn_t *conn, const char *url,
  const char* related_start, 
  const char* related_start_info, 
  const char* related_type)
{
	herror_t             status;
	char            buffer[300];
	char            temp[75];
	char            boundary[75];

	/* 
		Set Content-type 
		Set multipart/related parameter
		  type=..; start=.. ; start-info= ..; boundary=...
		  
	*/
	sprintf(buffer, "multipart/related;");
	/*
	  using sprintf instead of snprintf because visual c does not support snprintf
	*/
#ifdef WIN32
#define snprintf(buffer, num, s1, s2) sprintf(buffer, s1,s2)
#endif

  if (related_type) {
    snprintf(temp, 75, " type=\"%s\";", related_type); 
    strcat(buffer, temp);
  }
  
  if (related_start) {
    snprintf(temp, 75, " start=\"%s\";", related_start); 
    strcat(buffer, temp);
  }

  if (related_start_info) {
    snprintf(temp, 75, " start-info=\"%s\";", related_start_info); 
    strcat(buffer, temp);
  }

  _httpc_mime_get_boundary(conn, boundary);
  snprintf(temp, 75, " boundary=\"%s\"", boundary);
  strcat(buffer, temp);

	httpc_set_header(conn, HEADER_CONTENT_TYPE, buffer);

	status = httpc_post_begin(conn, url);
	return status;
}


herror_t httpc_mime_next(httpc_conn_t *conn, 
  const char* content_id,
  const char* content_type, 
  const char* transfer_encoding)
{
  herror_t            status;
  char           buffer[512];
  char           boundary[75];

  /* Get the boundary string */
  _httpc_mime_get_boundary(conn, boundary);
  sprintf(buffer, "\r\n--%s\r\n", boundary);

  /* Send boundary */
  status = http_output_stream_write(conn->out, 
    (const byte_t*)buffer, strlen(buffer));

	if (status != H_OK)
		return status;

	/* Send Content header */
	sprintf(buffer, "%s: %s\r\n%s: %s\r\n%s: %s\r\n\r\n", 
	 HEADER_CONTENT_TYPE, content_type,
	 HEADER_CONTENT_TRANSFER_ENCODING, transfer_encoding,
	 HEADER_CONTENT_ID, content_id);

  status = http_output_stream_write(conn->out, 
    (const byte_t*)buffer, strlen(buffer));

	return status;
}


herror_t httpc_mime_end(httpc_conn_t *conn, hresponse_t** out)
{
  herror_t            status;
  char           buffer[512];
  char           boundary[75];

  /* Get the boundary string */
  _httpc_mime_get_boundary(conn, boundary);
  sprintf(buffer, "\r\n--%s--\r\n\r\n", boundary);

  /* Send boundary */
  status = http_output_stream_write(conn->out, 
    (const byte_t*)buffer, strlen(buffer));

  if (status != H_OK)
    return status;

  /* Flush put stream */
  status = http_output_stream_flush(conn->out);

  if (status != H_OK)
  {
    return status;
  }

	status = hresponse_new_from_socket(conn->sock, out);
	if (status != H_OK)
	{
  	return status;
	}
		
	return H_OK;

}


/**
  Send boundary and part header and continue 
  with next part
*/
herror_t
httpc_mime_send_file (httpc_conn_t * conn,
                      const char *content_id,
                      const char *content_type,
                      const char *transfer_encoding, const char *filename)
{
  herror_t status;
  FILE *fd = fopen (filename, "rb");
  byte_t buffer[MAX_FILE_BUFFER_SIZE];
  size_t size;

  if (fd == NULL)
    return herror_new("httpc_mime_send_file", FILE_ERROR_OPEN, 
	"Can not open file '%s'", filename);

  status =
    httpc_mime_next(conn, content_id, content_type, transfer_encoding);
  if (status != H_OK)
  {
    fclose (fd);
    return status;
  }

  while (!feof (fd))
  {
    size = fread (buffer, 1, MAX_FILE_BUFFER_SIZE, fd);
    if (size == -1)
    {
      fclose (fd);
      return herror_new("httpc_mime_send_file", FILE_ERROR_READ, 
			"Can not read from file '%s'", filename);
    }

	if (size>0)
	{
		/*DEBUG: fwrite(buffer, 1, size, stdout);*/
		status = http_output_stream_write (conn->out, buffer, size);
		if (status != H_OK) {
		fclose (fd);
		return status;
		}
	}
  }

  fclose (fd);
  log_verbose1("file sent!");
  return H_OK;
}