Removed test code which was accidentally committed.
[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     (if (string-contains selector ":")
109         (let ((l (string-split selector ":")))
110           (serve-script (car l) (cdr l) config))
111         (case (infer-selector-type selector)
112           ((1) (serve-directory-file selector config))
113           ((7) (let ((l (string-split selector "?")))
114                  (serve-script (car l) arguments config)))
115           ((0) (serve-text-file selector config))
116           ((h) (serve-url selector config))
117           (else (serve-binary-file selector config))))))
118
119 (define (legal-filename? filename config)
120   (and (string-prefix? (config-root-dir config)
121                        (normalize-pathname filename))
122        (file-exists? filename)
123        (not (directory-exists? filename))
124        (file-readable? filename)))
125
126 (define (legal-script-filename? filename config)
127   (and (legal-filename? filename config)
128        (string-suffix? ".scm" filename)
129        (file-executable? filename)))
130
131 (define (serve-directory-file selector config)
132   (let ((filename (make-pathname (list (config-root-dir config) selector)
133                                  gopher-index-filename)))
134     (if (legal-filename? filename config)
135         (begin
136           (with-input-from-file filename
137             (lambda ()
138               (let loop ((c (peek-char)))
139                 (if (eof-object? c)
140                     'done
141                     (begin
142                       (if (eq? c #\,)
143                           (begin
144                             (read-char)
145                             (serve-record (read) selector config)
146                             (read-line))
147                           (serve-info-records (read-line)))
148                       (loop (peek-char)))))))
149           (if (config-display-footer config)
150               (serve-info-records burrower-footer))
151           (print ".\r"))
152         (error "No legal index file not found."))))
153   
154 (define (serve-text-file selector config)
155   (let ((filename (make-pathname (config-root-dir config) selector)))
156     (if (legal-filename? filename config)
157         (begin
158           (with-input-from-file filename
159             (lambda ()
160               (for-each
161                (lambda (line)
162                  (print line "\r"))
163                (read-lines))))
164           (print ".\r"))
165         (error "File not found." filename))))
166
167 (define (serve-binary-file selector config)
168   (let ((filename (make-pathname (config-root-dir config) selector)))
169     (if (legal-filename? filename config)
170         (with-input-from-file filename
171           (lambda ()
172             (let loop ((b (read-byte)))
173               (if (eof-object? b)
174                   'done
175                   (begin
176                     (write-byte b)
177                     (loop (read-byte)))))))
178         (error "File not found." filename))))
179
180 (define (serve-url selector config)
181   (let ((url (substring selector 4)))
182     (print
183      "<html><head><title>Redirection</title>"
184      "<meta http-equiv=\"refresh\" content=\"10; URL='" url "'\" />"
185      "</head><body>"
186      "<p>If you are seeing this page, your gopher browser does not "
187      "properly support URL directory entries or cannot follow such "
188      "links.</p>"
189      "<p>If you are viewing this page using a web browser, you should "
190      "be redirected shortly.  Otherwise, you can manually open the "
191      "the follwing url:\n"
192      "\n"
193      "<a href=\"" url "\">" url "</a>\n"
194      "</body></html>")))
195
196 (define (serve-script selector arguments config)
197   (let ((filename (make-pathname (config-root-dir config) selector)))
198     (if (legal-script-filename? filename config)
199         (let* ((sexp (with-input-from-file filename read))
200                (script-result (with-selector-dir
201                                selector config
202                                (lambda ()
203                                  (apply (eval sexp) arguments)))))
204           (when (pair? script-result)
205             (serve-records script-result
206                            (pathname-directory selector) config)
207             (print ".\r")))
208         (error "No legal index script not found." filename))))
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          (close-input-port in-port)
268          (close-output-port out-port))))))
269
270 (define (serve-expression expression dir-selector config)
271   (with-selector-dir
272    dir-selector config
273    (lambda ()
274      (serve-records (eval expression) dir-selector config))))
275
276
277 ;;; Utility methods
278
279 (define (with-current-working-directory directory thunk)
280   (let ((old-wd (current-directory))
281         (result 'none))
282     (condition-case
283         (begin
284           (change-directory directory)
285           (set! result (thunk))
286           (change-directory old-wd)
287           result)
288       (o (exn)
289          (change-directory old-wd)
290          (signal o)))))
291
292 (define (with-selector-dir selector config thunk)
293   (with-current-working-directory
294    (make-pathname (config-root-dir config)
295                   (pathname-directory selector)) thunk))
296
297
298 ;;; Main
299
300 (define (print-usage progname)
301   (print "Usage:\n"
302          progname " -h/--help\n"
303          progname " [-n/--no-footer] gopher-root-dir server-hostname [server-port]\n"
304          "\n"
305          "The -n option tells the server to not display a directory footer."))
306
307 (define (main)
308   (let* ((progname (car (argv)))
309          (args (cdr (argv)))
310          (config (make-config '() '() 70 #t)))
311
312     (if (or (null? args)
313             (equal? (car args) "-h")
314             (equal? (car args) "--help"))
315         (print-usage progname)
316         (begin
317           (if (or (equal? (car args) "-n")
318                   (equal? (car args) "--no-footer"))
319               (begin
320                 (config-display-footer-set! config #f)
321                 (set! args (cdr args))))
322           (if (or (< (length args) 2)
323                   (> (length args) 3))
324               (print-usage progname)
325               (begin
326                 (config-root-dir-set! config (car args))
327                 (config-host-set! config (cadr args))
328                 (if (= (length args) 3)
329                     (config-port-set! config (string->number (caddr args))))
330                 (run-server config)))))))
331
332 (main)
333
334 ;; (define (test)
335 ;;   (run-server (make-config "gopher-root" "localhost" 70 #t)))
336
337 ;; (test)