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
|
package gophermap
import (
"bufio"
"bytes"
"context"
"errors"
"fmt"
"io"
"net/url"
"os"
"os/exec"
"path/filepath"
"sort"
"strconv"
"strings"
sr "tildegit.org/tjp/sliderule"
"tildegit.org/tjp/sliderule/gopher"
"tildegit.org/tjp/sliderule/internal"
"tildegit.org/tjp/sliderule/internal/types"
)
// ExtendedMapDocument is a gophermap doc with gophernicus's extensions
//
// These are documented at: gopher://gopher.gophernicus.org/0/docs/README.Gophermap
type ExtendedMapDocument struct {
Lines []gopher.MapItem
Location *url.URL
}
// ParseExtended parses a gophermap document including gophernicus extensions.
func ParseExtended(input io.Reader, location *url.URL) (*ExtendedMapDocument, error) {
rdr := bufio.NewReader(input)
doc := &ExtendedMapDocument{Location: location}
outer:
for num := 1; ; num += 1 {
var item gopher.MapItem
var spl []string
line, err := rdr.ReadString('\n')
isEOF := errors.Is(err, io.EOF)
if err != nil && !isEOF {
return nil, err
}
line = strings.TrimRight(line, "\r\n")
if len(line) > 0 {
switch line[0] {
case '#':
doc.Lines = append(doc.Lines, gopher.MapItem{
Type: CommentType,
Display: strings.TrimPrefix(line[1:], " "),
})
goto next
case '!':
doc.Lines = append(doc.Lines, gopher.MapItem{
Type: TitleType,
Display: line[1:],
})
goto next
case '-':
doc.Lines = append(doc.Lines, gopher.MapItem{
Type: HiddenType,
Selector: line[1:],
})
goto next
case ':':
doc.Lines = append(doc.Lines, gopher.MapItem{
Type: ExtensionType,
Display: line[1:],
})
goto next
case '=':
doc.Lines = append(doc.Lines, gopher.MapItem{
Type: InclusionType,
Selector: line[1:],
})
goto next
}
}
switch line {
case "~":
doc.Lines = append(doc.Lines, gopher.MapItem{Type: UserListType})
goto next
case "%":
doc.Lines = append(doc.Lines, gopher.MapItem{Type: VHostListType})
goto next
case ".":
doc.Lines = append(doc.Lines, gopher.MapItem{Type: EndDocType})
break outer
case "*":
doc.Lines = append(doc.Lines, gopher.MapItem{Type: DirListType})
break outer
}
if !strings.Contains(line, "\t") {
doc.Lines = append(doc.Lines, gopher.MapItem{
Type: gopher.InfoMessageType,
Display: line,
Selector: location.Path,
Hostname: location.Hostname(),
Port: location.Port(),
})
goto next
}
item = gopher.MapItem{Type: types.Status(line[0])}
spl = strings.Split(line[1:], "\t")
item.Display = string(spl[0])
if len(spl) == 1 {
item.Selector = location.Path
} else {
item.Selector = string(spl[1])
}
if len(spl) < 3 {
item.Hostname = location.Hostname()
} else {
item.Hostname = string(spl[2])
}
if len(spl) < 4 {
item.Port = location.Port()
} else {
item.Port = string(spl[3])
}
if _, err = strconv.Atoi(item.Port); err != nil {
return doc, InvalidLine(num)
}
doc.Lines = append(doc.Lines, item)
next:
if isEOF {
break
}
}
return doc, nil
}
// Extensions to gopher types from Gophernicus.
const (
// CommentType is omitted from generated compatible gophermaps.
CommentType types.Status = '#'
// TitleType defines the title of a gophermap document.
TitleType types.Status = '!'
// HiddenType hides a link from the generated compatible gophermap.
HiddenType types.Status = '-'
// ExtensionType defines the gopher type to use for files in the current directory with a given extension.
ExtensionType types.Status = ':'
// UserListType generates a list of users with valid ~/public_gopher directories.
UserListType types.Status = '~'
// VHostListType generates a listing of virtual hosts.
//
// It is not supported in sliderule.
VHostListType types.Status = '%'
// InclusionType causes another gophermap to be included at this location.
InclusionType types.Status = '='
// DirListType stops parsing the current file and ends the generated gophermap with a listing of the current directory.
DirListType types.Status = '*'
// EndDocType ends the current gophermap file.
EndDocType types.Status = '.'
)
type FileSystemSettings struct {
ParseExtended bool
Exec bool
ListUsers bool
DirMaps []string
DirTag string
}
// Compatible builds a standards-compliant gophermap from the current extended menu.
func (edoc *ExtendedMapDocument) Compatible(cwd string, settings FileSystemSettings) (gopher.MapDocument, string, error) {
doc := gopher.MapDocument{}
title := ""
hidden := map[string]struct{}{}
extensions := map[string]types.Status{}
lineloop:
for num, item := range edoc.Lines {
switch item.Type {
case CommentType:
case TitleType:
title = item.Display
case HiddenType:
hidden[item.Selector] = struct{}{}
case ExtensionType:
from, to, found := strings.Cut(item.Display, "=")
if !found {
return nil, "", InvalidLine(num + 1)
}
extensions[from] = types.Status(to[0])
case UserListType:
if !settings.ListUsers {
doc = append(doc, gopher.MapItem{
Type: gopher.InfoMessageType,
Display: "~",
Selector: edoc.Location.Path,
Hostname: edoc.Location.Hostname(),
Port: edoc.Location.Port(),
})
}
users, err := internal.ListUsersWithHomeSubdir("public_gopher", 4)
if err != nil {
return nil, "", err
}
sort.Strings(users)
for _, user := range users {
doc = append(doc, gopher.MapItem{
Type: gopher.MenuType,
Display: "~" + user,
Selector: "/~" + user,
Hostname: edoc.Location.Hostname(),
Port: edoc.Location.Port(),
})
}
case VHostListType:
return nil, "", errors.New("Virtual host listings '%' are not supported")
case InclusionType:
subEdoc, err := openExtended(item.Selector, edoc.Location, settings)
if err != nil {
return nil, "", err
}
lines, _, err := subEdoc.Compatible(filepath.Dir(item.Selector), settings)
if err != nil {
return nil, "", err
}
doc = append(doc, lines...)
case DirListType:
dirlist, err := listDir(cwd, edoc.Location, settings, hidden, extensions)
if err != nil {
return nil, "", err
}
doc = append(doc, dirlist...)
break lineloop
case EndDocType:
break lineloop
default:
doc = append(doc, item)
}
}
return doc, title, nil
}
func openExtended(path string, location *url.URL, settings FileSystemSettings) (*ExtendedMapDocument, error) {
file, err := os.Open(path)
if err != nil {
return nil, err
}
defer func() {
_ = file.Close()
}()
if settings.Exec {
info, err := file.Stat()
if err != nil {
return nil, err
}
m := info.Mode()
if m.IsRegular() && m&5 == 5 {
cmd := exec.Command(path)
cmd.Env = []string{}
cmd.Dir = filepath.Dir(path)
outbuf := &bytes.Buffer{}
cmd.Stdout = outbuf
if err := cmd.Run(); err != nil {
var exErr *exec.ExitError
if errors.As(err, &exErr) {
return nil, fmt.Errorf("Inclusion exec returned exit code %d", exErr.ExitCode())
}
return nil, err
}
return ParseExtended(outbuf, location)
}
}
return ParseExtended(file, location)
}
func ExtendMiddleware(fsroot, urlroot string, settings *FileSystemSettings) sr.Middleware {
return sr.Middleware(func(handler sr.Handler) sr.Handler {
return sr.HandlerFunc(func(ctx context.Context, request *sr.Request) *sr.Response {
response := handler.Handle(ctx, request)
if !settings.ParseExtended || response.Status != gopher.MenuType {
return response
}
defer func() { _ = response.Close() }()
edoc, err := ParseExtended(response.Body, request.URL)
if err != nil {
return gopher.Error(err).Response()
}
fpath := strings.TrimPrefix(request.Path, urlroot)
fpath = strings.Trim(fpath, "/")
fpath = filepath.Join(fsroot, fpath)
doc, _, err := edoc.Compatible(filepath.Dir(fpath), *settings)
if err != nil {
return gopher.Error(err).Response()
}
return doc.Response()
})
})
}
|