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