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