-
Notifications
You must be signed in to change notification settings - Fork 10
/
gopher.go
1388 lines (1192 loc) · 32.9 KB
/
gopher.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 gopher provides an implementation of the Gopher protocol (RFC 1436)
//
// Much of the API is similar in design to the net/http package of the
// standard library. To build custom Gopher servers implement handler
// functions or the `Handler{}` interface. Implementing a client is as
// simple as calling `gopher.Get(uri)` and passing in a `uri` such as
// `"gopher://gopher.floodgap.com/"`.
package gopher
import (
"bufio"
"bytes"
"crypto/rand"
"crypto/tls"
"encoding/json"
"errors"
"fmt"
"io"
"log"
"net"
"net/http"
"net/url"
"os"
"path"
"path/filepath"
"sort"
"strconv"
"strings"
"sync"
"golang.org/x/net/context"
)
// Item Types
const (
FILE = ItemType('0') // Item is a file
DIRECTORY = ItemType('1') // Item is a directory
PHONEBOOK = ItemType('2') // Item is a CSO phone-book server
ERROR = ItemType('3') // Error
BINHEX = ItemType('4') // Item is a BinHexed Macintosh file.
DOSARCHIVE = ItemType('5') // Item is DOS binary archive of some sort. (*)
UUENCODED = ItemType('6') // Item is a UNIX uuencoded file.
INDEXSEARCH = ItemType('7') // Item is an Index-Search server.
TELNET = ItemType('8') // Item points to a text-based telnet session.
BINARY = ItemType('9') // Item is a binary file! (*)
// (*) Client must read until the TCP connection is closed.
REDUNDANT = ItemType('+') // Item is a redundant server
TN3270 = ItemType('T') // Item points to a text-based tn3270 session.
GIF = ItemType('g') // Item is a GIF format graphics file.
IMAGE = ItemType('I') // Item is some kind of image file.
// non-standard
INFO = ItemType('i') // Item is an informational message
HTML = ItemType('h') // Item is a HTML document
AUDIO = ItemType('s') // Item is an Audio file
PNG = ItemType('p') // Item is a PNG Image
DOC = ItemType('d') // Item is a Document
)
const (
// END represents the terminator used in directory responses
END = byte('.')
// TAB is the delimiter used to separate item response parts
TAB = byte('\t')
// CRLF is the delimiter used per line of response item
CRLF = "\r\n"
// DEFAULT is the default item type
DEFAULT = BINARY
)
// contextKey is a value for use with context.WithValue. It's used as
// a pointer so it fits in an interface{} without allocation.
type contextKey struct {
name string
}
func (k *contextKey) String() string {
return "gopher context value " + k.name
}
var (
// ServerContextKey is a context key. It can be used in Gopher
// handlers with context.WithValue to access the server that
// started the handler. The associated value will be of type *Server.
ServerContextKey = &contextKey{"gopher-server"}
// LocalAddrContextKey is a context key. It can be used in
// Gopher handlers with context.WithValue to access the address
// the local address the connection arrived on.
// The associated value will be of type net.Addr.
LocalAddrContextKey = &contextKey{"local-addr"}
)
// ItemType represents the type of an item
type ItemType byte
// Return a human friendly represation of an ItemType
func (it ItemType) String() string {
switch it {
case FILE:
return "TXT"
case DIRECTORY:
return "DIR"
case PHONEBOOK:
return "PHO"
case ERROR:
return "ERR"
case BINHEX:
return "HEX"
case DOSARCHIVE:
return "ARC"
case UUENCODED:
return "UUE"
case INDEXSEARCH:
return "QRY"
case TELNET:
return "TEL"
case BINARY:
return "BIN"
case REDUNDANT:
return "DUP"
case TN3270:
return "TN3"
case GIF:
return "GIF"
case IMAGE:
return "IMG"
case INFO:
return "NFO"
case HTML:
return "HTM"
case AUDIO:
return "SND"
case PNG:
return "PNG"
case DOC:
return "DOC"
default:
return "???"
}
}
// Item describes an entry in a directory listing.
type Item struct {
Type ItemType `json:"type"`
Description string `json:"description"`
Selector string `json:"selector"`
Host string `json:"host"`
Port int `json:"port"`
// non-standard extensions (ignored by standard clients)
Extras []string `json:"extras"`
}
// ParseItem parses a line of text into an item
func ParseItem(line string) (item *Item, err error) {
parts := strings.Split(strings.Trim(line, "\r\n"), "\t")
if len(parts[0]) < 1 {
return nil, errors.New("no item type: " + string(line))
}
item = &Item{
Type: ItemType(parts[0][0]),
Description: string(parts[0][1:]),
Extras: make([]string, 0),
}
// Selector
if len(parts) > 1 {
item.Selector = string(parts[1])
} else {
item.Selector = ""
}
// Host
if len(parts) > 2 {
item.Host = string(parts[2])
} else {
item.Host = "null.host"
}
// Port
if len(parts) > 3 {
port, err := strconv.Atoi(string(parts[3]))
if err != nil {
// Ignore parsing errors for bad servers for INFO types
if item.Type != INFO {
return nil, err
}
item.Port = 0
}
item.Port = port
} else {
item.Port = 0
}
// Extras
if len(parts) >= 4 {
for _, v := range parts[4:] {
item.Extras = append(item.Extras, string(v))
}
}
return
}
// MarshalJSON serializes an Item into a JSON structure
func (i *Item) MarshalJSON() ([]byte, error) {
return json.Marshal(struct {
Type string `json:"type"`
Description string `json:"description"`
Selector string `json:"selector"`
Host string `json:"host"`
Port int `json:"port"`
Extras []string `json:"extras"`
}{
Type: string(i.Type),
Description: i.Description,
Selector: i.Selector,
Host: i.Host,
Port: i.Port,
Extras: i.Extras,
})
}
// MarshalText serializes an Item into an array of bytes
func (i *Item) MarshalText() ([]byte, error) {
b := []byte{}
b = append(b, byte(i.Type))
b = append(b, []byte(i.Description)...)
b = append(b, TAB)
b = append(b, []byte(i.Selector)...)
b = append(b, TAB)
b = append(b, []byte(i.Host)...)
b = append(b, TAB)
b = append(b, []byte(strconv.Itoa(i.Port))...)
for _, s := range i.Extras {
b = append(b, TAB)
b = append(b, []byte(s)...)
}
b = append(b, []byte(CRLF)...)
return b, nil
}
func (i *Item) isDirectoryLike() bool {
switch i.Type {
case DIRECTORY:
return true
case INDEXSEARCH:
return true
default:
return false
}
}
// Directory representes a Gopher Menu of Items
type Directory struct {
Items []*Item `json:"items"`
}
// ToJSON returns the Directory as JSON bytes
func (d *Directory) ToJSON() ([]byte, error) {
jsonBytes, err := json.Marshal(d)
return jsonBytes, err
}
// ToText returns the Directory as UTF-8 encoded bytes
func (d *Directory) ToText() ([]byte, error) {
var buffer bytes.Buffer
for _, i := range d.Items {
val, err := i.MarshalText()
if err != nil {
return nil, err
}
buffer.Write(val)
}
return buffer.Bytes(), nil
}
// Response represents a Gopher resource that
// Items contains a non-empty array of Item(s)
// for directory types, otherwise the Body
// contains the fetched resource (file, image, etc).
type Response struct {
Type ItemType
Dir Directory
Body io.Reader
}
// Get fetches a Gopher resource by URI
func Get(uri string) (*Response, error) {
u, err := url.Parse(uri)
if err != nil {
return nil, err
}
if u.Scheme != "gopher" {
return nil, errors.New("invalid scheme for uri")
}
var (
host string
port int
)
hostport := strings.Split(u.Host, ":")
if len(hostport) == 2 {
host = hostport[0]
n, err := strconv.ParseInt(hostport[1], 10, 32)
if err != nil {
return nil, err
}
port = int(n)
} else {
host, port = hostport[0], 70
}
var (
Type ItemType
Selector string
)
path := strings.TrimPrefix(u.Path, "/")
if len(path) > 2 {
Type = ItemType(path[0])
Selector = path[1:]
if u.RawQuery != "" {
Selector += "\t" + u.RawQuery
}
} else if len(path) == 1 {
Type = ItemType(path[0])
Selector = ""
} else {
Type = ItemType(DIRECTORY)
Selector = ""
}
i := Item{Type: Type, Selector: Selector, Host: host, Port: port}
res := Response{Type: i.Type}
if i.isDirectoryLike() {
d, err := i.FetchDirectory()
if err != nil {
return nil, err
}
res.Dir = d
} else {
reader, err := i.FetchFile()
if err != nil {
return nil, err
}
res.Body = reader
}
return &res, nil
}
// FetchFile fetches data, not directory information.
// Calling this on a DIRECTORY Item type
// or unsupported type will return an error.
func (i *Item) FetchFile() (io.Reader, error) {
if i.Type == DIRECTORY {
return nil, errors.New("cannot fetch a directory as a file")
}
conn, err := net.Dial("tcp", i.Host+":"+strconv.Itoa(i.Port))
if err != nil {
return nil, err
}
_, err = conn.Write([]byte(i.Selector + CRLF))
if err != nil {
conn.Close()
return nil, err
}
return conn, nil
}
// FetchDirectory fetches directory information, not data.
// Calling this on an Item whose type is not DIRECTORY will return an error.
func (i *Item) FetchDirectory() (Directory, error) {
if !i.isDirectoryLike() {
return Directory{}, errors.New("cannot fetch a file as a directory")
}
conn, err := net.Dial("tcp", i.Host+":"+strconv.Itoa(i.Port))
if err != nil {
return Directory{}, err
}
_, err = conn.Write([]byte(i.Selector + CRLF))
if err != nil {
return Directory{}, err
}
reader := bufio.NewReader(conn)
scanner := bufio.NewScanner(reader)
scanner.Split(bufio.ScanLines)
var items []*Item
for scanner.Scan() {
line := strings.Trim(scanner.Text(), "\r\n")
if len(line) == 0 {
continue
}
if len(line) == 1 && line[0] == END {
break
}
item, err := ParseItem(line)
if err != nil {
log.Printf("Error parsing %q: %q", line, err)
continue
}
items = append(items, item)
}
return Directory{items}, nil
}
// Request repsesnts an inbound request to a listening server.
// LocalHost and LocalPort may be used by the Handler for local links.
// These are specified in the call to ListenAndServe.
type Request struct {
conn net.Conn
Selector string
LocalHost string
LocalPort int
}
// A Handler responds to a Gopher request.
//
// ServeGopher should write data or items to the ResponseWriter
// and then return. Returning signals that the request is finished; it
// is not valid to use the ResponseWriter concurrently with the completion
// of the ServeGopher call.
//
// Handlers should not modify the provided request.
//
// If ServeGopher panics, the server (the caller of ServeGopher) assumes
// that the effect of the panic was isolated to the active request.
// It recovers the panic, logs a stack trace to the server error log,
// and hangs up the connection.
type Handler interface {
ServeGopher(ResponseWriter, *Request)
}
// FileExtensions defines a mapping of known file extensions to gopher types
var FileExtensions = map[string]ItemType{
".txt": FILE,
".gif": GIF,
".jpg": IMAGE,
".jpeg": IMAGE,
".png": IMAGE,
".html": HTML,
".ogg": AUDIO,
".mp3": AUDIO,
".wav": AUDIO,
".mod": AUDIO,
".it": AUDIO,
".xm": AUDIO,
".mid": AUDIO,
".vgm": AUDIO,
".s": FILE,
".c": FILE,
".py": FILE,
".h": FILE,
".md": FILE,
".go": FILE,
".fs": FILE,
}
// MimeTypes defines a mapping of known mimetypes to gopher types
var MimeTypes = map[string]ItemType{
"text/html": HTML,
"text/*": FILE,
"image/gif": GIF,
"image/*": IMAGE,
"audio/*": AUDIO,
"application/x-tar": DOSARCHIVE,
"application/x-gtar": DOSARCHIVE,
"application/x-xz": DOSARCHIVE,
"application/x-zip": DOSARCHIVE,
"application/x-gzip": DOSARCHIVE,
"application/x-bzip2": DOSARCHIVE,
}
func matchExtension(f os.FileInfo) ItemType {
extension := strings.ToLower(filepath.Ext(f.Name()))
k, ok := FileExtensions[extension]
if !ok {
return DEFAULT
}
return k
}
func matchMimeType(mimeType string) ItemType {
for k, v := range MimeTypes {
matched, err := filepath.Match(k, mimeType)
if !matched || (err != nil) {
continue
}
return v
}
return DEFAULT
}
// GetItemType returns the Gopher Type of the given path
func GetItemType(p string) ItemType {
fi, err := os.Stat(p)
if err != nil {
return DEFAULT
}
if fi.IsDir() {
return DIRECTORY
}
f, err := os.Open(p)
if err != nil {
return matchExtension(fi)
}
b := make([]byte, 512)
n, err := io.ReadAtLeast(f, b, 512)
if (err != nil) || (n != 512) {
return matchExtension(fi)
}
mimeType := http.DetectContentType(b)
mimeParts := strings.Split(mimeType, ";")
return matchMimeType(mimeParts[0])
}
// Server defines parameters for running a Gopher server.
// A zero value for Server is valid configuration.
type Server struct {
//Addr string // TCP address to listen on, ":gopher" if empty
Handler Handler // handler to invoke, gopher.DefaultServeMux if nil
LocalHostname string //FQDN Hostname to bind on
RemoteHostname string // FQDN Hostname to reach this server on
Port string
// ErrorLog specifies an optional logger for errors accepting
// connections and unexpected behavior from handlers.
// If nil, logging goes to os.Stderr via the log package's
// standard logger.
ErrorLog *log.Logger
}
// serverHandler delegates to either the server's Handler or
// DefaultServeMux and also handles "OPTIONS *" requests.
type serverHandler struct {
s *Server
}
func (sh serverHandler) ServeGopher(rw ResponseWriter, req *Request) {
handler := sh.s.Handler
if handler == nil {
handler = DefaultServeMux
}
handler.ServeGopher(rw, req)
}
// ListenAndServe starts serving gopher requests using the given Handler.
// The address passed to ListenAndServe should be an internet-accessable
// domain name, optionally followed by a colon and the port number.
//
// If the address is not a FQDN, LocalHost as passed to the Handler
// may not be accessible to clients, so links may not work.
func (s *Server) ListenAndServe() error {
addrPort := s.Port
if addrPort == "" {
addrPort = ":70"
}
localHost := s.LocalHostname
if localHost == "" {
localHost = "localhost"
}
ln, err := net.Listen("tcp", localHost+":"+addrPort)
if err != nil {
return err
}
return s.Serve(ln)
}
// ListenAndServeTLS listens on the TCP network address srv.Addr and
// then calls Serve to handle requests on incoming TLS connections.
// Accepted connections are configured to enable TCP keep-alives.
//
// Filenames containing a certificate and matching private key for the
// server must be provided if neither the Server's TLSConfig.Certificates
// nor TLSConfig.GetCertificate are populated. If the certificate is
// signed by a certificate authority, the certFile should be the
// concatenation of the server's certificate, any intermediates, and
// the CA's certificate.
//
// If srv.Addr is blank, ":gophers" is used (port 73).
//
// ListenAndServeTLS always returns a non-nil error.
func (s *Server) ListenAndServeTLS(certFile, keyFile string) error {
addrPort := s.Port
if addrPort == "" {
addrPort = ":73"
}
localHost := s.LocalHostname
if localHost == "" {
localHost = "localhost"
}
cert, err := tls.LoadX509KeyPair(certFile, keyFile)
if err != nil {
log.Fatalf("server: loadkeys: %s", err)
}
config := tls.Config{Certificates: []tls.Certificate{cert}}
config.Rand = rand.Reader
ln, err := tls.Listen("tcp", localHost+addrPort, &config)
if err != nil {
log.Fatalf("server: listen: %s", err)
}
return s.Serve(ln)
}
// Serve ...
func (s *Server) Serve(l net.Listener) error {
defer l.Close()
ctx := context.Background()
ctx = context.WithValue(ctx, ServerContextKey, s)
ctx = context.WithValue(ctx, LocalAddrContextKey, l.Addr())
for {
rw, err := l.Accept()
if err != nil {
fmt.Errorf("error accepting new client: %s", err)
return err
}
c := s.newConn(rw)
go c.serve(ctx)
}
}
// A conn represents the server side of a Gopher connection.
type conn struct {
// server is the server on which the connection arrived.
// Immutable; never nil.
server *Server
// rwc is the underlying network connection.
// This is never wrapped by other types and is the value given out
// to CloseNotifier callers. It is usually of type *net.TCPConn or
// *tls.Conn.
rwc net.Conn
// remoteAddr is rwc.RemoteAddr().String(). It is not populated synchronously
// inside the Listener's Accept goroutine, as some implementations block.
// It is populated immediately inside the (*conn).serve goroutine.
// This is the value of a Handler's (*Request).RemoteAddr.
remoteAddr string
// tlsState is the TLS connection state when using TLS.
// nil means not TLS.
tlsState *tls.ConnectionState
// mu guards hijackedv, use of bufr, (*response).closeNotifyCh.
mu sync.Mutex
}
// Create new connection from rwc.
func (s *Server) newConn(rwc net.Conn) *conn {
c := &conn{
server: s,
rwc: rwc,
}
return c
}
func (c *conn) serve(ctx context.Context) {
c.remoteAddr = c.rwc.RemoteAddr().String()
w, err := c.readRequest(ctx)
if err != nil {
if err == io.EOF {
return // don't reply
}
if neterr, ok := err.(net.Error); ok && neterr.Timeout() {
return // don't reply
}
io.WriteString(c.rwc, "3\tbad request\terror.host\t0")
return
}
serverHandler{c.server}.ServeGopher(w, w.req)
w.End()
}
func readRequest(rwc net.Conn) (req *Request, err error) {
reader := bufio.NewReader(rwc)
scanner := bufio.NewScanner(reader)
scanner.Split(bufio.ScanLines)
scanner.Scan()
req = &Request{
Selector: scanner.Text(),
}
// If empty selector, assume /
if req.Selector == "" {
req.Selector = "/"
}
// If no leading / prefix, add one
if !strings.HasPrefix(req.Selector, "/") {
req.Selector = "/" + req.Selector
}
return req, nil
}
func (c *conn) close() (err error) {
c.mu.Lock() // while using bufr
err = c.rwc.Close()
c.mu.Unlock()
return
}
func (c *conn) readRequest(ctx context.Context) (w *response, err error) {
c.mu.Lock() // while using bufr
req, err := readRequest(c.rwc)
c.mu.Unlock()
if err != nil {
return nil, err
}
localaddr := ctx.Value(LocalAddrContextKey).(*net.TCPAddr)
host, port, err := net.SplitHostPort(localaddr.String())
if err != nil {
return nil, err
}
n, err := strconv.ParseInt(port, 10, 32)
if err != nil {
return nil, err
}
server := ctx.Value(ServerContextKey).(*Server)
if server.RemoteHostname == "" {
req.LocalHost = host
req.LocalPort = int(n)
} else {
req.LocalHost = server.RemoteHostname
// TODO: Parse this from -bind option
req.LocalPort = int(n)
}
w = &response{
conn: c,
req: req,
}
w.w = bufio.NewWriter(c.rwc)
return w, nil
}
func (s *Server) logf(format string, args ...interface{}) {
if s.ErrorLog != nil {
s.ErrorLog.Printf(format, args...)
} else {
log.Printf(format, args...)
}
}
// ListenAndServe listens on the TCP network address addr
// and then calls Serve with handler to handle requests
// on incoming connections.
//
// A trivial example server is:
//
// package main
//
// import (
// "io"
// "log"
//
// "github.com/prologic/go-gopher"
// )
//
// // hello world, the gopher server
// func HelloServer(w gopher.ResponseWriter, req *gopher.Request) {
// w.WriteInfo("hello, world!")
// }
//
// func main() {
// gopher.HandleFunc("/hello", HelloServer)
// log.Fatal(gopher.ListenAndServe(":7000", nil))
// }
//
// ListenAndServe always returns a non-nil error.
func ListenAndServe(remote string, local string, port string, handler Handler) error {
server := &Server{LocalHostname: local, RemoteHostname: remote, Port: port, Handler: handler}
return server.ListenAndServe()
}
// ListenAndServeTLS acts identically to ListenAndServe, except that it
// expects TLS connections. Additionally, files containing a certificate and
// matching private key for the server must be provided. If the certificate
// is signed by a certificate authority, the certFile should be the
// concatenation of the server's certificate, any intermediates,
// and the CA's certificate.
//
// A trivial example server is:
//
// import (
// "log"
//
// "github.com/prologic/go-gopher",
// )
//
// func HelloServer(w gopher.ResponseWriter, req *gopher.Request) {
// w.WriteInfo("hello, world!")
// }
//
// func main() {
// gopher.HandleFunc("/", handler)
// log.Printf("About to listen on 73. Go to gophers://127.0.0.1:73/")
// err := gopher.ListenAndServeTLS(":73", "cert.pem", "key.pem", nil)
// log.Fatal(err)
// }
//
// One can use generate_cert.go in crypto/tls to generate cert.pem and key.pem.
//
// ListenAndServeTLS always returns a non-nil error.
func ListenAndServeTLS(remote string, local string, port string, certFile, keyFile string, handler Handler) error {
server := &Server{LocalHostname: local, RemoteHostname: remote, Port: port, Handler: handler}
return server.ListenAndServeTLS(certFile, keyFile)
}
// ServeMux is a Gopher request multiplexer.
// It matches the URL of each incoming request against a list of registered
// patterns and calls the handler for the pattern that
// most closely matches the URL.
//
// Patterns name fixed, rooted paths, like "/favicon.ico",
// or rooted subtrees, like "/images/" (note the trailing slash).
// Longer patterns take precedence over shorter ones, so that
// if there are handlers registered for both "/images/"
// and "/images/thumbnails/", the latter handler will be
// called for paths beginning "/images/thumbnails/" and the
// former will receive requests for any other paths in the
// "/images/" subtree.
//
// Note that since a pattern ending in a slash names a rooted subtree,
// the pattern "/" matches all paths not matched by other registered
// patterns, not just the URL with Path == "/".
//
// If a subtree has been registered and a request is received naming the
// subtree root without its trailing slash, ServeMux redirects that
// request to the subtree root (adding the trailing slash). This behavior can
// be overridden with a separate registration for the path without
// the trailing slash. For example, registering "/images/" causes ServeMux
// to redirect a request for "/images" to "/images/", unless "/images" has
// been registered separately.
//
// ServeMux also takes care of sanitizing the URL request path,
// redirecting any request containing . or .. elements or repeated slashes
// to an equivalent, cleaner URL.
type ServeMux struct {
mu sync.RWMutex
m map[string]muxEntry
}
type muxEntry struct {
explicit bool
h Handler
pattern string
}
// NewServeMux allocates and returns a new ServeMux.
func NewServeMux() *ServeMux { return new(ServeMux) }
// DefaultServeMux is the default ServeMux used by Serve.
var DefaultServeMux = &defaultServeMux
var defaultServeMux ServeMux
// Does selector match pattern?
func selectorMatch(pattern, selector string) bool {
if len(pattern) == 0 {
// should not happen
return false
}
n := len(pattern)
if pattern[n-1] != '/' {
return pattern == selector
}
return len(selector) >= n && selector[0:n] == pattern
}
// Return the canonical path for p, eliminating . and .. elements.
func cleanPath(p string) string {
if p == "" {
return "/"
}
if p[0] != '/' {
p = "/" + p
}
np := path.Clean(p)
// path.Clean removes trailing slash except for root;
// put the trailing slash back if necessary.
if p[len(p)-1] == '/' && np != "/" {
np += "/"
}
return np
}
// Find a handler on a handler map given a path string
// Most-specific (longest) pattern wins
func (mux *ServeMux) match(selector string) (h Handler, pattern string) {
var n = 0
for k, v := range mux.m {
if !selectorMatch(k, selector) {
continue
}
if h == nil || len(k) > n {
n = len(k)
h = v.h
pattern = v.pattern
}
}
return
}
// Handler returns the handler to use for the given request,
// consulting r.Selector. It always returns
// a non-nil handler.
//
// Handler also returns the registered pattern that matches the request.
//
// If there is no registered handler that applies to the request,
// Handler returns a ``resource not found'' handler and an empty pattern.
func (mux *ServeMux) Handler(r *Request) (h Handler, pattern string) {
return mux.handler(r.Selector)
}
// handler is the main implementation of Handler.
func (mux *ServeMux) handler(selector string) (h Handler, pattern string) {
mux.mu.RLock()
defer mux.mu.RUnlock()
h, pattern = mux.match(selector)
if h == nil {
h, pattern = NotFoundHandler(), ""
}
return
}
// ServeGopher dispatches the request to the handler whose
// pattern most closely matches the request URL.
func (mux *ServeMux) ServeGopher(w ResponseWriter, r *Request) {
h, _ := mux.Handler(r)
h.ServeGopher(w, r)
}
// Handle registers the handler for the given pattern.
// If a handler already exists for pattern, Handle panics.
func (mux *ServeMux) Handle(pattern string, handler Handler) {
mux.mu.Lock()
defer mux.mu.Unlock()
if pattern == "" {
panic("gopher: invalid pattern " + pattern)
}
if handler == nil {
panic("gopher: nil handler")