Scripts now evaluated with cwd set to their location.
[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 (process-request config request-line)
40   (let ((uri (uri-normalize-path-segments (absolute-uri request-line))))
41     (cond
42      ((not (eq? (uri-scheme uri) 'gemini))
43       (fail-permanent "Unsupported scheme."))
44      ((not (uri-host uri))
45       (fail-permanent "URL lacks host name."))
46      ((not (equal? (uri-host uri) (config-host config)))
47       (fail-permanent "Proxy requests forbidden."))
48      ((uri-path-relative? uri)
49       (fail-permanent "Path must be absolute."))
50      ((not (document-available? config uri))
51       (fail-permanent "Document not found."))
52      ((and (document-path-directory? config uri)
53            (uri-lacks-trailing-slash? uri))
54       (redirect-permanent (uri-with-trailing-slash uri)))
55      ((document-script? config uri)
56       (serve-script config uri))
57      (else 
58       (serve-document config uri)))))
59
60 (define (fail-permanent reason)
61   (print "50 " reason "\r"))
62
63 (define (redirect-permanent new-uri)
64   (print "30 " (uri->string new-uri) "\r"))
65
66 (define (serve-query prompt)
67   (print "10 " prompt "\r"))
68
69 (define (uri-lacks-trailing-slash? uri)
70   (not (string-null? (last (uri-path uri)))))
71
72 (define (uri-with-trailing-slash uri)
73   (update-uri uri path: (append (uri-path uri) '(""))))
74
75 (define (document-available? config uri)
76   (file-exists? (document-path config uri)))
77
78 (define (document-script? config uri)
79   (let ((path (document-path config uri)))
80     (and (file-exists? path)
81          (file-executable? path)
82          (equal? (pathname-extension path) "scm"))))
83
84 (define (document-path-directory? config uri)
85   (directory-exists? (document-path-raw config uri)))
86
87 (define (document-path-raw config uri)
88   (let* ((crumbs (reverse (cons (config-root-dir config) (cdr (uri-path uri))))))
89     (make-pathname (reverse (cdr crumbs)) (car crumbs))))
90
91 (define (document-path config uri)
92   (let* ((path (document-path-raw config uri)))
93     (if (directory-exists? path)
94         (make-pathname path "index.gmi")
95         path)))
96
97 (define (ext->mime ext)
98   (let* ((mime-detected (assoc ext file-types)))
99     (cdr (if mime-detected
100              mime-detected
101              (assoc "txt" file-types)))))
102
103 (define (serve-document-header mime)
104   (print "20 " (string-intersperse mime ";") "\r"))
105     
106 (define (serve-document config uri)
107   (let* ((path (document-path config uri))
108          (ext (pathname-extension path))
109          (mime (ext->mime ext)))
110     (serve-document-header mime)
111     (cond 
112      ((file-executable? path)
113       (serve-text-dynamic path)) ; Binary-files can also be generated here, but the source is dynamic text
114      ((string-prefix? "text/" (car mime))
115       (serve-text-plain path))
116      (else (serve-binary path)))))
117
118 (define (serve-text-plain path)
119   (with-input-from-file path
120     (lambda ()
121       (let loop ((str (read-string)))
122         (unless (eof-object? str)
123           (print* str)
124           (loop (read-string)))))))
125
126 (define (serve-text-dynamic path)
127   (with-input-from-file path
128     (lambda ()
129       (let loop ((c (peek-char)))
130         (if (eof-object? c)
131             'done
132             (begin
133               (if (eq? c #\,)
134                   (begin
135                     (read-char)
136                     (serve-dynamic-element (read) (pathname-directory path))
137                     (read-line))
138                   (print (read-line)))
139               (loop (peek-char))))))))
140                               
141 (define (serve-dynamic-element element working-directory)
142   (match element
143     (('eval expression)
144      (with-current-working-directory
145       working-directory
146       (lambda ()
147         (eval expression))))
148     (('shell command)
149      (with-current-working-directory
150       working-directory
151       (lambda ()
152         (let-values (((in-port out-port id) (process command)))
153           (let ((string (read-string #f in-port)))
154             (unless (eof-object? string)
155               (print string))
156             (close-input-port in-port)
157             (close-output-port out-port))))))
158     (else (error "Unknown element type."))))
159
160 (define (serve-script config uri)
161   ;; Scripts are responsible for the entire response, including header
162   (let* ((path (document-path config uri))
163          (proc (eval (with-input-from-file path read))))
164     (with-current-working-directory
165      (pathname-directory (document-path config uri))
166      (lambda ()
167        (apply proc (list uri))))))
168
169 (define (with-current-working-directory directory thunk)
170   (let ((old-wd (current-directory))
171         (result 'none))
172     (condition-case
173         (begin
174           (change-directory directory)
175           (set! result (thunk))
176           (change-directory old-wd)
177           result)
178       (o (exn)
179          (change-directory old-wd)
180          (signal o)))))
181
182 (define (run-server config)
183   (set-buffering-mode! (current-output-port) #:line)
184   (define listener (ssl-listen* port: (config-port config)
185                                 certificate: (config-certfile config)
186                                 private-key: (config-keyfile config)
187                                 protocol: 'tlsv12))
188
189   (print "Host: '" (config-host config) "'\n"
190          "Port: '" (config-port config) "'\n"
191          "Root directory: '" (config-root-dir config) "'\n"
192          "Cert file: '" (config-certfile config) "'\n"
193          "Key file: '" (config-keyfile config) "'\n"
194          "\n"
195          "Gemini server listening ...")
196
197   (drop-privs config)
198   (server-loop listener config))
199
200 (define (drop-privs config)
201   (let ((uid (config-uid config))
202         (gid (config-gid config)))
203     (if gid ; Group first, since only root can switch groups.
204         (set! (current-group-id) gid))
205     (if uid
206         (set! (current-user-id) uid))))
207
208
209 (define (server-loop listener config)
210   (let-values (((in-port out-port) (ssl-accept listener)))
211     (let-values (((local-ip remote-ip) (tcp-addresses (ssl-port->tcp-port in-port))))
212       (print "Accepted connection from " remote-ip
213              " on " (seconds->string))
214       (condition-case
215           (let ((request-line (read-line in-port)))
216             (print* "Serving request '" request-line "' ... ")
217             (with-output-to-port out-port
218               (lambda ()
219                 (process-request config request-line)))
220             (print "done."))
221         (o (exn)
222            (print-error-message o))))
223     (close-input-port in-port)
224     (close-output-port out-port))
225   (server-loop listener config))
226
227
228 (define (print-usage progname)
229   (let ((indent-str (make-string (string-length progname) #\space)))
230     (print "Usage:\n"
231            progname " [-h/--help]\n"
232            progname " [-p/--port PORT] [-u/--user UID] [-g/--group GID]\n"
233            indent-str " server-root-dir hostname certfile keyfile")))
234
235 (define (main)
236   (let* ((progname (pathname-file (car (argv))))
237          (config (make-config #f #f 1965 #f #f #f #f)))
238     (if (null? (cdr (argv)))
239         (print-usage progname)
240         (let loop ((args (cdr (argv))))
241           (let ((this-arg (car args))
242                 (rest-args (cdr args)))
243             (if (string-prefix? "-" this-arg)
244                 (cond
245                  ((or (equal? this-arg "-h")
246                       (equal? this-arg "--help"))
247                   (print-usage progname))
248                  ((or (equal? this-arg "-p")
249                       (equal? this-arg "--port"))
250                   (config-port-set! config (string->number (car rest-args)))
251                   (loop (cdr rest-args)))
252                  ((or (equal? this-arg "-u")
253                       (equal? this-arg "--user"))
254                   (config-uid-set! config (string->number (car rest-args)))
255                   (loop (cdr rest-args)))
256                  ((or (equal? this-arg "-g")
257                       (equal? this-arg "--group"))
258                   (config-gid-set! config (string->number (car rest-args)))
259                   (loop (cdr rest-args)))
260                  (else
261                   (print-usage progname)))
262                 (match args
263                   ((root-dir host certfile keyfile)
264                    (config-root-dir-set! config root-dir)
265                    (config-host-set! config host)
266                    (config-certfile-set! config certfile)
267                    (config-keyfile-set! config keyfile)
268                    (run-server config))
269                   (else
270                    (print "One or more invalid arguments.")
271                    (print-usage progname)))))))))
272
273 (main)