Added missing termination periods to text and index output.
[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 posix)
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) (string-suffix? "/" l)) 1)
93      ((has-suffix? l ".txt" ".org" ".md") 0)
94      ((has-suffix? l ".png" ".jpg" ".gif" ".bmp" ".tif" ".tga") 'I)
95      ((has-suffix? l "?.scm" "%3f.scm") 7)
96      ((has-prefix? l "url:" "/url:") 'h)
97      (else 9))))
98
99
100 ;;; Selector retrieval
101
102 (define (serve-selector raw-selector config)
103   (let* ((selector-list (string-split raw-selector "\t"))
104          (selector (car selector-list))
105          (arguments (cdr selector-list)))
106     (case (infer-selector-type selector)
107       ((1) (serve-directory selector config))
108       ((0) (serve-text-file selector config))
109       ((7) (serve-query selector arguments config))
110       ((h) (serve-url selector config))
111       (else (serve-binary-file selector config)))))
112
113 (define (legal-filename? filename config)
114   (and (string-prefix? (config-root-dir config)
115                        (normalize-pathname filename))
116        (regular-file? filename)))
117
118 (define (serve-directory selector config)
119   (let ((filename (make-pathname (list (config-root-dir config) selector)
120                                  gopher-index-filename)))
121     (if (legal-filename? filename config)
122         (begin
123           (with-input-from-file filename
124             (lambda ()
125               (let loop ((c (peek-char)))
126                 (if (eof-object? c)
127                     'done
128                     (begin
129                       (if (eq? c #\,)
130                           (begin
131                             (read-char)
132                             (serve-record (read) selector config)
133                             (read-line))
134                           (serve-info-records (read-line)))
135                       (loop (peek-char)))))))
136           (if (config-display-footer config)
137               (serve-info-records burrower-footer))
138           (print ".\r"))
139         (error "Index file not found."))))
140   
141 (define (serve-text-file selector config)
142   (let ((filename (make-pathname (config-root-dir config) selector)))
143     (if (legal-filename? filename config)
144         (begin
145           (with-input-from-file filename
146             (lambda ()
147               (for-each
148                (lambda (line)
149                  (print line "\r"))
150                (read-lines))))
151           (print ".\r"))
152         (error "File not found." filename))))
153
154 (define (serve-binary-file selector config)
155   (let ((filename (make-pathname (config-root-dir config) selector)))
156     (if (legal-filename? filename config)
157         (with-input-from-file filename
158           (lambda ()
159             (let loop ((b (read-byte)))
160               (if (eof-object? b)
161                   'done
162                   (begin
163                     (write-byte b)
164                     (loop (read-byte)))))))
165         (error "File not found." filename))))
166
167 (define (serve-query selector arguments config)
168   (let ((filename (make-pathname (config-root-dir config)
169                                  (string-translate* selector '(("%3f" . "?"))))))
170     (if (and (legal-filename? filename config)
171              (= (length arguments) 1))
172         (with-input-from-file filename
173           (lambda ()
174             (serve-info-records
175              (with-selector-dir
176               selector config
177               (lambda ()
178                 (apply (eval (read)) arguments))))))
179         (error "Invalid query." selector arguments))))
180
181
182 (define (serve-url selector config)
183   (let ((url (substring selector 4)))
184     (print
185      "<html><head><title>Redirection</title>"
186      "<meta http-equiv=\"refresh\" content=\"10; URL='" url "'\" />"
187      "</head><body>"
188      "<p>If you are seeing this page, your gopher browser does not "
189      "properly support URL directory entries or cannot follow such "
190      "links.</p>"
191      "<p>If you are viewing this page using a web browser, you should "
192      "be redirected shortly.  Otherwise, you can manually open the "
193      "the follwing url:\n"
194      "\n"
195      "<a href=\"" url "\">" url "</a>\n"
196      "</body></html>")))
197
198
199 ;;; Index rendering
200
201 (define (serve-info-records string)
202   (for-each
203    (lambda (line)
204      (print* "i")
205      (for-each (lambda (char)
206                  (print* (if (eq? char #\tab)
207                              "    "
208                              char)))
209                (string->list line))
210      (print "\tfake\tfake\t1\r"))
211    (string-split string "\n" #t)))
212
213 (define (serve-record record dir-selector config)
214   (match record
215     (('shell command) (serve-shell-command command dir-selector config))
216     (('eval expression) (serve-expression expression dir-selector config))
217     (('url display-string url)
218      (print #\h display-string "\tURL:" url
219             "\t" (config-host config)
220             "\t" (config-port config) "\r"))
221     ((type display-string selector host port)
222      (print type display-string "\t" selector "\t" host "\t" port "\r"))
223     ((type display-string selector host)
224      (serve-record (list type display-string selector host 70)
225                    dir-selector config))
226     ((type display-string selector)
227      (serve-record (list type display-string
228                          (make-pathname dir-selector selector)
229                          (config-host config) (config-port config))
230                    dir-selector config))
231     ((display-string selector)
232      (serve-record (list (infer-selector-type selector) display-string selector)
233                    dir-selector config))
234     ((selector)
235      (serve-record (list (infer-selecto-type selector) selector)
236                    dir-selector config))
237     (else (error "Unknown record type."))))
238
239 (define (serve-shell-command command dir-selector config)
240   (with-selector-dir
241    dir-selector config
242    (lambda ()
243      (let-values (((in-port out-port id) (process command)))
244        (let ((string (read-string #f in-port)))
245          (if (and (not (eof-object? string))
246                   (> (string-length string) 0))
247              (serve-info-records (string-chomp string "\n"))))))))
248
249 (define (serve-expression expression dir-selector config)
250   (with-selector-dir
251    dir-selector config
252    (lambda ()
253      (serve-info-records (conc (eval expression))))))
254
255
256 ;;; Utility methods
257
258 (define (with-current-working-directory directory thunk)
259   (let ((old-wd (current-directory))
260         (result 'none))
261     (condition-case
262         (begin
263           (change-directory directory)
264           (set! result (thunk))
265           (change-directory old-wd)
266           result)
267       (o (exn)
268          (change-directory old-wd)
269          (signal o)))))
270
271 (define (with-selector-dir selector config thunk)
272   (with-current-working-directory
273    (make-pathname (config-root-dir config)
274                   (pathname-directory selector)) thunk))
275
276 ;;; main
277
278 (define (print-usage progname)
279   (print "Usage:\n"
280          progname " -h/--help\n"
281          progname " [-n/--no-footer] gopher-root-dir server-hostname [server-port]\n"
282          "\n"
283          "The -n option tells the server to not display a directory footer."))
284
285 (define (main)
286   (let* ((progname (car (argv)))
287          (args (cdr (argv)))
288          (config (make-config '() '() 70 #t)))
289
290     (if (or (null? args)
291             (equal? (car args) "-h")
292             (equal? (car args) "--help"))
293         (print-usage progname)
294         (begin
295           (if (or (equal? (car args) "-n")
296                   (equal? (car args) "--no-footer"))
297               (begin
298                 (config-display-footer-set! config #f)
299                 (set! args (cdr args))))
300           (if (or (< (length args) 2)
301                   (> (length args) 3))
302               (print-usage progname)
303               (begin
304                 (config-root-dir-set! config (car args))
305                 (config-host-set! config (cadr args))
306                 (if (= (length args) 3)
307                     (config-port-set! config (string->number (caddr args))))
308                 (run-server config)))))))
309
310 ;; (main)
311
312 (define (test)
313   (run-server (make-config "gopher-root" "localhost" 70 #t)))
314
315 ;; (test)