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