-
-
Notifications
You must be signed in to change notification settings - Fork 93
/
dms.go
1007 lines (941 loc) · 26.6 KB
/
dms.go
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
package dms
import (
"bytes"
"crypto/md5"
"encoding/xml"
"errors"
"fmt"
"io"
"io/ioutil"
"log"
"mime"
"net"
"net/http"
"net/http/pprof"
"net/url"
"os"
"os/exec"
"os/user"
"path"
"path/filepath"
"strings"
"time"
"github.com/anacrolix/dms/dlna"
"github.com/anacrolix/dms/soap"
"github.com/anacrolix/dms/ssdp"
"github.com/anacrolix/dms/transcode"
"github.com/anacrolix/dms/upnp"
"github.com/anacrolix/dms/upnpav"
"github.com/anacrolix/ffprobe"
)
const (
serverField = "Linux/3.4 DLNADOC/1.50 UPnP/1.0 DMS/1.0"
rootDeviceType = "urn:schemas-upnp-org:device:MediaServer:1"
rootDeviceModelName = "dms 1.0"
resPath = "/res"
iconPath = "/icon"
rootDescPath = "/rootDesc.xml"
contentDirectorySCPDURL = "/scpd/ContentDirectory.xml"
contentDirectoryEventSubURL = "/evt/ContentDirectory"
serviceControlURL = "/ctl"
deviceIconPath = "/deviceIcon"
)
type transcodeSpec struct {
mimeType string
DLNAProfileName string
Transcode func(path string, start, length time.Duration, stderr io.Writer) (r io.ReadCloser, err error)
}
var transcodes = map[string]transcodeSpec{
"t": {
mimeType: "video/mpeg",
DLNAProfileName: "MPEG_PS_PAL",
Transcode: transcode.Transcode,
},
"vp8": {mimeType: "video/webm", Transcode: transcode.VP8Transcode},
"chromecast": {mimeType: "video/mp4", Transcode: transcode.ChromecastTranscode},
}
func makeDeviceUuid(unique string) string {
h := md5.New()
if _, err := io.WriteString(h, unique); err != nil {
panic(err)
}
buf := h.Sum(nil)
return upnp.FormatUUID(buf)
}
// Groups the service definition with its XML description.
type service struct {
upnp.Service
SCPD string
}
// Exposed UPnP AV services.
var services = []*service{
{
Service: upnp.Service{
ServiceType: "urn:schemas-upnp-org:service:ContentDirectory:1",
ServiceId: "urn:upnp-org:serviceId:ContentDirectory",
EventSubURL: contentDirectoryEventSubURL,
},
SCPD: contentDirectoryServiceDescription,
},
// {
// Service: upnp.Service{
// ServiceType: "urn:schemas-upnp-org:service:ConnectionManager:3",
// ServiceId: "urn:upnp-org:serviceId:ConnectionManager",
// },
// SCPD: connectionManagerServiceDesc,
// },
}
// The control URL for every service is the same. We're able to infer the desired service from the request headers.
func init() {
for _, s := range services {
s.ControlURL = serviceControlURL
}
}
func devices() []string {
return []string{
"urn:schemas-upnp-org:device:MediaServer:1",
}
}
func serviceTypes() (ret []string) {
for _, s := range services {
ret = append(ret, s.ServiceType)
}
return
}
func (me *Server) httpPort() int {
return me.HTTPConn.Addr().(*net.TCPAddr).Port
}
func (me *Server) serveHTTP() error {
srv := &http.Server{
Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if me.LogHeaders {
fmt.Fprintf(os.Stderr, "%s %s\r\n", r.Method, r.RequestURI)
r.Header.Write(os.Stderr)
fmt.Fprintln(os.Stderr)
}
w.Header().Set("Ext", "")
w.Header().Set("Server", serverField)
me.httpServeMux.ServeHTTP(&mitmRespWriter{
ResponseWriter: w,
logHeader: me.LogHeaders,
}, r)
}),
}
err := srv.Serve(me.HTTPConn)
select {
case <-me.closed:
return nil
default:
return err
}
}
// An interface with these flags should be valid for SSDP.
const ssdpInterfaceFlags = net.FlagUp | net.FlagMulticast
func (me *Server) doSSDP() {
active := 0
stopped := make(chan struct{})
for _, if_ := range me.Interfaces {
active++
go func(if_ net.Interface) {
defer func() {
stopped <- struct{}{}
}()
me.ssdpInterface(if_)
}(if_)
}
for active > 0 {
<-stopped
active--
}
}
// Run SSDP server on an interface.
func (me *Server) ssdpInterface(if_ net.Interface) {
s := ssdp.Server{
Interface: if_,
Devices: devices(),
Services: serviceTypes(),
Location: func(ip net.IP) string {
return me.location(ip)
},
Server: serverField,
UUID: me.rootDeviceUUID,
NotifyInterval: me.NotifyInterval,
}
if err := s.Init(); err != nil {
if if_.Flags&ssdpInterfaceFlags != ssdpInterfaceFlags {
// Didn't expect it to work anyway.
return
}
if strings.Contains(err.Error(), "listen") {
// OSX has a lot of dud interfaces. Failure to create a socket on
// the interface are what we're expecting if the interface is no
// good.
return
}
log.Printf("error creating ssdp server on %s: %s", if_.Name, err)
return
}
defer s.Close()
log.Println("started SSDP on", if_.Name)
stopped := make(chan struct{})
go func() {
defer close(stopped)
if err := s.Serve(); err != nil {
log.Printf("%q: %q\n", if_.Name, err)
}
}()
select {
case <-me.closed:
// Returning will close the server.
case <-stopped:
}
}
var (
startTime time.Time
)
type Icon struct {
Width, Height, Depth int
Mimetype string
io.ReadSeeker
}
type Server struct {
HTTPConn net.Listener
FriendlyName string
Interfaces []net.Interface
httpServeMux *http.ServeMux
RootObjectPath string
rootDescXML []byte
rootDeviceUUID string
FFProbeCache Cache
closed chan struct{}
ssdpStopped chan struct{}
// The service SOAP handler keyed by service URN.
services map[string]UPnPService
LogHeaders bool
// Disable transcoding, and the resource elements implied in the CDS.
NoTranscode bool
// Disable media probing with ffprobe
NoProbe bool
Icons []Icon
// Stall event subscription requests until they drop. A workaround for
// some bad clients.
StallEventSubscribe bool
// Time interval between SSPD announces
NotifyInterval time.Duration
// Ignore hidden files and directories
IgnoreHidden bool
// Ingnore unreadable files and directories
IgnoreUnreadable bool
}
// UPnP SOAP service.
type UPnPService interface {
Handle(action string, argsXML []byte, r *http.Request) (respArgs map[string]string, err *upnp.Error)
Subscribe(callback []*url.URL, timeoutSeconds int) (sid string, actualTimeout int, err error)
Unsubscribe(sid string) error
}
type Cache interface {
Set(key interface{}, value interface{})
Get(key interface{}) (value interface{}, ok bool)
}
type dummyFFProbeCache struct{}
func (dummyFFProbeCache) Set(interface{}, interface{}) {}
func (dummyFFProbeCache) Get(interface{}) (interface{}, bool) {
return nil, false
}
// Public definition so that external modules can persist cache contents.
type FfprobeCacheItem struct {
Key ffmpegInfoCacheKey
Value *ffprobe.Info
}
// update the UPnP object fields from ffprobe data
// priority is given the format section, and then the streams sequentially
func itemExtra(item *upnpav.Object, info *ffprobe.Info) {
setFromTags := func(m map[string]interface{}) {
for key, val := range m {
setIfUnset := func(s *string) {
if *s == "" {
*s = val.(string)
}
}
switch strings.ToLower(key) {
case "tag:artist":
setIfUnset(&item.Artist)
case "tag:album":
setIfUnset(&item.Album)
case "tag:genre":
setIfUnset(&item.Genre)
}
}
}
setFromTags(info.Format)
for _, m := range info.Streams {
setFromTags(m)
}
}
func init() {
if err := mime.AddExtensionType(".rmvb", "application/vnd.rn-realmedia-vbr"); err != nil {
panic(err)
}
if err := mime.AddExtensionType(".ogv", "video/ogg"); err != nil {
panic(err)
}
}
// Example: "video/mpeg"
type mimeType string
func (me mimeType) IsMedia() bool {
if me == "application/vnd.rn-realmedia-vbr" {
return true
}
return me.Type().IsMedia()
}
// Attempts to guess mime type by peeling off extensions, such as those given
// to incomplete files. TODO: This function may be misleading, since it
// ignores non-media mime-types in processing.
func mimeTypeByBaseName(name string) mimeType {
for name != "" {
ext := strings.ToLower(path.Ext(name))
if ext == "" {
break
}
ret := mimeType(mime.TypeByExtension(ext))
if ret.IsMedia() {
return ret
}
switch ext {
case ".part":
index := strings.LastIndex(name, ".")
if index >= 0 {
name = name[:index]
}
default:
return ""
}
}
return ""
}
// Used to determine the MIME-type for the given path
func MimeTypeByPath(path_ string) (ret mimeType) {
defer func() {
if ret == "video/x-msvideo" {
ret = "video/avi"
}
}()
ret = mimeTypeByBaseName(path.Base(path_))
if ret != "" {
return
}
file, _ := os.Open(path_)
if file == nil {
return
}
var data [512]byte
n, _ := file.Read(data[:])
file.Close()
ret = mimeType(http.DetectContentType(data[:n]))
return
}
// Returns the group "type", the part before the '/'.
func (mt mimeType) Type() mimeTypeType {
return mimeTypeType(strings.SplitN(string(mt), "/", 2)[0])
}
type ffmpegInfoCacheKey struct {
Path string
ModTime int64
}
func transcodeResources(host, path, resolution, duration string) (ret []upnpav.Resource) {
ret = make([]upnpav.Resource, 0, len(transcodes))
for k, v := range transcodes {
ret = append(ret, upnpav.Resource{
ProtocolInfo: fmt.Sprintf("http-get:*:%s:%s", v.mimeType, dlna.ContentFeatures{
SupportTimeSeek: true,
Transcoded: true,
ProfileName: v.DLNAProfileName,
}.String()),
URL: (&url.URL{
Scheme: "http",
Host: host,
Path: resPath,
RawQuery: url.Values{
"path": {path},
"transcode": {k},
}.Encode(),
}).String(),
Resolution: resolution,
Duration: duration,
})
}
return
}
// The part of a MIME type before the '/'.
type mimeTypeType string
// Returns true if the type is typical media.
func (mtt mimeTypeType) IsMedia() bool {
switch mtt {
case "video", "audio":
return true
default:
return false
}
}
func parseDLNARangeHeader(val string) (ret dlna.NPTRange, err error) {
if !strings.HasPrefix(val, "npt=") {
err = errors.New("bad prefix")
return
}
ret, err = dlna.ParseNPTRange(val[len("npt="):])
if err != nil {
return
}
return
}
// Determines the time-based range to transcode, and sets the appropriate
// headers. Returns !ok if there was an error and the caller should stop
// handling the request.
func handleDLNARange(w http.ResponseWriter, hs http.Header) (r dlna.NPTRange, partialResponse, ok bool) {
if len(hs[http.CanonicalHeaderKey(dlna.TimeSeekRangeDomain)]) == 0 {
ok = true
return
}
partialResponse = true
h := hs.Get(dlna.TimeSeekRangeDomain)
r, err := parseDLNARangeHeader(h)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
// Passing an exact NPT duration seems to cause trouble pass the "iono"
// (*) duration instead.
//
// TODO: Check that the request range can't already have /.
w.Header().Set(dlna.TimeSeekRangeDomain, h+"/*")
ok = true
return
}
func (me *Server) serveDLNATranscode(w http.ResponseWriter, r *http.Request, path_ string, ts transcodeSpec, tsname string) {
w.Header().Set(dlna.TransferModeDomain, "Streaming")
w.Header().Set("content-type", ts.mimeType)
w.Header().Set(dlna.ContentFeaturesDomain, (dlna.ContentFeatures{
Transcoded: true,
SupportTimeSeek: true,
}).String())
// If a range of any kind is given, we have to respond with 206 if we're
// interpreting that range. Since only the DLNA range is handled in this
// function, it alone determines if we'll give a partial response.
range_, partialResponse, ok := handleDLNARange(w, r.Header)
if !ok {
return
}
ffInfo, _ := me.ffmpegProbe(path_)
if ffInfo != nil {
if duration, err := ffInfo.Duration(); err == nil {
s := fmt.Sprintf("%f", duration.Seconds())
w.Header().Set("content-duration", s)
w.Header().Set("x-content-duration", s)
}
}
stderrPath := func() string {
u, _ := user.Current()
return filepath.Join(u.HomeDir, ".dms", "log", tsname, filepath.Base(path_))
}()
os.MkdirAll(filepath.Dir(stderrPath), 0750)
logFile, err := os.Create(stderrPath)
if err != nil {
log.Printf("couldn't create transcode log file: %s", err)
} else {
defer logFile.Close()
log.Printf("logging transcode to %q", stderrPath)
}
p, err := ts.Transcode(path_, range_.Start, range_.End-range_.Start, logFile)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
defer p.Close()
// I recently switched this to returning 200 if no range is specified for
// pure UPnP clients. It's possible that DLNA clients will *always* expect
// 206. It appears the HTTP standard requires that 206 only be used if a
// response is not interpreting any range headers.
w.WriteHeader(func() int {
if partialResponse {
return http.StatusPartialContent
} else {
return http.StatusOK
}
}())
io.Copy(w, p)
}
func init() {
startTime = time.Now()
}
func getDefaultFriendlyName() string {
return fmt.Sprintf("%s: %s on %s", rootDeviceModelName, func() string {
user, err := user.Current()
if err != nil {
panic(err)
}
return user.Name
}(), func() string {
name, err := os.Hostname()
if err != nil {
panic(err)
}
return name
}())
}
func xmlMarshalOrPanic(value interface{}) []byte {
ret, err := xml.MarshalIndent(value, "", " ")
if err != nil {
panic(err)
}
return ret
}
// TODO: Document the use of this for debugging.
type mitmRespWriter struct {
http.ResponseWriter
loggedHeader bool
logHeader bool
}
func (me *mitmRespWriter) WriteHeader(code int) {
me.doLogHeader(code)
me.ResponseWriter.WriteHeader(code)
}
func (me *mitmRespWriter) doLogHeader(code int) {
if !me.logHeader {
return
}
fmt.Fprintln(os.Stderr, code)
for k, v := range me.Header() {
fmt.Fprintln(os.Stderr, k, v)
}
fmt.Fprintln(os.Stderr)
me.loggedHeader = true
}
func (me *mitmRespWriter) Write(b []byte) (int, error) {
if !me.loggedHeader {
me.doLogHeader(200)
}
return me.ResponseWriter.Write(b)
}
func (me *mitmRespWriter) CloseNotify() <-chan bool {
return me.ResponseWriter.(http.CloseNotifier).CloseNotify()
}
// Set the SCPD serve paths.
func init() {
for _, s := range services {
p := path.Join("/scpd", s.ServiceId)
s.SCPDURL = p
}
}
// Install handlers to serve SCPD for each UPnP service.
func handleSCPDs(mux *http.ServeMux) {
for _, s := range services {
mux.HandleFunc(s.SCPDURL, func(serviceDesc string) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("content-type", `text/xml; charset="utf-8"`)
http.ServeContent(w, r, ".xml", startTime, bytes.NewReader([]byte(serviceDesc)))
}
}(s.SCPD))
}
}
// Marshal SOAP response arguments into a response XML snippet.
func marshalSOAPResponse(sa upnp.SoapAction, args map[string]string) []byte {
soapArgs := make([]soap.Arg, 0, len(args))
for argName, value := range args {
soapArgs = append(soapArgs, soap.Arg{
XMLName: xml.Name{Local: argName},
Value: value,
})
}
return []byte(fmt.Sprintf(`<u:%[1]sResponse xmlns:u="%[2]s">%[3]s</u:%[1]sResponse>`, sa.Action, sa.ServiceURN.String(), xmlMarshalOrPanic(soapArgs)))
}
// Handle a SOAP request and return the response arguments or UPnP error.
func (me *Server) soapActionResponse(sa upnp.SoapAction, actionRequestXML []byte, r *http.Request) (map[string]string, *upnp.Error) {
service, ok := me.services[sa.Type]
if !ok {
// TODO: What's the invalid service error?!
return nil, &upnp.InvalidActionError
}
return service.Handle(sa.Action, actionRequestXML, r)
}
// Handle a service control HTTP request.
func (me *Server) serviceControlHandler(w http.ResponseWriter, r *http.Request) {
soapActionString := r.Header.Get("SOAPACTION")
soapAction, ok := upnp.ParseActionHTTPHeader(soapActionString)
if !ok {
http.Error(w, fmt.Sprintf("invalid soapaction: %#v", soapActionString), http.StatusBadRequest)
return
}
var env soap.Envelope
if err := xml.NewDecoder(r.Body).Decode(&env); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
//AwoX/1.1 UPnP/1.0 DLNADOC/1.50
//log.Println(r.UserAgent())
w.Header().Set("Content-Type", `text/xml; charset="utf-8"`)
w.Header().Set("Ext", "")
w.Header().Set("Server", serverField)
soapRespXML, code := func() ([]byte, int) {
respArgs, err := me.soapActionResponse(soapAction, env.Body.Action, r)
if err != nil {
return xmlMarshalOrPanic(soap.NewFault("UPnPError", err)), 500
}
return marshalSOAPResponse(soapAction, respArgs), 200
}()
bodyStr := fmt.Sprintf(`<?xml version="1.0" encoding="utf-8" standalone="yes"?><s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/" s:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"><s:Body>%s</s:Body></s:Envelope>`, soapRespXML)
w.WriteHeader(code)
if _, err := w.Write([]byte(bodyStr)); err != nil {
panic(err)
}
}
func safeFilePath(root, given string) string {
return filepath.Join(root, filepath.FromSlash(path.Clean("/" + given))[1:])
}
func (s *Server) filePath(_path string) string {
return safeFilePath(s.RootObjectPath, _path)
}
func (me *Server) serveIcon(w http.ResponseWriter, r *http.Request) {
filePath := me.filePath(r.URL.Query().Get("path"))
c := r.URL.Query().Get("c")
if c == "" {
c = "png"
}
cmd := exec.Command("ffmpegthumbnailer", "-i", filePath, "-o", "/dev/stdout", "-c"+c)
// cmd.Stderr = os.Stderr
body, err := cmd.Output()
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
http.ServeContent(w, r, "", time.Now(), bytes.NewReader(body))
}
func (server *Server) contentDirectoryInitialEvent(urls []*url.URL, sid string) {
body, err := xml.Marshal(upnp.PropertySet{
Properties: []upnp.Property{
upnp.Property{
Variable: upnp.Variable{
XMLName: xml.Name{
Local: "SystemUpdateID",
},
Value: "0",
},
},
// upnp.Property{
// Variable: upnp.Variable{
// XMLName: xml.Name{
// Local: "ContainerUpdateIDs",
// },
// },
// },
// upnp.Property{
// Variable: upnp.Variable{
// XMLName: xml.Name{
// Local: "TransferIDs",
// },
// },
// },
},
Space: "urn:schemas-upnp-org:event-1-0",
})
if err != nil {
panic(err)
}
body = append([]byte(`<?xml version="1.0"?>`+"\n"), body...)
eventingLogger.Print(string(body))
for _, _url := range urls {
bodyReader := bytes.NewReader(body)
req, err := http.NewRequest("NOTIFY", _url.String(), bodyReader)
if err != nil {
panic(err)
}
req.Header["CONTENT-TYPE"] = []string{`text/xml; charset="utf-8"`}
req.Header["NT"] = []string{"upnp:event"}
req.Header["NTS"] = []string{"upnp:propchange"}
req.Header["SID"] = []string{sid}
req.Header["SEQ"] = []string{"0"}
// req.Header["TRANSFER-ENCODING"] = []string{"chunked"}
// req.ContentLength = int64(bodyReader.Len())
eventingLogger.Print(req.Header)
eventingLogger.Print("starting notify")
resp, err := http.DefaultClient.Do(req)
eventingLogger.Print("finished notify")
if err != nil {
log.Print(err)
continue
}
eventingLogger.Print(resp)
b, _ := ioutil.ReadAll(resp.Body)
eventingLogger.Println(string(b))
resp.Body.Close()
}
}
var eventingLogger = log.New(ioutil.Discard, "", 0)
func (server *Server) contentDirectoryEventSubHandler(w http.ResponseWriter, r *http.Request) {
if server.StallEventSubscribe {
// I have an LG TV that doesn't like my eventing implementation.
// Returning unimplemented (501?) errors, results in repeat subscribe
// attempts which hits some kind of error count limit on the TV
// causing it to forcefully disconnect. It also won't work if the CDS
// service doesn't include an EventSubURL. The best thing I can do is
// cause every attempt to subscribe to timeout on the TV end, which
// reduces the error rate enough that the TV continues to operate
// without eventing.
//
// I've not found a reliable way to identify this TV, since it and
// others don't seem to include any client-identifying headers on
// SUBSCRIBE requests.
//
// TODO: Get eventing to work with the problematic TV.
t := time.Now()
<-w.(http.CloseNotifier).CloseNotify()
eventingLogger.Printf("stalled subscribe connection went away after %s", time.Since(t))
return
}
// The following code is a work in progress. It partially implements
// the spec on eventing but hasn't been completed as I have nothing to
// test it with.
eventingLogger.Print(r.Header)
service := server.services["ContentDirectory"]
eventingLogger.Println(r.RemoteAddr, r.Method, r.Header.Get("SID"))
if r.Method == "SUBSCRIBE" && r.Header.Get("SID") == "" {
urls := upnp.ParseCallbackURLs(r.Header.Get("CALLBACK"))
eventingLogger.Println(urls)
var timeout int
fmt.Sscanf(r.Header.Get("TIMEOUT"), "Second-%d", &timeout)
eventingLogger.Println(timeout, r.Header.Get("TIMEOUT"))
sid, timeout, _ := service.Subscribe(urls, timeout)
w.Header()["SID"] = []string{sid}
w.Header()["TIMEOUT"] = []string{fmt.Sprintf("Second-%d", timeout)}
// TODO: Shouldn't have to do this to get headers logged.
w.WriteHeader(http.StatusOK)
go func() {
time.Sleep(100 * time.Millisecond)
server.contentDirectoryInitialEvent(urls, sid)
}()
} else if r.Method == "SUBSCRIBE" {
http.Error(w, "meh", http.StatusPreconditionFailed)
} else {
eventingLogger.Printf("unhandled event method: %s", r.Method)
}
}
func (server *Server) initMux(mux *http.ServeMux) {
mux.HandleFunc("/", func(resp http.ResponseWriter, req *http.Request) {
resp.Header().Set("content-type", "text/html")
err := rootTmpl.Execute(resp, struct {
Readonly bool
Path string
}{
true,
server.RootObjectPath,
})
if err != nil {
log.Println(err)
}
})
mux.HandleFunc(contentDirectoryEventSubURL, server.contentDirectoryEventSubHandler)
mux.HandleFunc(iconPath, server.serveIcon)
mux.HandleFunc(resPath, func(w http.ResponseWriter, r *http.Request) {
filePath := server.filePath(r.URL.Query().Get("path"))
if ignored, err := server.IgnorePath(filePath); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
} else if ignored {
http.Error(w, "no such object", http.StatusNotFound)
return
}
k := r.URL.Query().Get("transcode")
if k == "" {
http.ServeFile(w, r, filePath)
return
}
if server.NoTranscode {
http.Error(w, "transcodes disabled", http.StatusNotFound)
return
}
spec, ok := transcodes[k]
if !ok {
http.Error(w, fmt.Sprintf("bad transcode spec key: %s", k), http.StatusBadRequest)
return
}
server.serveDLNATranscode(w, r, filePath, spec, k)
})
mux.HandleFunc(rootDescPath, func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("content-type", `text/xml; charset="utf-8"`)
w.Header().Set("content-length", fmt.Sprint(len(server.rootDescXML)))
w.Header().Set("server", serverField)
w.Write(server.rootDescXML)
})
handleSCPDs(mux)
mux.HandleFunc(serviceControlURL, server.serviceControlHandler)
mux.HandleFunc("/debug/pprof/", pprof.Index)
for i, di := range server.Icons {
mux.HandleFunc(fmt.Sprintf("%s/%d", deviceIconPath, i), func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", di.Mimetype)
http.ServeContent(w, r, "", time.Time{}, di.ReadSeeker)
})
}
}
func (s *Server) initServices() {
urn, err := upnp.ParseServiceType(services[0].ServiceType)
if err != nil {
panic(err)
}
s.services = map[string]UPnPService{
urn.Type: &contentDirectoryService{
Server: s,
},
}
}
func (srv *Server) Serve() (err error) {
srv.initServices()
srv.closed = make(chan struct{})
if srv.FriendlyName == "" {
srv.FriendlyName = getDefaultFriendlyName()
}
if srv.HTTPConn == nil {
srv.HTTPConn, err = net.Listen("tcp", "")
if err != nil {
return
}
}
if srv.Interfaces == nil {
ifs, err := net.Interfaces()
if err != nil {
log.Print(err)
}
var tmp []net.Interface
for _, if_ := range ifs {
if if_.Flags&net.FlagUp == 0 || if_.MTU <= 0 {
continue
}
tmp = append(tmp, if_)
}
srv.Interfaces = tmp
}
if srv.FFProbeCache == nil {
srv.FFProbeCache = dummyFFProbeCache{}
}
srv.httpServeMux = http.NewServeMux()
srv.rootDeviceUUID = makeDeviceUuid(srv.FriendlyName)
srv.rootDescXML, err = xml.MarshalIndent(
upnp.DeviceDesc{
SpecVersion: upnp.SpecVersion{Major: 1, Minor: 0},
Device: upnp.Device{
DeviceType: rootDeviceType,
FriendlyName: srv.FriendlyName,
Manufacturer: "Matt Joiner <anacrolix@gmail.com>",
ModelName: rootDeviceModelName,
UDN: srv.rootDeviceUUID,
ServiceList: func() (ss []upnp.Service) {
for _, s := range services {
ss = append(ss, s.Service)
}
return
}(),
IconList: func() (ret []upnp.Icon) {
for i, di := range srv.Icons {
ret = append(ret, upnp.Icon{
Height: di.Height,
Width: di.Width,
Depth: di.Depth,
Mimetype: di.Mimetype,
URL: fmt.Sprintf("%s/%d", deviceIconPath, i),
})
}
return
}(),
},
},
" ", " ")
if err != nil {
return
}
srv.rootDescXML = append([]byte(`<?xml version="1.0"?>`), srv.rootDescXML...)
log.Println("HTTP srv on", srv.HTTPConn.Addr())
srv.initMux(srv.httpServeMux)
srv.ssdpStopped = make(chan struct{})
go func() {
srv.doSSDP()
close(srv.ssdpStopped)
}()
return srv.serveHTTP()
}
func (srv *Server) Close() (err error) {
close(srv.closed)
err = srv.HTTPConn.Close()
<-srv.ssdpStopped
return
}
func didl_lite(chardata string) string {
return `<DIDL-Lite` +
` xmlns:dc="http://purl.org/dc/elements/1.1/"` +
` xmlns:upnp="urn:schemas-upnp-org:metadata-1-0/upnp/"` +
` xmlns="urn:schemas-upnp-org:metadata-1-0/DIDL-Lite/"` +
` xmlns:dlna="urn:schemas-dlna-org:metadata-1-0/">` +
chardata +
`</DIDL-Lite>`
}
func (me *Server) location(ip net.IP) string {
url := url.URL{
Scheme: "http",
Host: (&net.TCPAddr{
IP: ip,
Port: me.httpPort(),
}).String(),
Path: rootDescPath,
}
return url.String()
}
// Can return nil info with nil err if an earlier Probe gave an error.
func (srv *Server) ffmpegProbe(path string) (info *ffprobe.Info, err error) {
// We don't want relative paths in the cache.
path, err = filepath.Abs(path)
if err != nil {
return
}
fi, err := os.Stat(path)
if err != nil {
return
}
key := ffmpegInfoCacheKey{path, fi.ModTime().UnixNano()}
value, ok := srv.FFProbeCache.Get(key)
if !ok {
info, err = ffprobe.Run(path)
err = suppressFFmpegProbeDataErrors(err)
srv.FFProbeCache.Set(key, info)
return
}
info = value.(*ffprobe.Info)
return
}
// IgnorePath detects if a file/directory should be ignored.
func (server *Server) IgnorePath(path string) (bool, error) {
if !filepath.IsAbs(path) {
return false, fmt.Errorf("Path must be absolute: %s", path)
}
if server.IgnoreHidden {
if hidden, err := isHiddenPath(path); err != nil {
return false, err
} else if hidden {
return true, nil
}
}
if server.IgnoreUnreadable {
if readable, err := isReadablePath(path); err != nil {
return false, err
} else if !readable {
return true, nil
}
}
return false, nil
}
func tryToOpenPath(path string) (bool, error) {
// Ugly but portable way to check if we can open a file/directory
if fh, err := os.Open(path); err == nil {