forked from b-rad-NDi/tv-now
-
Notifications
You must be signed in to change notification settings - Fork 1
/
UpnpMicroStack.c
2191 lines (2025 loc) · 79.9 KB
/
UpnpMicroStack.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 ILIBCRITICALEXIT(i) do { printf("%s() Line %d BAD!\n", __func__, 3651); exit(254); } while(0);
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/time.h>
#include <netdb.h>
#include <string.h>
#include <sys/ioctl.h>
#include <net/if.h>
#include <sys/utsname.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <semaphore.h>
#include <time.h>
#include "ILibParsers.h"
#include "UpnpMicroStack.h"
#include "ILibWebServer.h"
#include "ILibWebClient.h"
#include "ILibAsyncSocket.h"
#include "PortingFunctions.h"
#include "version.h"
#define UPNP_HTTP_MAXSOCKETS 64
#define MAX_UPNP_SUBSCRIBERS 100
#define UPNP_PORT 1900
#define UPNP_GROUP "239.255.255.250"
#define UpnpMIN(a,b) (((a)<(b))?(a):(b))
#define LVL3DEBUG(x)
struct UpnpDataObject;
struct SubscriberInfo
{
char* SID;
int SIDLength;
int SEQ;
int Address;
unsigned short Port;
char* Path;
int PathLength;
int RefCount;
int Disposing;
struct timeval RenewByTime;
struct SubscriberInfo *Next;
struct SubscriberInfo *Previous;
};
struct SubscriberContainer
{
struct SubscriberInfo* subscriber;
int Disposing;
};
struct UpnpDataObject
{
void (*PreSelect)(void* object,fd_set *readset, fd_set *writeset, fd_set *errorset, int* blocktime);
void (*PostSelect)(void* object,int slct, fd_set *readset, fd_set *writeset, fd_set *errorset);
void (*Destroy)(void* object);
void *EventClient;
void *Chain;
int UpdateFlag;
/* Network Poll */
unsigned int NetworkPollTime;
int ForceExit;
char *UUID;
char *UDN;
char *Serial;
void *WebServerTimer;
void *HTTPServer;
char *DeviceDescription;
int DeviceDescriptionLength;
int InitialNotify;
char* ConnectionManager_SourceProtocolInfo;
char* ConnectionManager_SinkProtocolInfo;
char* ConnectionManager_CurrentConnectionIDs;
char* ContentDirectory_SystemUpdateID;
struct sockaddr_in addr;
int addrlen;
int MSEARCH_sock;
struct ip_mreq mreq;
char message[4096];
int *AddressList;
int AddressListLength;
int _NumEmbeddedDevices;
int WebSocketPortNumber;
int *NOTIFY_SEND_socks;
int NOTIFY_RECEIVE_sock;
int SID;
struct timeval CurrentTime;
int NotifyCycleTime;
struct timeval NotifyTime;
sem_t EventLock;
struct SubscriberInfo *HeadSubscriberPtr_ConnectionManager;
int NumberOfSubscribers_ConnectionManager;
struct SubscriberInfo *HeadSubscriberPtr_ContentDirectory;
int NumberOfSubscribers_ContentDirectory;
};
struct MSEARCH_state
{
char *ST;
int STLength;
void *upnp;
struct sockaddr_in dest_addr;
};
#define UPNP_XML_LOCATION "./%s"
#define XML_GET_TEMPLATE "HTTP/1.1 200 OK\r\nEXT:\r\nContent-Type: text/xml; charset=\"utf-8\"\r\nCache-Control: no-cache\r\nPragma: no-cache\r\n%sServer: POSIX, UPnP/1.0, NDi TV-Now/"TV_NOW_VERSION"\r\nConnection: close\r\nAccept-Ranges: bytes\r\nDate: %s\r\nContent-Length: %d\r\n\r\n%s"
//#define XML_GET_TEMPLATE "HTTP/1.1 200 OK\r\nCONTENT-TYPE: text/xml; charset=\"utf-8\"\r\nServer: POSIX, UPnP/1.0, NDi TV-Now/"TV_NOW_VERSION"\r\nContent-Length: %d\r\n\r\n%s\r\n\r\n"
void getRFC1123(char* result)
{
char daysofweek[7][4] = { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };
char months[12][4] = { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
if (result == NULL) return;
time_t t = time(NULL);
struct tm lt = *gmtime(&t);
sprintf(result, "%s, %02d %s %d %02d:%02d:%02d GMT",
daysofweek[lt.tm_wday],
lt.tm_mday, months[lt.tm_mon], lt.tm_year + 1900,
lt.tm_hour, lt.tm_min, lt.tm_sec);
return;
}
void SendXML(struct ILibWebServer_Session *session, struct packetheader* header, char* location)
{
char file_location[128];
char *file_contents, *buffer;
char dateString[64] = { 0 };
sprintf(file_location, UPNP_XML_LOCATION, location);
int len = file_get_contents(file_location, &file_contents);
if (len >= 0) {
getRFC1123(&dateString[0]);
char* langHeader = ILibGetHeaderLine(header, "ACCEPT-LANGUAGE", 15);
if (langHeader == NULL)
{
buffer = (char*)malloc(strlen(XML_GET_TEMPLATE) + len + 3 + 64);
len = snprintf(buffer, strlen(XML_GET_TEMPLATE) + len + 3 + 64, XML_GET_TEMPLATE, "", dateString, len, file_contents);
}
else
{
buffer = (char*)malloc(strlen(XML_GET_TEMPLATE) + len + 3 + 23 + 64);
len = snprintf(buffer, strlen(XML_GET_TEMPLATE) + len + 3 + 23 + 64, XML_GET_TEMPLATE, "Content-Language: en\r\n", dateString, len, file_contents);
}
ILibWebServer_Send_Raw(session, buffer, len, 0, 1);
free(file_contents);
}
}
/* Pre-declarations */
void UpnpSendNotify(const struct UpnpDataObject *upnp);
void UpnpSendByeBye();
void UpnpMainInvokeSwitch();
void UpnpSendDataXmlEscaped(const void* UPnPToken, const char* Data, const int DataLength, const int Terminate);
void UpnpSendData(const void* UPnPToken, const char* Data, const int DataLength, const int Terminate);
int UpnpPeriodicNotify(struct UpnpDataObject *upnp);
void UpnpSendEvent_Body(void *upnptoken, char *body, int bodylength, struct SubscriberInfo *info);
void* UpnpGetWebServerToken(const void *MicroStackToken)
{
return(((struct UpnpDataObject*)MicroStackToken)->HTTPServer);
}
#define UpnpBuildSsdpResponsePacket(outpacket,outlenght,ipaddr,port,EmbeddedDeviceNumber,USN,USNex,ST,NTex,NotifyTime)\
{\
*outlenght = sprintf(outpacket,"HTTP/1.1 200 OK\r\nLOCATION: http://%d.%d.%d.%d:%d/\r\nEXT:\r\nSERVER: POSIX, UPnP/1.0, NDi TV-Now/"TV_NOW_VERSION"\r\nUSN: uuid:%s%s\r\nCACHE-CONTROL: max-age=%d\r\nST: %s%s\r\n\r\n" ,(ipaddr&0xFF),((ipaddr>>8)&0xFF),((ipaddr>>16)&0xFF),((ipaddr>>24)&0xFF),port,USN,USNex,NotifyTime,ST,NTex);\
}
#define UpnpBuildSsdpNotifyPacket(outpacket,outlenght,ipaddr,port,EmbeddedDeviceNumber,USN,USNex,NT,NTex,NotifyTime)\
{\
*outlenght = sprintf(outpacket,"NOTIFY * HTTP/1.1\r\nLOCATION: http://%d.%d.%d.%d:%d/\r\nHOST: 239.255.255.250:1900\r\nSERVER: POSIX, UPnP/1.0, NDi TV-Now/"TV_NOW_VERSION"\r\nNTS: ssdp:alive\r\nUSN: uuid:%s%s\r\nCACHE-CONTROL: max-age=%d\r\nNT: %s%s\r\n\r\n",(ipaddr&0xFF),((ipaddr>>8)&0xFF),((ipaddr>>16)&0xFF),((ipaddr>>24)&0xFF),port,USN,USNex,NotifyTime,NT,NTex);\
}
void UpnpAsyncResponse_START(const void* UPnPToken, const char* actionName, const char* serviceUrnWithVersion)
{
char* RESPONSE_HEADER = "\r\nEXT:\r\nCONTENT-TYPE: text/xml\r\nSERVER: POSIX, UPnP/1.0, NDi TV-Now/"TV_NOW_VERSION;
char* RESPONSE_BODY = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n<s:Envelope s:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\" xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\">\r\n<s:Body>\r\n<u:%sResponse xmlns:u=\"%s\">";
struct ILibWebServer_Session *session = (struct ILibWebServer_Session*)UPnPToken;
int headSize = (int)strlen(RESPONSE_BODY) + (int)strlen(actionName) + (int)strlen(serviceUrnWithVersion) + 1;
char* head = (char*) malloc (headSize);
int headLength = sprintf(head, RESPONSE_BODY, actionName, serviceUrnWithVersion);
ILibWebServer_StreamHeader_Raw(session,200,"OK",RESPONSE_HEADER,1);
ILibWebServer_StreamBody(session,head,headLength,0,0);
}
void UpnpAsyncResponse_DONE(const void* UPnPToken, const char* actionName)
{
char* RESPONSE_FOOTER = "</u:%sResponse>\r\n </s:Body>\r\n</s:Envelope>";
int footSize = (int)strlen(RESPONSE_FOOTER) + (int)strlen(actionName);
char* footer = (char*) malloc(footSize);
struct ILibWebServer_Session *session = (struct ILibWebServer_Session*)UPnPToken;
int footLength = sprintf(footer, RESPONSE_FOOTER, actionName);
ILibWebServer_StreamBody(session,footer,footLength,0,1);
}
void UpnpAsyncResponse_OUT(const void* UPnPToken, const char* outArgName, const char* bytes, const int byteLength, const int startArg, const int endArg)
{
struct ILibWebServer_Session *session = (struct ILibWebServer_Session*)UPnPToken;
if (startArg != 0)
{
ILibWebServer_StreamBody(session,"<",1,1,0);
ILibWebServer_StreamBody(session,(char*)outArgName,(int)strlen(outArgName),1,0);
ILibWebServer_StreamBody(session,">",1,1,0);
}
if(byteLength>0)
{
ILibWebServer_StreamBody(session,(char*)bytes,byteLength,1,0);
}
if (endArg != 0)
{
ILibWebServer_StreamBody(session,"</",2,1,0);
ILibWebServer_StreamBody(session,(char*)outArgName,(int)strlen(outArgName),1,0);
ILibWebServer_StreamBody(session,">\r\n",3,1,0);
}
}
void UpnpIPAddressListChanged(void *MicroStackToken)
{
((struct UpnpDataObject*)MicroStackToken)->UpdateFlag = 1;
ILibForceUnBlockChain(((struct UpnpDataObject*)MicroStackToken)->Chain);
}
void UpnpInit(struct UpnpDataObject *state,const int NotifyCycleSeconds,const unsigned short PortNumber)
{
int ra = 1;
int i;
struct sockaddr_in addr;
struct ip_mreq mreq;
unsigned char TTL = 4;
/* Complete State Reset */
memset(state,0,sizeof(struct UpnpDataObject));
/* Setup Notification Timer */
state->NotifyCycleTime = NotifyCycleSeconds;
gettimeofday(&(state->CurrentTime),NULL);
(state->NotifyTime).tv_sec = (state->CurrentTime).tv_sec + (state->NotifyCycleTime/2);
memset((char *)&(state->addr), 0, sizeof(state->addr));
state->addr.sin_family = AF_INET;
state->addr.sin_addr.s_addr = htonl(INADDR_ANY);
state->addr.sin_port = (unsigned short)htons(UPNP_PORT);
state->addrlen = sizeof(state->addr);
/* Set up socket */
state->AddressListLength = ILibGetLocalIPAddressList(&(state->AddressList));
state->NOTIFY_SEND_socks = (int*)MALLOC(sizeof(int)*(state->AddressListLength));
state->NOTIFY_RECEIVE_sock = socket(AF_INET, SOCK_DGRAM, 0);
memset((char *)&(addr), 0, sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = htonl(INADDR_ANY);
addr.sin_port = (unsigned short)htons(UPNP_PORT);
if (setsockopt(state->NOTIFY_RECEIVE_sock, SOL_SOCKET, SO_REUSEADDR,(char*)&ra, sizeof(ra)) < 0)
{
printf("Setting SockOpt SO_REUSEADDR failed\r\n");
exit(1);
}
if (bind(state->NOTIFY_RECEIVE_sock, (struct sockaddr *) &(addr), sizeof(addr)) < 0)
{
printf("Could not bind to UPnP Listen Port\r\n");
exit(1);
}
for(i=0;i<state->AddressListLength;++i)
{
state->NOTIFY_SEND_socks[i] = socket(AF_INET, SOCK_DGRAM, 0);
memset((char *)&(addr), 0, sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = state->AddressList[i];
addr.sin_port = (unsigned short)htons(UPNP_PORT);
if (setsockopt(state->NOTIFY_SEND_socks[i], SOL_SOCKET, SO_REUSEADDR,(char*)&ra, sizeof(ra)) == 0)
{
if (setsockopt(state->NOTIFY_SEND_socks[i], IPPROTO_IP, IP_MULTICAST_TTL,(char*)&TTL, sizeof(TTL)) < 0)
{
/* Ignore this case */
}
if (bind(state->NOTIFY_SEND_socks[i], (struct sockaddr *) &(addr), sizeof(addr)) == 0)
{
mreq.imr_multiaddr.s_addr = inet_addr(UPNP_GROUP);
mreq.imr_interface.s_addr = state->AddressList[i];
if (setsockopt(state->NOTIFY_RECEIVE_sock, IPPROTO_IP, IP_ADD_MEMBERSHIP,(char*)&mreq, sizeof(mreq)) < 0)
{
/* Does not matter */
}
}
}
}
}
void UpnpPostMX_Destroy(void *object)
{
struct MSEARCH_state *mss = (struct MSEARCH_state*)object;
FREE(mss->ST);
FREE(mss);
}
void UpnpPostMX_MSEARCH(void *object)
{
struct MSEARCH_state *mss = (struct MSEARCH_state*)object;
char *b = (char*)MALLOC(sizeof(char)*5000);
int packetlength;
struct sockaddr_in response_addr;
int response_addrlen;
int *response_socket;
int cnt;
int i;
struct sockaddr_in dest_addr = mss->dest_addr;
char *ST = mss->ST;
int STLength = mss->STLength;
struct UpnpDataObject *upnp = (struct UpnpDataObject*)mss->upnp;
response_socket = (int*)MALLOC(upnp->AddressListLength*sizeof(int));
for(i=0;i<upnp->AddressListLength;++i)
{
response_socket[i] = socket(AF_INET, SOCK_DGRAM, 0);
if (response_socket[i]< 0)
{
printf("response socket");
exit(1);
}
memset((char *)&(response_addr), 0, sizeof(response_addr));
response_addr.sin_family = AF_INET;
response_addr.sin_addr.s_addr = upnp->AddressList[i];
response_addr.sin_port = (unsigned short)htons(0);
response_addrlen = sizeof(response_addr);
if (bind(response_socket[i], (struct sockaddr *) &(response_addr), sizeof(response_addr)) < 0)
{
/* Ignore if this happens */
}
}
if(STLength==15 && memcmp(ST,"upnp:rootdevice",15)==0)
{
for(i=0;i<upnp->AddressListLength;++i)
{
UpnpBuildSsdpResponsePacket(b,&packetlength,upnp->AddressList[i],(unsigned short)upnp->WebSocketPortNumber,0,upnp->UDN,"::upnp:rootdevice","upnp:rootdevice","",upnp->NotifyCycleTime);
cnt = sendto(response_socket[i], b, packetlength, 0,(struct sockaddr *) &dest_addr, sizeof(dest_addr));
}
}
else if(STLength==8 && memcmp(ST,"ssdp:all",8)==0)
{
for(i=0;i<upnp->AddressListLength;++i)
{
UpnpBuildSsdpResponsePacket(b,&packetlength,upnp->AddressList[i],(unsigned short)upnp->WebSocketPortNumber,0,upnp->UDN,"::upnp:rootdevice","upnp:rootdevice","",upnp->NotifyCycleTime);
cnt = sendto(response_socket[i], b, packetlength, 0,
(struct sockaddr *) &dest_addr, sizeof(dest_addr));
UpnpBuildSsdpResponsePacket(b,&packetlength,upnp->AddressList[i],(unsigned short)upnp->WebSocketPortNumber,0,upnp->UDN,"",upnp->UUID,"",upnp->NotifyCycleTime);
cnt = sendto(response_socket[i], b, packetlength, 0,
(struct sockaddr *) &dest_addr, sizeof(dest_addr));
UpnpBuildSsdpResponsePacket(b,&packetlength,upnp->AddressList[i],(unsigned short)upnp->WebSocketPortNumber,0,upnp->UDN,"::urn:schemas-upnp-org:device:MediaServer:1","urn:schemas-upnp-org:device:MediaServer:1","",upnp->NotifyCycleTime);
cnt = sendto(response_socket[i], b, packetlength, 0,
(struct sockaddr *) &dest_addr, sizeof(dest_addr));
UpnpBuildSsdpResponsePacket(b,&packetlength,upnp->AddressList[i],(unsigned short)upnp->WebSocketPortNumber,0,upnp->UDN,"::urn:schemas-upnp-org:service:ContentDirectory:1","urn:schemas-upnp-org:service:ContentDirectory:1","",upnp->NotifyCycleTime);
cnt = sendto(response_socket[i], b, packetlength, 0,
(struct sockaddr *) &dest_addr, sizeof(dest_addr));
UpnpBuildSsdpResponsePacket(b,&packetlength,upnp->AddressList[i],(unsigned short)upnp->WebSocketPortNumber,0,upnp->UDN,"::urn:schemas-upnp-org:service:ConnectionManager:1","urn:schemas-upnp-org:service:ConnectionManager:1","",upnp->NotifyCycleTime);
cnt = sendto(response_socket[i], b, packetlength, 0,
(struct sockaddr *) &dest_addr, sizeof(dest_addr));
}
}
if(STLength==(int)strlen(upnp->UUID) && memcmp(ST,upnp->UUID,(int)strlen(upnp->UUID))==0)
{
for(i=0;i<upnp->AddressListLength;++i)
{
UpnpBuildSsdpResponsePacket(b,&packetlength,upnp->AddressList[i],(unsigned short)upnp->WebSocketPortNumber,0,upnp->UDN,"",upnp->UUID,"",upnp->NotifyCycleTime);
cnt = sendto(response_socket[i], b, packetlength, 0,
(struct sockaddr *) &dest_addr, sizeof(dest_addr));
}
}
if(STLength>=41 && memcmp(ST,"urn:schemas-upnp-org:device:MediaServer:1",41)==0)
{
for(i=0;i<upnp->AddressListLength;++i)
{
UpnpBuildSsdpResponsePacket(b,&packetlength,upnp->AddressList[i],(unsigned short)upnp->WebSocketPortNumber,0,upnp->UDN,"::urn:schemas-upnp-org:device:MediaServer:1","urn:schemas-upnp-org:device:MediaServer:1","",upnp->NotifyCycleTime);
cnt = sendto(response_socket[i], b, packetlength, 0,
(struct sockaddr *) &dest_addr, sizeof(dest_addr));
}
}
if(STLength>=47 && memcmp(ST,"urn:schemas-upnp-org:service:ContentDirectory:1",47)==0)
{
for(i=0;i<upnp->AddressListLength;++i)
{
UpnpBuildSsdpResponsePacket(b,&packetlength,upnp->AddressList[i],(unsigned short)upnp->WebSocketPortNumber,0,upnp->UDN,"::urn:schemas-upnp-org:service:ContentDirectory:1","urn:schemas-upnp-org:service:ContentDirectory:1","",upnp->NotifyCycleTime);
cnt = sendto(response_socket[i], b, packetlength, 0,
(struct sockaddr *) &dest_addr, sizeof(dest_addr));
}
}
if(STLength>=48 && memcmp(ST,"urn:schemas-upnp-org:service:ConnectionManager:1",48)==0)
{
for(i=0;i<upnp->AddressListLength;++i)
{
UpnpBuildSsdpResponsePacket(b,&packetlength,upnp->AddressList[i],(unsigned short)upnp->WebSocketPortNumber,0,upnp->UDN,"::urn:schemas-upnp-org:service:ConnectionManager:1","urn:schemas-upnp-org:service:ConnectionManager:1","",upnp->NotifyCycleTime);
cnt = sendto(response_socket[i], b, packetlength, 0,
(struct sockaddr *) &dest_addr, sizeof(dest_addr));
}
}
for(i=0;i<upnp->AddressListLength;++i)
{
close(response_socket[i]);
}
FREE(response_socket);
FREE(mss->ST);
FREE(mss);
FREE(b);
}
void UpnpProcessMSEARCH(struct UpnpDataObject *upnp, struct packetheader *packet)
{
char* ST = NULL;
int STLength = 0;
struct packetheader_field_node *node;
int MANOK = 0;
unsigned long MXVal;
int MXOK = 0;
int MX;
struct MSEARCH_state *mss = NULL;
if(memcmp(packet->DirectiveObj,"*",1)==0)
{
if(memcmp(packet->Version,"1.1",3)==0)
{
node = packet->FirstField;
while(node!=NULL)
{
if(strncasecmp(node->Field,"ST",2)==0)
{
ST = (char*)MALLOC(1+node->FieldDataLength);
memcpy(ST,node->FieldData,node->FieldDataLength);
ST[node->FieldDataLength] = 0;
STLength = node->FieldDataLength;
}
else if(strncasecmp(node->Field,"MAN",3)==0 && memcmp(node->FieldData,"\"ssdp:discover\"",15)==0)
{
MANOK = 1;
}
else if(strncasecmp(node->Field,"MX",2)==0 && ILibGetULong(node->FieldData,node->FieldDataLength,&MXVal)==0)
{
MXOK = 1;
MXVal = MXVal>10?10:MXVal;
}
node = node->NextField;
}
if(MANOK!=0 && MXOK!=0)
{
MX = (int)(0 + ((unsigned short)rand() % MXVal));
mss = (struct MSEARCH_state*)MALLOC(sizeof(struct MSEARCH_state));
mss->ST = ST;
mss->STLength = STLength;
mss->upnp = upnp;
memset((char *)&(mss->dest_addr), 0, sizeof(mss->dest_addr));
mss->dest_addr.sin_family = AF_INET;
mss->dest_addr.sin_addr = packet->Source->sin_addr;
mss->dest_addr.sin_port = packet->Source->sin_port;
ILibLifeTime_Add(upnp->WebServerTimer,mss,MX,&UpnpPostMX_MSEARCH,&UpnpPostMX_Destroy);
}
else
{
FREE(ST);
}
}
}
}
void UpnpDispatch_ConnectionManager_GetCurrentConnectionInfo(struct parser_result *xml, struct ILibWebServer_Session *ReaderObject)
{
struct parser_result *temp;
struct parser_result *temp2;
struct parser_result *temp3;
struct parser_result_field *field;
char *VarName;
int VarNameLength;
int i;
long TempLong;
int OK = 0;
char *p_ConnectionID = NULL;
int p_ConnectionIDLength = 0;
int _ConnectionID = 0;
field = xml->FirstResult;
if (field->data == NULL || field->datalength == 0)
{
UpnpResponse_Error(ReaderObject, 501, "Invalid XML");
return;
}
while(field!=NULL)
{
if((memcmp(field->data,"?",1)!=0) && (memcmp(field->data,"/",1)!=0))
{
temp = ILibParseString(field->data,0,field->datalength," ",1);
temp2 = ILibParseString(temp->FirstResult->data,0,temp->FirstResult->datalength,":",1);
if(temp2->NumResults==1)
{
VarName = temp2->FirstResult->data;
VarNameLength = temp2->FirstResult->datalength;
}
else
{
temp3 = ILibParseString(temp2->FirstResult->data,0,temp2->FirstResult->datalength,">",1);
if(temp3->NumResults==1)
{
VarName = temp2->FirstResult->NextResult->data;
VarNameLength = temp2->FirstResult->NextResult->datalength;
}
else
{
VarName = temp2->FirstResult->data;
VarNameLength = temp2->FirstResult->datalength;
}
ILibDestructParserResults(temp3);
}
for(i=0;i<VarNameLength;++i)
{
if( i!=0 && ((VarName[i]==' ')||(VarName[i]=='/')||(VarName[i]=='>')) )
{
VarNameLength = i;
break;
}
}
if(VarNameLength==12 && memcmp(VarName,"ConnectionID",12) == 0)
{
temp3 = ILibParseString(field->data,0,field->datalength,">",1);
if(memcmp(temp3->FirstResult->data+temp3->FirstResult->datalength-1,"/",1) != 0)
{
p_ConnectionID = temp3->LastResult->data;
p_ConnectionIDLength = temp3->LastResult->datalength;
}
OK |= 1;
ILibDestructParserResults(temp3);
}
ILibDestructParserResults(temp2);
ILibDestructParserResults(temp);
}
field = field->NextResult;
}
if (OK != 1)
{
UpnpResponse_Error(ReaderObject,402,"Incorrect Arguments");
return;
}
/* Type Checking */
OK = ILibGetLong(p_ConnectionID,p_ConnectionIDLength, &TempLong);
if(OK!=0)
{
UpnpResponse_Error(ReaderObject,402,"Argument[ConnectionID] illegal value");
return;
}
_ConnectionID = (int)TempLong;
UpnpConnectionManager_GetCurrentConnectionInfo((void*)ReaderObject,_ConnectionID);
}
#define UpnpDispatch_ConnectionManager_GetProtocolInfo(xml, session)\
{\
UpnpConnectionManager_GetProtocolInfo((void*)session);\
}
#define UpnpDispatch_ConnectionManager_GetCurrentConnectionIDs(xml, session)\
{\
UpnpConnectionManager_GetCurrentConnectionIDs((void*)session);\
}
void UpnpDispatch_ContentDirectory_Browse(struct parser_result *xml, struct ILibWebServer_Session *ReaderObject)
{
struct parser_result *temp;
struct parser_result *temp2;
struct parser_result *temp3;
struct parser_result_field *field;
char *VarName;
int VarNameLength;
int i;
unsigned long TempULong;
int OK = 0;
char *p_ObjectID = NULL;
int p_ObjectIDLength = 0;
char* _ObjectID = "";
int _ObjectIDLength;
char *p_BrowseFlag = NULL;
int p_BrowseFlagLength = 0;
char* _BrowseFlag = "";
int _BrowseFlagLength;
char *p_Filter = NULL;
int p_FilterLength = 0;
char* _Filter = "";
int _FilterLength;
char *p_StartingIndex = NULL;
int p_StartingIndexLength = 0;
unsigned int _StartingIndex = 0;
char *p_RequestedCount = NULL;
int p_RequestedCountLength = 0;
unsigned int _RequestedCount = 0;
char *p_SortCriteria = NULL;
int p_SortCriteriaLength = 0;
char* _SortCriteria = "";
int _SortCriteriaLength;
field = xml->FirstResult;
/*
if (field->data == NULL || field->datalength == 0)
{
UpnpResponse_Error(ReaderObject, 501, "Invalid XML");
return;
}
*/
while(field!=NULL)
{
if((memcmp(field->data,"?",1)!=0) && (memcmp(field->data,"/",1)!=0))
{
temp = ILibParseString(field->data,0,field->datalength," ",1);
temp2 = ILibParseString(temp->FirstResult->data,0,temp->FirstResult->datalength,":",1);
if(temp2->NumResults==1)
{
VarName = temp2->FirstResult->data;
VarNameLength = temp2->FirstResult->datalength;
}
else
{
temp3 = ILibParseString(temp2->FirstResult->data,0,temp2->FirstResult->datalength,">",1);
if(temp3->NumResults==1)
{
VarName = temp2->FirstResult->NextResult->data;
VarNameLength = temp2->FirstResult->NextResult->datalength;
}
else
{
VarName = temp2->FirstResult->data;
VarNameLength = temp2->FirstResult->datalength;
}
ILibDestructParserResults(temp3);
}
for(i=0;i<VarNameLength;++i)
{
if( i!=0 && ((VarName[i]==' ')||(VarName[i]=='/')||(VarName[i]=='>')) )
{
VarNameLength = i;
break;
}
}
if(VarNameLength==8 && memcmp(VarName,"ObjectID",8) == 0)
{
temp3 = ILibParseString(field->data,0,field->datalength,">",1);
if(memcmp(temp3->FirstResult->data+temp3->FirstResult->datalength-1,"/",1) != 0)
{
p_ObjectID = temp3->LastResult->data;
p_ObjectIDLength = temp3->LastResult->datalength;
p_ObjectID[p_ObjectIDLength] = 0;
}
else
{
p_ObjectID = temp3->LastResult->data;
p_ObjectIDLength = 0;
p_ObjectID[p_ObjectIDLength] = 0;
}
OK |= 1;
ILibDestructParserResults(temp3);
}
else if(VarNameLength==10 && memcmp(VarName,"BrowseFlag",10) == 0)
{
temp3 = ILibParseString(field->data,0,field->datalength,">",1);
if(memcmp(temp3->FirstResult->data+temp3->FirstResult->datalength-1,"/",1) != 0)
{
p_BrowseFlag = temp3->LastResult->data;
p_BrowseFlagLength = temp3->LastResult->datalength;
p_BrowseFlag[p_BrowseFlagLength] = 0;
}
else
{
p_BrowseFlag = temp3->LastResult->data;
p_BrowseFlagLength = 0;
p_BrowseFlag[p_BrowseFlagLength] = 0;
}
OK |= 2;
ILibDestructParserResults(temp3);
}
else if(VarNameLength==6 && memcmp(VarName,"Filter",6) == 0)
{
temp3 = ILibParseString(field->data,0,field->datalength,">",1);
if(memcmp(temp3->FirstResult->data+temp3->FirstResult->datalength-1,"/",1) != 0)
{
p_Filter = temp3->LastResult->data;
p_FilterLength = temp3->LastResult->datalength;
p_Filter[p_FilterLength] = 0;
}
else
{
p_Filter = temp3->LastResult->data;
p_FilterLength = 0;
p_Filter[p_FilterLength] = 0;
}
OK |= 4;
ILibDestructParserResults(temp3);
}
else if(VarNameLength==13 && memcmp(VarName,"StartingIndex",13) == 0)
{
temp3 = ILibParseString(field->data,0,field->datalength,">",1);
if(memcmp(temp3->FirstResult->data+temp3->FirstResult->datalength-1,"/",1) != 0)
{
p_StartingIndex = temp3->LastResult->data;
p_StartingIndexLength = temp3->LastResult->datalength;
}
OK |= 8;
ILibDestructParserResults(temp3);
}
else if(VarNameLength==14 && memcmp(VarName,"RequestedCount",14) == 0)
{
temp3 = ILibParseString(field->data,0,field->datalength,">",1);
if(memcmp(temp3->FirstResult->data+temp3->FirstResult->datalength-1,"/",1) != 0)
{
p_RequestedCount = temp3->LastResult->data;
p_RequestedCountLength = temp3->LastResult->datalength;
}
OK |= 16;
ILibDestructParserResults(temp3);
}
else if(VarNameLength==12 && memcmp(VarName,"SortCriteria",12) == 0)
{
temp3 = ILibParseString(field->data,0,field->datalength,">",1);
if(memcmp(temp3->FirstResult->data+temp3->FirstResult->datalength-1,"/",1) != 0)
{
p_SortCriteria = temp3->LastResult->data;
p_SortCriteriaLength = temp3->LastResult->datalength;
p_SortCriteria[p_SortCriteriaLength] = 0;
}
else
{
p_SortCriteria = temp3->LastResult->data;
p_SortCriteriaLength = 0;
p_SortCriteria[p_SortCriteriaLength] = 0;
}
OK |= 32;
ILibDestructParserResults(temp3);
}
ILibDestructParserResults(temp2);
ILibDestructParserResults(temp);
}
field = field->NextResult;
}
if (OK != 63)
{
UpnpResponse_Error(ReaderObject,402,"Incorrect Arguments");
return;
}
/* Type Checking */
_ObjectIDLength = ILibInPlaceXmlUnEscape(p_ObjectID);
_ObjectID = p_ObjectID;
_BrowseFlagLength = ILibInPlaceXmlUnEscape(p_BrowseFlag);
_BrowseFlag = p_BrowseFlag;
if(memcmp(_BrowseFlag, "BrowseMetadata\0",15) != 0
&& memcmp(_BrowseFlag, "BrowseDirectChildren\0",21) != 0
)
{
UpnpResponse_Error(ReaderObject,402,"Argument[BrowseFlag] contains a value that is not in AllowedValueList");
return;
}
_FilterLength = ILibInPlaceXmlUnEscape(p_Filter);
_Filter = p_Filter;
OK = ILibGetULong(p_StartingIndex,p_StartingIndexLength, &TempULong);
if(OK!=0)
{
UpnpResponse_Error(ReaderObject,402,"Argument[StartingIndex] illegal value");
return;
}
_StartingIndex = (unsigned int)TempULong;
OK = ILibGetULong(p_RequestedCount,p_RequestedCountLength, &TempULong);
if(OK!=0)
{
UpnpResponse_Error(ReaderObject,402,"Argument[RequestedCount] illegal value");
return;
}
_RequestedCount = (unsigned int)TempULong;
_SortCriteriaLength = ILibInPlaceXmlUnEscape(p_SortCriteria);
_SortCriteria = p_SortCriteria;
UpnpContentDirectory_Browse((void*)ReaderObject,_ObjectID,_BrowseFlag,_Filter,_StartingIndex,_RequestedCount,_SortCriteria);
}
#define UpnpDispatch_ContentDirectory_GetSortCapabilities(xml, session)\
{\
UpnpContentDirectory_GetSortCapabilities((void*)session);\
}
#define UpnpDispatch_ContentDirectory_GetSystemUpdateID(xml, session)\
{\
UpnpContentDirectory_GetSystemUpdateID((void*)session);\
}
#define UpnpDispatch_ContentDirectory_GetSearchCapabilities(xml, session)\
{\
UpnpContentDirectory_GetSearchCapabilities((void*)session);\
}
void UpnpProcessPOST(struct ILibWebServer_Session *session, struct packetheader* header, char *bodyBuffer, int offset, int bodyBufferLength)
{
struct packetheader_field_node *f = header->FirstField;
char* HOST;
char* SOAPACTION = NULL;
int SOAPACTIONLength = 0;
struct parser_result *r;
struct parser_result *xml;
xml = ILibParseString(bodyBuffer,offset,bodyBufferLength,"<",1);
while(f!=NULL)
{
if(f->FieldLength==4 && strncasecmp(f->Field,"HOST",4)==0)
{
HOST = f->FieldData;
}
else if(f->FieldLength==10 && strncasecmp(f->Field,"SOAPACTION",10)==0)
{
r = ILibParseString(f->FieldData,0,f->FieldDataLength,"#",1);
SOAPACTION = r->LastResult->data;
SOAPACTIONLength = r->LastResult->datalength-1;
ILibDestructParserResults(r);
}
f = f->NextField;
}
if(header->DirectiveObjLength==25 && memcmp((header->DirectiveObj)+1,"ContentDirectory/control",24)==0)
{
if(SOAPACTIONLength==6 && memcmp(SOAPACTION,"Browse",6)==0)
{
UpnpDispatch_ContentDirectory_Browse(xml, session);
}
else if(SOAPACTIONLength==19 && memcmp(SOAPACTION,"GetSortCapabilities",19)==0)
{
UpnpDispatch_ContentDirectory_GetSortCapabilities(xml, session);
}
else if(SOAPACTIONLength==17 && memcmp(SOAPACTION,"GetSystemUpdateID",17)==0)
{
UpnpDispatch_ContentDirectory_GetSystemUpdateID(xml, session);
}
else if(SOAPACTIONLength==21 && memcmp(SOAPACTION,"GetSearchCapabilities",21)==0)
{
UpnpDispatch_ContentDirectory_GetSearchCapabilities(xml, session);
}
}
else if(header->DirectiveObjLength==26 && memcmp((header->DirectiveObj)+1,"ConnectionManager/control",25)==0)
{
if(SOAPACTIONLength==24 && memcmp(SOAPACTION,"GetCurrentConnectionInfo",24)==0)
{
UpnpDispatch_ConnectionManager_GetCurrentConnectionInfo(xml, session);
}
else if(SOAPACTIONLength==15 && memcmp(SOAPACTION,"GetProtocolInfo",15)==0)
{
UpnpDispatch_ConnectionManager_GetProtocolInfo(xml, session);
}
else if(SOAPACTIONLength==23 && memcmp(SOAPACTION,"GetCurrentConnectionIDs",23)==0)
{
UpnpDispatch_ConnectionManager_GetCurrentConnectionIDs(xml, session);
}
}
ILibDestructParserResults(xml);
}
struct SubscriberInfo* UpnpRemoveSubscriberInfo(struct SubscriberInfo **Head, int *TotalSubscribers,char* SID, int SIDLength)
{
struct SubscriberInfo *info = *Head;
struct SubscriberInfo **ptr = Head;
if (*TotalSubscribers <=0 || *TotalSubscribers > MAX_UPNP_SUBSCRIBERS || SIDLength <= 0 || SIDLength > 64)
{
dprintf(1, "BAD DATA--ignoring\n");
return info;
}
while(info!=NULL)
{
if(info->SIDLength==SIDLength && memcmp(info->SID,SID,SIDLength)==0)
{
*ptr = info->Next;
if(info->Next!=NULL)
{
(*ptr)->Previous = info->Previous;
if((*ptr)->Previous!=NULL)
{
(*ptr)->Previous->Next = info->Next;
if((*ptr)->Previous->Next!=NULL)
{
(*ptr)->Previous->Next->Previous = (*ptr)->Previous;
}
}
}
dprintf(1, "%s( %p:%d ) Line %d\n", __func__, info, info->RefCount, __LINE__);
break;
}
ptr = &(info->Next);
info = info->Next;
}
if(info!=NULL)
{
info->Previous = NULL;
info->Next = NULL;
--(*TotalSubscribers);
}
return(info);
}
static inline void UpnpDestructSubscriberInfo(struct SubscriberInfo* info)
{
dprintf(1, "%s( %p:%d ) Line %d\n", __func__, info, info->RefCount, __LINE__);
/* TODO: this is memory leak
* Address this issue to fix random segfault due to premature destruction
*/
// return;
if (info->Path) free(info->Path);
if (info->SID) free(info->SID);
memset(info, 0, sizeof(struct SubscriberInfo));
info->RefCount = -1;
free(info);
}
#define UpnpDestructEventObject(EvObject)\
{\
FREE(EvObject->PacketBody);\
FREE(EvObject);\
}
#define UpnpDestructEventDataObject(EvData)\
{\
FREE(EvData);\
}