Version bump.
[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         (chicken sort)
18         (chicken random)
19         srfi-1 srfi-13 matchable base64)
20
21 (define lambdamail-version "LambdaMail v1.6.0")
22
23 (define-record config host port spool-dir user group)
24
25 (define (time-stamp)
26   (time->string (seconds->local-time) "%d %b %Y %T %z"))
27
28
29 ;;; Server initialization
30 ;;
31
32 (define (drop-privs config)
33   (let ((uid (config-user config))
34         (gid (config-group config)))
35     (if (not (null? gid)) ; Group first, since only root can switch groups.
36         (set! (current-group-id) gid))
37     (if (not (null? uid))
38         (set! (current-user-id) uid))))
39
40 (define (run-server config)
41   (set-buffering-mode! (current-output-port) #:line)
42   (let ((listener (tcp-listen (config-port config) 10 "::")))
43     (print lambdamail-version
44            " listening on port " (config-port config) " ...")
45     (print "(Host name: " (config-host config)
46            ", Spool dir: " (config-spool-dir config) ")")
47     (drop-privs config)
48     (server-loop listener config '())))
49
50
51 ;;; Main server loop
52 ;;
53
54 (define (server-loop listener config undelivered-messages)
55   (let* ((messages (append (receive-messages listener config) undelivered-messages)))
56     (server-loop listener config (deliver-messages config messages))))
57
58
59 ;;; Messages
60 ;;
61
62 (define-record message to from text user password stamp)
63 (define-record multi-message tos from text user password stamps)
64 (define (make-empty-multi-message) (make-multi-message '() "" "" "" "" '()))
65
66
67 ;;; Receiving messages
68 ;;
69
70 (define (receive-messages listener config)
71   (let ((messages '()))
72     (print "*** Waiting for incoming mail")
73     (let-values (((in-port out-port) (tcp-accept listener)))
74       (let-values (((local-ip remote-ip) (tcp-addresses in-port)))
75         (print "Accepted connection from " remote-ip " on " (time-stamp)))
76       (condition-case
77           (set! messages (process-smtp (make-smtp-session in-port out-port config) config))
78         (o (exn)
79            (print-error-message o)))
80       (print "Terminating connection.")
81       (close-input-port in-port)
82       (close-output-port out-port))
83     messages))
84
85 (define (make-smtp-session in-port out-port config)
86   (let ((helo ""))
87     (lambda command
88       (match command
89         (('get-line) (read-line in-port))
90         (('send strings ...) (write-line (conc (apply conc strings) "\r") out-port))
91         (('set-helo! h) (set! helo h))
92         (('helo) helo)))))
93
94 (define (smtp-command? cmd-string input-string)
95   (string-prefix? cmd-string (string-downcase input-string)))
96
97 (define (smtp-command-args cmd-string input-string)
98   (if (> (string-length input-string) (string-length cmd-string))
99       (string-trim (string-drop input-string (string-length cmd-string)))
100       ""))
101
102 (define (process-smtp smtp-session config)
103   (smtp-session 'send "220 " (config-host config) " " lambdamail-version)
104   (let loop ((mmsg (make-empty-multi-message))
105              (received-messages '()))
106     (let ((line (smtp-session 'get-line)))
107       (print "got " line)
108       (if (not (string? line))
109           '() ; Don't keep anything on unexpected termination.
110           (cond
111            ((smtp-command? "helo" line)
112             (smtp-session 'set-helo! (smtp-command-args "helo" line))
113             (smtp-session 'send "250 ok")
114             (loop mmsg received-messages))
115            ((smtp-command? "ehlo" line)
116             (smtp-session 'set-helo! (smtp-command-args "helo" line))
117             (smtp-session 'send
118                           "250-" (config-host config)
119                           " Hello " (smtp-command-args "ehlo" line))
120             (smtp-session 'send "250 AUTH PLAIN")
121             ;; (smtp-session 'send "250 STARTTLS")
122             (loop mmsg received-messages))
123            ((smtp-command? "auth plain" line)
124             (let* ((auth-string (smtp-command-args "auth plain" line))
125                    (auth-decoded (base64-decode auth-string))
126                    (auth-list (string-split auth-decoded "\x00"))
127                    (user (car auth-list))
128                    (password (cadr auth-list)))
129               (multi-message-user-set! mmsg user)
130               (multi-message-password-set! mmsg password)
131               (print "Attempted login, user: " user ", password: " password)
132               (smtp-session 'send "235 authentication successful")
133               (loop mmsg received-messages)))
134            ((smtp-command? "mail from:" line)
135             (multi-message-from-set! mmsg (smtp-command-args "mail from:" line))
136             (smtp-session 'send "250 ok")
137             (loop mmsg received-messages))
138            ((smtp-command? "rcpt to:" line)
139             (let* ((to (smtp-command-args "rcpt to:" line))
140                    (stamp (make-message-stamp to mmsg config)))
141               (print to)
142               (if (car stamp)
143                   (begin
144                     (multi-message-tos-set! mmsg (cons to (multi-message-tos mmsg)))
145                     (multi-message-stamps-set! mmsg (cons stamp (multi-message-stamps mmsg)))
146                     (smtp-session 'send "250 ok"))
147                   (begin
148                     (smtp-session 'send "551 relay forbidden"))))
149             (loop mmsg received-messages))
150            ((smtp-command? "data" line)
151             (smtp-session 'send "354 intermediate")
152             (let text-loop ((text ""))
153               (let ((text-line (smtp-session 'get-line)))
154                 (if (string=? "." text-line)
155                     (multi-message-text-set! mmsg text)
156                     (text-loop (conc text text-line "\n")))))
157             (smtp-session 'send "250 ok")
158             (loop (make-empty-multi-message)
159                   (append (make-single-recipient-messages mmsg smtp-session config)
160                           received-messages)))
161            ((smtp-command? "quit" line)
162             (smtp-session 'send "221 closing transmission channel")
163             received-messages)
164            ((string=? "" (string-trim line))
165             (loop mmsg received-messages))
166            (else
167             (smtp-session 'send "502 command not implemented")
168             (loop mmsg received-messages)))))))
169
170 (define (make-single-recipient-messages mmsg smtp-session config)
171   (map
172    (lambda (to stamp)
173      (print "making singleton messages: " to " " stamp)
174      (make-message to (multi-message-from mmsg)
175                    (conc "Received: from " (smtp-session 'helo) "\n"
176                          "\tby " (config-host config) "\n"
177                          "\tfor " to ";\n"
178                          "\t" (time-stamp) "\n"
179                          (multi-message-text mmsg))
180                    (multi-message-user mmsg)
181                    (multi-message-password mmsg)
182                    stamp))
183    (multi-message-tos mmsg)
184    (multi-message-stamps mmsg)))
185
186
187 ;;; Message stamping and validation
188 ;;
189
190 (define (get-local-addresses config)
191   (map (lambda (p) (cons
192                     (conc "<" (car p) "@" (config-host config) ">")
193                     (cdr p)))
194        (map (lambda (file)
195               (list (pathname-file file) file
196                     (let ((password-file (conc file ".auth")))
197                       (if (file-exists? password-file)
198                           (with-input-from-file password-file read-line)
199                           #f))))
200             (filter directory-exists?
201                     (glob (conc (config-spool-dir config) "/*"))))))
202
203 (define (make-message-stamp to mmsg config)
204   (let* ((local-addresses (get-local-addresses config))
205          (local-dest (assoc to local-addresses))
206          (local-src (assoc (multi-message-from mmsg) local-addresses)))
207     (cond
208      (local-dest
209       (list #t 'local (cadr local-dest)))
210      (local-src
211       (let ((host-password (caddr local-src)))
212         (if (and (string=? (conc "<" (multi-message-user mmsg) "@" (config-host config) ">")
213                            (multi-message-from mmsg))
214                  host-password
215                  (string=? (multi-message-password mmsg) host-password))
216             (list #t 'remote)
217             (begin
218               (print "Provided password " (multi-message-password mmsg))
219               (print "Host password " host-password)
220               (list #f 'remote)))))
221      (else
222       (list #f 'relay)))))
223
224
225 ;;; Sending/Delivering messages
226 ;;
227
228 (define (deliver-messages config messages)
229   (print "*** Attempting delivery of " (length messages) " mail items.")
230   (filter (lambda (msg) (not (deliver-message msg config)))
231           messages))
232
233 (define (deliver-message msg config)
234   (print "From: " (message-from msg))
235   (print "To: " (message-to msg))
236   (condition-case
237     (match (message-stamp msg)
238       ((#t 'local dest-dir) (deliver-message-local msg dest-dir))
239       ((#t 'remote) (deliver-message-remote msg config))
240       ((#f 'remote)
241        (print "* REMOTE DELIVERY NOT ALLOWED (auth failure)")
242        #t)
243       (else
244        (print "* DELIVERY NOT ALLOWED (relay forbidden)")
245        #t))
246     (o (exn)
247        (print "* DELIVERY FAILED")
248        (print-error-message o)
249        #t)))
250
251 ;; Local delivery
252
253 (define unique-file-name
254   (let ((counter 0))
255     (lambda ()
256       (set! counter (modulo (+ counter 1) 1000))
257       (conc (current-seconds) "_" counter))))
258
259 (define (deliver-message-local msg dest-dir)
260   (with-output-to-file (conc dest-dir "/" (unique-file-name))
261     (lambda ()
262       (print (message-text msg))))
263   (print "* MESSAGE DELIVERED (local)")
264   #t)
265
266
267 ;; Remote delivery
268
269 (define (get-domain-from-email email-string)
270   (car (string-split (cadr (string-split email-string "@")) ">")))
271
272 ;; This is a hack - there's no built-in interface to res_query()
273 ;; in chicken, so we have to resort to a system call to dig...
274 (define (get-mail-server-for-domain domain)
275   (let* ((mx-lines (let-values (((in out id) (process (conc "dig " domain " mx +short"))))
276                      (with-input-from-port in read-lines)))
277          (mx-entries (map (lambda (l)
278                             (let ((s (string-split l)))
279                               (list (string->number (car s)) 
280                                     (string-drop-right (cadr s) 1)))) ; remove trailing "."
281                           mx-lines))
282          (sorted-mx-entries (sort mx-entries (lambda (e f) (< (car e) (car f))))))
283     (if (null? sorted-mx-entries)
284         domain ; fall-back to email address domain if no mx entries
285         (cadar sorted-mx-entries)))) ; otherwise pick the highest priority server
286
287 (define (deliver-message-remote msg config)
288   (let* ((domain (get-domain-from-email (message-to msg)))
289          (mail-server (get-mail-server-for-domain domain)))
290     (print "Attempting delivery to " mail-server)
291     (let-values (((tcp-in tcp-out) (tcp-connect mail-server 25)))
292       (let ((smtp-session (make-outgoing-smtp-session tcp-in tcp-out)))
293         (let ((result (and
294                        (smtp-session 'expect "220")
295                        (smtp-session 'send "helo " (config-host config))
296                        (smtp-session 'expect "250")
297                        (smtp-session 'send "mail from:" (message-from msg))
298                        (smtp-session 'expect "250")
299                        (smtp-session 'send "rcpt to:" (message-to msg))
300                        (smtp-session 'expect "250")
301                        (smtp-session 'send "data")
302                        (smtp-session 'expect "354")
303                        (smtp-session 'send (message-text msg))
304                        (smtp-session 'send ".")
305                        (smtp-session 'expect "250" "5") ;Do not try again on rejects.
306                        (smtp-session 'send "quit"))))
307           (close-input-port tcp-in)
308           (close-output-port tcp-out)
309           (print "Connection closed.")
310           (if result
311               (print "* MESSAGE DELIVERED (remote)")
312               (print "* REMOTE DELIVERY FAILED (unexpected server response)"))
313           result)))))
314
315 (define (or-list l)
316   (fold (lambda (a b) (or a b)) #f l))
317
318 (define ((make-outgoing-smtp-session tcp-in tcp-out) . command)
319   (match command
320     (('expect codes ...)
321      (let loop ((result (read-line tcp-in)))
322        (if (and (> (string-length result) 3)
323                 (eq? (string-ref result 3) #\-))
324            (loop (read-line tcp-in)) ;status continues on next line
325            (begin
326              (print "Expecting one of " codes " got " result)
327              (or-list (map (lambda (code)
328                              (string-prefix? code result))
329                            codes))))))
330     (('send strings ...)
331      (print "Sending " (if (> (string-length (car strings)) 30)
332                            (string-take (car strings) 30)
333                            (car strings)))
334      (let ((processed-string
335             (string-translate* (conc (apply conc strings) "\n")
336                                '(("\n" . "\r\n")))))
337        (write-string processed-string #f tcp-out)))))
338
339
340 ;;; Command line argument parsing
341 ;;
342
343 (define (print-usage progname)
344   (print "Usage:\n"
345          progname " -h/--help\n"
346          progname " -v/--version\n"
347          progname " [-u/--user UID] [-g/--group GID] hostname [[port [spooldir]]\n"
348          "\n"
349          "The -u and -g options can be used to set the UID and GID of the process\n"
350          "following the creation of the TCP port listener (which often requires root)."))
351
352 (define (print-version)
353   (print lambdamail-version))
354
355 (define (main)
356   (let ((progname (pathname-file (car (argv))))
357         (config (make-config "" 25 "/var/spool/mail" '() '())))
358     (if (null? (cdr (argv)))
359         (print-usage progname)
360         (let loop ((args (cdr (argv))))
361           (let ((this-arg (car args))
362                 (rest-args (cdr args)))
363             (if (string-prefix? "-" this-arg)
364                 (cond
365                  ((or (equal? this-arg "-u")
366                       (equal? this-arg "--user"))
367                   (config-user-set! config (string->number (car rest-args)))
368                   (loop (cdr rest-args)))
369                  ((or (equal? this-arg "-g")
370                       (equal? this-arg "--group"))
371                   (config-group-set! config (string->number (car rest-args)))
372                   (loop (cdr rest-args)))
373                  ((or (equal? this-arg "-h")
374                       (equal? this-arg "--help"))
375                   (print-usage progname))
376                  ((or (equal? this-arg "-v")
377                       (equal? this-arg "--version"))
378                   (print-version))
379                  (else
380                   (print "Unknown option " this-arg "\n")
381                   (print-usage progname)))
382                 (begin
383                   (config-host-set! config this-arg)
384                   (unless (null? rest-args)
385                     (config-port-set! config (string->number (car rest-args)))
386                     (unless (null? (cdr rest-args))
387                       (config-spool-dir-set! config (cadr rest-args))))
388                   (run-server config))))))))
389
390 (main)
391
392 ;; (define (test)
393 ;;   (run-server (make-config "localhost" 2525 "spool" '() '())))
394
395 ;; (test)