forked from libswift/libswift
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhttpgw.cpp
1219 lines (1018 loc) · 39.4 KB
/
httpgw.cpp
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
/*
* httpgw.cpp
* gateway for serving swift content via HTTP, libevent2 based.
*
* Created by Victor Grishchenko, Arno Bakker
* Copyright 2010-2012 TECHNISCHE UNIVERSITEIT DELFT. All rights reserved.
*
*/
#include "swift.h"
#include <event2/http.h>
#include <event2/bufferevent.h>
#include <sstream>
#ifndef WIN32
#include <signal.h>
#endif
using namespace swift;
static uint32_t HTTPGW_VOD_PROGRESS_STEP_BYTES = (256*1024); // configurable
// For best performance make bigger than HTTPGW_PROGRESS_STEP_BYTES
#define HTTPGW_VOD_MAX_WRITE_BYTES (512*1024)
#define HTTPGW_LIVE_PROGRESS_STEP_BYTES (16*1024)
// For best performance make bigger than HTTPGW_PROGRESS_STEP_BYTES
#define HTTPGW_LIVE_MAX_WRITE_BYTES (32*1024)
// Report swift download progress every 2^layer * chunksize bytes (so 0 = report every chunk)
// Note: for LIVE this cannot be reliably used to force a prebuffer size,
// as this gets called with a subtree of size X has been downloaded. If the
// hook-in point is in the middle of such a subtree, the call won't happen
// until the next full subtree has been downloaded, i.e. after ~1.5 times the
// prebuf has been downloaded. See HTTPGW_MIN_PREBUF_BYTES
//
#define HTTPGW_FIRST_PROGRESS_BYTE_INTERVAL_AS_LAYER 0 // must be 0
// Arno: libevent2 has a liberal understanding of socket writability,
// that may result in tens of megabytes being cached in memory. Limit that
// amount at app level.
#define HTTPGW_MAX_OUTBUF_BYTES (2*1024*1024)
// Arno: Minium amout of content to have download before replying to HTTP
static uint32_t HTTPGW_MIN_PREBUF_BYTES = (256*1024); // configurable
#define HTTPGW_MAX_REQUEST 128
struct http_gw_t {
int id;
uint64_t offset;
uint64_t tosend;
int td;
uint64_t lastcpoffset; // last offset at which we checkpointed
struct evhttp_request *sinkevreq;
struct event *sinkevwrite;
std::string mfspecname; // (optional) name from multi-file spec
std::string xcontentdur;
std::string mimetype;
bool replied;
bool closing;
uint64_t startoff; // MULTIFILE: starting offset in content range of desired file
uint64_t endoff; // MULTIFILE: ending offset (careful, for an e.g. 100 byte interval this is 99)
int replycode; // HTTP status code
int64_t rangefirst; // First byte wanted in HTTP GET Range request or -1
int64_t rangelast; // Last byte wanted in HTTP GET Range request (also 99 for 100 byte interval) or -1
bool foundH264NALU;
int64_t echofilesize;
} http_requests[HTTPGW_MAX_REQUEST];
int http_gw_reqs_open = 0;
int http_gw_reqs_count = 0;
struct evhttp *http_gw_event;
struct evhttp_bound_socket *http_gw_handle;
uint32_t httpgw_chunk_size = SWIFT_DEFAULT_CHUNK_SIZE; // Copy of cmdline param
double *httpgw_maxspeed = NULL; // Copy of cmdline param
std::string httpgw_storage_dir="";
Address httpgw_bindaddr;
// Arno, 2010-11-30: for SwarmPlayer 3000 backend autoquit when no HTTP req is received
bool sawhttpconn = false;
typedef std::pair<int,struct evhttp_request *> tdevreqpair;
typedef std::vector<tdevreqpair> tdevreqvector; // not a lot of reqs, so keep simple
tdevreqvector httpgw_tdevreqvec;
/*
* Local prototypes
*/
void HttpGwSubscribeToWrite(http_gw_t *req);
void HttpGwNewRequestCallback (struct evhttp_request *evreq, void *arg);
http_gw_t *HttpGwFindRequestByEV(struct evhttp_request *evreq) {
for (int httpc=0; httpc<http_gw_reqs_open; httpc++) {
if (http_requests[httpc].sinkevreq==evreq)
return &http_requests[httpc];
}
return NULL;
}
http_gw_t *HttpGwFindRequestByTD(int td) {
for (int httpc=0; httpc<http_gw_reqs_open; httpc++) {
if (http_requests[httpc].td==td) {
return &http_requests[httpc];
}
}
return NULL;
}
http_gw_t *HttpGwFindRequestBySwarmID(Sha1Hash &wanthash) {
int td = swift::Find(wanthash);
if (td < 0)
return NULL;
return HttpGwFindRequestByTD(td);
}
void HttpGwCloseConnection (http_gw_t* req) {
dprintf("%s @%i http get: cleanup evreq %p\n",tintstr(),req->id, req->sinkevreq);
struct evhttp_connection *evconn = evhttp_request_get_connection(req->sinkevreq);
req->closing = true;
if (!req->replied)
evhttp_request_free(req->sinkevreq);
else if (req->offset > req->startoff)
evhttp_send_reply_end(req->sinkevreq); //WARNING: calls HttpGwLibeventCloseCallback
req->sinkevreq = NULL;
if (req->sinkevwrite != NULL)
{
event_free(req->sinkevwrite);
req->sinkevwrite = NULL;
}
// Note: for some reason calling conn_free here prevents the last chunks
// to be sent to the requester?
// evhttp_connection_free(evconn); // WARNING: calls HttpGwLibeventCloseCallback
// Current close policy: checkpoint and DO NOT close transfer, keep on
// seeding forever. More sophisticated clients should use CMD GW and issue
// REMOVE.
swift::Checkpoint(req->td);
// Arno, 2012-05-04: MULTIFILE: once the selected file has been downloaded
// swift will download all content that comes afterwards too. Poor man's
// fix to avoid this: seek to end of content when HTTP done. VOD PiecePicker
// will then no download anything. Better would be to seek to end when
// swift partial download is done, not the serving via HTTP.
//
swift::Seek(req->td,swift::Size(req->td)-1,SEEK_CUR);
//swift::Close(req->td);
int oldtd = req->td;
*req = http_requests[--http_gw_reqs_open];
// Arno, 2013-06-26: See if there were concurrent requests for same swarm,
// we serve them sequentially.
//
tdevreqvector::iterator iter;
for (iter=httpgw_tdevreqvec.begin(); iter != httpgw_tdevreqvec.end(); iter++)
{
tdevreqpair pair = *iter;
int gottd = pair.first;
struct evhttp_request *evreq = pair.second;
if (gottd == oldtd)
{
httpgw_tdevreqvec.erase(iter);
dprintf("%s T%i http get: Dequeuing request\n",tintstr(), gottd );
HttpGwNewRequestCallback(evreq,evreq); // note: second evreq significant!
break;
}
}
}
void HttpGwLibeventCloseCallback(struct evhttp_connection *evconn, void *evreqvoid) {
// Called by libevent on connection close, either when the other side closes
// or when we close (because we call evhttp_connection_free()). To prevent
// doing cleanup twice, we see if there is a http_gw_req that has the
// passed evreqvoid as sinkevreq. If so, clean up, if not, ignore.
// I.e. evhttp_request * is used as sort of request ID
//
fprintf(stderr,"HttpGwLibeventCloseCallback: called\n");
http_gw_t * req = HttpGwFindRequestByEV((struct evhttp_request *)evreqvoid);
if (req == NULL)
dprintf("%s @-1 http closecb: conn already closed\n",tintstr() );
else {
dprintf("%s @%i http closecb\n",tintstr(),req->id);
if (req->closing)
dprintf("%s @%i http closecb: already closing\n",tintstr(), req->id);
else
HttpGwCloseConnection(req);
}
}
void HttpGwWrite(struct evhttp_request *evreq) {
//
// Write to HTTP socket.
//
http_gw_t* req = HttpGwFindRequestByEV(evreq);
if (req == NULL) {
print_error("httpgw: MayWrite: can't find req for transfer");
return;
}
// When writing first data, send reply header
if (req->offset == req->startoff) {
// Not just for chunked encoding, see libevent2's http.c
dprintf("%s @%d http reply 2: %d\n",tintstr(),req->id, req->replycode );
evhttp_send_reply_start(req->sinkevreq, req->replycode, "OK");
req->replied = true;
}
// SEEKTODO: stop downloading when file complete
// Update endoff as size becomes less fuzzy
if (swift::Size(req->td) < req->endoff)
req->endoff = swift::Size(req->td)-1;
// How much can we write?
uint64_t relcomplete = swift::SeqComplete(req->td,req->startoff);
if (relcomplete > req->endoff)
relcomplete = req->endoff+1-req->startoff;
int64_t avail = relcomplete-(req->offset-req->startoff);
dprintf("%s @%d http write: avail %lld relcomp %llu offset %llu start %llu end %llu tosend %llu\n",tintstr(),req->id, avail, relcomplete, req->offset, req->startoff, req->endoff, req->tosend );
struct evhttp_connection *evconn = evhttp_request_get_connection(req->sinkevreq);
struct bufferevent* buffy = evhttp_connection_get_bufferevent(evconn);
struct evbuffer *outbuf = bufferevent_get_output(buffy);
// Arno: If sufficient data to write (avoid small increments) and out buffer
// not filled then write to socket. Unfortunately, libevent2 has a liberal
// understanding of socket writability that may result in tens of megabytes
// being cached in memory. Limit that amount at app level.
//
if (avail > 0 && evbuffer_get_length(outbuf) < HTTPGW_MAX_OUTBUF_BYTES)
{
int64_t max_write_bytes = 0;
if (swift::ttype(req->td) == FILE_TRANSFER)
max_write_bytes = HTTPGW_VOD_MAX_WRITE_BYTES;
else
max_write_bytes = HTTPGW_LIVE_MAX_WRITE_BYTES;
// Allocate buffer to read into. TODO: let swift::Read accept evb
char *buf = (char *)malloc(max_write_bytes);
uint64_t tosend = std::min(max_write_bytes,avail);
size_t rd = swift::Read(req->td,buf,tosend,swift::GetHookinOffset(req->td)+req->offset);
if (rd<0) {
print_error("httpgw: MayWrite: error pread");
HttpGwCloseConnection(req);
free(buf);
return;
}
// Construct evbuffer and send incrementally
struct evbuffer *evb = evbuffer_new();
int ret = 0;
// ARNO LIVE raw H264 hack
if (req->mimetype == "video/h264")
{
if (req->offset == req->startoff)
{
// Arno, 2012-10-24: When tuning into a live stream of raw H.264
// you must
// 1. Replay Sequence Picture Set (SPS) and Picture Parameter Set (PPS)
// 2. Find first NALU in video stream (starts with 00 00 00 01 and next bit is 0
// 3. Write that first NALU
//
// PROBLEM is that SPS and PPS contain info on video size, frame rate,
// and stuff, so is stream specific. The hardcoded values here are
// for H.264 640x480 15 fps 500000 bits/s obtained via Spydroid.
//
const unsigned char h264sps[] = { 0x00, 0x00, 0x00, 0x01, 0x27, 0x42, 0x80, 0x29, 0x8D, 0x95, 0x01, 0x40, 0x7B, 0x20 };
const unsigned char h264pps[] = { 0x00, 0x00, 0x00, 0x01, 0x28, 0xDE, 0x09, 0x88 };
dprintf("%s @%i http write: adding H.264 SPS and PPS\n",tintstr(),req->id );
ret = evbuffer_add(evb,h264sps,sizeof(h264sps));
if (ret < 0)
print_error("httpgw: MayWrite: error evbuffer_add H.264 SPS");
ret = evbuffer_add(evb,h264pps,sizeof(h264pps));
if (ret < 0)
print_error("httpgw: MayWrite: error evbuffer_add H.264 PPS");
}
}
else
req->foundH264NALU = true; // Other MIME type
// Find first H.264 NALU
size_t naluoffset = 0;
if (!req->foundH264NALU && rd >= 5)
{
for (int i=0; i<rd-5; i++)
{
// Find startcode before NALU
if (buf[i] == '\x00' && buf[i+1] == '\x00' && buf[i+2] == '\x00' && buf[i+3] == '\x01')
{
char naluhead = buf[i+4];
if ((naluhead & 0x80) == 0)
{
// Found NALU
// http://mailman.videolan.org/pipermail/x264-devel/2007-February/002681.html
naluoffset = i;
req->foundH264NALU = true;
dprintf("%s @%i http write: Found H.264 NALU at %d\n",tintstr(),req->id, naluoffset );
break;
}
}
}
}
// Live tuned-in or VOD:
if (req->foundH264NALU)
{
// Arno, 2012-10-24: LIVE Don't change rd here, as that should be a multiple of chunks
ret = evbuffer_add(evb,buf+naluoffset,rd-naluoffset);
if (ret < 0) {
print_error("httpgw: MayWrite: error evbuffer_add");
evbuffer_free(evb);
HttpGwCloseConnection(req);
free(buf);
return;
}
}
if (evbuffer_get_length(evb) > 0)
evhttp_send_reply_chunk(req->sinkevreq, evb);
evbuffer_free(evb);
free(buf);
int wn = rd;
dprintf("%s @%i http write: sent %db\n",tintstr(),req->id,wn);
req->offset += wn;
req->tosend -= wn;
// PPPLUG
swift::Seek(req->td,req->offset,SEEK_CUR);
}
// Arno, 2010-11-30: tosend is set to fuzzy len, so need extra/other test.
if (req->tosend==0 || req->offset == req->endoff+1) {
// Done; wait for outbuffer to empty
dprintf("%s @%i http write: done, wait for buffer empty\n",tintstr(),req->id);
if (evbuffer_get_length(outbuf) == 0) {
dprintf("%s @%i http write: final done\n",tintstr(),req->id );
HttpGwCloseConnection(req);
}
}
else {
// wait for data
dprintf("%s @%i http write: waiting for data\n",tintstr(),req->id);
}
}
void HttpGwLibeventMayWriteCallback(evutil_socket_t fd, short events, void *evreqvoid )
{
//
// HTTP socket is ready to be written to.
//
http_gw_t * req = HttpGwFindRequestByEV((struct evhttp_request *)evreqvoid);
if (req == NULL)
return;
HttpGwWrite(req->sinkevreq);
if (swift::ttype(req->td) == FILE_TRANSFER) {
if (swift::Complete(req->td)+HTTPGW_VOD_MAX_WRITE_BYTES >= swift::Size(req->td)) {
// We don't get progress callback for last chunk < chunk size, nor
// when all data is already on disk. In that case, just keep on
// subscribing to HTTP socket writability until all data is sent.
//
if (req->sinkevreq != NULL) // Conn closed
HttpGwSubscribeToWrite(req);
}
}
}
void HttpGwSubscribeToWrite(http_gw_t *req) {
//
// Subscribing to writability of the socket requires libevent2 >= 2.0.17
// (or our backported version)
//
struct evhttp_connection *evconn = evhttp_request_get_connection(req->sinkevreq);
struct event_base *evbase = evhttp_connection_get_base(evconn);
struct bufferevent* evbufev = evhttp_connection_get_bufferevent(evconn);
if (req->sinkevwrite != NULL)
event_free(req->sinkevwrite); // does event_del()
req->sinkevwrite = event_new(evbase,bufferevent_getfd(evbufev),EV_WRITE,HttpGwLibeventMayWriteCallback,req->sinkevreq);
struct timeval t;
t.tv_sec = 10;
int ret = event_add(req->sinkevwrite,&t);
//fprintf(stderr,"httpgw: HttpGwSubscribeToWrite: added event\n");
}
void HttpGwSwiftPlayingProgressCallback (int td, bin_t bin) {
// Ready to play or playing, and subsequent HTTPGW_PROGRESS_STEP_BYTES
// available. So subscribe to a callback when HTTP socket becomes writable
// to write it out.
dprintf("%s T%i http play progress\n",tintstr(),td);
http_gw_t* req = HttpGwFindRequestByTD(td);
if (req == NULL)
return;
if (req->sinkevreq == NULL) // Conn closed
return;
// Arno, 2011-12-20: We have new data to send, wait for HTTP socket writability
HttpGwSubscribeToWrite(req);
}
void HttpGwSwiftPrebufferProgressCallback (int td, bin_t bin) {
//
// Prebuffering, and subsequent bytes of content downloaded.
//
// If sufficient prebuffer, next step is to subscribe to a callback for
// writing out the reply and body.
//
dprintf("%s T%i http prebuf progress\n",tintstr(),td);
http_gw_t* req = HttpGwFindRequestByTD(td);
if (req == NULL)
{
dprintf("%s T%i http prebuf progress: req not found\n",tintstr(),td);
return;
}
// ARNOSMPTODO: bitrate-dependent prebuffering?
dprintf("%s T%i http prebuf progress: startoff %llu endoff %llu\n",tintstr(),td, req->startoff, req->endoff);
int64_t wantsize = std::min(req->endoff+1-req->startoff,(uint64_t)HTTPGW_MIN_PREBUF_BYTES);
dprintf("%s T%i http prebuf progress: want %lld got %lld\n",tintstr(),td, wantsize, swift::SeqComplete(req->td,req->startoff) );
if (swift::SeqComplete(req->td,req->startoff) < wantsize)
{
// wait for more data
return;
}
// First HTTPGW_MIN_PREBUF_BYTES bytes of request received.
swift::RemoveProgressCallback(td,&HttpGwSwiftPrebufferProgressCallback);
int stepbytes = 0;
if (swift::ttype(td) == FILE_TRANSFER)
stepbytes = HTTPGW_VOD_PROGRESS_STEP_BYTES;
else
stepbytes = HTTPGW_LIVE_PROGRESS_STEP_BYTES;
int progresslayer = bytes2layer(stepbytes,swift::ChunkSize(td));
swift::AddProgressCallback(td,&HttpGwSwiftPlayingProgressCallback,progresslayer);
//
// We have sufficient data now, see if HTTP socket is writable so we can
// write the HTTP reply and first part of body.
//
HttpGwSwiftPlayingProgressCallback(td,bin_t(0,0));
}
bool HttpGwParseContentRangeHeader(http_gw_t *req,uint64_t filesize)
{
struct evkeyvalq *reqheaders = evhttp_request_get_input_headers(req->sinkevreq);
struct evkeyvalq *repheaders = evhttp_request_get_output_headers(req->sinkevreq);
const char *contentrangecstr =evhttp_find_header(reqheaders,"Range");
if (contentrangecstr == NULL) {
req->rangefirst = -1;
req->rangelast = -1;
req->replycode = 200;
return true;
}
std::string range = contentrangecstr;
// Handle RANGE query
bool bad = false;
int idx = range.find("=");
if (idx == std::string::npos)
return false;
std::string seek = range.substr(idx+1);
dprintf("%s @%i http get: range request spec %s\n",tintstr(),req->id, seek.c_str() );
if (seek.find(",") != std::string::npos) {
// - Range header contains set, not supported at the moment
bad = true;
} else {
// Determine first and last bytes of requested range
idx = seek.find("-");
dprintf("%s @%i http get: range request idx %d\n", tintstr(),req->id, idx );
if (idx == std::string::npos)
return false;
if (idx == 0) {
// -444 format
req->rangefirst = -1;
} else {
std::istringstream(seek.substr(0,idx)) >> req->rangefirst;
}
dprintf("%s @%i http get: range request first %s %lld\n", tintstr(),req->id, seek.substr(0,idx).c_str(), req->rangefirst );
if (idx == seek.length()-1)
req->rangelast = -1;
else {
// 444- format
std::istringstream(seek.substr(idx+1)) >> req->rangelast;
}
dprintf("%s @%i http get: range request last %s %lld\n", tintstr(),req->id, seek.substr(idx+1).c_str(), req->rangelast );
// Check sanity of range request
if (filesize == -1) {
// - No length (live)
bad = true;
}
else if (req->rangefirst == -1 && req->rangelast == -1) {
// - Invalid input
bad = true;
}
else if (req->rangefirst >= (int64_t)filesize) {
bad = true;
}
else if (req->rangelast >= (int64_t)filesize) {
if (req->rangefirst == -1) {
// If the entity is shorter than the specified
// suffix-length, the entire entity-body is used.
req->rangelast = filesize-1;
}
else
bad = true;
}
}
if (bad) {
// Send 416 - Requested Range not satisfiable
std::ostringstream cross;
if (filesize == -1)
cross << "bytes */*";
else
cross << "bytes */" << filesize;
evhttp_add_header(repheaders, "Content-Range", cross.str().c_str() );
evhttp_send_error(req->sinkevreq,416,"Malformed range specification");
req->replied = true;
dprintf("%s @%i http get: ERROR 416 invalid range %lld-%lld\n",tintstr(),req->id,req->rangefirst,req->rangelast );
return false;
}
// Convert wildcards into actual values
if (req->rangefirst != -1 && req->rangelast == -1) {
// "100-" : byte 100 and further
req->rangelast = filesize - 1;
}
else if (req->rangefirst == -1 && req->rangelast != -1) {
// "-100" = last 100 bytes
req->rangefirst = filesize - req->rangelast;
req->rangelast = filesize - 1;
}
// Generate header
std::ostringstream cross;
cross << "bytes " << req->rangefirst << "-" << req->rangelast << "/" << filesize;
evhttp_add_header(repheaders, "Content-Range", cross.str().c_str() );
// Reply is sent when content is avail
req->replycode = 206;
dprintf("%s @%i http get: valid range %lld-%lld\n",tintstr(),req->id,req->rangefirst,req->rangelast );
return true;
}
void HttpGwFirstProgressCallback (int td, bin_t bin) {
//
// First bytes of content downloaded (first in absolute sense)
// We can now determine if a request for a file inside a multi-file
// swarm is valid, and calculate the absolute offsets of the request
// content, taking into account HTTP Range: headers. Or return error.
//
// If valid, next step is to subscribe a new callback for prebuffering.
//
dprintf("%s T%i http first progress\n",tintstr(),td);
// Need the first chunk
if (swift::SeqComplete(td) == 0)
{
dprintf("%s T%i http first: not enough seqcomp\n",tintstr(),td );
return;
}
http_gw_t* req = HttpGwFindRequestByTD(td);
if (req == NULL)
{
dprintf("%s T%i http first: req not found\n",tintstr(),td);
return;
}
// Protection against spurious callback
if (req->tosend > 0)
{
dprintf("%s @%i http first: already set tosend\n",tintstr(),req->id);
return;
}
if (req->xcontentdur == "-1")
{
fprintf(stderr,"httpgw: Live: hook-in at %llu\n", swift::GetHookinOffset(td) );
dprintf("%s @%i http first: hook-in at %llu\n",tintstr(),req->id, swift::GetHookinOffset(td) );
}
// MULTIFILE
// Is storage ready?
Storage *storage = swift::GetStorage(td);
if (storage == NULL)
{
dprintf("%s @%i http first: not storage object?\n",tintstr(),req->id);
return;
}
if (!storage->IsReady())
{
dprintf("%s 2%i http first: Storage not ready, wait\n",tintstr(),req->id);
return; // wait for some more data
}
/*
* Good to go: Calculate info needed for header of HTTP reply, return
* error if it doesn't make sense
*/
uint64_t filesize = 0;
if (req->mfspecname != "")
{
// MULTIFILE
// Find out size of selected file
storage_files_t sfs = storage->GetStorageFiles();
storage_files_t::iterator iter;
bool found = false;
for (iter = sfs.begin(); iter < sfs.end(); iter++)
{
StorageFile *sf = *iter;
if (sf->GetSpecPathName() == req->mfspecname)
{
found = true;
req->startoff = sf->GetStart();
req->endoff = sf->GetEnd();
filesize = sf->GetSize();
break;
}
}
if (!found) {
evhttp_send_error(req->sinkevreq,404,"Individual file not found in multi-file content.");
req->replied = true;
dprintf("%s @%i http get: ERROR 404 file %s not found in multi-file\n",tintstr(),req->id,req->mfspecname.c_str() );
return;
}
}
else
{
// Single file
if (req->echofilesize != -1)
filesize = req->echofilesize;
else
filesize = swift::Size(td);
req->startoff = 0;
req->endoff = filesize-1;
}
// Handle HTTP GET Range request, i.e. additional offset within content
// or file. Sets some headers or sends HTTP error.
if (req->xcontentdur == "-1") //LIVE
{
req->rangefirst = -1;
req->replycode = 200;
}
else if (!HttpGwParseContentRangeHeader(req,filesize))
return;
if (req->rangefirst != -1)
{
// Range request
// Arno, 2012-06-15: Oops, use startoff before mod.
req->endoff = req->startoff + req->rangelast;
req->startoff += req->rangefirst;
req->tosend = req->rangelast+1-req->rangefirst;
}
else
{
req->tosend = filesize;
}
req->offset = req->startoff;
// SEEKTODO: concurrent requests to same resource
if (req->startoff != 0)
{
// Seek to multifile/range start
int ret = swift::Seek(req->td,req->startoff,SEEK_SET);
if (ret < 0) {
evhttp_send_error(req->sinkevreq,500,"Internal error: Cannot seek to file start in range request or multi-file content.");
req->replied = true;
dprintf("%s @%i http get: ERROR 500 cannot seek to %llu\n",tintstr(),req->id, req->startoff);
return;
}
}
// Prepare rest of headers. Not actually sent till HttpGwWrite
// calls evhttp_send_reply_start()
//
struct evkeyvalq *reqheaders = evhttp_request_get_output_headers(req->sinkevreq);
//evhttp_add_header(reqheaders, "Connection", "keep-alive" );
evhttp_add_header(reqheaders, "Connection", "close" );
evhttp_add_header(reqheaders, "Content-Type", req->mimetype.c_str() );
if (req->xcontentdur != "-1")
{
if (req->xcontentdur.length() > 0)
evhttp_add_header(reqheaders, "X-Content-Duration", req->xcontentdur.c_str() );
// Convert size to string
std::ostringstream closs;
closs << req->tosend;
evhttp_add_header(reqheaders, "Content-Length", closs.str().c_str() );
}
else
{
// LIVE
// Uses chunked encoding, configured by not setting a Content-Length header
evhttp_add_header(reqheaders, "Accept-Ranges", "none" );
}
dprintf("%s @%i http first: headers set, tosend %lli\n",tintstr(),req->id,req->tosend);
// Reconfigure callbacks for prebuffering
swift::RemoveProgressCallback(td,&HttpGwFirstProgressCallback);
int stepbytes = 0;
if (swift::ttype(td) == FILE_TRANSFER)
stepbytes = HTTPGW_VOD_PROGRESS_STEP_BYTES;
else
stepbytes = HTTPGW_LIVE_PROGRESS_STEP_BYTES;
int progresslayer = bytes2layer(stepbytes,swift::ChunkSize(td));
swift::AddProgressCallback(td,&HttpGwSwiftPrebufferProgressCallback,progresslayer);
// We have some data now, see if sufficient prebuffer to go play
// (happens when some content already on disk, or fast DL
//
HttpGwSwiftPrebufferProgressCallback(td,bin_t(0,0));
}
bool swift::ParseURI(std::string uri,parseduri_t &map)
{
//
// Format: tswift://tracker:port/roothash-in-hex/filename$chunksize@duration
// where the server part, filename, chunksize and duration may be optional
//
std::string scheme="";
std::string server="";
std::string path="";
if (uri.substr(0,((std::string)SWIFT_URI_SCHEME).length()) == SWIFT_URI_SCHEME)
{
// scheme present
scheme = SWIFT_URI_SCHEME;
int sidx = uri.find("//");
if (sidx != std::string::npos)
{
// server part present
int eidx = uri.find("/",sidx+2);
server = uri.substr(sidx+2,eidx-(sidx+2));
path = uri.substr(eidx);
}
else
path = uri.substr(((std::string)SWIFT_URI_SCHEME).length()+1);
}
else
path = uri;
std::string hashstr="";
std::string filename="";
std::string modstr="";
int sidx = path.find("/",1);
int midx = path.find("$",1);
if (midx == std::string::npos)
midx = path.find("@",1);
if (sidx == std::string::npos && midx == std::string::npos) {
// No multi-file, no modifiers
hashstr = path.substr(1,path.length());
} else if (sidx != std::string::npos && midx == std::string::npos) {
// multi-file, no modifiers
hashstr = path.substr(1,sidx-1);
filename = path.substr(sidx+1,path.length()-sidx);
} else if (sidx == std::string::npos && midx != std::string::npos) {
// No multi-file, modifiers
hashstr = path.substr(1,midx-1);
modstr = path.substr(midx,path.length()-midx);
} else {
// multi-file, modifiers
hashstr = path.substr(1,sidx-1);
filename = path.substr(sidx+1,midx-(sidx+1));
modstr = path.substr(midx,path.length()-midx);
}
std::string durstr="";
std::string chunkstr="";
sidx = modstr.find("@");
if (sidx == std::string::npos)
{
durstr = "";
if (modstr.length() > 1)
chunkstr = modstr.substr(1);
}
else
{
if (sidx == 0)
{
// Only durstr
chunkstr = "";
durstr = modstr.substr(sidx+1);
}
else
{
chunkstr = modstr.substr(1,sidx-1);
durstr = modstr.substr(sidx+1);
}
}
map.insert(stringpair("scheme",scheme));
map.insert(stringpair("server",server));
map.insert(stringpair("path",path));
// Derivatives
map.insert(stringpair("hash",hashstr));
map.insert(stringpair("filename",filename));
map.insert(stringpair("chunksizestr",chunkstr));
map.insert(stringpair("durationstr",durstr));
return true;
}
void HttpGwNewRequestCallback (struct evhttp_request *evreq, void *arg) {
dprintf("%s @%i http get: new request\n",tintstr(),http_gw_reqs_count+1);
if (evhttp_request_get_command(evreq) != EVHTTP_REQ_GET) {
return;
}
sawhttpconn = true;
// 1. Get swift URI
std::string uri = evhttp_request_get_uri(evreq);
struct evkeyvalq *reqheaders = evhttp_request_get_input_headers(evreq);
dprintf("%s @%i http get: new request %s\n",tintstr(),http_gw_reqs_count+1,uri.c_str() );
// Arno, 2012-04-19: libevent adds "Connection: keep-alive" to reply headers
// if there is one in the request headers, even if a different Connection
// reply header has already been set. And we don't do persistent conns here.
//
evhttp_remove_header(reqheaders,"Connection"); // Remove Connection: keep-alive
// 2. Parse swift URI
std::string hashstr = "", mfstr="", durstr="", chunksizestr = "";
if (uri.length() <= 1) {
evhttp_send_error(evreq,400,"Path must be root hash in hex, 40 bytes.");
dprintf("%s @%i http get: ERROR 400 Path must be root hash in hex\n",tintstr(),0 );
return;
}
parseduri_t puri;
if (!swift::ParseURI(uri,puri))
{
evhttp_send_error(evreq,400,"Path format is /roothash-in-hex/filename$chunksize@duration");
dprintf("%s @%i http get: ERROR 400 Path format violation\n",tintstr(),0 );
return;
}
hashstr = puri["hash"];
mfstr = puri["filename"];
durstr = puri["durationstr"];
chunksizestr = puri["chunksizestr"];
// Handle LIVE
std::string mimetype = "video/mp2t";
std::string echofilesizestr="";
if (hashstr.substr(hashstr.length()-5) == ".h264")
{
// LIVESOURCE=ANDROID
hashstr = hashstr.substr(0,40); // strip .h264
durstr = "-1";
mimetype = "video/h264";
}
else if (hashstr.substr(hashstr.length()-4) == ".mp4")
{
// iOS .mp4
std::string hstr = hashstr.substr(0,40); // strip ext
if (hashstr.length() > 44)
echofilesizestr = hashstr.substr(41,hashstr.length()-45);
mimetype = "video/mp4";
hashstr = hstr;
}
else if (hashstr.length() > 40 && hashstr.substr(hashstr.length()-2) == "-1")
{
// Arno, 2012-06-15: LIVE: VLC can't take @-1 as in URL, so workaround
hashstr = hashstr.substr(0,40);
durstr = "-1";
mimetype = "video/mp2t";
}
else if (durstr.length() > 0 && durstr != "-1")
{
// Used in SwarmPlayer 3000
mimetype = "video/ogg";
}
// More info
const char *contentrangecstr =evhttp_find_header(reqheaders,"Range");
if (contentrangecstr == NULL)
contentrangecstr = "";
dprintf("%s @%i http get: demands %s mf %s dur %s mime %s range %s echofs %s\n",tintstr(),http_gw_reqs_open+1,hashstr.c_str(),mfstr.c_str(),durstr.c_str(), mimetype.c_str(), contentrangecstr, echofilesizestr.c_str() );
uint32_t chunksize=httpgw_chunk_size; // default externally configured
if (chunksizestr.length() > 0)
std::istringstream(chunksizestr) >> chunksize;
// ARNO: QUICKFIX
int64_t echofilesize=-1;
if (echofilesizestr != "")
{
int ret = sscanf(echofilesizestr.c_str(),"%llu",&echofilesize);
if (ret != 1)
{
evhttp_send_error(evreq,400,"Echo file size in path is bad");
dprintf("%s @%i http get: ERROR 400 Echo file size in path is bad\n",tintstr(),0 );
return;
}
}
// 3. Check for concurrent requests, currently not supported.
Sha1Hash swarm_id = Sha1Hash(true,hashstr.c_str());
http_gw_t *existreq = HttpGwFindRequestBySwarmID(swarm_id);
if (existreq != NULL)
{
// Arno, 2013-06-26: Queue requests for same swarm. Running them
// concurrently is complex because there is just a single piece picker
// cursor, and swift only supports 1 progress callback per swarm.
//
if (evreq == arg)
{
// Safety catch against repeated queuing
evhttp_send_error(evreq,508,"Loop detected serving concurrent requests to same swarm.");
dprintf("%s @%i http get: ERROR 508 Loop detected serving concurrent requests to same swarm.\n",tintstr(),0 );
return;
}