Added directory scripts.
[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           (serve-records (with-selector-dir selector config
137                                             (lambda ()
138                                               (apply (eval sexp) arguments)))
139                          selector config)
140          (print ".\r"))
141         (error "No legal index script not found." filename))))
142
143 (define (serve-directory-file selector config)
144   (let ((filename (make-pathname (list (config-root-dir config) selector)
145                                  gopher-index-filename)))
146     (if (legal-filename? filename config)
147         (begin
148           (with-input-from-file filename
149             (lambda ()
150               (let loop ((c (peek-char)))
151                 (if (eof-object? c)
152                     'done
153                     (begin
154                       (if (eq? c #\,)
155                           (begin
156                             (read-char)
157                             (serve-record (read) selector config)
158                             (read-line))
159                           (serve-info-records (read-line)))
160                       (loop (peek-char)))))))
161           (if (config-display-footer config)
162               (serve-info-records burrower-footer))
163           (print ".\r"))
164         (error "No legal index file not found."))))
165   
166 (define (serve-text-file selector config)
167   (let ((filename (make-pathname (config-root-dir config) selector)))
168     (if (legal-filename? filename config)
169         (begin
170           (with-input-from-file filename
171             (lambda ()
172               (for-each
173                (lambda (line)
174                  (print line "\r"))
175                (read-lines))))
176           (print ".\r"))
177         (error "File not found." filename))))
178
179 (define (serve-binary-file selector config)
180   (let ((filename (make-pathname (config-root-dir config) selector)))
181     (if (legal-filename? filename config)
182         (with-input-from-file filename
183           (lambda ()
184             (let loop ((b (read-byte)))
185               (if (eof-object? b)
186                   'done
187                   (begin
188                     (write-byte b)
189                     (loop (read-byte)))))))
190         (error "File not found." filename))))
191
192 (define (serve-url selector config)
193   (let ((url (substring selector 4)))
194     (print
195      "<html><head><title>Redirection</title>"
196      "<meta http-equiv=\"refresh\" content=\"10; URL='" url "'\" />"
197      "</head><body>"
198      "<p>If you are seeing this page, your gopher browser does not "
199      "properly support URL directory entries or cannot follow such "
200      "links.</p>"
201      "<p>If you are viewing this page using a web browser, you should "
202      "be redirected shortly.  Otherwise, you can manually open the "
203      "the follwing url:\n"
204      "\n"
205      "<a href=\"" url "\">" url "</a>\n"
206      "</body></html>")))
207
208
209 ;;; Index rendering
210
211 (define (serve-records records dir-selector config)
212   (for-each
213    (lambda (record)
214      (serve-record record dir-selector config))
215    records))
216
217 (define (serve-info-records string)
218   (for-each
219    (lambda (line)
220      (print* "i")
221      (for-each (lambda (char)
222                  (print* (if (eq? char #\tab)
223                              "    "
224                              char)))
225                (string->list line))
226      (print "\tfake\tfake\t1\r"))
227    (string-split string "\n" #t)))
228
229 (define (serve-record record dir-selector config)
230   (match record
231     ((? string?) (serve-info-records record))
232     (('shell command) (serve-shell-command command dir-selector config))
233     (('eval expression) (serve-expression expression dir-selector config))
234     (('url display-string url)
235      (print #\h display-string "\tURL:" url
236             "\t" (config-host config)
237             "\t" (config-port config) "\r"))
238     ((type display-string selector host port)
239      (print type display-string "\t" selector "\t" host "\t" port "\r"))
240     ((type display-string selector host)
241      (serve-record (list type display-string selector host 70)
242                    dir-selector config))
243     ((type display-string selector)
244      (serve-record (list type display-string
245                          (make-pathname dir-selector selector)
246                          (config-host config) (config-port config))
247                    dir-selector config))
248     ((display-string selector)
249      (serve-record (list (infer-selector-type selector) display-string selector)
250                    dir-selector config))
251     ((selector)
252      (serve-record (list (infer-selector-type selector) selector)
253                    dir-selector config))
254     (else (error "Unknown record type."))))
255
256 (define (serve-shell-command command dir-selector config)
257   (with-selector-dir
258    dir-selector config
259    (lambda ()
260      (let-values (((in-port out-port id) (process command)))
261        (let ((string (read-string #f in-port)))
262          (if (and (not (eof-object? string))
263                   (> (string-length string) 0))
264              (serve-info-records (string-chomp string "\n"))))))))
265
266 (define (serve-expression expression dir-selector config)
267   (with-selector-dir
268    dir-selector config
269    (lambda ()
270      (serve-records (eval expression) dir-selector config))))
271
272
273 ;;; Utility methods
274
275 (define (with-current-working-directory directory thunk)
276   (let ((old-wd (current-directory))
277         (result 'none))
278     (condition-case
279         (begin
280           (change-directory directory)
281           (set! result (thunk))
282           (change-directory old-wd)
283           result)
284       (o (exn)
285          (change-directory old-wd)
286          (signal o)))))
287
288 (define (with-selector-dir selector config thunk)
289   (with-current-working-directory
290    (make-pathname (config-root-dir config)
291                   (pathname-directory selector)) thunk))
292
293
294 ;;; Main
295
296 (define (print-usage progname)
297   (print "Usage:\n"
298          progname " -h/--help\n"
299          progname " [-n/--no-footer] gopher-root-dir server-hostname [server-port]\n"
300          "\n"
301          "The -n option tells the server to not display a directory footer."))
302
303 (define (main)
304   (let* ((progname (car (argv)))
305          (args (cdr (argv)))
306          (config (make-config '() '() 70 #t)))
307
308     (if (or (null? args)
309             (equal? (car args) "-h")
310             (equal? (car args) "--help"))
311         (print-usage progname)
312         (begin
313           (if (or (equal? (car args) "-n")
314                   (equal? (car args) "--no-footer"))
315               (begin
316                 (config-display-footer-set! config #f)
317                 (set! args (cdr args))))
318           (if (or (< (length args) 2)
319                   (> (length args) 3))
320               (print-usage progname)
321               (begin
322                 (config-root-dir-set! config (car args))
323                 (config-host-set! config (cadr args))
324                 (if (= (length args) 3)
325                     (config-port-set! config (string->number (caddr args))))
326                 (run-server config)))))))
327
328 (main)
329
330 ;; (define (test)
331 ;;   (run-server (make-config "gopher-root" "localhost" 70 #t)))
332
333 ;; (test)