Maintain a persistent environment for evals.
[rags.git] / rags.scm
1 ;; The Right-Awful Gemini Server
2 ;; 
3 ;; This is a gemini server in the spirit of the
4 ;; scratchy gopher server.  Just as for that server,
5 ;; rags uses runtime evaluation of embedded scheme
6 ;; expressions to provide dynamically generated content.
7 ;; 
8 ;; See the readme for details.
9
10 (import (chicken io)
11         (chicken port)
12         (chicken file)
13         (chicken string)
14         (chicken pathname)
15         (chicken condition)
16         (chicken time posix)
17         (chicken process)
18         (chicken process-context)
19         (chicken process-context posix)
20         matchable srfi-13 srfi-1
21         uri-common tcp6 openssl)
22
23 (define-record config
24   root-dir host port certfile keyfile uid gid) 
25
26 (define file-types
27   '(("gmi" "text/gemini" "charset=utf-8")
28     ("txt" "text/plain" "charset=utf-8")
29     ("csv" "text/csv" "charset=utf-8")
30     ("html" "text/html" "charset=utf-8")
31     ("xml" "text/xml" "charset=utf-8")
32     ("pdf" "application/pdf")
33     ("zip" "application/zip")
34     ("jpg" "image/jpeg")
35     ("jpeg" "image/jpeg")
36     ("png" "image/png")
37     ("mp3" "audio/mpeg")))
38
39 (define eval-env-file "eval-env.scm")
40 (define eval-env (interaction-environment))
41
42 (define (process-request config request-line)
43   (let ((uri (uri-normalize-path-segments (absolute-uri request-line))))
44     (cond
45      ((not (eq? (uri-scheme uri) 'gemini))
46       (fail-permanent "Unsupported scheme."))
47      ((not (uri-host uri))
48       (fail-permanent "URL lacks host name."))
49      ((not (equal? (uri-host uri) (config-host config)))
50       (fail-permanent "Proxy requests forbidden."))
51      ((uri-path-relative? uri)
52       (fail-permanent "Path must be absolute."))
53      ((not (document-available? config uri))
54       (fail-permanent "Document not found."))
55      ((and (document-path-directory? config uri)
56            (uri-lacks-trailing-slash? uri))
57       (redirect-permanent (uri-with-trailing-slash uri)))
58      ((document-script? config uri)
59       (serve-script config uri))
60      (else 
61       (serve-document config uri)))))
62
63 (define (fail-permanent reason)
64   (print "50 " reason "\r"))
65
66 (define (redirect-permanent new-uri)
67   (print "30 " (uri->string new-uri) "\r"))
68
69 (define (serve-query prompt)
70   (print "10 " prompt "\r"))
71
72 (define (uri-lacks-trailing-slash? uri)
73   (not (string-null? (last (uri-path uri)))))
74
75 (define (uri-with-trailing-slash uri)
76   (update-uri uri path: (append (uri-path uri) '(""))))
77
78 (define (document-available? config uri)
79   (file-exists? (document-path config uri)))
80
81 (define (document-script? config uri)
82   (let ((path (document-path config uri)))
83     (and (file-exists? path)
84          (file-executable? path)
85          (equal? (pathname-extension path) "scm"))))
86
87 (define (document-path-directory? config uri)
88   (directory-exists? (document-path-raw config uri)))
89
90 (define (document-path-raw config uri)
91   (let* ((crumbs (reverse (cons (config-root-dir config) (cdr (uri-path uri))))))
92     (make-pathname (reverse (cdr crumbs)) (car crumbs))))
93
94 (define (document-path config uri)
95   (let* ((path (document-path-raw config uri)))
96     (if (directory-exists? path)
97         (make-pathname path "index.gmi")
98         path)))
99
100 (define (ext->mime ext)
101   (let* ((mime-detected (assoc ext file-types)))
102     (cdr (if mime-detected
103              mime-detected
104              (assoc "txt" file-types)))))
105
106 (define (serve-document-header mime)
107   (print "20 " (string-intersperse mime ";") "\r"))
108     
109 (define (serve-document config uri)
110   (let* ((path (document-path config uri))
111          (ext (pathname-extension path))
112          (mime (ext->mime ext)))
113     (serve-document-header mime)
114     (cond 
115      ((file-executable? path)
116       (serve-text-dynamic path)) ; Binary-files can also be generated here, but the source is dynamic text
117      ((string-prefix? "text/" (car mime))
118       (serve-text-plain path))
119      (else (serve-binary path)))))
120
121 (define (serve-text-plain path)
122   (with-input-from-file path
123     (lambda ()
124       (let loop ((str (read-string)))
125         (unless (eof-object? str)
126           (print* str)
127           (loop (read-string)))))))
128
129 (define (serve-text-dynamic path)
130   (with-input-from-file path
131     (lambda ()
132       (let loop ((c (peek-char)))
133         (if (eof-object? c)
134             'done
135             (begin
136               (if (eq? c #\,)
137                   (begin
138                     (read-char)
139                     (serve-dynamic-element (read) (pathname-directory path))
140                     (read-line))
141                   (print (read-line)))
142               (loop (peek-char))))))))
143                               
144 (define (serve-dynamic-element element working-directory)
145   (match element
146     (('eval expression)
147      (with-current-working-directory
148       working-directory
149       (lambda ()
150         (eval expression eval-env))))
151     (('shell command)
152      (with-current-working-directory
153       working-directory
154       (lambda ()
155         (let-values (((in-port out-port id) (process command)))
156           (let ((string (read-string #f in-port)))
157             (unless (eof-object? string)
158               (print string))
159             (close-input-port in-port)
160             (close-output-port out-port))))))
161     (else (error "Unknown element type."))))
162
163 (define (serve-script config uri)
164   ;; Scripts are responsible for the entire response, including header
165   (let* ((path (document-path config uri))
166          (proc (eval (with-input-from-file path read) eval-env)))
167     (with-current-working-directory
168      (pathname-directory (document-path config uri))
169      (lambda ()
170        (apply proc (list uri))))))
171
172 (define (with-current-working-directory directory thunk)
173   (let ((old-wd (current-directory))
174         (result 'none))
175     (condition-case
176         (begin
177           (change-directory directory)
178           (set! result (thunk))
179           (change-directory old-wd)
180           result)
181       (o (exn)
182          (change-directory old-wd)
183          (signal o)))))
184
185 (define (run-server config)
186   (set-buffering-mode! (current-output-port) #:line)
187   (define listener (ssl-listen* port: (config-port config)
188                                 certificate: (config-certfile config)
189                                 private-key: (config-keyfile config)
190                                 protocol: 'tlsv12))
191
192   (print "Host: '" (config-host config) "'\n"
193          "Port: '" (config-port config) "'\n"
194          "Root directory: '" (config-root-dir config) "'\n"
195          "Cert file: '" (config-certfile config) "'\n"
196          "Key file: '" (config-keyfile config) "'\n")
197
198   (print* "Dropping privilages ... ")
199   (drop-privs config)
200   (print "done")
201
202   (print* "Setting up environment ... ")
203   (setup-env config)
204   (print "done")
205
206   (print "\nGemini server listening ...")
207   (server-loop listener config))
208
209 (define (setup-env config)
210   (with-current-working-directory
211    (config-root-dir config)
212    (lambda ()
213      (if (and (file-exists? eval-env-file) (file-readable? eval-env-file))
214          (with-input-from-file eval-env-file
215            (lambda ()
216              (let loop ((next-expr (read)))
217                (unless (eof-object? next-expr)
218                  (eval next-expr eval-env)
219                  (loop (read))))))))))
220
221 (define (drop-privs config)
222   (let ((uid (config-uid config))
223         (gid (config-gid config)))
224     (if gid ; Group first, since only root can switch groups.
225         (set! (current-group-id) gid))
226     (if uid
227         (set! (current-user-id) uid))))
228
229
230 (define (server-loop listener config)
231   (let-values (((in-port out-port) (ssl-accept listener)))
232     (let-values (((local-ip remote-ip) (tcp-addresses (ssl-port->tcp-port in-port))))
233       (print "Accepted connection from " remote-ip
234              " on " (seconds->string))
235       (condition-case
236           (let ((request-line (read-line in-port)))
237             (print* "Serving request '" request-line "' ... ")
238             (with-output-to-port out-port
239               (lambda ()
240                 (process-request config request-line)))
241             (print "done."))
242         (o (exn)
243            (print-error-message o))))
244     (close-input-port in-port)
245     (close-output-port out-port))
246   (server-loop listener config))
247
248
249 (define (print-usage progname)
250   (let ((indent-str (make-string (string-length progname) #\space)))
251     (print "Usage:\n"
252            progname " [-h/--help]\n"
253            progname " [-p/--port PORT] [-u/--user UID] [-g/--group GID]\n"
254            indent-str " server-root-dir hostname certfile keyfile")))
255
256 (define (main)
257   (let* ((progname (pathname-file (car (argv))))
258          (config (make-config #f #f 1965 #f #f #f #f)))
259     (if (null? (command-line-arguments))
260         (print-usage progname)
261         (let loop ((args (command-line-arguments)))
262           (let ((this-arg (car args))
263                 (rest-args (cdr args)))
264             (if (string-prefix? "-" this-arg)
265                 (cond
266                  ((or (equal? this-arg "-h")
267                       (equal? this-arg "--help"))
268                   (print-usage progname))
269                  ((or (equal? this-arg "-p")
270                       (equal? this-arg "--port"))
271                   (config-port-set! config (string->number (car rest-args)))
272                   (loop (cdr rest-args)))
273                  ((or (equal? this-arg "-u")
274                       (equal? this-arg "--user"))
275                   (config-uid-set! config (string->number (car rest-args)))
276                   (loop (cdr rest-args)))
277                  ((or (equal? this-arg "-g")
278                       (equal? this-arg "--group"))
279                   (config-gid-set! config (string->number (car rest-args)))
280                   (loop (cdr rest-args)))
281                  (else
282                   (print-usage progname)))
283                 (match args
284                   ((root-dir host certfile keyfile)
285                    (config-root-dir-set! config root-dir)
286                    (config-host-set! config host)
287                    (config-certfile-set! config certfile)
288                    (config-keyfile-set! config keyfile)
289                    (run-server config))
290                   (else
291                    (print "One or more invalid arguments.")
292                    (print-usage progname)))))))))
293
294 (main)