forked from miniupnp/miniupnp
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathminissdpd.c
1710 lines (1644 loc) · 45.7 KB
/
minissdpd.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
/* $Id: minissdpd.c,v 1.61 2021/11/04 23:27:28 nanard Exp $ */
/* vim: tabstop=4 shiftwidth=4 noexpandtab
* MiniUPnP project
* (c) 2007-2024 Thomas Bernard
* website : http://miniupnp.free.fr/ or https://miniupnp.tuxfamily.org/
* This software is subject to the conditions detailed
* in the LICENCE file provided within the distribution */
#include "config.h"
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <signal.h>
#include <errno.h>
#include <sys/time.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <unistd.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <syslog.h>
#include <ctype.h>
#include <time.h>
#include <sys/queue.h>
/* for chmod : */
#include <sys/stat.h>
/* unix sockets */
#include <sys/un.h>
/* for getpwnam() and getgrnam() */
#if 0
#include <pwd.h>
#include <grp.h>
#endif
/* LOG_PERROR does not exist on Solaris */
#ifndef LOG_PERROR
#define LOG_PERROR 0
#endif /* LOG_PERROR */
#include "getifaddr.h"
#include "upnputils.h"
#include "openssdpsocket.h"
#include "daemonize.h"
#include "codelength.h"
#include "ifacewatch.h"
#include "minissdpdtypes.h"
#include "asyncsendto.h"
#define SET_MAX(max, x) if((x) > (max)) (max) = (x)
#ifndef MIN
#define MIN(x,y) (((x)<(y))?(x):(y))
#endif
/* current request management structure */
struct reqelem {
int socket;
int is_notify; /* has subscribed to notifications */
LIST_ENTRY(reqelem) entries;
unsigned char * output_buffer;
int output_buffer_offset;
int output_buffer_len;
};
/* device data structures */
struct header {
const char * p; /* string pointer */
int l; /* string length */
};
#define HEADER_NT 0
#define HEADER_USN 1
#define HEADER_LOCATION 2
struct device {
struct device * next;
time_t t; /* validity time */
struct header headers[3]; /* NT, USN and LOCATION headers */
char data[];
};
/* Services stored for answering to M-SEARCH */
struct service {
char * st; /* Service type */
char * usn; /* Unique identifier */
char * server; /* Server string */
char * location; /* URL */
LIST_ENTRY(service) entries;
};
LIST_HEAD(servicehead, service) servicelisthead;
#define NTS_SSDP_ALIVE 1
#define NTS_SSDP_BYEBYE 2
#define NTS_SSDP_UPDATE 3
/* request types */
enum request_type {
MINISSDPD_GET_VERSION = 0,
MINISSDPD_SEARCH_TYPE = 1,
MINISSDPD_SEARCH_USN = 2,
MINISSDPD_SEARCH_ALL = 3,
MINISSDPD_SUBMIT = 4,
MINISSDPD_NOTIF = 5
};
/* discovered device list kept in memory */
struct device * devlist = 0;
/* bootid and configid */
unsigned int upnp_bootid = 1;
unsigned int upnp_configid = 1337;
/* LAN interfaces/addresses */
struct lan_addr_list lan_addrs;
/* connected clients */
LIST_HEAD(reqstructhead, reqelem) reqlisthead;
/* functions prototypes */
#define NOTIF_NEW 1
#define NOTIF_UPDATE 2
#define NOTIF_REMOVE 3
static void
sendNotifications(int notif_type, const struct device * dev, const struct service * serv);
/* functions */
/* parselanaddr()
* parse address with mask
* ex: 192.168.1.1/24 or 192.168.1.1/255.255.255.0
*
* Can also use the interface name (ie eth0)
*
* return value :
* 0 : ok
* -1 : error */
static int
parselanaddr(struct lan_addr_s * lan_addr, const char * str)
{
const char * p;
int n;
char tmp[16];
memset(lan_addr, 0, sizeof(struct lan_addr_s));
p = str;
while(*p && *p != '/' && !isspace(*p))
p++;
n = p - str;
if(!isdigit(str[0]) && n < (int)sizeof(lan_addr->ifname)) {
/* not starting with a digit : suppose it is an interface name */
memcpy(lan_addr->ifname, str, n);
lan_addr->ifname[n] = '\0';
if(getifaddr(lan_addr->ifname, lan_addr->str, sizeof(lan_addr->str),
&lan_addr->addr, &lan_addr->mask) < 0)
goto parselan_error;
/*printf("%s => %s\n", lan_addr->ifname, lan_addr->str);*/
} else {
if(n>15)
goto parselan_error;
memcpy(lan_addr->str, str, n);
lan_addr->str[n] = '\0';
if(!inet_aton(lan_addr->str, &lan_addr->addr))
goto parselan_error;
}
if(*p == '/') {
const char * q = ++p;
while(*p && isdigit(*p))
p++;
if(*p=='.') {
/* parse mask in /255.255.255.0 format */
while(*p && (*p=='.' || isdigit(*p)))
p++;
n = p - q;
if(n>15)
goto parselan_error;
memcpy(tmp, q, n);
tmp[n] = '\0';
if(!inet_aton(tmp, &lan_addr->mask))
goto parselan_error;
} else {
/* it is a /24 format */
int nbits = atoi(q);
if(nbits > 32 || nbits < 0)
goto parselan_error;
lan_addr->mask.s_addr = htonl(nbits ? (0xffffffffu << (32 - nbits)) : 0);
}
} else if(lan_addr->mask.s_addr == 0) {
/* by default, networks are /24 */
lan_addr->mask.s_addr = htonl(0xffffff00u);
}
#ifdef ENABLE_IPV6
if(lan_addr->ifname[0] != '\0') {
lan_addr->index = if_nametoindex(lan_addr->ifname);
if(lan_addr->index == 0)
fprintf(stderr, "Cannot get index for network interface %s\n",
lan_addr->ifname);
} else {
fprintf(stderr,
"Error: please specify LAN network interface by name instead of IPv4 address : %s\n",
str);
return -1;
}
#endif /* ENABLE_IPV6 */
return 0;
parselan_error:
fprintf(stderr, "Error parsing address/mask (or interface name) : %s\n",
str);
return -1;
}
static int
write_buffer(struct reqelem * req)
{
if(req->output_buffer && req->output_buffer_len > 0) {
int n = write(req->socket,
req->output_buffer + req->output_buffer_offset,
req->output_buffer_len);
if(n >= 0) {
req->output_buffer_offset += n;
req->output_buffer_len -= n;
} else if(errno == EINTR || errno == EWOULDBLOCK || errno == EAGAIN) {
return 0;
}
return n;
} else {
return 0;
}
}
static int
add_to_buffer(struct reqelem * req, const unsigned char * data, int len)
{
unsigned char * tmp;
if(req->output_buffer_offset > 0) {
memmove(req->output_buffer, req->output_buffer + req->output_buffer_offset, req->output_buffer_len);
req->output_buffer_offset = 0;
}
tmp = realloc(req->output_buffer, req->output_buffer_len + len);
if(tmp == NULL) {
syslog(LOG_ERR, "%s: failed to allocate %d bytes",
__func__, req->output_buffer_len + len);
return -1;
}
req->output_buffer = tmp;
memcpy(req->output_buffer + req->output_buffer_len, data, len);
req->output_buffer_len += len;
return len;
}
static int
write_or_buffer(struct reqelem * req, const unsigned char * data, int len)
{
if(write_buffer(req) < 0)
return -1;
if(req->output_buffer && req->output_buffer_len > 0) {
return add_to_buffer(req, data, len);
} else {
int n = write(req->socket, data, len);
if(n == len)
return len;
if(n < 0) {
if(errno == EINTR || errno == EWOULDBLOCK || errno == EAGAIN) {
n = add_to_buffer(req, data, len);
if(n < 0) return n;
} else {
return n;
}
} else {
n = add_to_buffer(req, data + n, len - n);
if(n < 0) return n;
}
}
return len;
}
static const char *
nts_to_str(int nts)
{
switch(nts)
{
case NTS_SSDP_ALIVE:
return "ssdp:alive";
case NTS_SSDP_BYEBYE:
return "ssdp:byebye";
case NTS_SSDP_UPDATE:
return "ssdp:update";
}
return "unknown";
}
/* updateDevice() :
* adds or updates the device to the list.
* return value :
* 0 : the device was updated (or nothing done)
* 1 : the device was new */
static int
updateDevice(const struct header * headers, time_t t)
{
struct device ** pp = &devlist;
struct device * p = *pp; /* = devlist; */
while(p)
{
if( p->headers[HEADER_NT].l == headers[HEADER_NT].l
&& (0==memcmp(p->headers[HEADER_NT].p, headers[HEADER_NT].p, headers[HEADER_NT].l))
&& p->headers[HEADER_USN].l == headers[HEADER_USN].l
&& (0==memcmp(p->headers[HEADER_USN].p, headers[HEADER_USN].p, headers[HEADER_USN].l)) )
{
/*printf("found! %d\n", (int)(t - p->t));*/
syslog(LOG_DEBUG, "device updated : %.*s", headers[HEADER_USN].l, headers[HEADER_USN].p);
p->t = t;
/* update Location ! */
if(headers[HEADER_LOCATION].l > p->headers[HEADER_LOCATION].l)
{
struct device * tmp;
tmp = realloc(p, sizeof(struct device)
+ headers[0].l+headers[1].l+headers[2].l);
if(!tmp) /* allocation error */
{
syslog(LOG_ERR, "updateDevice() : memory allocation error");
*pp = p->next; /* remove "p" from the list */
free(p);
return 0;
}
p = tmp;
*pp = p;
}
memcpy(p->data + p->headers[0].l + p->headers[1].l,
headers[2].p, headers[2].l);
/* TODO : check p->headers[HEADER_LOCATION].l */
return 0;
}
pp = &p->next;
p = *pp; /* p = p->next; */
}
syslog(LOG_INFO, "new device discovered : %.*s",
headers[HEADER_USN].l, headers[HEADER_USN].p);
/* add */
{
char * pc;
int i;
p = malloc( sizeof(struct device)
+ headers[0].l+headers[1].l+headers[2].l );
if(!p) {
syslog(LOG_ERR, "updateDevice(): cannot allocate memory");
return -1;
}
p->next = devlist;
p->t = t;
pc = p->data;
for(i = 0; i < 3; i++)
{
p->headers[i].p = pc;
p->headers[i].l = headers[i].l;
memcpy(pc, headers[i].p, headers[i].l);
pc += headers[i].l;
}
devlist = p;
sendNotifications(NOTIF_NEW, p, NULL);
}
return 1;
}
/* removeDevice() :
* remove a device from the list
* return value :
* 0 : no device removed
* -1 : device removed */
static int
removeDevice(const struct header * headers)
{
struct device ** pp = &devlist;
struct device * p = *pp; /* = devlist */
while(p)
{
if( p->headers[HEADER_NT].l == headers[HEADER_NT].l
&& (0==memcmp(p->headers[HEADER_NT].p, headers[HEADER_NT].p, headers[HEADER_NT].l))
&& p->headers[HEADER_USN].l == headers[HEADER_USN].l
&& (0==memcmp(p->headers[HEADER_USN].p, headers[HEADER_USN].p, headers[HEADER_USN].l)) )
{
syslog(LOG_INFO, "remove device : %.*s", headers[HEADER_USN].l, headers[HEADER_USN].p);
sendNotifications(NOTIF_REMOVE, p, NULL);
*pp = p->next;
free(p);
return -1;
}
pp = &p->next;
p = *pp; /* p = p->next; */
}
syslog(LOG_WARNING, "device not found for removing : %.*s", headers[HEADER_USN].l, headers[HEADER_USN].p);
return 0;
}
/* sent notifications to client having subscribed */
static void
sendNotifications(int notif_type, const struct device * dev, const struct service * serv)
{
struct reqelem * req;
unsigned int m;
unsigned char rbuf[RESPONSE_BUFFER_SIZE];
unsigned char * rp;
for(req = reqlisthead.lh_first; req; req = req->entries.le_next) {
if(!req->is_notify) continue;
rbuf[0] = '\xff'; /* special code for notifications */
rbuf[1] = (unsigned char)notif_type;
rbuf[2] = 0;
rp = rbuf + 3;
if(dev) {
/* response :
* 1 - Location
* 2 - NT (device/service type)
* 3 - usn */
m = dev->headers[HEADER_LOCATION].l;
CODELENGTH(m, rp);
memcpy(rp, dev->headers[HEADER_LOCATION].p, dev->headers[HEADER_LOCATION].l);
rp += dev->headers[HEADER_LOCATION].l;
m = dev->headers[HEADER_NT].l;
CODELENGTH(m, rp);
memcpy(rp, dev->headers[HEADER_NT].p, dev->headers[HEADER_NT].l);
rp += dev->headers[HEADER_NT].l;
m = dev->headers[HEADER_USN].l;
CODELENGTH(m, rp);
memcpy(rp, dev->headers[HEADER_USN].p, dev->headers[HEADER_USN].l);
rp += dev->headers[HEADER_USN].l;
rbuf[2]++;
}
if(serv) {
/* response :
* 1 - Location
* 2 - NT (device/service type)
* 3 - usn */
m = strlen(serv->location);
CODELENGTH(m, rp);
memcpy(rp, serv->location, m);
rp += m;
m = strlen(serv->st);
CODELENGTH(m, rp);
memcpy(rp, serv->st, m);
rp += m;
m = strlen(serv->usn);
CODELENGTH(m, rp);
memcpy(rp, serv->usn, m);
rp += m;
rbuf[2]++;
}
if(rbuf[2] > 0) {
if(write_or_buffer(req, rbuf, rp - rbuf) < 0) {
syslog(LOG_ERR, "(s=%d) write: %m", req->socket);
/*goto error;*/
}
}
}
}
/* SendSSDPMSEARCHResponse() :
* build and send response to M-SEARCH SSDP packets. */
static void
SendSSDPMSEARCHResponse(int s, const struct sockaddr * sockname,
const char * st, size_t st_len, const char * usn,
const char * server, const char * location)
{
int l, n;
char buf[1024];
socklen_t sockname_len;
/*
* follow guideline from document "UPnP Device Architecture 1.0"
* uppercase is recommended.
* DATE: is recommended
* SERVER: OS/ver UPnP/1.0 miniupnpd/1.0
* - check what to put in the 'Cache-Control' header
*
* have a look at the document "UPnP Device Architecture v1.1 */
l = snprintf(buf, sizeof(buf), "HTTP/1.1 200 OK\r\n"
"CACHE-CONTROL: max-age=1800\r\n"
/*"DATE: ...\r\n"*/
"ST: %.*s\r\n"
"USN: %s\r\n"
"EXT:\r\n"
"SERVER: %s\r\n"
"LOCATION: %s\r\n"
"OPT: \"http://schemas.upnp.org/upnp/1/0/\"; ns=01\r\n" /* UDA v1.1 */
"01-NLS: %u\r\n" /* same as BOOTID. UDA v1.1 */
"BOOTID.UPNP.ORG: %u\r\n" /* UDA v1.1 */
"CONFIGID.UPNP.ORG: %u\r\n" /* UDA v1.1 */
"\r\n",
(int)st_len, st, usn,
server, location,
upnp_bootid, upnp_bootid, upnp_configid);
#ifdef ENABLE_IPV6
sockname_len = (sockname->sa_family == PF_INET6)
? sizeof(struct sockaddr_in6)
: sizeof(struct sockaddr_in);
#else /* ENABLE_IPV6 */
sockname_len = sizeof(struct sockaddr_in);
#endif /* ENABLE_IPV6 */
n = sendto_or_schedule(s, buf, l, 0, sockname, sockname_len);
if(n < 0) {
syslog(LOG_ERR, "%s: sendto(udp): %m", __func__);
}
}
/* Process M-SEARCH requests */
static void
processMSEARCH(int s, const char * st, size_t st_len,
const struct sockaddr * addr)
{
struct service * serv;
#ifdef ENABLE_IPV6
char buf[64];
#endif /* ENABLE_IPV6 */
if(!st || st_len==0)
return;
#ifdef ENABLE_IPV6
sockaddr_to_string(addr, buf, sizeof(buf));
syslog(LOG_INFO, "SSDP M-SEARCH from %s ST:%.*s",
buf, (int)st_len, st);
#else /* ENABLE_IPV6 */
syslog(LOG_INFO, "SSDP M-SEARCH from %s:%d ST: %.*s",
inet_ntoa(((const struct sockaddr_in *)addr)->sin_addr),
ntohs(((const struct sockaddr_in *)addr)->sin_port),
(int)st_len, st);
#endif /* ENABLE_IPV6 */
if(st_len==8 && (0==memcmp(st, "ssdp:all", 8))) {
/* send a response for all services */
for(serv = servicelisthead.lh_first;
serv;
serv = serv->entries.le_next) {
SendSSDPMSEARCHResponse(s, addr,
serv->st, strlen(serv->st), serv->usn,
serv->server, serv->location);
}
} else if(st_len > 5 && (0==memcmp(st, "uuid:", 5))) {
/* find a matching UUID value */
for(serv = servicelisthead.lh_first;
serv;
serv = serv->entries.le_next) {
if(0 == strncmp(serv->usn, st, st_len)) {
SendSSDPMSEARCHResponse(s, addr,
serv->st, strlen(serv->st), serv->usn,
serv->server, serv->location);
}
}
} else {
size_t l;
int st_ver = 0;
char atoi_buffer[8];
/* remove version at the end of the ST string */
for (l = st_len; l > 0; l--) {
if (st[l-1] == ':') {
memset(atoi_buffer, 0, sizeof(atoi_buffer));
memcpy(atoi_buffer, st + l, MIN((sizeof(atoi_buffer) - 1), st_len - l));
st_ver = atoi(atoi_buffer);
break;
}
}
if (l == 0)
l = st_len;
/* answer for each matching service */
/* From UPnP Device Architecture v1.1 :
* 1.3.2 [...] Updated versions of device and service types
* are REQUIRED to be full backward compatible with
* previous versions. Devices MUST respond to M-SEARCH
* requests for any supported version. For example, if a
* device implements “urn:schemas-upnporg:service:xyz:2”,
* it MUST respond to search requests for both that type
* and “urn:schemas-upnp-org:service:xyz:1”. The response
* MUST specify the same version as was contained in the
* search request. [...] */
for(serv = servicelisthead.lh_first;
serv;
serv = serv->entries.le_next) {
if(0 == strncmp(serv->st, st, l)) {
syslog(LOG_DEBUG, "Found matching service : %s %s (v %d)", serv->st, serv->location, st_ver);
SendSSDPMSEARCHResponse(s, addr,
st, st_len, serv->usn,
serv->server, serv->location);
}
}
}
}
/**
* helper function.
* reject any non ASCII or non printable character.
*/
static int
containsForbiddenChars(const unsigned char * p, int len)
{
while(len > 0) {
if(*p < ' ' || *p >= '\x7f')
return 1;
p++;
len--;
}
return 0;
}
#define METHOD_MSEARCH 1
#define METHOD_NOTIFY 2
/* ParseSSDPPacket() :
* parse a received SSDP Packet and call
* updateDevice() or removeDevice() as needed
* return value :
* -1 : a device was removed
* 0 : no device removed nor added
* 1 : a device was added. */
static int
ParseSSDPPacket(int s, const char * p, ssize_t n,
const struct sockaddr * addr,
const char * searched_device)
{
const char * linestart;
const char * lineend;
const char * nameend;
const char * valuestart;
struct header headers[3];
int i, r = 0;
int methodlen;
int nts = -1;
int method = -1;
unsigned int lifetime = 180; /* 3 minutes by default */
const char * st = NULL;
int st_len = 0;
/* first check from what subnet is the sender */
if(get_lan_for_peer(addr) == NULL) {
char addr_str[64];
sockaddr_to_string(addr, addr_str, sizeof(addr_str));
syslog(LOG_WARNING, "peer %s is not from a LAN",
addr_str);
return 0;
}
/* do the parsing */
memset(headers, 0, sizeof(headers));
for(methodlen = 0;
methodlen < n && (isalpha(p[methodlen]) || p[methodlen]=='-');
methodlen++);
if(methodlen==8 && 0==memcmp(p, "M-SEARCH", 8))
method = METHOD_MSEARCH;
else if(methodlen==6 && 0==memcmp(p, "NOTIFY", 6))
method = METHOD_NOTIFY;
else if(methodlen==4 && 0==memcmp(p, "HTTP", 4)) {
/* answer to a M-SEARCH => process it as a NOTIFY
* with NTS: ssdp:alive */
method = METHOD_NOTIFY;
nts = NTS_SSDP_ALIVE;
}
linestart = p;
while(linestart < p + n - 2) {
/* start parsing the line : detect line end */
lineend = linestart;
while(lineend < p + n && *lineend != '\n' && *lineend != '\r')
lineend++;
/*printf("line: '%.*s'\n", lineend - linestart, linestart);*/
/* detect name end : ':' character */
nameend = linestart;
while(nameend < lineend && *nameend != ':')
nameend++;
/* detect value */
if(nameend < lineend)
valuestart = nameend + 1;
else
valuestart = nameend;
/* trim spaces */
while(valuestart < lineend && isspace(*valuestart))
valuestart++;
/* suppress leading " if needed */
if(valuestart < lineend && *valuestart=='\"')
valuestart++;
if(nameend > linestart && valuestart < lineend) {
int l = nameend - linestart; /* header name length */
int m = lineend - valuestart; /* header value length */
/* suppress tailing spaces */
while(m>0 && isspace(valuestart[m-1]))
m--;
/* suppress tailing ' if needed */
if(m>0 && valuestart[m-1] == '\"')
m--;
i = -1;
/*printf("--%.*s: (%d)%.*s--\n", l, linestart,
m, m, valuestart);*/
if(l==2 && 0==strncasecmp(linestart, "nt", 2))
i = HEADER_NT;
else if(l==3 && 0==strncasecmp(linestart, "usn", 3))
i = HEADER_USN;
else if(l==3 && 0==strncasecmp(linestart, "nts", 3)) {
if(m==10 && 0==strncasecmp(valuestart, "ssdp:alive", 10))
nts = NTS_SSDP_ALIVE;
else if(m==11 && 0==strncasecmp(valuestart, "ssdp:byebye", 11))
nts = NTS_SSDP_BYEBYE;
else if(m==11 && 0==strncasecmp(valuestart, "ssdp:update", 11))
nts = NTS_SSDP_UPDATE;
}
else if(l==8 && 0==strncasecmp(linestart, "location", 8))
i = HEADER_LOCATION;
else if(l==13 && 0==strncasecmp(linestart, "cache-control", 13)) {
/* parse "name1=value1, name_alone, name2=value2" string */
const char * name = valuestart; /* name */
const char * val; /* value */
int rem = m; /* remaining bytes to process */
while(rem > 0) {
val = name;
while(val < name + rem && *val != '=' && *val != ',')
val++;
if(val >= name + rem)
break;
if(*val == '=') {
while(val < name + rem && (*val == '=' || isspace(*val)))
val++;
if(val >= name + rem)
break;
if(0==strncasecmp(name, "max-age", 7))
lifetime = (unsigned int)strtoul(val, 0, 0);
/* move to the next name=value pair */
while(rem > 0 && *name != ',') {
rem--;
name++;
}
/* skip spaces */
while(rem > 0 && (*name == ',' || isspace(*name))) {
rem--;
name++;
}
} else {
rem -= (val - name);
name = val;
while(rem > 0 && (*name == ',' || isspace(*name))) {
rem--;
name++;
}
}
}
/*syslog(LOG_DEBUG, "**%.*s**%u", m, valuestart, lifetime);*/
} else if(l==2 && 0==strncasecmp(linestart, "st", 2)) {
st = valuestart;
st_len = m;
if(method == METHOD_NOTIFY)
i = HEADER_NT; /* it was a M-SEARCH response */
}
if(i>=0) {
headers[i].p = valuestart;
headers[i].l = m;
}
}
linestart = lineend;
while((linestart < p + n) && (*linestart == '\n' || *linestart == '\r'))
linestart++;
}
#if 0
printf("NTS=%d\n", nts);
for(i=0; i<3; i++) {
if(headers[i].p)
printf("%d-'%.*s'\n", i, headers[i].l, headers[i].p);
}
#endif
syslog(LOG_DEBUG,"SSDP request: '%.*s' (%d) %s %s=%.*s",
methodlen, p, method, nts_to_str(nts),
(method==METHOD_NOTIFY)?"nt":"st",
(method==METHOD_NOTIFY)?headers[HEADER_NT].l:st_len,
(method==METHOD_NOTIFY)?headers[HEADER_NT].p:st);
switch(method) {
case METHOD_NOTIFY:
if(nts==NTS_SSDP_ALIVE || nts==NTS_SSDP_UPDATE) {
if(headers[HEADER_NT].p && headers[HEADER_USN].p && headers[HEADER_LOCATION].p) {
/* filter if needed */
if(searched_device &&
0 != memcmp(headers[HEADER_NT].p, searched_device, headers[HEADER_NT].l))
break;
r = updateDevice(headers, time(NULL) + lifetime);
} else {
syslog(LOG_WARNING, "missing header nt=%p usn=%p location=%p",
headers[HEADER_NT].p, headers[HEADER_USN].p,
headers[HEADER_LOCATION].p);
}
} else if(nts==NTS_SSDP_BYEBYE) {
if(headers[HEADER_NT].p && headers[HEADER_USN].p) {
r = removeDevice(headers);
} else {
syslog(LOG_WARNING, "missing header nt=%p usn=%p",
headers[HEADER_NT].p, headers[HEADER_USN].p);
}
}
break;
case METHOD_MSEARCH:
processMSEARCH(s, st, st_len, addr);
break;
default:
{
char addr_str[64];
sockaddr_to_string(addr, addr_str, sizeof(addr_str));
syslog(LOG_WARNING, "method %.*s, don't know what to do (from %s)",
methodlen, p, addr_str);
}
}
return r;
}
/* OpenUnixSocket()
* open the unix socket and call bind() and listen()
* return -1 in case of error */
static int
OpenUnixSocket(const char * path)
{
struct sockaddr_un addr;
int s;
int rv;
s = socket(AF_UNIX, SOCK_STREAM, 0);
if(s < 0)
{
syslog(LOG_ERR, "socket(AF_UNIX): %m");
return -1;
}
/* unlink the socket pseudo file before binding */
rv = unlink(path);
if(rv < 0 && errno != ENOENT)
{
syslog(LOG_ERR, "unlink(unixsocket, \"%s\"): %m", path);
close(s);
return -1;
}
addr.sun_family = AF_UNIX;
strncpy(addr.sun_path, path, sizeof(addr.sun_path));
if(bind(s, (struct sockaddr *)&addr,
sizeof(struct sockaddr_un)) < 0)
{
syslog(LOG_ERR, "bind(unixsocket, \"%s\"): %m", path);
close(s);
return -1;
}
else if(listen(s, 5) < 0)
{
syslog(LOG_ERR, "listen(unixsocket): %m");
close(s);
return -1;
}
/* Change rights so everyone can communicate with us */
if(chmod(path, 0666) < 0)
{
syslog(LOG_WARNING, "chmod(\"%s\"): %m", path);
}
return s;
}
static ssize_t processRequestSub(struct reqelem * req, const unsigned char * buf, ssize_t n);
/* processRequest() :
* process the request coming from a unix socket */
void processRequest(struct reqelem * req)
{
ssize_t n, r;
unsigned char buf[2048];
const unsigned char * p;
n = read(req->socket, buf, sizeof(buf));
if(n<0) {
if(errno == EINTR || errno == EAGAIN || errno == EWOULDBLOCK)
return; /* try again later */
syslog(LOG_ERR, "(s=%d) processRequest(): read(): %m", req->socket);
goto error;
}
if(n==0) {
syslog(LOG_INFO, "(s=%d) request connection closed", req->socket);
goto error;
}
p = buf;
while (n > 0)
{
r = processRequestSub(req, p, n);
if (r < 0)
goto error;
p += r;
n -= r;
}
return;
error:
close(req->socket);
req->socket = -1;
}
static ssize_t processRequestSub(struct reqelem * req, const unsigned char * buf, ssize_t n)
{
unsigned int l, m;
unsigned int baselen; /* without the version */
const unsigned char * p;
enum request_type type;
struct device * d = devlist;
unsigned char rbuf[RESPONSE_BUFFER_SIZE];
unsigned char * rp;
unsigned char nrep = 0;
time_t t;
struct service * newserv = NULL;
struct service * serv;
t = time(NULL);
type = buf[0];
p = buf + 1;
DECODELENGTH_CHECKLIMIT(l, p, buf + n);
if(l > (unsigned)(buf+n-p)) {
syslog(LOG_WARNING, "bad request (length encoding l=%u n=%u)",
l, (unsigned)n);
goto error;
}
if(l == 0 && type != MINISSDPD_SEARCH_ALL
&& type != MINISSDPD_GET_VERSION && type != MINISSDPD_NOTIF) {
syslog(LOG_WARNING, "bad request (length=0, type=%d)", type);
goto error;
}
syslog(LOG_INFO, "(s=%d) request type=%d str='%.*s'",
req->socket, type, l, p);
switch(type) {
case MINISSDPD_GET_VERSION:
rp = rbuf;
CODELENGTH((sizeof(MINISSDPD_VERSION) - 1), rp);
memcpy(rp, MINISSDPD_VERSION, sizeof(MINISSDPD_VERSION) - 1);
rp += (sizeof(MINISSDPD_VERSION) - 1);
if(write_or_buffer(req, rbuf, rp - rbuf) < 0) {
syslog(LOG_ERR, "(s=%d) write: %m", req->socket);
goto error;
}
p += l;
break;
case MINISSDPD_SEARCH_TYPE: /* request by type */
case MINISSDPD_SEARCH_USN: /* request by USN (unique id) */
case MINISSDPD_SEARCH_ALL: /* everything */
rp = rbuf+1;
/* From UPnP Device Architecture v1.1 :
* 1.3.2 [...] Updated versions of device and service types
* are REQUIRED to be full backward compatible with
* previous versions. Devices MUST respond to M-SEARCH
* requests for any supported version. For example, if a
* device implements “urn:schemas-upnporg:service:xyz:2”,
* it MUST respond to search requests for both that type
* and “urn:schemas-upnp-org:service:xyz:1”. The response
* MUST specify the same version as was contained in the
* search request. [...] */
baselen = l; /* remove the version */
while(baselen > 0) {
if(p[baselen-1] == ':')
break;
if(!(p[baselen-1] >= '0' && p[baselen-1] <= '9'))
break;
baselen--;
}
while(d && (nrep < 255)) {
if(d->t < t) {
syslog(LOG_INFO, "outdated device");
} else {
/* test if we can put more responses in the buffer */
if(d->headers[HEADER_LOCATION].l + d->headers[HEADER_NT].l
+ d->headers[HEADER_USN].l + 6
+ (rp - rbuf) >= (int)sizeof(rbuf))
break;
if( (type==MINISSDPD_SEARCH_TYPE && 0==memcmp(d->headers[HEADER_NT].p, p, baselen))
||(type==MINISSDPD_SEARCH_USN && 0==memcmp(d->headers[HEADER_USN].p, p, l))
||(type==MINISSDPD_SEARCH_ALL) ) {
/* response :
* 1 - Location
* 2 - NT (device/service type)
* 3 - usn */
m = d->headers[HEADER_LOCATION].l;
CODELENGTH(m, rp);
memcpy(rp, d->headers[HEADER_LOCATION].p, d->headers[HEADER_LOCATION].l);
rp += d->headers[HEADER_LOCATION].l;
m = d->headers[HEADER_NT].l;
CODELENGTH(m, rp);
memcpy(rp, d->headers[HEADER_NT].p, d->headers[HEADER_NT].l);
rp += d->headers[HEADER_NT].l;
m = d->headers[HEADER_USN].l;
CODELENGTH(m, rp);
memcpy(rp, d->headers[HEADER_USN].p, d->headers[HEADER_USN].l);
rp += d->headers[HEADER_USN].l;
nrep++;
}
}
d = d->next;
}
/* Also look in service list */
for(serv = servicelisthead.lh_first;
serv && (nrep < 255);
serv = serv->entries.le_next) {
/* test if we can put more responses in the buffer */
if(strlen(serv->location) + strlen(serv->st)
+ strlen(serv->usn) + 6 + (rp - rbuf) >= sizeof(rbuf))
break;
if( (type==MINISSDPD_SEARCH_TYPE && 0==strncmp(serv->st, (const char *)p, l))
||(type==MINISSDPD_SEARCH_USN && 0==strncmp(serv->usn, (const char *)p, l))
||(type==MINISSDPD_SEARCH_ALL) ) {
/* response :
* 1 - Location
* 2 - NT (device/service type)
* 3 - usn */
m = strlen(serv->location);
CODELENGTH(m, rp);
memcpy(rp, serv->location, m);
rp += m;