Modularized some of the header code.
[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     (apply (eval (with-input-from-file path read))
164            (list uri))))
165
166 (define (with-current-working-directory directory thunk)
167   (let ((old-wd (current-directory))
168         (result 'none))
169     (condition-case
170         (begin
171           (change-directory directory)
172           (set! result (thunk))
173           (change-directory old-wd)
174           result)
175       (o (exn)
176          (change-directory old-wd)
177          (signal o)))))
178
179 (define (run-server config)
180   (set-buffering-mode! (current-output-port) #:line)
181   (define listener (ssl-listen* port: (config-port config)
182                                 certificate: (config-certfile config)
183                                 private-key: (config-keyfile config)
184                                 protocol: 'tlsv12))
185
186   (print "Host: '" (config-host config) "'\n"
187          "Port: '" (config-port config) "'\n"
188          "Root directory: '" (config-root-dir config) "'\n"
189          "Cert file: '" (config-certfile config) "'\n"
190          "Key file: '" (config-keyfile config) "'\n"
191          "\n"
192          "Gemini server listening ...")
193
194   (drop-privs config)
195   (server-loop listener config))
196
197 (define (drop-privs config)
198   (let ((uid (config-uid config))
199         (gid (config-gid config)))
200     (if gid ; Group first, since only root can switch groups.
201         (set! (current-group-id) gid))
202     (if uid
203         (set! (current-user-id) uid))))
204
205
206 (define (server-loop listener config)
207   (let-values (((in-port out-port) (ssl-accept listener)))
208     (let-values (((local-ip remote-ip) (tcp-addresses (ssl-port->tcp-port in-port))))
209       (print "Accepted connection from " remote-ip
210              " on " (seconds->string))
211       (condition-case
212           (let ((request-line (read-line in-port)))
213             (print* "Serving request '" request-line "' ... ")
214             (with-output-to-port out-port
215               (lambda ()
216                 (process-request config request-line)))
217             (print "done."))
218         (o (exn)
219            (print-error-message o))))
220     (close-input-port in-port)
221     (close-output-port out-port))
222   (server-loop listener config))
223
224
225 (define (print-usage progname)
226   (let ((indent-str (make-string (string-length progname) #\space)))
227     (print "Usage:\n"
228            progname " [-h/--help]\n"
229            progname " [-p/--port PORT] [-u/--user UID] [-g/--group GID]\n"
230            indent-str " server-root-dir hostname certfile keyfile")))
231
232 (define (main)
233   (let* ((progname (pathname-file (car (argv))))
234          (config (make-config #f #f 1965 #f #f #f #f)))
235     (if (null? (cdr (argv)))
236         (print-usage progname)
237         (let loop ((args (cdr (argv))))
238           (let ((this-arg (car args))
239                 (rest-args (cdr args)))
240             (if (string-prefix? "-" this-arg)
241                 (cond
242                  ((or (equal? this-arg "-h")
243                       (equal? this-arg "--help"))
244                   (print-usage progname))
245                  ((or (equal? this-arg "-p")
246                       (equal? this-arg "--port"))
247                   (config-port-set! config (string->number (car rest-args)))
248                   (loop (cdr rest-args)))
249                  ((or (equal? this-arg "-u")
250                       (equal? this-arg "--user"))
251                   (config-uid-set! config (string->number (car rest-args)))
252                   (loop (cdr rest-args)))
253                  ((or (equal? this-arg "-g")
254                       (equal? this-arg "--group"))
255                   (config-gid-set! config (string->number (car rest-args)))
256                   (loop (cdr rest-args)))
257                  (else
258                   (print-usage progname)))
259                 (match args
260                   ((root-dir host certfile keyfile)
261                    (config-root-dir-set! config root-dir)
262                    (config-host-set! config host)
263                    (config-certfile-set! config certfile)
264                    (config-keyfile-set! config keyfile)
265                    (run-server config))
266                   (else
267                    (print "One or more invalid arguments.")
268                    (print-usage progname)))))))))
269
270 (main)