summaryrefslogtreecommitdiffstats
path: root/nanohttp/nanohttp-client.c
blob: f8efeaf6852a9a46b65be0dd6b9f1d64bb486001 (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
/******************************************************************
*  $Id: nanohttp-client.c,v 1.44 2006/11/23 15:27:33 m0gg 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
******************************************************************/
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif

#ifdef HAVE_SYS_TIME_H
#include <sys/time.h>
#endif

#ifdef HAVE_STDLIB_H
#include <stdlib.h>
#endif

#ifdef HAVE_STDIO_H
#include <stdio.h>
#endif

#ifdef HAVE_STDLIB_H
#include <stdlib.h>
#endif

#ifdef HAVE_STDARG_H
#include <stdarg.h>
#endif

#ifdef HAVE_ERRNO_H
#include <errno.h>
#endif

#ifdef HAVE_STRING_H
#include <string.h>
#endif

#ifdef HAVE_TIME_H
#include <time.h>
#endif

#ifdef HAVE_NETINET_IN_H
#include <netinet/in.h>
#endif

#include "nanohttp-common.h"
#include "nanohttp-socket.h"
#include "nanohttp-stream.h"
#include "nanohttp-request.h"
#include "nanohttp-response.h"
#include "nanohttp-base64.h"
#include "nanohttp-logging.h"
#include "nanohttp-client.h"

/*--------------------------------------------------
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)
{
  return hsocket_module_init(argc, argv);
}

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

  return;
}

/*--------------------------------------------------
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(void)
{
  static int counter = 10000;
  herror_t status;
  httpc_conn_t *res;
 
  if (!(res = (httpc_conn_t *) malloc(sizeof(httpc_conn_t))))
  {
    log_error2("malloc failed (%s)", strerror(errno));
    return NULL;
  }

  if (!(res->sock = (struct hsocket_t *)malloc(sizeof(struct hsocket_t))))
  {
    log_error2("malloc failed (%s)", strerror(errno));
    free(res);
    return NULL;
  }

  if ((status = hsocket_init(res->sock)) != H_OK)
  {
    log_warn2("hsocket_init failed (%s)", herror_message(status));
    return NULL;
  }

  res->header = NULL;
  res->version = HTTP_1_1;
  res->out = NULL;
  res->_dime_package_nr = 0;
  res->_dime_sent_bytes = 0;
  res->id = counter++;

  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->sock);
  free(conn);

  return;
}

/*--------------------------------------------------
 FUNCTION: httpc_close_free
 DESC: Close and free the given http client object.
 ----------------------------------------------------*/
void
httpc_close_free(httpc_conn_t * conn)
{
  if (conn == NULL)
    return;

  hsocket_close(conn->sock);
  httpc_free(conn);

  return;
}

int
httpc_add_header(httpc_conn_t *conn, const char *key, const char *value)
{
  if (!conn)
  {
    log_warn1("Connection object is NULL");
    return -1;
  }

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

  return 0;
}

void
httpc_add_headers(httpc_conn_t *conn, const hpair_t *values)
{
  if (conn == NULL)
  {
    log_warn1("Connection object is NULL");
    return;
  }

  for ( ;values; values=values->next)
    httpc_add_header(conn, values->key, values->value);

  return;
}
 
/*--------------------------------------------------
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;
  }

  for (p = conn->header; p; p = p->next)
  {
    if (p->key && !strcmp(p->key, key))
    {
      free(p->value);
      p->value = strdup(value);
      return 1;
    }
  }

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

  return 0;
}

static int
_httpc_set_basic_authorization_header(httpc_conn_t *conn, const char *key, const char *user, const char *password)
{
  /* XXX: use malloc/free */
  char in[64], out[64];

  if (!user)
    user = "";

  if (!password)
    password = "";

  memset(in, 0, 64);
  memset(out, 0, 64);

  sprintf(in, "%s:%s", user, password);

  base64_encode(in, out);

  sprintf(in, "Basic %s", out);

  return httpc_set_header(conn, key, in);
}

int
httpc_set_basic_authorization(httpc_conn_t *conn, const char *user, const char *password)
{
  return _httpc_set_basic_authorization_header(conn, HEADER_AUTHORIZATION, user, password);
}

int
httpc_set_basic_proxy_authorization(httpc_conn_t *conn, const char *user, const char *password)
{
  return _httpc_set_basic_authorization_header(conn, HEADER_PROXY_AUTHORIZATION, user, password);
}

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

  ts = time(NULL);
  localtime_r(&ts, &stm);
  strftime(buffer, 32, "%a, %d %b %Y %H:%M:%S GMT", &stm);

  httpc_set_header(conn, HEADER_DATE, buffer);

  return;
}


/*--------------------------------------------------
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 *walker;
  herror_t status;
  char buffer[1024];

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

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

/*--------------------------------------------------
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;
  int ssl;

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

  if ((status = hurl_parse(&url, urlstr)) != 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);

  ssl = url.protocol == PROTOCOL_HTTPS ? 1 : 0;

  /* Open connection */
  if ((status = hsocket_open(conn->sock, url.host, url.port, ssl)) != H_OK)
    return status;

  switch(method)
  {
    case HTTP_REQUEST_GET:

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

    case HTTP_REQUEST_POST:

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

    default:
      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");
  }

  log_verbose1("Sending request...");
  if ((status = hsocket_send(conn->sock, buffer)) != H_OK)
  {
    log_error2("Cannot send request (%s)", herror_message(status));
    hsocket_close(conn->sock);
    return status;
  }

  log_verbose1("Sending header...");
  if ((status = httpc_send_header(conn)) != H_OK)
  {
    log_error2("Cannot send header (%s)", herror_message(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;

  if ((status = httpc_talk_to_server(HTTP_REQUEST_GET, conn, urlstr)) != H_OK)
    return status;

  if ((status = hresponse_new_from_socket(conn->sock, out)) != 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;

  if ((status = httpc_talk_to_server(HTTP_REQUEST_POST, conn, url)) != 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;

  if ((status = http_output_stream_flush(conn->out)) != H_OK)
    return status;

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

  return H_OK;
}

/* ---------------------------------------------------
  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, 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);

  return http_output_stream_write(conn->out, buffer, strlen(buffer));
}


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, buffer, strlen(buffer));

  if (status != H_OK)
    return status;

  if ((status = http_output_stream_flush(conn->out)) != H_OK)
    return status;

  if ((status = hresponse_new_from_socket(conn->sock, out)) != 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");
  unsigned char 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;
}