File: http.c

package info (click to toggle)
gmerlin 2.0.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 11,108 kB
  • sloc: ansic: 133,761; javascript: 6,967; makefile: 1,400; sh: 702; sed: 16
file content (571 lines) | stat: -rw-r--r-- 12,183 bytes parent folder | download
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
/*****************************************************************
 * gmerlin - a general purpose multimedia framework and applications
 *
 * Copyright (c) 2001 - 2024 Members of the Gmerlin project
 * http://github.com/bplaum
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program 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 General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 * *****************************************************************/



#include <config.h>

#include <gavl/gavl.h>
#include <gavl/metatags.h>
#include <gavl/gavlsocket.h>
#include <gavl/http.h>

#include <gmerlin/http.h>
#include <gmerlin/utils.h>
#include <gmerlin/log.h>

#define LOG_DOMAIN "gmerlin.http"


#include <string.h>
#include <ctype.h>
#include <stdlib.h>
#include <time.h>
#include <unistd.h>
#include <errno.h>
#include <unistd.h>
#include <pthread.h>


#define META_PROTOCOL   "$PROTOCOL"
#define META_PATH       "$PATH"
#define META_METHOD     "$METHOD"
#define META_STATUS_INT "$STATUS_INT"
#define META_STATUS_STR "$STATUS_STR"
#define META_EMPTY      "$EMPTY"

// Keepalive timeout
#define KA_TIMEOUT (10*GAVL_TIME_SCALE) // 10 Secs

int bg_http_response_write(int fd, gavl_dictionary_t * req)
  {
  int result, len = 0;
  char * line;
  
  line = gavl_http_response_to_string(req, &len);
  
  result = gavl_socket_write_data(fd, (const uint8_t*)line, len);

  if(!result)
    {
    fprintf(stderr, "Writing response failed: %d %d %s\n", len, result, strerror(errno));
    }

  free(line);
  return result;
  }

void bg_http_header_set_empty_var(gavl_dictionary_t * h, const char * name)
  {
  gavl_dictionary_set_string(h, name, META_EMPTY);
  }


int bg_http_response_check_keepalive(gavl_dictionary_t * res)
  {
  const char * protocol;
  const char * var;
  
  protocol = gavl_http_response_get_protocol(res);

  /* Under HTTP/1.1, connections are keep-alive by default */
  if(!strcmp(protocol, "HTTP/1.1"))
    {
    if((var = gavl_dictionary_get_string(res, "Connection")) &&
       !strcasecmp(var, "close"))
      return 0;
    else
      return 1;
    }
  else
    {
    if((var = gavl_dictionary_get_string(res, "Connection")) &&
       !strcasecmp(var, "keep-alive"))
      return 1;
    else
      return 0;
    }
  return 0;
  }

static gavl_io_t * open_io(const char * protocol, const char * host, int port)
  {
  gavl_socket_address_t * addr = NULL;
  int use_tls = 0;
  int fd;
  gavl_io_t * ret = NULL;
  
  if(!strcasecmp(protocol, "https"))
    {
    if(port == -1)
      port = 443;
    
    use_tls = 1;
    }
  else if(strcasecmp(protocol, "http"))
    {
    goto fail;
    }

  if(port == -1)
    port = 80;

  addr = gavl_socket_address_create();
  
  if(!gavl_socket_address_set(addr, host, port, SOCK_STREAM))
    goto fail;
  
  
  if((fd = gavl_socket_connect_inet(addr, 5000)) < 0)
    goto fail;
  
  //  fprintf(stderr, "Request:\n");
  //  gavl_dictionary_dump(&req, 2);

  /* Wrap https */
  
  if(use_tls)
    {
    ret = gavl_io_create_tls_client(fd, host, GAVL_IO_SOCKET_DO_CLOSE);
    }
  else
    {
    ret = gavl_io_create_socket(fd, 30000, GAVL_IO_SOCKET_DO_CLOSE);
    }

  fail:
  if(addr)
    gavl_socket_address_destroy(addr);
  
  return ret;
  }

int bg_http_send_request(const char * url, 
                         int head, const gavl_dictionary_t * vars, gavl_io_t ** io_p)
  {
  gavl_dictionary_t req;

  int ret = 0;
  char * host = NULL;
  char * path = NULL;
  char * protocol = NULL;
  char * request_host = NULL;
  int port = -1;
  //  int status = -1;
  
  gavl_io_t * io = NULL;
  
  gavl_dictionary_init(&req);

  //  fprintf(stderr, "http_get: %s\n", url);
  
  if(!gavl_url_split(url,
                   &protocol,
                   NULL,
                   NULL,
                   &host,
                   &port,
                   &path))
    goto fail;

  /* Keepalive socket */
  if(*io_p)
    io = *io_p;
  else
    io = open_io(protocol, host, port);

  if(!io)
    goto fail;
  
  request_host = bg_url_get_host(host, port);
  
  if(head)
    gavl_http_request_init(&req, "HEAD", path, "HTTP/1.1");
  else
    gavl_http_request_init(&req, "GET", path, "HTTP/1.1");

  gavl_dictionary_set_string(&req, "Host", request_host);
  gavl_dictionary_set_string(&req, "Connection", "Close");

  if(vars)
    gavl_dictionary_merge2(&req, vars);
  
  if(!gavl_http_request_write(io, &req))
    goto fail;


  if(io_p)
    {
    *io_p = io;
    io = NULL;
    }
  
  ret = 1;
  
  fail:

  if(io)
    gavl_io_destroy(io);
  
  return ret;
  }

int bg_http_read_response(gavl_io_t * io,
                          char ** redirect,
                          gavl_dictionary_t * res)
  {
  int ret = 0;
  int status;
  

  if(!gavl_http_response_read(io, res))
    {
    gavl_log(GAVL_LOG_ERROR, LOG_DOMAIN, "Reading response failed");
    goto fail;
    }
  
  status = gavl_http_response_get_status_int(res);

  if(status == 200) // Success
    {
    if(!gavl_dictionary_get_string_i(res, "Content-Type")) // No mimetype
      {
      gavl_log(GAVL_LOG_ERROR, LOG_DOMAIN, "No mimetype given");
      goto fail;
      }
    ret = 1;
    }
  else if((status >= 300) && (status < 400)) // Redirection
    {
    *redirect = gavl_strdup(gavl_dictionary_get_string_i(res, "Location"));
    if(!(*redirect))
      {
      gavl_log(GAVL_LOG_ERROR, LOG_DOMAIN,
             "No location for redirection");
      goto fail;
      }
    ret = 1;
    }
  else // Failure
    {
    gavl_log(GAVL_LOG_ERROR, LOG_DOMAIN, "Downloading failed: %d %s",  
           gavl_http_response_get_status_int(res),
           gavl_http_response_get_status_str(res));
    }

  
  fail:
  

  return ret;
  
  }

int bg_http_get_range(const char * url, gavl_buffer_t * ret, gavl_dictionary_t * dict,
                      int64_t offset, int64_t size)
  {
  gavl_io_t * io;
  io = gavl_http_client_create();

  if((offset > 0) || (size > 0))
    {
    if(size <= 0)
      gavl_http_client_set_range(io, offset, -1);
    else
      gavl_http_client_set_range(io, offset, offset + size);
    }

  gavl_http_client_set_response_body(io, ret);
  
  if(!gavl_http_client_open(io, "GET", url))
    return 0;

  if(dict)
    {
    const gavl_dictionary_t * resp;
    resp = gavl_http_client_get_response(io);
    gavl_dictionary_set_string(dict, GAVL_META_MIMETYPE,
                               gavl_dictionary_get_string_i(resp, "Content-Type"));
    }
  gavl_io_destroy(io);
  return 1;
  }

int bg_http_get(const char * url, gavl_buffer_t * buf, gavl_dictionary_t * dict)
  {
  return bg_http_get_range(url, buf, dict, 0, 0);
  }

#define BYTES_TO_READ (10*1024)

char * bg_http_download(const char * url, const char * out_base)
  {
  gavl_io_t * io;
  
  int ret = 0;
  const char * pos1;
  const char * pos2;
  
  char * extension = NULL;
  char * filename = NULL;
  gavl_buffer_t  buf;
  const gavl_dictionary_t * res;
  FILE * out = NULL;
  int64_t bytes_read;
  
  io = gavl_http_client_create();
  
  //  gavl_dictionary_init(&dict);
  gavl_buffer_init(&buf);

  /* */
  
  //  if(!bg_http_get(url, &buf, &dict))
  //    goto fail;
  
  if(!gavl_http_client_open(io, "GET", url))
    goto fail;

  res = gavl_http_client_get_response(io);
  
  /* Figure out extension */
  if((pos1 = strrchr(url, '.')))
    {
    pos1++;
    
    if((pos2 = strchr(url, '?')))
      extension = gavl_strndup(pos1, pos2);
    else
      extension = gavl_strdup(pos1);

    if(!bg_ext_to_mimetype(extension))
      {
      free(extension);
      extension = NULL;
      }
    }

  if(!extension)
    {
    if((pos1 = gavl_dictionary_get_string_i(res, "Content-Type")))
      extension = gavl_strdup(bg_mimetype_to_ext(pos1));
    }

  if(!extension)
    {
    gavl_log(GAVL_LOG_ERROR, LOG_DOMAIN, "Couldn't download %s, no suitable extension found", url);
    goto fail;
    }

  filename = gavl_sprintf("%s.%s", out_base, extension);

  /* TODO: Download */
  
  gavl_buffer_alloc(&buf, BYTES_TO_READ);

  out = fopen(filename, "w");

  bytes_read = 0;
  
  while(1)
    {
    buf.len = gavl_io_read_data(io, buf.buf, BYTES_TO_READ);

    /* Read error */
    if(buf.len < 0)
      goto fail;
    
    if(buf.len > 0)
      {
      /* Write error */
      if(fwrite(buf.buf, 1, buf.len, out) < buf.len)
        goto fail;
      bytes_read += buf.len;
      }
    
    /* EOF */
    if(buf.len < BYTES_TO_READ)
      break;
    }
  
  
  //  bg_write_file(filename, buf.buf, buf.len);
  gavl_log(GAVL_LOG_INFO, LOG_DOMAIN, "Downloaded %s (%"PRId64" bytes)", url, bytes_read);
  
  ret = 1;
  fail:

  if(out)
    fclose(out);
  
  if(!ret)
    {
    free(filename);
    filename = NULL;
    }

  if(extension)
    free(extension);
  
  gavl_buffer_free(&buf);
  return filename;
  }


int bg_http_write_data(gavl_io_t * io, const uint8_t * data, int len, int chunked)
  {
  if(chunked)
    {
    char buf[128];
    int slen;
    int result;

    /* Length in hex + \r\n */
    snprintf(buf, 128, "%x\r\n", len);
    slen = strlen(buf);
    if(gavl_io_write_data(io, (uint8_t*)buf, slen) < slen)
      return 0;
    
    /* Chunk */
    if((result = gavl_io_write_data(io, data, len) < len))
      return 0;

    /* Trailing \r\n */
    strncpy(buf, "\r\n", 128);
    if(gavl_io_write_data(io, (uint8_t*)buf, 2) < 2)
      return 0;
    return result;
    }
  else
    return gavl_io_write_data(io, data, len);
  }

void bg_http_flush(gavl_io_t * io, int chunked)
  {
  if(chunked)
    {
    char buf[128];
    strncpy(buf, "0\r\n\r\n", 128);
    gavl_io_write_data(io, (uint8_t*)buf, 5);
    }
  }

struct bg_http_keepalive_s
  {
  struct
    {
    int fd;
    gavl_time_t last_active;
    } * sockets;

  int num_sockets;
  int max_sockets;
  pthread_mutex_t mutex;
  };

bg_http_keepalive_t * bg_http_keepalive_create(int max_sockets)
  {
  bg_http_keepalive_t * ret = calloc(1, sizeof(*ret));
  ret->sockets = malloc(max_sockets * sizeof(*ret->sockets));
  pthread_mutex_init(&ret->mutex, NULL);
  ret->max_sockets = max_sockets;
  return ret;
  }

void bg_http_keepalive_destroy(bg_http_keepalive_t * ka)
  {
  int i;
  for(i = 0; i < ka->num_sockets; i++)
    close(ka->sockets[i].fd);
  
  if(ka->sockets)
    free(ka->sockets);

  pthread_mutex_destroy(&ka->mutex);
  
  free(ka);
  }

void bg_http_keepalive_push(bg_http_keepalive_t * ka, int fd,
                            gavl_time_t current_time)
  {
  //  fprintf(stderr, "keepalive_push %d %d %d\n", ka->num_sockets, ka->max_sockets, fd);

  pthread_mutex_lock(&ka->mutex);

  if(ka->num_sockets == ka->max_sockets)
    {
    close(ka->sockets[ka->num_sockets-1].fd);
    ka->num_sockets--;
    }

  if(ka->num_sockets)
    memmove(ka->sockets + 1,  ka->sockets, sizeof(*ka->sockets) * ka->num_sockets);
  
  ka->sockets[0].fd = fd;
  ka->sockets[0].last_active = current_time;
  ka->num_sockets++;
  
  pthread_mutex_unlock(&ka->mutex);
  }

int bg_http_keepalive_accept
(bg_http_keepalive_t * ka, gavl_time_t current_time, int * idx)
  {
  int i;
  int ret = -1;

  pthread_mutex_lock(&ka->mutex);
    
  while(*idx < ka->num_sockets)
    {
    //    
    if(gavl_fd_can_read(ka->sockets[*idx].fd, 0))
      {
      ret = ka->sockets[*idx].fd;

      if(*idx < ka->num_sockets - 1)
        memmove(ka->sockets + (*idx), ka->sockets + (*idx) + 1,
                sizeof(*ka->sockets) * (ka->num_sockets - 1 - (*idx)));
      ka->num_sockets--;
      break;
      }
    (*idx)++;
    }

  /* Remove outdated sockets */
  i = ka->num_sockets - 1;

  while(i >= 0)
    {
    if(current_time - ka->sockets[i].last_active > KA_TIMEOUT)
      {
      close(ka->sockets[i].fd);
      ka->num_sockets--;
      }      
    else
      break;
    i--;
    }
  
  pthread_mutex_unlock(&ka->mutex);
  return ret;
  }