summaryrefslogtreecommitdiffstats
path: root/nanohttp/nanohttp-stream.c
blob: 09d06b243280a424fcbece21c43221e9d2c45a4c (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
/******************************************************************
*  $Id: nanohttp-stream.c,v 1.15 2006/11/23 15:27:33 m0gg Exp $
*
* CSOAP Project:  A http client/server library in C
* Copyright (C) 2003-2004  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_STDIO_H
#include <stdio.h>
#endif

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

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

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

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

#include "nanohttp-common.h"
#include "nanohttp-socket.h"
#include "nanohttp-logging.h"
#include "nanohttp-stream.h"

/*------------------------------------------------------------
HTTP INPUT STREAM
------------------------------------------------------------*/

static int
_http_stream_is_content_length(hpair_t * header)
{
  return hpairnode_get_ignore_case(header, HEADER_CONTENT_LENGTH) != NULL;
}

static int
_http_stream_is_chunked(hpair_t * header)
{
  char *chunked;
  chunked = hpairnode_get_ignore_case(header, HEADER_TRANSFER_ENCODING);
  if (chunked != NULL)
  {
    if (!strcmp(chunked, TRANSFER_ENCODING_CHUNKED))
    {
      return 1;
    }
  }

  return 0;
}

/**
  Creates a new input stream. 
*/
struct http_input_stream_t *
http_input_stream_new(struct hsocket_t *sock, hpair_t * header)
{
  struct http_input_stream_t *result;
  char *content_length;

  /* Paranoya check */
  /* if (header == NULL) return NULL; */
  /* Create object */
  if (!(result = (struct http_input_stream_t *) malloc(sizeof(struct http_input_stream_t))))
  {
    log_error2("malloc failed (%s)", strerror(errno));
    return NULL;
  }

  result->sock = sock;
  result->err = H_OK;

  /* Find connection type */
  hpairnode_dump_deep(header);
  /* Check if Content-type */
  if (_http_stream_is_content_length(header))
  {
    log_verbose1("Stream transfer with 'Content-length'");
    content_length = hpairnode_get_ignore_case(header, HEADER_CONTENT_LENGTH);
    result->content_length = atoi(content_length);
    result->received = 0;
    result->type = HTTP_TRANSFER_CONTENT_LENGTH;
  }
  /* Check if Chunked */
  else if (_http_stream_is_chunked(header))
  {
    log_verbose1("Stream transfer with 'chunked'");
    result->type = HTTP_TRANSFER_CHUNKED;
    result->chunk_size = -1;
    result->received = -1;
  }
  /* Assume connection close */
  else
  {
    log_verbose1("Stream transfer with 'Connection: close'");
    result->type = HTTP_TRANSFER_CONNECTION_CLOSE;
    result->connection_closed = 0;
    result->received = 0;
  }
  return result;
}

/**
  Creates a new input stream from file. 
  This function was added for MIME messages 
  and for debugging.
*/
struct http_input_stream_t *
http_input_stream_new_from_file(const char *filename)
{
  struct http_input_stream_t *result;
  FILE *fd;
 
  if (!(fd = fopen(filename, "rb"))) {

    log_error2("fopen failed (%s)", strerror(errno));
    return NULL;
  }

  /* Create object */
  if (!(result = (struct http_input_stream_t *) malloc(sizeof(struct http_input_stream_t)))) 
  {
    log_error2("malloc failed (%s)", strerror(errno));
    fclose(fd);
    return NULL;
  }

  result->type = HTTP_TRANSFER_FILE;
  result->fd = fd;
  result->deleteOnExit = 0;
  strcpy(result->filename, filename);

  return result;
}

/**
  Free input stream
*/
void
http_input_stream_free(struct http_input_stream_t * stream)
{
  if (stream->type == HTTP_TRANSFER_FILE && stream->fd)
  {
    fclose(stream->fd);
    if (stream->deleteOnExit)
      log_info2("Removing '%s'", stream->filename);
    /* remove(stream->filename); */
  }

  free(stream);
}

static int
_http_input_stream_is_content_length_ready(struct http_input_stream_t * stream)
{
  return (stream->content_length > stream->received);
}

static int
_http_input_stream_is_chunked_ready(struct http_input_stream_t * stream)
{
  return stream->chunk_size != 0;
}

static int
_http_input_stream_is_connection_closed_ready(struct http_input_stream_t * stream)
{
  return !stream->connection_closed;
}

static int
_http_input_stream_is_file_ready(struct http_input_stream_t * stream)
{
  return !feof(stream->fd);
}

static int
_http_input_stream_content_length_read(struct http_input_stream_t * stream, unsigned char *dest, int size)
{
  herror_t status;
  int read;

  /* check limit */
  if (stream->content_length - stream->received < size)
    size = stream->content_length - stream->received;

  /* read from socket */
  if ((status = hsocket_read(stream->sock, dest, size, 1, &read)) != H_OK)
  {
    stream->err = status;
    return -1;
  }

  stream->received += read;
  return read;
}

static int
_http_input_stream_chunked_read_chunk_size(struct http_input_stream_t * stream)
{
  char chunk[25];
  int status, i = 0;
  int chunk_size;
  herror_t err;

  while (1)
  {
    err = hsocket_read(stream->sock, &(chunk[i]), 1, 1, &status);
    if (status != 1)
    {
      stream->err = herror_new("_http_input_stream_chunked_read_chunk_size",
                               GENERAL_INVALID_PARAM,
                               "This should never happen!");
      return -1;
    }

    if (err != H_OK)
    {
      log_error4("[%d] %s(): %s ", herror_code(err), herror_func(err),
                 herror_message(err));

      stream->err = err;
      return -1;
    }

    if (chunk[i] == '\r' || chunk[i] == ';')
    {
      chunk[i] = '\0';
    }
    else if (chunk[i] == '\n')
    {
      chunk[i] = '\0';          /* double check */
      chunk_size = strtol(chunk, (char **) NULL, 16);   /* hex to dec */
      /* 
         log_verbose3("chunk_size: '%s' as dec: '%d'", chunk, chunk_size); */
      return chunk_size;
    }

    if (i == 24)
    {
      stream->err =
        herror_new("_http_input_stream_chunked_read_chunk_size",
                   STREAM_ERROR_NO_CHUNK_SIZE, "reached max line == %d", i);
      return -1;
    }
    else
      i++;
  }

  /* this should never happen */
  stream->err =
    herror_new("_http_input_stream_chunked_read_chunk_size",
               STREAM_ERROR_NO_CHUNK_SIZE, "reached max line == %d", i);
  return -1;
}

static int
_http_input_stream_chunked_read(struct http_input_stream_t * stream, unsigned char *dest,
                                int size)
{
  int status, counter;
  int remain, read = 0;
  char ch;
  herror_t err;

  while (size > 0)
  {
    remain = stream->chunk_size - stream->received;

    if (remain == 0 && stream->chunk_size != -1)
    {
      /* This is not the first chunk. so skip new line until chunk size
         string */
      counter = 100;            /* maximum for stop infinity */
      while (1)
      {
        if ((err = hsocket_read(stream->sock, &ch, 1, 1, &status)) != H_OK)
        {
          stream->err = err;
          return -1;
        }

        if (ch == '\n')
        {
          break;
        }
        if (counter-- == 0)
        {
          stream->err = herror_new("_http_input_stream_chunked_read",
                                   STREAM_ERROR_WRONG_CHUNK_SIZE,
                                   "Wrong chunk-size");
          return -1;
        }
      }
    }

    if (remain == 0)
    {
      /* receive new chunk size */
      stream->chunk_size = _http_input_stream_chunked_read_chunk_size(stream);
      stream->received = 0;

      if (stream->chunk_size < 0)
      {
        /* TODO (#1#): set error flag */
        return stream->chunk_size;
      }
      else if (stream->chunk_size == 0)
      {
        return read;
      }
      remain = stream->chunk_size;
    }

    /* show remaining chunk size in socket */
    if (remain < size)
    {
      /* read from socket */
      if ((err = hsocket_read(stream->sock, &(dest[read]), remain, 1, &status)) != H_OK)
      {
        stream->err = err;
        return -1;
      }
      if (status != remain)
      {
        stream->err = herror_new("_http_input_stream_chunked_read",
                                 GENERAL_INVALID_PARAM,
                                 "This should never happen (remain=%d)(status=%d)!",
                                 remain, status);
        return -1;
      }
    }
    else
    {
      /* read from socket */
      err = hsocket_read(stream->sock, &(dest[read]), size, 1, &status);
      if (status != size)
      {
        stream->err = herror_new("_http_input_stream_chunked_read",
                                 GENERAL_INVALID_PARAM,
                                 "This should never happen (size=%d)(status=%d)!",
                                 size, status);
        return -1;
      }
      if (err != H_OK)
      {
        stream->err = err;
        return -1;
      }
    }

    read += status;
    size -= status;
    stream->received += status;
  }

  return read;
}


static int
_http_input_stream_connection_closed_read(struct http_input_stream_t * stream, unsigned char *dest, int size)
{
  int status;
  herror_t err;

  /* read from socket */
  if ((err = hsocket_read(stream->sock, dest, size, 0, &status)) != H_OK)
  {
    stream->err = err;
    return -1;
  }

  if (status == 0)
    stream->connection_closed = 1;

  stream->received += status;
  return status;
}

static int
_http_input_stream_file_read(struct http_input_stream_t * stream, unsigned char *dest, int size)
{
  size_t len;

  if ((len = fread(dest, 1, size, stream->fd)) == -1)
  {
    stream->err = herror_new("_http_input_stream_file_read",
                             HSOCKET_ERROR_RECEIVE, "fread() returned -1");
    return -1;
  }

  return len;
}

/**
  Returns the actual status of the stream.
*/
int
http_input_stream_is_ready(struct http_input_stream_t * stream)
{
  /* paranoia check */
  if (stream == NULL)
    return 0;

  /* reset error flag */
  stream->err = H_OK;

  switch (stream->type)
  {
  case HTTP_TRANSFER_CONTENT_LENGTH:
    return _http_input_stream_is_content_length_ready(stream);
  case HTTP_TRANSFER_CHUNKED:
    return _http_input_stream_is_chunked_ready(stream);
  case HTTP_TRANSFER_CONNECTION_CLOSE:
    return _http_input_stream_is_connection_closed_ready(stream);
  case HTTP_TRANSFER_FILE:
    return _http_input_stream_is_file_ready(stream);
  default:
    return 0;
  }

}

/**
  Returns the actual read bytes
  <0 on error
*/
int
http_input_stream_read(struct http_input_stream_t * stream, unsigned char *dest, int size)
{
  int len = 0;
  /* paranoia check */
  if (stream == NULL)
  {
    return -1;
  }

  /* XXX: possible memleak! reset error flag */
  stream->err = H_OK;

  switch (stream->type)
  {
  case HTTP_TRANSFER_CONTENT_LENGTH:
    len = _http_input_stream_content_length_read(stream, dest, size);
    break;
  case HTTP_TRANSFER_CHUNKED:
    len = _http_input_stream_chunked_read(stream, dest, size);
    break;
  case HTTP_TRANSFER_CONNECTION_CLOSE:
    len = _http_input_stream_connection_closed_read(stream, dest, size);
    break;
  case HTTP_TRANSFER_FILE:
    len = _http_input_stream_file_read(stream, dest, size);
    break;
  default:
    stream->err = herror_new("http_input_stream_read",
                             STREAM_ERROR_INVALID_TYPE,
                             "%d is invalid stream type", stream->type);
    return -1;
  }

  return len;
}


/*
-------------------------------------------------------------------

HTTP OUTPUT STREAM

-------------------------------------------------------------------
*/



/**
  Creates a new output stream. Transfer code will be found from header.
*/
struct http_output_stream_t *
http_output_stream_new(struct hsocket_t *sock, hpair_t * header)
{
  struct http_output_stream_t *result;
  char *content_length;

  /* Paranoya check */
/*  if (header == NULL)
    return NULL;
*/
  /* Create object */
  if (!(result = (struct http_output_stream_t *) malloc(sizeof(struct http_output_stream_t))))
  {
    log_error2("malloc failed (%s)", strerror(errno));
    return NULL;
  }

  result->sock = sock;
  result->sent = 0;

  /* Find connection type */

  /* Check if Content-type */
  if (_http_stream_is_content_length(header))
  {
    log_verbose1("Stream transfer with 'Content-length'");
    content_length = hpairnode_get_ignore_case(header, HEADER_CONTENT_LENGTH);
    result->content_length = atoi(content_length);
    result->type = HTTP_TRANSFER_CONTENT_LENGTH;
  }
  /* Check if Chunked */
  else if (_http_stream_is_chunked(header))
  {
    log_verbose1("Stream transfer with 'chunked'");
    result->type = HTTP_TRANSFER_CHUNKED;
  }
  /* Assume connection close */
  else
  {
    log_verbose1("Stream transfer with 'Connection: close'");
    result->type = HTTP_TRANSFER_CONNECTION_CLOSE;
  }

  return result;
}

/**
  Free output stream
*/
void
http_output_stream_free(struct http_output_stream_t * stream)
{
  free(stream);

  return;
}

/**
  Writes 'size' bytes of 'bytes' into stream.
  Returns socket error flags or H_OK.
*/
herror_t
http_output_stream_write(struct http_output_stream_t * stream,
                         const unsigned char *bytes, int size)
{
  herror_t status;
  char chunked[15];

  if (stream->type == HTTP_TRANSFER_CHUNKED)
  {
    sprintf(chunked, "%x\r\n", size);
    if ((status = hsocket_send(stream->sock, chunked)) != H_OK)
      return status;
  }

  if (size > 0)
  {
    if ((status = hsocket_nsend(stream->sock, bytes, size)) != H_OK)
      return status;
  }

  if (stream->type == HTTP_TRANSFER_CHUNKED)
  {
    if ((status = hsocket_send(stream->sock, "\r\n")) != H_OK)
      return status;
  }

  return H_OK;
}

/**
  Writes 'strlen()' bytes of 'str' into stream.
  Returns socket error flags or H_OK.
*/
herror_t
http_output_stream_write_string(struct http_output_stream_t * stream,
                                const char *str)
{
  return http_output_stream_write(stream, str, strlen(str));
}


herror_t
http_output_stream_flush(struct http_output_stream_t * stream)
{
  herror_t status;

  if (stream->type == HTTP_TRANSFER_CHUNKED)
  {
    if ((status = hsocket_send(stream->sock, "0\r\n\r\n")) != H_OK)
      return status;
  }

  return H_OK;
}