Still working on best way to serve active selectors.
[scratchy.git] / burrower.scm
1 ;;; Imports
2
3 ;; Chicken 5
4 (import (chicken tcp)
5         (chicken port)
6         (chicken io)
7         (chicken string)
8         (chicken pathname)
9         (chicken file)
10         (chicken time posix)
11         (chicken condition)
12         (chicken process)
13         (chicken process-context)
14         srfi-1 srfi-13 matchable)
15
16 ;; Chicken 4
17 ;; (use srfi-1 srfi-13 tcp posix matchable)
18
19 ;;; Global constants
20
21 (define gopher-index-filename "index")
22
23 (define burrower-version "1.0.0")
24
25 (define burrower-footer
26   (conc "\n"
27         "--------------------------------------------------\n"
28         "This gopher hole was dug using Burrower v" burrower-version ".\n"
29         "Powered by Chicken Scheme!"))
30
31 ;;; Server loop
32
33 ;; We don't yet use worker threads here to handle requests,
34 ;; the server just blocks until the first request is finished.
35 ;; While we should fix this, it's actually probably okay, as
36 ;; we genuinely don't expect a huge flood of gopher traffic. :-(
37
38 (define-record config root-dir host port display-footer)
39
40 (define (run-server config)
41   (set-buffering-mode! (current-output-port) #:line)
42   (print "Gopher server listening on port " (config-port config) " ...")
43   (let ((listener (tcp-listen (config-port config))))
44     (let server-loop ()
45       (let-values (((in-port out-port) (tcp-accept listener)))
46         (let* ((line (read-line in-port))
47                (selector (string-trim-both line)))
48           (let-values (((local-ip remote-ip) (tcp-addresses in-port)))
49             (print "Accepted connection from " remote-ip
50                    " on " (seconds->string))
51             (condition-case
52                 (begin
53                   (with-output-to-port out-port
54                     (lambda ()
55                       (serve-selector (if (= (string-length selector) 0)
56                                           "/"
57                                           selector)
58                                       config)))
59                   (print "... served selector '" selector "'. Closing connection."))
60               (o (exn)
61                  (print-error-message o out-port)
62                  (print-error-message o)
63                  (print "Error while attempting to serve selector " selector ".")))))
64         (close-input-port in-port)
65         (close-output-port out-port))
66       (server-loop))
67     (tcp-close listener)))
68
69
70 ;;; Selector type inference
71
72 (define (true-for-one? predicate values)
73   (if (null? values)
74       #f
75       (if (predicate (car values))
76           #t
77           (true-for-one? predicate (cdr values)))))
78
79 (define (has-suffix? selector . suffixes)
80   (true-for-one? (lambda (suffix)
81                    (string-suffix? suffix selector))
82                  suffixes))
83
84 (define (has-prefix? selector . prefixes)
85   (true-for-one? (lambda (prefix)
86                    (string-prefix? prefix selector))
87                  prefixes))
88
89 (define (infer-selector-type selector)
90   (let ((l (string-downcase selector)))
91     (cond
92      ((or (= (string-length l) 0)
93           (string-suffix? "/" l)
94           (string-contains l ":")) 1)
95      ((has-suffix? l ".txt" ".org" ".md") 0)
96      ((has-suffix? l ".png" ".jpg" ".gif" ".bmp" ".tif" ".tga") 'I)
97      ((has-suffix? l "?" "%3f") 7)
98      ((has-prefix? l "url:" "/url:") 'h)
99      (else 9))))
100
101
102 ;;; Selector retrieval
103
104 (define (serve-selector raw-selector config)
105   (let* ((selector-list (string-split raw-selector "\t"))
106          (selector (car selector-list))
107          (arguments (cdr selector-list)))
108     (case (infer-selector-type selector)
109       ((1) (if (string-contains selector ":")
110                (let ((l (string-split selector ":")))
111                  (serve-directory-script (car l) (cdr l)
112                                          config))
113                (serve-directory-file selector config)))
114       ((7) (let ((l (string-split selector "?")))
115              (serve-directory-script (car l) arguments config)))
116       ((0) (serve-text-file selector config))
117       ((h) (serve-url selector config))
118       (else (serve-binary-file selector config)))))
119
120 (define (legal-filename? filename config)
121   (and (string-prefix? (config-root-dir config)
122                        (normalize-pathname filename))
123        (file-exists? filename)
124        (not (directory-exists? filename))
125        (file-readable? filename)))
126
127 (define (legal-script-filename? filename config)
128   (and (legal-filename? filename config)
129        (string-suffix? ".scm" filename)
130        (file-executable? filename)))
131
132 (define (serve-directory-script selector arguments config)
133   (let ((filename (make-pathname (config-root-dir config) selector)))
134     (if (legal-script-filename? filename config)
135         (let* ((sexp (with-input-from-file filename read))
136                (selector-dir (pathname-directory selector)))
137           (serve-records (with-selector-dir
138                           selector config
139                           (lambda ()
140                             (apply (eval sexp) arguments)))
141                          selector-dir config)
142          (print ".\r"))
143         (error "No legal index script not found." filename))))
144
145 (define (serve-directory-file selector config)
146   (let ((filename (make-pathname (list (config-root-dir config) selector)
147                                  gopher-index-filename)))
148     (if (legal-filename? filename config)
149         (begin
150           (with-input-from-file filename
151             (lambda ()
152               (let loop ((c (peek-char)))
153                 (if (eof-object? c)
154                     'done
155                     (begin
156                       (if (eq? c #\,)
157                           (begin
158                             (read-char)
159                             (serve-record (read) selector config)
160                             (read-line))
161                           (serve-info-records (read-line)))
162                       (loop (peek-char)))))))
163           (if (config-display-footer config)
164               (serve-info-records burrower-footer))
165           (print ".\r"))
166         (error "No legal index file not found."))))
167   
168 (define (serve-text-file selector config)
169   (let ((filename (make-pathname (config-root-dir config) selector)))
170     (if (legal-filename? filename config)
171         (begin
172           (with-input-from-file filename
173             (lambda ()
174               (for-each
175                (lambda (line)
176                  (print line "\r"))
177                (read-lines))))
178           (print ".\r"))
179         (error "File not found." filename))))
180
181 (define (serve-binary-file selector config)
182   (let ((filename (make-pathname (config-root-dir config) selector)))
183     (if (legal-filename? filename config)
184         (with-input-from-file filename
185           (lambda ()
186             (let loop ((b (read-byte)))
187               (if (eof-object? b)
188                   'done
189                   (begin
190                     (write-byte b)
191                     (loop (read-byte)))))))
192         (error "File not found." filename))))
193
194 (define (serve-url selector config)
195   (let ((url (substring selector 4)))
196     (print
197      "<html><head><title>Redirection</title>"
198      "<meta http-equiv=\"refresh\" content=\"10; URL='" url "'\" />"
199      "</head><body>"
200      "<p>If you are seeing this page, your gopher browser does not "
201      "properly support URL directory entries or cannot follow such "
202      "links.</p>"
203      "<p>If you are viewing this page using a web browser, you should "
204      "be redirected shortly.  Otherwise, you can manually open the "
205      "the follwing url:\n"
206      "\n"
207      "<a href=\"" url "\">" url "</a>\n"
208      "</body></html>")))
209
210
211 ;;; Index rendering
212
213 (define (serve-records records dir-selector config)
214   (for-each
215    (lambda (record)
216      (serve-record record dir-selector config))
217    records))
218
219 (define (serve-info-records string)
220   (for-each
221    (lambda (line)
222      (print* "i")
223      (for-each (lambda (char)
224                  (print* (if (eq? char #\tab)
225                              "    "
226                              char)))
227                (string->list line))
228      (print "\tfake\tfake\t1\r"))
229    (string-split string "\n" #t)))
230
231 (define (serve-record record dir-selector config)
232   (match record
233     ((? string?) (serve-info-records record))
234     (('shell command) (serve-shell-command command dir-selector config))
235     (('eval expression) (serve-expression expression dir-selector config))
236     (('url display-string url)
237      (print #\h display-string "\tURL:" url
238             "\t" (config-host config)
239             "\t" (config-port config) "\r"))
240     ((type display-string selector host port)
241      (print type display-string "\t" selector "\t" host "\t" port "\r"))
242     ((type display-string selector host)
243      (serve-record (list type display-string selector host 70)
244                    dir-selector config))
245     ((type display-string selector)
246      (serve-record (list type display-string
247                          (make-pathname dir-selector selector)
248                          (config-host config) (config-port config))
249                    dir-selector config))
250     ((display-string selector)
251      (serve-record (list (infer-selector-type selector) display-string selector)
252                    dir-selector config))
253     ((selector)
254      (serve-record (list (infer-selector-type selector) selector)
255                    dir-selector config))
256     (else (error "Unknown record type."))))
257
258 (define (serve-shell-command command dir-selector config)
259   (with-selector-dir
260    dir-selector config
261    (lambda ()
262      (let-values (((in-port out-port id) (process command)))
263        (let ((string (read-string #f in-port)))
264          (if (and (not (eof-object? string))
265                   (> (string-length string) 0))
266              (serve-info-records (string-chomp string "\n"))))))))
267
268 (define (serve-expression expression dir-selector config)
269   (with-selector-dir
270    dir-selector config
271    (lambda ()
272      (serve-records (eval expression) dir-selector config))))
273
274
275 ;;; Utility methods
276
277 (define (with-current-working-directory directory thunk)
278   (let ((old-wd (current-directory))
279         (result 'none))
280     (condition-case
281         (begin
282           (change-directory directory)
283           (set! result (thunk))
284           (change-directory old-wd)
285           result)
286       (o (exn)
287          (change-directory old-wd)
288          (signal o)))))
289
290 (define (with-selector-dir selector config thunk)
291   (with-current-working-directory
292    (make-pathname (config-root-dir config)
293                   (pathname-directory selector)) thunk))
294
295
296 ;;; Main
297
298 (define (print-usage progname)
299   (print "Usage:\n"
300          progname " -h/--help\n"
301          progname " [-n/--no-footer] gopher-root-dir server-hostname [server-port]\n"
302          "\n"
303          "The -n option tells the server to not display a directory footer."))
304
305 (define (main)
306   (let* ((progname (car (argv)))
307          (args (cdr (argv)))
308          (config (make-config '() '() 70 #t)))
309
310     (if (or (null? args)
311             (equal? (car args) "-h")
312             (equal? (car args) "--help"))
313         (print-usage progname)
314         (begin
315           (if (or (equal? (car args) "-n")
316                   (equal? (car args) "--no-footer"))
317               (begin
318                 (config-display-footer-set! config #f)
319                 (set! args (cdr args))))
320           (if (or (< (length args) 2)
321                   (> (length args) 3))
322               (print-usage progname)
323               (begin
324                 (config-root-dir-set! config (car args))
325                 (config-host-set! config (cadr args))
326                 (if (= (length args) 3)
327                     (config-port-set! config (string->number (caddr args))))
328                 (run-server config)))))))
329
330 ;; (main)
331
332 (define (test)
333   (run-server (make-config "gopher-root" "localhost" 70 #t)))
334
335 (test)