e66e4de82d6186d27ba55c3881afb15dcb52773c
[lambdamail.git] / lambdamail.scm
1 ;; Super-basic bell-and-whistle-free SMTP server.
2 ;;
3 ;; Intended for a single-user system 
4
5 (import tcp6
6         (chicken port)
7         (chicken io)
8         (chicken string)
9         (chicken pathname)
10         (chicken file)
11         (chicken time)
12         (chicken time posix)
13         (chicken process)
14         (chicken process-context)
15         (chicken process-context posix)
16         (chicken condition)
17         srfi-1 srfi-13 matchable base64)
18
19 (define lambdamail-version "LambdaMail v0.0.1")
20
21 (define-record config host port spool-dir user group)
22 (define-record message to from text user password)
23 (define (make-empty-message) (make-message "" "" "" "" ""))
24
25
26 ;;; Server initialization
27 ;;
28
29 (define (drop-privs config)
30   (let ((uid (config-user config))
31         (gid (config-group config)))
32     (if (not (null? gid)) ; Group first, since only root can switch groups.
33         (set! (current-group-id) gid))
34     (if (not (null? uid))
35         (set! (current-user-id) uid))))
36
37 (define (run-server config)
38   (set-buffering-mode! (current-output-port) #:line)
39   (let ((listener (tcp-listen (config-port config) 10 "::")))
40     (print lambdamail-version
41            " listening on port " (config-port config) " ...")
42     (print "(Host name: " (config-host config)
43            ", Spool dir: " (config-spool-dir config) ")")
44     (drop-privs config)
45     (server-loop listener config '())))
46
47
48 ;;; Main server loop
49 ;;
50
51 (define (server-loop listener config undelivered-messages)
52   (let* ((messages (append (receive-messages listener config) undelivered-messages)))
53     (server-loop listener config (deliver-messages config messages))))
54
55
56 ;;; Receiving messages
57 ;;
58
59 (define (receive-messages listener config)
60   (let ((messages '()))
61     (let-values (((in-port out-port) (tcp-accept listener)))
62       (let-values (((local-ip remote-ip) (tcp-addresses in-port)))
63         (print "Accepted connection from " remote-ip " on " (seconds->string)))
64       (condition-case
65           (set! messages (process-smtp (make-smtp-session in-port out-port config) config))
66         (o (exn)
67            (print-error-message o)))
68       (print "Terminating connection.")
69       (close-input-port in-port)
70       (close-output-port out-port))
71     messages))
72
73 (define (make-smtp-session in-port out-port config)
74   (let ((user "")
75         (password ""))
76     (lambda command
77       (match command
78         (('get-line) (read-line in-port))
79         (('send strings ...) (write-line (conc (apply conc strings) "\r") out-port))
80         (('set-user! u) (set! user u))
81         (('set-password! p) (set! password p))
82         (('user) user)
83         (('password) password)))))
84
85 (define (smtp-command? cmd-string input-string)
86   (string-prefix? cmd-string (string-downcase input-string)))
87
88 (define (smtp-command-args cmd-string input-string)
89   (if (> (string-length input-string) (string-length cmd-string))
90       (string-trim (string-drop input-string (string-length cmd-string)))
91       ""))
92
93 (define (process-smtp smtp-session config)
94   (smtp-session 'send "220 " (config-host config) lambdamail-version)
95   (let loop ((msg (make-empty-message))
96              (received-messages '()))
97     (let ((line (smtp-session 'get-line)))
98       (when (string? line)
99         (print "got " line)
100         (cond
101          ((smtp-command? "helo" line)
102           (smtp-session 'send "250 ok")
103           (loop msg received-messages))
104          ((smtp-command? "ehlo" line)
105           (smtp-session 'send
106                         "250-" (config-host config)
107                         " Hello " (smtp-command-args "ehlo" line))
108           (smtp-session 'send "250 AUTH PLAIN")
109           ;; (smtp-session 'send "250 STARTTLS")
110           (loop msg received-messages))
111          ((smtp-command? "auth plain" line)
112           (let* ((auth-string (smtp-command-args "auth plain" line))
113                  (auth-decoded (base64-decode auth-string))
114                  (auth-list (string-split auth-decoded "\x00"))
115                  (user (car auth-list))
116                  (password (cadr auth-list)))
117             (smtp-session 'set-user! user)
118             (smtp-session 'set-password! password)
119             (print "Attempted login, user: " user ", password: " password)
120             (smtp-session 'send "235 authentication successful")
121             (loop msg received-messages)))
122          ((smtp-command? "mail from:" line)
123           (message-from-set! msg (smtp-command-args "mail from:" line))
124           (smtp-session 'send "250 ok")
125           (loop msg received-messages))
126          ((smtp-command? "rcpt to:" line)
127           (message-to-set! msg (smtp-command-args "rcpt to:" line))
128           (smtp-session 'send "250 ok")
129           (loop msg received-messages))
130          ((smtp-command? "data" line)
131           (smtp-session 'send "354 intermediate")
132           (let text-loop ((text ""))
133             (let ((text-line (smtp-session 'get-line)))
134               (if (string=? "." text-line)
135                   (message-text-set! msg text)
136                   (text-loop (conc text text-line "\n")))))
137           (message-user-set! msg (smtp-session 'user))
138           (message-password-set! msg (smtp-session 'password))
139           (smtp-session 'send "250 ok")
140           (loop (make-empty-message) (cons msg received-messages)))
141          ((smtp-command? "quit" line)
142           (smtp-session 'send "221 closing transmission channel")
143           received-messages)
144          ((string=? "" (string-trim line))
145           (loop msg received-messages))
146          (else
147           (smtp-session 'send "502 command not implemented")
148           (loop msg received-messages)))))))
149
150
151 ;;; Sending/Delivering messages
152 ;;
153
154 (define (deliver-messages config messages)
155   (print "Attempting delivery of " (length messages) " mail items.")
156   (filter (lambda (msg) (not (deliver-message msg config)))
157           messages))
158
159 (define (deliver-message msg config)
160   (condition-case
161       (begin
162         (let* ((local-addresses (get-local-addresses config))
163                (dest (assoc (message-to msg) local-addresses))
164                (orig (assoc (message-from msg) local-addresses)))
165           (cond
166            (dest
167             (let ((dest-dir (cadr dest)))
168               (deliver-message-local msg dest-file))
169             (print "Message DELIVERED (local):"))
170            (orig
171             (let ((password (caddr orig)))
172               (if (and
173                    (string=? (conc "<" (message-user msg) "@" (config-host config) ">")
174                              (message-from msg))
175                    password
176                    (string=? (message-password msg) password))
177                   (begin
178                     (deliver-message-remote msg config)
179                     (print "Message DELIVERED (remote):"))
180                   (print "Message DELIVERY REJECTED (auth failure):"))))
181            (else
182             (print "Message DELIVERY REJECTED (relay forbidden):"))))
183         (print " * From: " (message-from msg))
184         (print " * To: " (message-to msg))
185         #t)
186     (o (exn)
187        (print "Message delivery failed.")
188        (print-error-message o))))
189
190 ;; Local delivery
191
192 (define (get-local-addresses config)
193   (map (lambda (p) (cons
194                     (conc "<" (car p) "@" (config-host config) ">")
195                     (cdr p)))
196        (map (lambda (file)
197               (list (pathname-file file) file
198                     (let ((password-file (conc file ".auth")))
199                       (if (file-exists? password-file)
200                           (with-input-from-file password-file read-line)
201                           #f))))
202             (filter directory-exists?
203                     (glob (conc (config-spool-dir config) "/*"))))))
204
205 (define (deliver-message-local msg dest-dir)
206   (with-output-to-file (conc dest-dir "/" (current-seconds))
207     (lambda ()
208       (print (message-text msg)))))
209
210
211 ;; Remote delivery
212
213 (define (get-host-from-email email-string)
214   (car (string-split (cadr (string-split email-string "@")) ">")))
215
216 (define (deliver-message-remote msg config)
217   (let ((host (get-host-from-email (message-to msg))))
218     (print "Attempting delivery to host " host)
219     (let-values (((tcp-in tcp-out) (tcp-connect host 25)))
220       (let ((smtp-session (make-outgoing-smtp-session tcp-in tcp-out)))
221         (let ((result (and
222                        (smtp-session 'expect "220")
223                        (smtp-session 'send "helo " (config-host config))
224                        (smtp-session 'expect "250")
225                        (smtp-session 'send "mail from:" (message-from msg))
226                        (smtp-session 'expect "250")
227                        (smtp-session 'send "rcpt to:" (message-to msg))
228                        (smtp-session 'expect "250")
229                        (smtp-session 'send "data")
230                        (smtp-session 'expect "354")
231                        (smtp-session 'send (message-text msg))
232                        (smtp-session 'expect "250")
233                        (smtp-session 'send "quit"))))
234           (close-input-port tcp-in)
235           (close-output-port tcp-out)
236           result)))))
237
238 (define ((make-outgoing-smtp-session tcp-in tcp-out) command)
239   (match command
240     (('expect code)
241      (string-prefix? "220" (read-line tcp-in)))
242     (('send strings ...)
243      (write-string (string-translate (conc (apply conc strings) "\n") "\n" "\r\n")
244                    out-port))))
245
246 ;;; Command line argument parsing
247 ;;
248
249 (define (print-usage progname)
250   (print "Usage:\n"
251          progname " -h/--help\n"
252          progname " [-u/--user UID] [-g/--group GID] hostname [[port [spooldir]]\n"
253          "\n"
254          "The -u and -g options can be used to set the UID and GID of the process\n"
255          "following the creation of the TCP port listener (which often requires root)."))
256
257 (define (main)
258   (let ((progname (pathname-file (car (argv))))
259         (config (make-config "" 25 "/var/spool/mail" '() '())))
260     (if (null? (cdr (argv)))
261         (print-usage progname)
262         (let loop ((args (cdr (argv))))
263           (let ((this-arg (car args))
264                 (rest-args (cdr args)))
265             (if (string-prefix? "-" this-arg)
266                 (cond
267                  ((or (equal? this-arg "-u")
268                       (equal? this-arg "--user"))
269                   (config-user-set! config (string->number (car rest-args)))
270                   (loop (cdr rest-args)))
271                  ((or (equal? this-arg "-g")
272                       (equal? this-arg "--group"))
273                   (config-group-set! config (string->number (car rest-args)))
274                   (loop (cdr rest-args)))
275                  ((or (equal? this-arg "-h")
276                       (equal? this-arg "--help"))
277                   (print-usage progname))
278                  (else
279                   (print "Unknown option " this-arg "\n")
280                   (print-usage progname)))
281                 (begin
282                   (config-host-set! config this-arg)
283                   (unless (null? rest-args)
284                     (config-port-set! config (string->number (car rest-args)))
285                     (unless (null? (cdr rest-args))
286                       (config-spool-dir-set! config (cadr rest-args))))
287                   (run-server config))))))))
288
289 (main)
290
291 ;; (define (test)
292 ;;   (run-server (make-config "localhost" 2525 "spool" '() '())))