forked from b-rad-NDi/tv-now
-
Notifications
You must be signed in to change notification settings - Fork 1
/
MicroMediaServer.c
1879 lines (1599 loc) · 50.3 KB
/
MicroMediaServer.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
/*****************************************************************************
* Copyright (C) 2012- Brad Love : b-rad at next dimension dot cc
* Next Dimension Innovations : http://nextdimension.cc
* http://b-rad.cc
* Copyright 2006 - 2011 Intel Corporation
*
* This file is part of TV-Now
* TV-Now is an Open Source DLNA Media Server. TV-Now's purpose is
* to serve Live TV (and recorded content) over the local network
* to televisions, computers, media players, tablets, and consoles.
* TV-Now delivers EPG data in the DLNA container for compatible
* clients and also offers an html5+jquery tv player with full EPG.
* TV-Now uses the libdvbtee library as its backend.
*
* TV-Now is compatible with:
* - ATSC
* - Clear QAM
* - DVB-T
*
* TV-Now 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.
*
* Note: All additional terms from Section 7 of GPLv3 apply to this software.
* This includes requiring preservation of specified reasonable legal
* notices or author attributions in the material or in the Appropriate
* Legal Notices displayed by this software.
*
* You should have received a copy of the GNU General Public License v3
* along with TV-Now. If not, see <http://www.gnu.org/licenses/>.
*
* An Apache 2.0 licensed version of this software is privately maintained
* for licensing to interested commercial parties. Apache 2.0 license is
* compatible with the GPLv3, which allows the Apache 2.0 version to be
* included in proprietary systems, while keeping the public GPLv3 version
* completely open source. GPLv3 can NOT be re-licensed as Apache 2.0, since
* Apache 2.0 license is only a subset of GPLv3. To inquire about licensing
* the commercial version of TV-Now contact: tv-now at nextdimension dot cc
*
* Note about contributions and patch submissions:
* The commercial Apache 2.0 version of TV-Now is used as the master.
* The GPLv3 version of TV-Now will be identical to the Apache 2.0 version.
* All contributions and patches are licensed under Apache 2.0
* By submitting a patch you implicitly agree to
* http://www.apache.org/licenses/icla.txt
* You retain ownership and when merged the license will be upgraded to GPLv3.
*
*****************************************************************************/
#define MULTIPART_RANGE_DELIMITER "{{{{{-S3P4R470R-}}}}}"
#define _CRTDBG_MAP_ALLOC
#include <stdio.h>
#include <stdlib.h>
#ifdef WIN32
#include <crtdbg.h>
#endif
#include <inttypes.h>
#include <string.h>
#include "UpnpMicroStack.h"
#include "ILibParsers.h"
#include "MicroMediaServer.h"
#include "MyString.h"
#include "PortingFunctions.h"
#include "MimeTypes.h"
#include "version.h"
#include "CdsMediaObject.h"
#include "CdsMediaClass.h"
#include "CdsObjectToDidl.h"
#include "ILibWebServer.h"
#ifdef UNDER_CE
#define strnicmp _strnicmp
#define assert ASSERT
#endif
#ifdef WIN32
#ifndef UNDER_CE
#include "assert.h"
#endif
#endif
#ifdef _POSIX
#include "assert.h"
#define strnicmp strncasecmp
#include <semaphore.h>
#endif
// POSIX-style synchronization
#ifndef _POSIX
#define sem_t HANDLE
#define sem_init(x,y,z) *x=CreateSemaphore(NULL,z,FD_SETSIZE,NULL)
#define sem_destroy(x) (CloseHandle(*x)==0?1:0)
#define sem_wait(x) WaitForSingleObject(*x,INFINITE)
#define sem_trywait(x) ((WaitForSingleObject(*x,0)==WAIT_OBJECT_0)?0:1)
#define sem_post(x) ReleaseSemaphore(*x,1,NULL)
#define strncasecmp(x,y,z) _strnicmp(x,y,z)
#endif
/************************************************************************************/
/* START SECTION - Configuration info for the media server. */
/* This value should be one of the xxx_DIR_DELIMITER_STR values defined in the FileSystem configuration section. */
char* DIRDELIMITER;
/* The value of the shared root path. String value and its corresponding length variable initialized through SetRootPath(). */
char* ROOTPATH;
int ROOTPATHLENGTH;
/* MMS Stats */
void (*MmsOnStatsChanged) (void) = NULL;
void (*MmsOnTransfersChanged) (int) = NULL;
int MmsBrowseCount = 0;
int MmsHttpRequestCount = 0;
int MmsCurrentTransfersCount = 0;
struct MMSMEDIATRANSFERSTAT MmsMediaTransferStats[DOWNLOAD_STATS_ARRAY_SIZE];
void *MMS_Chain;
void *MMS_MicroStack;
sem_t MMS_IP_AddressesLock;
int *MMS_IP_Addresses;
int MMS_IP_AddressesLen;
/* END SECTION - Internal state variables and configuration for the media server. */
/************************************************************************************/
/************************************************************************************/
/* START SECTION - Stuff specific to FileSystem stuff. */
/* FileName To Didl struct */
struct FNTD
{
char* DirDelimiter; /* Delimiter used for directory names */
char* Root; /* Root path. */
int RootLength; /* Length of Root */
char* Filter; /* Comma separated list of tags to include. Use the * char to indicate all fields. NULL indicates minimum.*/
unsigned int SI; /* Starting index */
unsigned int RC; /* Requested count */
unsigned int CI; /* Current index - used internally. */
unsigned int NR; /* OUT: Number returned in DIDL response. used internally. */
unsigned int TM; /* OUT: Total number of matches. used internally */
unsigned long UpdateID; /* OUT: UpdateID. used internally. */
FILE* File; /* Print DIDL here if non-NULL. Works in conjuction with Socket. */
char* String; /* strcat DIDL here if non-NULL */
uint64_t FileSize; /* length of the file in bytes - used for res@size */
const char* ArgName; /* Needed if UpnpToken != NULL */
void* UpnpToken; /* Print DIDL here if non-NULL. Works in conjunction with File. */
char* BaseUri; /* http://[ip address]:[port]/dir */
int *AddressList;
int AddressListLen;
int Port;
};
/* CHAR and STRING defines for Win32 directory delimiter */
#define WIN32_DIR_DELIMITER_CHR '\\'
#define WIN32_DIR_DELIMITER_STR "\\"
/* CHAR and STRING defines for UNIX directory delimiter */
#define UNIX_DIR_DELIMITER_CHR '/'
#define UNIX_DIR_DELIMITER_STR "/"
#define MAX_PATH_LENGTH 1024
/* #define stuff used for ProcessDir */
#define RECURSE_NEVER 0 /* Never recurse */
#define RECURSE_WHEN_FOUND 1 /* Recurse directories immediately when entry found. */
#define RECURSE_AFTER_PROCESS 2 /* NOT IMPLEMENTED: Recurse subdirs after done processing entries in the directory. */
#define RECURSE_BEFORE_PROCESS 3 /* NOT IMPLEMENTED: Recurse subdirs before processing any entries in the directory.*/
#define PROCESS_WHEN_FOUND 0 /* Process the entry immediately. */
#define PROCESS_DIRS_FIRST 1 /* Process directory entries first. */
#define PROCESS_FILE_FIRST 2 /* Process file entries first. */
/* Returns file extension for ASCII-encoded paths. */
char* GetFileExtension(char* pathName, int returnCopy)
{
int len;
int i;
len = (int) strlen(pathName);
for (i = len-1; i >= 0; i--)
{
if (
(WIN32_DIR_DELIMITER_CHR == pathName[i]) ||
(UNIX_DIR_DELIMITER_CHR == pathName[i])
)
{
return NULL;
}
if ('.' == pathName[i])
{
if (returnCopy == 0)
{
return pathName+i;
}
else
{
char* deepCopy = (char*) malloc(len+1);
strcpy(deepCopy, pathName);
return deepCopy;
}
}
}
return NULL;
}
int GetLastIndexOfParentPath(char* pathName, char* dirDelimiter, int includeDelimiter)
{
int dLen;
int pLen;
int i, j, ij, len;
int foundDelim = 0;
dLen = (int) strlen(dirDelimiter);
pLen = (int) strlen(pathName);
for (i = pLen; i >= 0; i--)
{
for (j = 0; j < dLen; j++)
{
ij = i+j;
if (i+j < pLen)
{
if (dirDelimiter[j] != pathName[ij])
{
/* if a delimiter char doesn't match, then go to pathName[i-1] */
break;
}
if (j == dLen-1)
{
/* make sure we didn't find a delimiter that ends pathName */
if (i+dLen < pLen)
{
foundDelim = 1;
}
}
}
}
if (0 != foundDelim)
{
if (0 != includeDelimiter)
{
len = i+dLen;
}
else
{
len = i;
}
return len-1;
}
}
return -1;
}
/* Returns parent path of ASCII encoded path */
char* GetParentPath(char* pathName, char* dirDelimiter, int includeDelimiter)
{
char* substring;
int pos;
pos = GetLastIndexOfParentPath(pathName, dirDelimiter, includeDelimiter) + 1;
if (pos >= 0)
{
substring = (char*) malloc(pos+1);
strncpy(substring, pathName, pos);
substring[pos] = '\0';
return substring;
}
return NULL;
}
/* Returns filename for ascii-encoded path */
char* GetFileName(char* pathName, char* dirDelimiter, int returnExtension)
{
int pos = GetLastIndexOfParentPath(pathName, dirDelimiter, 1);
int pLen = (int) strlen(pathName);
int len = pLen - pos;
int dotPos;
char* name = NULL;
int i,j;
int nlen;
if (returnExtension == 0)
{
dotPos = LastIndexOf(pathName, ".");
if ((dotPos >= 0) && (dotPos >= pos))
{
len = len - (pLen-dotPos);
}
}
name = (char*)malloc(len+1);
j=pos+1;
nlen = len - 1;
for (i=0; i < len; i++)
{
name[i] = pathName[j];
j++;
}
name[nlen] = '\0';
if (EndsWith(name, dirDelimiter, 0))
{
name[nlen-(int) strlen(dirDelimiter)] = '\0';
}
return name;
}
void ProcessDir(char* dir, int processWhen, int recurseWhen, void (*callForEachFile)(char*, void*), void* arg)
{
char path[MAX_PATH_LENGTH];
char filename[MAX_PATH_LENGTH];
void* dirObj;
int ewDD;
struct FNTD* fntd = (struct FNTD*) arg;
int nextFile = 0;
uint64_t fileSize = 0;
if (callForEachFile == NULL) return;
dirObj = PCGetDirFirstFile(dir,filename,MAX_PATH_LENGTH,&fileSize);
if (dirObj == NULL)
{
fprintf(stderr, "ProcessDir: can't open %s\n", dir);
return;
}
ewDD = EndsWith(dir, DIRDELIMITER, 0);
do
{
if (ProceedWithDirEntry(dir, filename, MAX_PATH_LENGTH) != 0)
{
/* path is acceptable length */
if (ewDD != 0)
{
sprintf(path, "%s%s", dir, filename);
}
else
{
sprintf(path, "%s%s%s", dir, DIRDELIMITER, filename);
}
fntd->FileSize = fileSize;
(callForEachFile)(path, fntd);
}
nextFile = PCGetDirNextFile(dirObj,dir,filename,MAX_PATH_LENGTH, &fileSize);
}
while (nextFile != 0);
PCCloseDir(dirObj);
}
/* END SECTION - Stuff specific to FileSystem stuff. */
/************************************************************************************/
/************************************************************************************/
/* START SECTION - Virtual Directory stuff*/
struct RangeRequest
{
uint64_t StartIndex;
uint64_t BytesLeft;
uint64_t MultiRange;
};
struct WebRequest
{
void* UpnpToken;
char* UnescapedDirectiveObj;
int UnescapedDirectiveObjLen;
char *ansiPath;
char *fullPath;
char* Root;
int RootLen;
char* DirDelimiter;
int DirDelimLen;
char* VirtualDir;
int VirDirLen;
FILE *f;
char *buffer;
uint64_t totalBytes;
uint64_t sentBytes;
int tsi;
struct packetheader *p;
void *Range;
char *ct;
uint64_t cl;
};
char MungeHexDigit(char* one_hexdigit)
{
char r = -1;
char c = *one_hexdigit;
if (c >= '0' && c <= '9')
{
r = c - '0';
}
else if (c >= 'A' && c <= 'F')
{
r = c - 'A' + 10;
}
else if (c >= 'a' && c <= 'F')
{
r = c - 'a' + 10;
}
return r;
}
char GetCharFromHex(char* two_hexdigits)
{
char c1 = MungeHexDigit(two_hexdigits);
char c2 = MungeHexDigit(two_hexdigits+1);
char result = 0;
if (c1 != -1 && c2 != -1)
{
result = (c1 << 4) + c2;
}
return result;
}
#define SENDSIZE 32768
char *MMS_STRING_ROOT = "Root";
char *MMS_STRING_UNKNOWN = "Unknown";
char *MMS_STRING_RESULT = "Result";
void HandleDisconnect(struct ILibWebServer_Session *session)
{
struct WebRequest *wr;
if(session->User2!=NULL)
{
wr = (struct WebRequest*)session->User2;
memset(&(MmsMediaTransferStats[wr->tsi]),0,sizeof(struct MMSMEDIATRANSFERSTAT));
if (MmsOnTransfersChanged != NULL)
{
MmsOnTransfersChanged(wr->tsi);
}
free(wr->ansiPath);
free(wr->fullPath);
free(wr->buffer);
free(wr->UnescapedDirectiveObj);
ILibDestructPacket(wr->p);
FREE(wr);
session->User2 = NULL;
}
}
void HandleSendOK(struct ILibWebServer_Session *session)
{
int z,numRead;
struct WebRequest *wr = (struct WebRequest*)session->User2;
struct RangeRequest *rr = NULL;
char *buf;
if(wr->f!=NULL)
{
if(wr->Range!=NULL)
{
rr = (struct RangeRequest*)ILibQueue_PeekQueue(wr->Range);
if(rr!=NULL)
{
PCFileSeek(wr->f,(long)rr->StartIndex,SEEK_SET);
}
}
do
{
z=1;
numRead = (int)PCFileRead(wr->buffer, 1, SENDSIZE, wr->f);
if(rr!=NULL && numRead>0 && numRead>rr->BytesLeft)
{
numRead = rr->BytesLeft;
}
if(numRead>0 && (rr==NULL||((rr!=NULL)&&( rr->BytesLeft>0))))
{
wr->sentBytes+=numRead;
if(rr!=NULL) {rr->BytesLeft-=numRead;}
MmsMediaTransferStats[wr->tsi].position = wr->sentBytes;
if (MmsOnTransfersChanged != NULL)
{
MmsOnTransfersChanged(wr->tsi);
}
z = ILibWebServer_StreamBody(session,wr->buffer,numRead,1,0);
}
else
{
memset(&(MmsMediaTransferStats[wr->tsi]),0,sizeof(struct MMSMEDIATRANSFERSTAT));
if (MmsOnTransfersChanged != NULL)
{
MmsOnTransfersChanged(wr->tsi);
}
if(rr!=NULL)
{
rr = ILibQueue_DeQueue(wr->Range);
FREE(rr);
rr = ILibQueue_PeekQueue(wr->Range);
if(rr==NULL)
{
ILibQueue_Destroy(wr->Range);
wr->Range = NULL;
}
else
{
z=0;
PCFileSeek(wr->f,(long)rr->StartIndex,SEEK_SET);
if(rr->MultiRange!=0)
{
buf = (char*)malloc(1024);
sprintf(buf,"%s\r\nContent-Type: %s\r\nContent-Range: bytes %" PRIu64 "-%" PRIu64 "/%" PRIu64 "\r\n\r\n",
MULTIPART_RANGE_DELIMITER,wr->ct,rr->StartIndex,rr->BytesLeft,wr->cl);
ILibWebServer_StreamBody(session,buf,(int)strlen(buf),0,0);
}
continue;
}
}
// Done Reading
session->OnSendOK = NULL;
session->User2 = NULL;
ILibWebServer_StreamBody(session,wr->buffer,0,1,1);
PCFileClose(wr->f);
wr->f = NULL;
free(wr->ansiPath);
free(wr->fullPath);
ILibDestructPacket(wr->p);
free(wr->buffer);
free(wr->UnescapedDirectiveObj);
free(wr);
}
}while(z==0);
}
}
void* HandleWebRequest(void* webRequest)
{
struct WebRequest* wr = (struct WebRequest*) webRequest;
int ewSlash;
char* lastChar;
char* dj;
char* di;
int copied, slashCount, si;
int fpBufLen;
char *fp, *ud;
int k;
char* ext;
char* ct;
uint64_t cl = 0;
char *buf;
int bufLen;
int dirEntryType = 0;
void* f;
uint64_t totalSent;
int sendStatus;
uint64_t numRead;
int fpLen,fpSize;
int transferStatIndex = -1;
struct ILibWebServer_Session *session = (struct ILibWebServer_Session*)wr->UpnpToken;
int z;
struct packetheader_field_node *phf;
struct parser_result *pr,*pr2,*pr3;
struct parser_result_field *prf;
struct RangeRequest *rr;
session->OnDisconnect = &HandleDisconnect;
wr->buffer = NULL;
MmsCurrentTransfersCount++;
if (MmsOnStatsChanged != NULL) MmsOnStatsChanged();
/* remove trailing slash from directive, if present */
#ifdef _DEBUG
printf("\r\nDirective1='%s'", wr->p->DirectiveObj);
#endif
ewSlash = EndsWith(wr->p->DirectiveObj, "/", 0);
if (ewSlash != 0)
{
wr->p->DirectiveObj[wr->p->DirectiveObjLength-1] = '\0';
wr->p->DirectiveObjLength = wr->p->DirectiveObjLength - 1;
}
#ifdef _DEBUG
printf("\r\nDirective2='%s'", wr->p->DirectiveObj);
#endif
/* convert from escaped HTTP directive to unescaped directive */
wr->UnescapedDirectiveObj = (char*) malloc (wr->p->DirectiveObjLength+1);
wr->UnescapedDirectiveObjLen = wr->p->DirectiveObjLength;
lastChar = wr->p->DirectiveObj + wr->p->DirectiveObjLength;
dj = wr->p->DirectiveObj;
di = wr->UnescapedDirectiveObj;
while (dj < lastChar)
{
copied = 0;
if (*dj == '%')
{
char r = GetCharFromHex(dj+1);
if (r != 0)
{
*di = r;
dj = dj + 2;
copied = 1;
}
}
if (copied == 0)
{
*di = *dj;
}
dj = dj + 1;
di = di + 1;
}
*di = '\0';
wr->UnescapedDirectiveObjLen = (int) (di - wr->UnescapedDirectiveObj);
printf("\r\nUnescapedDirective='%s' %d=%d\r\n", wr->UnescapedDirectiveObj, wr->UnescapedDirectiveObjLen, (int) strlen(wr->UnescapedDirectiveObj));
/* determine the full local path where the directive should map to */
slashCount = 0;
for (si=0; si <wr->UnescapedDirectiveObjLen; si++)
{
if (wr->UnescapedDirectiveObj[si] == '/')
{
slashCount = slashCount + 1;
}
}
fpBufLen = wr->RootLen +wr->UnescapedDirectiveObjLen + (slashCount*wr->DirDelimLen) + 1;
wr->fullPath = (char*) malloc (fpBufLen);
sprintf(wr->fullPath, "%s", wr->Root);
fp = wr->fullPath + wr->RootLen;
ud = wr->UnescapedDirectiveObj + wr->VirDirLen + 2;
while (*ud != '\0')
{
if (*ud == '/')
{
for (k=0; k < wr->DirDelimLen; k++)
{
*fp = wr->DirDelimiter[k];
}
fp = fp + k;
}
else
{
*fp = *ud;
fp = fp + 1;
}
ud = ud + 1;
}
*fp = '\0';
fpLen = (int) strlen(wr->fullPath);
printf("Requesting='%s' strlen='%d'\r\n", wr->fullPath, fpLen);
fpSize = fpLen+1;
wr->ansiPath = (char*) malloc(fpSize);
/* TODO: Simply copy wr->fullPath to wr->ansiPath if PortingFunctions
* has been modified to support unicode file paths.
*/
Utf8ToAnsi(wr->ansiPath, wr->fullPath, fpSize);
/* determine if the path is a file or a directory, or nonexistent */
dirEntryType = PCGetFileDirType(wr->fullPath);
if (dirEntryType > 0)
{
if (dirEntryType == 1)
{
/* is a file */
printf("\r\nFound='%s' strlen='%d'\r\n", wr->fullPath, (int) strlen(wr->ansiPath));
/* otherwise, just send the file */
ext = (char*) GetFileExtension(wr->ansiPath, 0);
ct = (char*) FileExtensionToMimeType(ext, 0);
if (*ct == '\0') { ct = "application/octet-stream"; }
f = PCFileOpen(wr->ansiPath, "rb");
if (f != NULL)
{
if (transferStatIndex != -1)
{
#ifdef _WIN32_WCE
PCFileSeek(f,0,SEEK_END);
MmsMediaTransferStats[transferStatIndex].length = PCFileTell(f);
PCFileSeek(f,0,SEEK_SET);
#endif
#ifdef WIN32
PCFileSeek(f,0,SEEK_END);
MmsMediaTransferStats[transferStatIndex].length = PCFileTell(f);
PCFileSeek(f,0,SEEK_SET);
#endif
}
}
totalSent =0;
sendStatus = 0;
if (f != NULL)
{
for (k=0;k<20;k++)
{
if (MmsMediaTransferStats[k].filename == NULL)
{
transferStatIndex = k;
MmsMediaTransferStats[transferStatIndex].filename = wr->fullPath;
MmsMediaTransferStats[transferStatIndex].download = 1;
MmsMediaTransferStats[transferStatIndex].length = 0;
MmsMediaTransferStats[transferStatIndex].position = 0;
if (MmsOnTransfersChanged != NULL) MmsOnTransfersChanged(transferStatIndex);
break;
}
}
cl = PCGetFileSize(wr->fullPath);
buf = (char*)MALLOC(2048);
wr->tsi = transferStatIndex;
wr->totalBytes = cl;
wr->sentBytes=0;
wr->f = f;
session->OnSendOK = &HandleSendOK;
session->User2 = wr;
// Check If Range Request
phf = wr->p->FirstField;
while(phf!=NULL)
{
if(phf->FieldLength==5 && strncasecmp(phf->Field,"RANGE",5)==0)
{
wr->Range = ILibQueue_Create();
pr = ILibParseString(phf->FieldData,0,phf->FieldDataLength,"=",1);
pr2 = ILibParseString(pr->LastResult->data,0,pr->LastResult->datalength,",",1);
prf = pr2->FirstResult;
while(prf!=NULL)
{
rr = (struct RangeRequest*)malloc(sizeof(struct RangeRequest));
rr->MultiRange=(pr2->NumResults==1?0:1);
pr3 = ILibParseString(prf->data,0,prf->datalength,"-",1);
if(pr3->FirstResult->datalength==0)
{
rr->StartIndex = -1;
}
else
{
pr3->FirstResult->data[pr3->FirstResult->datalength] = 0;
rr->StartIndex = atoi(pr3->FirstResult->data);
}
if(pr3->LastResult->datalength==0)
{
rr->BytesLeft = cl-rr->StartIndex;
}
else
{
pr3->LastResult->data[pr3->LastResult->datalength] = 0;
if(rr->StartIndex==-1)
{
rr->BytesLeft = atoi(pr3->LastResult->data);
if(rr->BytesLeft>=cl)
{
rr->BytesLeft = cl;
rr->StartIndex = 0;
}
else
{
rr->StartIndex = cl-rr->BytesLeft;
}
}
else
{
rr->BytesLeft = atoi(pr3->LastResult->data) - rr->StartIndex;
if(rr->BytesLeft>(cl-rr->StartIndex))
{
rr->BytesLeft = cl-rr->StartIndex;
}
}
}
ILibQueue_EnQueue(wr->Range,rr);
ILibDestructParserResults(pr3);
prf = prf->NextResult;
}
ILibDestructParserResults(pr2);
ILibDestructParserResults(pr);
break;
}
phf=phf->NextField;
}
rr=NULL;
if(wr->Range!=NULL)
{
rr = (struct RangeRequest*)ILibQueue_PeekQueue(wr->Range);
if(rr->MultiRange==0)
{
// Single Range Request
bufLen = sprintf(buf,"\r\nServer: Next Dimension Innovations/TV-Now %s\r\nContent-Range: bytes %" PRIu64 "-%" PRIu64 "/%" PRIu64 "\r\nContent-Type: %s",
TV_NOW_VERSION, rr->StartIndex,rr->BytesLeft,cl,ct);
}
else
{
// MultiPart Range Request
wr->ct = ct;
wr->cl = cl;
bufLen = sprintf(buf, "\r\nServer: Next Dimension Innovations/TV-Now %s\r\nContent-Type: multipart/byteranges; boundary=%s",
TV_NOW_VERSION, MULTIPART_RANGE_DELIMITER);
}
}
else
{
rr=NULL;
bufLen = sprintf(buf, "\r\nServer: Next Dimension Innovations/TV-Now %s\r\nAccept-Range: bytes\r\nContent-Type: %s", TV_NOW_VERSION, ct);
}
if(wr->p->DirectiveLength==4 && strncasecmp(wr->p->Directive,"HEAD",4)==0)
{
PCFileClose(wr->f);
wr->f = NULL;
if(wr->Range!=NULL)
{
ILibWebServer_Send_Raw(session,"HTTP/1.1 206 Partial Content",28,1,0);
}
else
{
ILibWebServer_Send_Raw(session,"HTTP/1.1 200 OK",15,1,0);
}
ILibWebServer_Send_Raw(session,buf,(int)strlen(buf),0,0);
ILibWebServer_Send_Raw(session,"\r\n\r\n",4,1,1);
return(NULL);
}
if(wr->Range!=NULL)
{
ILibWebServer_StreamHeader_Raw(wr->UpnpToken,206,"Partial Content",buf,0);
if(rr->MultiRange!=0)
{
buf = (char*)malloc(1024);
bufLen = sprintf(buf,"%s\r\nContent-Type: %s\r\nContent-Range: bytes %" PRIu64 "-%" PRIu64 "/%" PRIu64 "\r\n\r\n",
MULTIPART_RANGE_DELIMITER,wr->ct,rr->StartIndex,rr->BytesLeft,wr->cl);
ILibWebServer_StreamBody(session,buf,(int)strlen(buf),0,0);
}
}
else
{
ILibWebServer_StreamHeader_Raw(wr->UpnpToken,200,"OK",buf,0);
}
wr->buffer = (char*)MALLOC(SENDSIZE);
if(rr!=NULL)
{
PCFileSeek(wr->f,(long)rr->StartIndex,SEEK_SET);
}
do
{
z=1;
numRead = (int)PCFileRead(wr->buffer, 1, SENDSIZE, wr->f);
if(rr!=NULL && numRead>0 && numRead>rr->BytesLeft)
{
numRead = rr->BytesLeft;
}
if(numRead>0 && (rr==NULL||((rr!=NULL)&&( rr->BytesLeft>0))))
{
wr->sentBytes+=numRead;
if(rr!=NULL) {rr->BytesLeft-=numRead;}
MmsMediaTransferStats[transferStatIndex].position = wr->sentBytes;
if (MmsOnTransfersChanged != NULL)
{
MmsOnTransfersChanged(transferStatIndex);
}
z = ILibWebServer_StreamBody(session,wr->buffer,numRead,1,0);
}
else
{
// Done Reading
if(rr!=NULL)
{
rr = ILibQueue_DeQueue(wr->Range);
FREE(rr);
rr = ILibQueue_PeekQueue(wr->Range);
if(rr==NULL)
{
ILibQueue_Destroy(wr->Range);
wr->Range = NULL;
}
else
{
z=0;
PCFileSeek(wr->f,(long)rr->StartIndex,SEEK_SET);
if(rr->MultiRange!=0)
{
buf = (char*)malloc(1024);
bufLen = sprintf(buf,"%s\r\nContent-Type: %s\r\nContent-Range: bytes %" PRIu64 "-%" PRIu64 "/%" PRIu64 "\r\n\r\n",
MULTIPART_RANGE_DELIMITER,wr->ct,rr->StartIndex,rr->BytesLeft,wr->cl);
ILibWebServer_StreamBody(session,buf,(int)strlen(buf),0,0);
}
continue;
}
}
memset(&(MmsMediaTransferStats[wr->tsi]),0,sizeof(struct MMSMEDIATRANSFERSTAT));
if (MmsOnTransfersChanged != NULL)
{
MmsOnTransfersChanged(wr->tsi);
}
session->OnSendOK = NULL;
session->User2 = NULL;
ILibWebServer_StreamBody(session,wr->buffer,0,1,1);
f = wr->f;
wr->f = NULL;
PCFileClose(f);
free(wr->ansiPath);
free(wr->fullPath);
free(wr->buffer);
free(wr->UnescapedDirectiveObj);
ILibDestructPacket(wr->p);
free(wr);
wr = NULL;
}
}while(z==0);
}
else
{
ILibWebServer_Send_Raw(session,"HTTP/1.1 404 File Not Found or File is Locked\r\nContent-Length: 0\r\n\r\n",66,1,1);
}
}
else
{
ILibWebServer_Send_Raw(session,"HTTP/1.1 404 File Not Found or File is Locked\r\nContent-Length: 0\r\n\r\n",66,1,1);
}
}
else
{
ILibWebServer_Send_Raw(session,"HTTP/1.1 404 File Not Found or File is Locked\r\nContent-Length: 0\r\n\r\n",66,1,1);
}
if (wr != NULL)
{
/* if we don't actually transfer stuff, we still need to deallocate some memory */
free(wr->ansiPath);
free(wr->fullPath);
free(wr->UnescapedDirectiveObj);
ILibDestructPacket(wr->p);
free(wr);
wr = NULL;
}
return NULL;
}
/* END SECTION - Virtual Directory stuff */
/************************************************************************************/
/************************************************************************************/
/* START SECTION - Stuff specific to CDS */
/* BrowseFlags */
#define BROWSEMETADATA "BrowseMetadata"
#define BROWSEDIRECTCHILDREN "BrowseDirectChildren"
/* DIDL formating */
#define DIDL_HEADER "<DIDL-Lite xmlns=\"urn:schemas-upnp-org:metadata-1-0/DIDL-Lite\" xmlns:dc=\"http://purl.org/dc/elements/1.1/\" xmlns:upnp=\"urn:schemas-upnp-org:metadata-1-0/upnp\">"
#define DIDL_FOOTER "\r\n</DIDL-Lite>\r\n"