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