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