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