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