forked from tvheadend/tvheadend
-
Notifications
You must be signed in to change notification settings - Fork 2
/
http.c
2145 lines (1872 loc) · 50.1 KB
/
http.c
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
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* tvheadend, HTTP interface
* Copyright (C) 2007 Andreas Öman
*
* 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 3 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 <https://www.gnu.org/licenses/>.
*/
#include "tvheadend.h"
#include "tcp.h"
#include "http.h"
#include "access.h"
#include "notify.h"
#include "channels.h"
#include "config.h"
#include "htsmsg_json.h"
#include "compat.h"
#include "openssl/opensslv.h"
#if ENABLE_ANDROID
#include <sys/socket.h>
#endif
void *http_server;
static int http_server_running;
static tvh_mutex_t http_paths_mutex = TVH_THREAD_MUTEX_INITIALIZER;
static http_path_list_t http_paths;
static struct strtab HTTP_cmdtab[] = {
{ "NONE", HTTP_CMD_NONE },
{ "GET", HTTP_CMD_GET },
{ "HEAD", HTTP_CMD_HEAD },
{ "POST", HTTP_CMD_POST },
{ "DESCRIBE", RTSP_CMD_DESCRIBE },
{ "OPTIONS", RTSP_CMD_OPTIONS },
{ "SETUP", RTSP_CMD_SETUP },
{ "PLAY", RTSP_CMD_PLAY },
{ "TEARDOWN", RTSP_CMD_TEARDOWN },
{ "PAUSE", RTSP_CMD_PAUSE },
{ "GET_PARAMETER", RTSP_CMD_GET_PARAMETER },
};
static struct strtab HTTP_versiontab[] = {
{ "HTTP/1.0", HTTP_VERSION_1_0 },
{ "HTTP/1.1", HTTP_VERSION_1_1 },
{ "RTSP/1.0", RTSP_VERSION_1_0 },
};
/**
*
*/
const char *
http_cmd2str(int val)
{
return val2str(val, HTTP_cmdtab);
}
int http_str2cmd(const char *str)
{
return str2val(str, HTTP_cmdtab);
}
const char *
http_ver2str(int val)
{
return val2str(val, HTTP_versiontab);
}
int http_str2ver(const char *str)
{
return str2val(str, HTTP_versiontab);
}
/**
*
*/
static int
http_resolve(http_connection_t *hc, http_path_t *_hp,
char **remainp, char **argsp)
{
http_path_t *hp;
int n = 0, cut = 0;
char *v, *path = tvh_strdupa(hc->hc_url);
char *npath;
/* Canocalize path (or at least remove excess slashes) */
v = path;
while (*v && *v != '?') {
if (*v == '/' && v[1] == '/') {
int l = strlen(v+1);
memmove(v, v+1, l);
v[l] = 0;
n++;
} else
v++;
}
while (1) {
tvh_mutex_lock(hc->hc_paths_mutex);
LIST_FOREACH(hp, hc->hc_paths, hp_link) {
if(!strncmp(path, hp->hp_path, hp->hp_len)) {
if(path[hp->hp_len] == 0 ||
path[hp->hp_len] == '/' ||
path[hp->hp_len] == '?')
break;
}
}
if (hp) {
*_hp = *hp;
hp = _hp;
}
tvh_mutex_unlock(hc->hc_paths_mutex);
if(hp == NULL)
return 0;
cut += hp->hp_len;
if(hp->hp_path_modify == NULL)
break;
npath = hp->hp_path_modify(hc, path, &cut);
if(npath == NULL)
break;
path = tvh_strdupa(npath);
free(npath);
}
v = hc->hc_url + n + cut;
*remainp = NULL;
*argsp = NULL;
switch(*v) {
case 0:
break;
case '/':
if(v[1] == '?') {
*argsp = v + 1;
break;
}
*remainp = v + 1;
v = strchr(v + 1, '?');
if(v != NULL) {
*v = 0; /* terminate remaining url */
*argsp = v + 1;
}
break;
case '?':
*v = 0; /* terminate remaining url */
*argsp = v + 1;
break;
default:
return 0;
}
return 1;
}
/*
* HTTP status code to string
*/
static const char *
http_rc2str(int code)
{
switch(code) {
case HTTP_STATUS_PSWITCH: /* 101 */ return "Switching Protocols";
case HTTP_STATUS_OK: /* 200 */ return "OK";
case HTTP_STATUS_PARTIAL_CONTENT: /* 206 */ return "Partial Content";
case HTTP_STATUS_FOUND: /* 302 */ return "Found";
case HTTP_STATUS_BAD_REQUEST: /* 400 */ return "Bad Request";
case HTTP_STATUS_UNAUTHORIZED: /* 401 */ return "Unauthorized";
case HTTP_STATUS_FORBIDDEN: /* 403 */ return "Forbidden";
case HTTP_STATUS_NOT_FOUND: /* 404 */ return "Not Found";
case HTTP_STATUS_NOT_ALLOWED: /* 405 */ return "Method Not Allowed";
case HTTP_STATUS_UNSUPPORTED: /* 415 */ return "Unsupported Media Type";
case HTTP_STATUS_BANDWIDTH: /* 453 */ return "Not Enough Bandwidth";
case HTTP_STATUS_BAD_SESSION: /* 454 */ return "Session Not Found";
case HTTP_STATUS_INTERNAL: /* 500 */ return "Internal Server Error";
case HTTP_STATUS_HTTP_VERSION: /* 505 */ return "HTTP/RTSP Version Not Supported";
default:
return "Unknown Code";
break;
}
}
static const char *cachedays[7] = {
"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"
};
static const char *cachemonths[12] = {
"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov",
"Dec"
};
/**
* Digest authentication helpers
*/
typedef struct http_nonce {
RB_ENTRY(http_nonce) link;
mtimer_t expire;
char nonce[64];
} http_nonce_t;
static RB_HEAD(, http_nonce) http_nonces;
static int
http_nonce_cmp(const void *a, const void *b)
{
return strcmp(((http_nonce_t *)a)->nonce, ((http_nonce_t *)b)->nonce);
}
static void
http_nonce_timeout(void *aux)
{
struct http_nonce *n = aux;
RB_REMOVE(&http_nonces, n, link);
free(n);
}
static char *
http_get_digest_hash(int algo, const char *msg)
{
switch (algo) {
case HTTP_AUTH_ALGO_MD5:
return md5sum(msg, 1);
case HTTP_AUTH_ALGO_SHA256:
return sha256sum(msg, 1);
default:
return sha512sum256(msg, 1);
}
}
static int
http_get_nonce(http_connection_t *hc)
{
struct http_nonce *n = calloc(1, sizeof(*n));
char stamp[33], *m;
int64_t mono;
static int64_t xor;
while (1) {
mono = getmonoclock();
mono ^= 0xa1687211885fcd30LL;
xor ^= 0xf6e398624aa55013LL;
snprintf(stamp, sizeof(stamp), "A!*Fz32%"PRId64"%"PRId64, mono, xor);
m = sha256sum_base64(stamp);
if (m == NULL) {
free(n);
return -1;
}
strlcpy(n->nonce, m, sizeof(n->nonce));
tvh_mutex_lock(&global_lock);
if (RB_INSERT_SORTED(&http_nonces, n, link, http_nonce_cmp)) {
tvh_mutex_unlock(&global_lock);
free(m);
continue; /* get unique hash */
}
mtimer_arm_rel(&n->expire, http_nonce_timeout, n, sec2mono(30));
tvh_mutex_unlock(&global_lock);
break;
}
hc->hc_nonce = m;
return 0;
}
static int
http_nonce_exists(const char *nonce)
{
struct http_nonce *n, tmp;
if (nonce == NULL)
return 0;
strlcpy(tmp.nonce, nonce, sizeof(tmp.nonce));
tvh_mutex_lock(&global_lock);
n = RB_FIND(&http_nonces, &tmp, link, http_nonce_cmp);
if (n) {
mtimer_arm_rel(&n->expire, http_nonce_timeout, n, sec2mono(2*60));
tvh_mutex_unlock(&global_lock);
return 1;
}
tvh_mutex_unlock(&global_lock);
return 0;
}
static char *
http_get_opaque(http_connection_t *hc, const char *realm)
{
char *a = alloca(strlen(realm) + strlen(hc->hc_nonce) + 1);
strcpy(a, realm);
strcat(a, hc->hc_nonce);
return sha256sum_base64(a);
}
/**
*
*/
void
http_alive(http_connection_t *hc)
{
if (hc->hc_nonce)
http_nonce_exists(hc->hc_nonce); /* update timer */
}
/**
*
*/
static void
http_auth_header
(htsbuf_queue_t *hdrs, const char *realm, const char *algo,
const char *nonce, const char *opaque)
{
htsbuf_qprintf(hdrs, "WWW-Authenticate: Digest realm=\"%s\", qop=auth", realm);
if (algo)
htsbuf_qprintf(hdrs, ", algorithm=%s", algo);
htsbuf_qprintf(hdrs, ", nonce=\"%s\"", nonce);
htsbuf_qprintf(hdrs, ", opaque=\"%s\"\r\n", opaque);
}
/**
* Transmit a HTTP reply
*/
void
http_send_header(http_connection_t *hc, int rc, const char *content,
int64_t contentlen,
const char *encoding, const char *location,
int maxage, const char *range,
const char *disposition,
http_arg_list_t *args)
{
struct tm tm0, *tm;
htsbuf_queue_t hdrs;
http_arg_t *ra;
time_t t;
int sess = 0;
assert(atomic_get(&hc->hc_extra_insend) > 0);
htsbuf_queue_init(&hdrs, 0);
htsbuf_qprintf(&hdrs, "%s %d %s\r\n",
http_ver2str(hc->hc_version), rc, http_rc2str(rc));
if (hc->hc_version != RTSP_VERSION_1_0){
htsbuf_qprintf(&hdrs, "Server: %s\r\n", config_get_http_server_name());
if (config.cors_origin && config.cors_origin[0]) {
htsbuf_qprintf(&hdrs, "Access-Control-Allow-Origin: %s\r\n%s%s%s", config.cors_origin,
"Access-Control-Allow-Methods: POST, GET, OPTIONS\r\n",
"Access-Control-Allow-Headers: x-requested-with,authorization,content-type\r\n",
"Access-Control-Allow-Credentials: true\r\n");
}
}
if(maxage == 0) {
if (hc->hc_version != RTSP_VERSION_1_0)
htsbuf_append_str(&hdrs, "Cache-Control: no-cache\r\n");
} else if (maxage > 0) {
time(&t);
tm = gmtime_r(&t, &tm0);
htsbuf_qprintf(&hdrs,
"Last-Modified: %s, %d %s %02d %02d:%02d:%02d GMT\r\n",
cachedays[tm->tm_wday], tm->tm_mday,
cachemonths[tm->tm_mon], tm->tm_year + 1900,
tm->tm_hour, tm->tm_min, tm->tm_sec);
t += maxage;
tm = gmtime_r(&t, &tm0);
htsbuf_qprintf(&hdrs,
"Expires: %s, %d %s %02d %02d:%02d:%02d GMT\r\n",
cachedays[tm->tm_wday], tm->tm_mday,
cachemonths[tm->tm_mon], tm->tm_year + 1900,
tm->tm_hour, tm->tm_min, tm->tm_sec);
htsbuf_qprintf(&hdrs, "Cache-Control: max-age=%d\r\n", maxage);
}
if(rc == HTTP_STATUS_UNAUTHORIZED) {
const char *realm = tvh_str_default(config.realm, "tvheadend");
if (config.http_auth == HTTP_AUTH_DIGEST ||
config.http_auth == HTTP_AUTH_PLAIN_DIGEST) {
char *opaque;
if (hc->hc_nonce == NULL && http_get_nonce(hc)) goto __noauth;
opaque = http_get_opaque(hc, realm);
if (opaque == NULL) goto __noauth;
if (config.http_auth_algo != HTTP_AUTH_ALGO_MD5)
http_auth_header(&hdrs, realm,
config.http_auth_algo == HTTP_AUTH_ALGO_SHA256 ?
"SHA-256" :
#if OPENSSL_VERSION_NUMBER >= 0x1010101fL && !defined(LIBRESSL_VERSION_NUMBER)
"SHA-512-256",
#else
"SHA-256",
#endif
hc->hc_nonce, opaque);
http_auth_header(&hdrs, realm, NULL, hc->hc_nonce, opaque);
free(opaque);
} else {
htsbuf_qprintf(&hdrs, "WWW-Authenticate: Basic realm=\"%s\"\r\n", realm);
}
}
__noauth:
if (hc->hc_version != RTSP_VERSION_1_0)
htsbuf_qprintf(&hdrs, "Connection: %s\r\n",
hc->hc_keep_alive ? "Keep-Alive" : "Close");
if(encoding != NULL)
htsbuf_qprintf(&hdrs, "Content-Encoding: %s\r\n", encoding);
if(location != NULL)
htsbuf_qprintf(&hdrs, "Location: %s\r\n", location);
if(content != NULL)
htsbuf_qprintf(&hdrs, "Content-Type: %s\r\n", content);
if(contentlen > 0)
htsbuf_qprintf(&hdrs, "Content-Length: %"PRId64"\r\n", contentlen);
else if(contentlen == INT64_MIN)
htsbuf_append_str(&hdrs, "Content-Length: 0\r\n");
if(range) {
htsbuf_qprintf(&hdrs, "Accept-Ranges: %s\r\n", "bytes");
htsbuf_qprintf(&hdrs, "Content-Range: %s\r\n", range);
}
if(disposition != NULL)
htsbuf_qprintf(&hdrs, "Content-Disposition: %s\r\n", disposition);
if(hc->hc_cseq) {
htsbuf_qprintf(&hdrs, "CSeq: %"PRIu64"\r\n", hc->hc_cseq);
if (++hc->hc_cseq == 0)
hc->hc_cseq = 1;
}
if (args) {
TAILQ_FOREACH(ra, args, link) {
if (strcmp(ra->key, "Session") == 0)
sess = 1;
htsbuf_qprintf(&hdrs, "%s: %s\r\n", ra->key, ra->val ?: "");
}
}
if(hc->hc_session && !sess)
htsbuf_qprintf(&hdrs, "Session: %s\r\n", hc->hc_session);
htsbuf_append_str(&hdrs, "\r\n");
tcp_write_queue(hc->hc_fd, &hdrs);
}
/*
* Transmit a websocket upgrade reply
*/
int
http_send_header_websocket(http_connection_t *hc, const char *protocol)
{
htsbuf_queue_t hdrs;
const int rc = HTTP_STATUS_PSWITCH;
uint8_t hash[20];
const char *s;
const char *guid = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
char encoded[512];
s = http_arg_get(&hc->hc_args, "sec-websocket-key");
if (s == NULL || strlen(s) < 10) {
http_error(hc, HTTP_STATUS_UNSUPPORTED);
return -1;
}
htsbuf_queue_init(&hdrs, 0);
htsbuf_qprintf(&hdrs, "%s %d %s\r\n",
http_ver2str(hc->hc_version), rc, http_rc2str(rc));
sha1_calc(hash, (uint8_t *)s, strlen(s), (uint8_t *)guid, strlen(guid));
base64_encode(encoded, sizeof(encoded), hash, sizeof(hash));
htsbuf_qprintf(&hdrs, "Upgrade: websocket\r\n"
"Connection: Upgrade\r\n"
"Sec-WebSocket-Accept: %s\r\n"
"Sec-WebSocket-Protocol: %s\r\n"
"\r\n",
encoded, protocol);
http_send_begin(hc);
tcp_write_queue(hc->hc_fd, &hdrs);
http_send_end(hc);
return 0;
}
/*
*
*/
int
http_encoding_valid(http_connection_t *hc, const char *encoding)
{
const char *accept;
char *tokbuf, *tok, *saveptr = NULL, *q, *s;
accept = http_arg_get(&hc->hc_args, "accept-encoding");
if (!accept)
return 0;
tokbuf = tvh_strdupa(accept);
tok = strtok_r(tokbuf, ",", &saveptr);
while (tok) {
while (*tok == ' ')
tok++;
// check for semicolon
if ((q = strchr(tok, ';')) != NULL) {
*q = '\0';
q++;
while (*q == ' ')
q++;
}
if ((s = strchr(tok, ' ')) != NULL)
*s = '\0';
// check for matching encoding with q > 0
if ((!strcasecmp(tok, encoding) || !strcmp(tok, "*")) && (q == NULL || strncmp(q, "q=0.000", strlen(q))))
return 1;
tok = strtok_r(NULL, ",", &saveptr);
}
return 0;
}
/**
*
*/
int
http_header_match(http_connection_t *hc, const char *name, const char *value)
{
char *tokbuf, *tok, *saveptr = NULL, *q, *s;
s = http_arg_get(&hc->hc_args, name);
if (s == NULL)
return 0;
tokbuf = tvh_strdupa(s);
tok = strtok_r(tokbuf, ",", &saveptr);
while (tok) {
while (*tok == ' ')
tok++;
s = tok;
if (*s == '"') {
q = strchr(++s, '"');
if (q)
*q = '\0';
} else {
q = strchr(s, ' ');
if (q)
*q = '\0';
}
if (strcasecmp(s, value) == 0)
return 1;
tok = strtok_r(NULL, ",", &saveptr);
}
return 0;
}
/**
*
*/
static char *
http_get_header_value(const char *hdr, const char *name)
{
char *s, *start, *val;
s = tvh_strdupa(hdr);
while (*s) {
while (*s && *s <= ' ') s++;
start = s;
while (*s && *s != '=') s++;
if (*s == '=') {
*s = '\0';
s++;
}
while (*s && *s <= ' ') s++;
if (*s == '"') {
val = ++s;
while (*s && *s != '"') s++;
if (*s == '"') {
*s = '\0';
s++;
}
while (*s && (*s <= ' ' || *s == ',')) s++;
} else {
val = s;
while (*s && *s != ',') s++;
*s = '\0';
s++;
}
if (*start && strcmp(name, start) == 0)
return strdup(val);
}
return NULL;
}
/**
*
*/
int
http_check_local_ip( http_connection_t *hc )
{
if (hc->hc_local_ip == NULL) {
hc->hc_local_ip = malloc(sizeof(*hc->hc_local_ip));
*hc->hc_local_ip = *hc->hc_self;
hc->hc_is_local_ip = ip_check_is_local_address(hc->hc_peer, hc->hc_self, hc->hc_local_ip) > 0;
}
return hc->hc_is_local_ip;
}
/**
* Transmit a HTTP reply
*/
static void
http_send_reply(http_connection_t *hc, int rc, const char *content,
const char *encoding, const char *location, int maxage)
{
size_t size = hc->hc_reply.hq_size;
uint8_t *data = NULL;
#if ENABLE_ZLIB
if (http_encoding_valid(hc, "gzip") && encoding == NULL && size > 256) {
uint8_t *data2 = (uint8_t *)htsbuf_to_string(&hc->hc_reply);
data = tvh_gzip_deflate(data2, size, &size);
free(data2);
encoding = "gzip";
}
#endif
http_send_begin(hc);
http_send_header(hc, rc, content, size,
encoding, location, maxage, 0, NULL, NULL);
if(!hc->hc_no_output) {
if (data == NULL)
tcp_write_queue(hc->hc_fd, &hc->hc_reply);
else
tvh_write(hc->hc_fd, data, size);
}
http_send_end(hc);
free(data);
}
/**
* Send HTTP error back
*/
void
http_error(http_connection_t *hc, int error)
{
const char *errtxt = http_rc2str(error);
const char *lang;
int level;
if (!atomic_get(&http_server_running)) return;
if (error != HTTP_STATUS_FOUND && error != HTTP_STATUS_MOVED) {
level = LOG_INFO;
if (error == HTTP_STATUS_UNAUTHORIZED)
level = LOG_DEBUG;
else if (error == HTTP_STATUS_BAD_REQUEST || error > HTTP_STATUS_UNAUTHORIZED)
level = LOG_ERR;
tvhlog(level, hc->hc_subsys, "%s: %s %s (%d) %s -- %d",
hc->hc_peer_ipstr, http_ver2str(hc->hc_version),
http_cmd2str(hc->hc_cmd), hc->hc_cmd, hc->hc_url, error);
}
if (hc->hc_version != RTSP_VERSION_1_0) {
htsbuf_queue_flush(&hc->hc_reply);
htsbuf_qprintf(&hc->hc_reply,
"<!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML 2.0//EN\">\r\n"
"<HTML><HEAD>\r\n"
"<TITLE>%d %s</TITLE>\r\n"
"</HEAD><BODY>\r\n"
"<H1>%d %s</H1>\r\n",
error, errtxt, error, errtxt);
if (error == HTTP_STATUS_UNAUTHORIZED) {
lang = hc->hc_access ? hc->hc_access->aa_lang_ui : NULL;
htsbuf_qprintf(&hc->hc_reply, "<P STYLE=\"text-align: center; margin: 2em\"><A HREF=\"%s/\" STYLE=\"border: 1px solid; border-radius: 4px; padding: .6em\">%s</A></P>",
tvheadend_webroot ? tvheadend_webroot : "",
tvh_gettext_lang(lang, N_("Default login")));
htsbuf_qprintf(&hc->hc_reply, "<P STYLE=\"text-align: center; margin: 2em\"><A HREF=\"%s/login\" STYLE=\"border: 1px solid; border-radius: 4px; padding: .6em\">%s</A></P>",
tvheadend_webroot ? tvheadend_webroot : "",
tvh_gettext_lang(lang, N_("New login")));
}
htsbuf_append_str(&hc->hc_reply, "</BODY></HTML>\r\n");
http_send_reply(hc, error, "text/html", NULL, NULL, 0);
} else {
http_send_reply(hc, error, NULL, NULL, NULL, 0);
}
}
/**
* Send an HTTP OK, simple version for text/html
*/
void
http_output_html(http_connection_t *hc)
{
return http_send_reply(hc, HTTP_STATUS_OK, "text/html; charset=UTF-8",
NULL, NULL, 0);
}
/**
* Send an HTTP OK, simple version for text/html
*/
void
http_output_content(http_connection_t *hc, const char *content)
{
return http_send_reply(hc, HTTP_STATUS_OK, content, NULL, NULL, 0);
}
/**
* Send an HTTP REDIRECT
*/
void
http_redirect(http_connection_t *hc, const char *location,
http_arg_list_t *req_args, int external)
{
const char *loc = location;
htsbuf_queue_flush(&hc->hc_reply);
if (req_args) {
http_arg_t *ra;
htsbuf_queue_t hq;
int first = 1;
htsbuf_queue_init(&hq, 0);
if (!external && tvheadend_webroot && location[0] == '/')
htsbuf_append_str(&hq, tvheadend_webroot);
htsbuf_append_str(&hq, location);
TAILQ_FOREACH(ra, req_args, link) {
if (!first)
htsbuf_append(&hq, "&", 1);
else
htsbuf_append(&hq, "?", 1);
first = 0;
htsbuf_append_and_escape_url(&hq, ra->key);
if (ra->val) {
htsbuf_append(&hq, "=", 1);
htsbuf_append_and_escape_url(&hq, ra->val);
}
}
loc = htsbuf_to_string(&hq);
htsbuf_queue_flush(&hq);
} else if (!external && tvheadend_webroot && location[0] == '/') {
loc = malloc(strlen(location) + strlen(tvheadend_webroot) + 1);
strcpy((char *)loc, tvheadend_webroot);
strcat((char *)loc, location);
}
htsbuf_qprintf(&hc->hc_reply,
"<!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML 2.0//EN\">\r\n"
"<HTML><HEAD>\r\n"
"<TITLE>Redirect</TITLE>\r\n"
"</HEAD><BODY>\r\n"
"Please follow <a href=\"%s\">%s</a>\r\n"
"</BODY></HTML>\r\n",
loc, loc);
http_send_reply(hc, HTTP_STATUS_FOUND, "text/html", NULL, loc, 0);
if (loc != location)
free((char *)loc);
}
/**
* Send an CSS @import
*/
void
http_css_import(http_connection_t *hc, const char *location)
{
const char *loc = location;
htsbuf_queue_flush(&hc->hc_reply);
if (tvheadend_webroot && location[0] == '/') {
loc = alloca(strlen(location) + strlen(tvheadend_webroot) + 1);
strcpy((char *)loc, tvheadend_webroot);
strcat((char *)loc, location);
}
htsbuf_qprintf(&hc->hc_reply, "@import url('%s');\r\n", loc);
http_send_reply(hc, HTTP_STATUS_OK, "text/css", NULL, loc, 0);
}
/**
*
*/
void
http_extra_destroy(http_connection_t *hc)
{
htsbuf_data_t *hd, *hd_next;
tvh_mutex_lock(&hc->hc_extra_lock);
for (hd = TAILQ_FIRST(&hc->hc_extra.hq_q); hd; hd = hd_next) {
hd_next = TAILQ_NEXT(hd, hd_link);
if (hd->hd_data_off <= 0) {
htsbuf_data_free(&hc->hc_extra, hd);
atomic_dec(&hc->hc_extra_chunks, 1);
}
}
tvh_mutex_unlock(&hc->hc_extra_lock);
}
/**
*
*/
int
http_extra_flush(http_connection_t *hc)
{
htsbuf_data_t *hd;
int r, serr = 0;
if (atomic_add(&hc->hc_extra_insend, 1) != 0)
goto fin;
while (1) {
r = -1;
serr = 0;
tvh_mutex_lock(&hc->hc_extra_lock);
if (atomic_add(&hc->hc_extra_insend, 0) != 1)
goto unlock;
hd = TAILQ_FIRST(&hc->hc_extra.hq_q);
if (hd == NULL)
goto unlock;
do {
r = send(hc->hc_fd, hd->hd_data + hd->hd_data_off,
hd->hd_data_size - hd->hd_data_off,
MSG_DONTWAIT | (TAILQ_NEXT(hd, hd_link) ? MSG_MORE : 0));
serr = errno;
} while (r < 0 && serr == EINTR);
if (r > 0 && r + hd->hd_data_off >= hd->hd_data_size) {
atomic_dec(&hc->hc_extra_chunks, 1);
htsbuf_data_free(&hc->hc_extra, hd);
} else if (r > 0) {
hd->hd_data_off += r;
hc->hc_extra.hq_size -= r;
}
unlock:
tvh_mutex_unlock(&hc->hc_extra_lock);
if (r < 0) {
if (ERRNO_AGAIN(serr))
serr = 0;
break;
}
}
fin:
atomic_dec(&hc->hc_extra_insend, 1);
return serr;
}
/**
*
*/
int
http_extra_flush_partial(http_connection_t *hc)
{
htsbuf_data_t *hd;
int r = 0;
unsigned int off, size;
void *data = NULL;
atomic_add(&hc->hc_extra_insend, 1);
tvh_mutex_lock(&hc->hc_extra_lock);
hd = TAILQ_FIRST(&hc->hc_extra.hq_q);
if (hd && hd->hd_data_off > 0) {
data = hd->hd_data;
hd->hd_data = NULL;
off = hd->hd_data_off;
size = hd->hd_data_size;
atomic_dec(&hc->hc_extra_chunks, 1);
htsbuf_data_free(&hc->hc_extra, hd);
}
tvh_mutex_unlock(&hc->hc_extra_lock);
if (data) {
r = tvh_write(hc->hc_fd, data + off, size - off);
free(data);
}
atomic_dec(&hc->hc_extra_insend, 1);
return r;
}
/**
*
*/
int
http_extra_send(http_connection_t *hc, const void *data,
size_t data_len, int may_discard)
{
uint8_t *b = malloc(data_len);
memcpy(b, data, data_len);
return http_extra_send_prealloc(hc, b, data_len, may_discard);
}
/**
*
*/
int
http_extra_send_prealloc(http_connection_t *hc, const void *data,
size_t data_len, int may_discard)
{
if (data == NULL) return 0;
tvh_mutex_lock(&hc->hc_extra_lock);
if (!may_discard || hc->hc_extra.hq_size <= 1024*1024) {
atomic_add(&hc->hc_extra_chunks, 1);
htsbuf_append_prealloc(&hc->hc_extra, data, data_len);
} else {
free((void *)data);
}
tvh_mutex_unlock(&hc->hc_extra_lock);
return http_extra_flush(hc);
}
/**
*
*/
char *
http_get_hostpath(http_connection_t *hc, char *buf, size_t buflen)
{
const char *host, *proto;
host = http_arg_get(&hc->hc_args, "Host") ?:
http_arg_get(&hc->hc_args, "X-Forwarded-Host");
proto = http_arg_get(&hc->hc_args, "X-Forwarded-Proto");
snprintf(buf, buflen, "%s:https://%s%s",
proto ?: "http", host ?: "localhost", tvheadend_webroot ?: "");
return buf;
}
/**
*
*/
static void
http_access_verify_ticket(http_connection_t *hc)
{
const char *ticket_id;
ticket_id = http_arg_get(&hc->hc_req_args, "ticket");
hc->hc_access = access_ticket_verify2(ticket_id, hc->hc_url);
if (hc->hc_access == NULL)
return;
hc->hc_auth_type = HC_AUTH_TICKET;
tvhinfo(hc->hc_subsys, "%s: using ticket %s for %s",
hc->hc_peer_ipstr, ticket_id, hc->hc_url);
}
/**
*
*/
static void
http_access_verify_auth(http_connection_t *hc)
{
const char *auth_id;
auth_id = http_arg_get(&hc->hc_req_args, "auth");
hc->hc_access = access_get_by_auth(hc->hc_peer, auth_id);
if (hc->hc_access == NULL)
return;
hc->hc_auth_type = HC_AUTH_PERM;
tvhinfo(hc->hc_subsys, "%s: using auth %s for %s",
hc->hc_peer_ipstr, auth_id, hc->hc_url);
}