Working on starttls implementation.
[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 openssl
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.7.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? "starttls" line)
124             (let ((args (smtp-command-args "starttls" line)))
125               (if (= 0 (string-length args))
126                   (smtp-session 'send "501 Syntax error (no parameters allowed)")
127                   (begin
128                     (smtp-session 'send "220 Ready to start TLS")
129
130                     ;; TODO: initiate TLS handshake using (ssl-start*)
131
132                     ))))
133            ((smtp-command? "auth plain" line)
134             (let* ((auth-string (smtp-command-args "auth plain" line))
135                    (auth-decoded (base64-decode auth-string))
136                    (auth-list (string-split auth-decoded "\x00"))
137                    (user (car auth-list))
138                    (password (cadr auth-list)))
139               (multi-message-user-set! mmsg user)
140               (multi-message-password-set! mmsg password)
141               (print "Attempted login, user: " user ", password: " password)
142               (smtp-session 'send "235 authentication successful")
143               (loop mmsg received-messages)))
144            ((smtp-command? "mail from:" line)
145             (multi-message-from-set! mmsg (smtp-command-args "mail from:" line))
146             (smtp-session 'send "250 ok")
147             (loop mmsg received-messages))
148            ((smtp-command? "rcpt to:" line)
149             (let* ((to (smtp-command-args "rcpt to:" line))
150                    (stamp (make-message-stamp to mmsg config)))
151               (print to)
152               (if (car stamp)
153                   (begin
154                     (multi-message-tos-set! mmsg (cons to (multi-message-tos mmsg)))
155                     (multi-message-stamps-set! mmsg (cons stamp (multi-message-stamps mmsg)))
156                     (smtp-session 'send "250 ok"))
157                   (begin
158                     (smtp-session 'send "551 relay forbidden"))))
159             (loop mmsg received-messages))
160            ((smtp-command? "data" line)
161             (smtp-session 'send "354 intermediate")
162             (let text-loop ((text ""))
163               (let ((text-line (smtp-session 'get-line)))
164                 (if (string=? "." text-line)
165                     (multi-message-text-set! mmsg text)
166                     (text-loop (conc text text-line "\n")))))
167             (smtp-session 'send "250 ok")
168             (loop (make-empty-multi-message)
169                   (append (make-single-recipient-messages mmsg smtp-session config)
170                           received-messages)))
171            ((smtp-command? "quit" line)
172             (smtp-session 'send "221 closing transmission channel")
173             received-messages)
174            ((string=? "" (string-trim line))
175             (loop mmsg received-messages))
176            (else
177             (smtp-session 'send "502 command not implemented")
178             (loop mmsg received-messages)))))))
179
180 (define (make-single-recipient-messages mmsg smtp-session config)
181   (map
182    (lambda (to stamp)
183      (print "making singleton messages: " to " " stamp)
184      (make-message to (multi-message-from mmsg)
185                    (conc "Received: from " (smtp-session 'helo) "\n"
186                          "\tby " (config-host config) "\n"
187                          "\tfor " to ";\n"
188                          "\t" (time-stamp) "\n"
189                          (multi-message-text mmsg))
190                    (multi-message-user mmsg)
191                    (multi-message-password mmsg)
192                    stamp))
193    (multi-message-tos mmsg)
194    (multi-message-stamps mmsg)))
195
196
197 ;;; Message stamping and validation
198 ;;
199
200 (define (get-local-addresses config)
201   (map (lambda (p) (cons
202                     (conc "<" (car p) "@" (config-host config) ">")
203                     (cdr p)))
204        (map (lambda (file)
205               (list (pathname-file file) file
206                     (let ((password-file (conc file ".auth")))
207                       (if (file-exists? password-file)
208                           (with-input-from-file password-file read-line)
209                           #f))))
210             (filter directory-exists?
211                     (glob (conc (config-spool-dir config) "/*"))))))
212
213 (define (make-message-stamp to mmsg config)
214   (let* ((local-addresses (get-local-addresses config))
215          (local-dest (assoc to local-addresses))
216          (local-src (assoc (multi-message-from mmsg) local-addresses)))
217     (cond
218      (local-dest
219       (list #t 'local (cadr local-dest)))
220      (local-src
221       (let ((host-password (caddr local-src)))
222         (if (and (string=? (conc "<" (multi-message-user mmsg) "@" (config-host config) ">")
223                            (multi-message-from mmsg))
224                  host-password
225                  (string=? (multi-message-password mmsg) host-password))
226             (list #t 'remote)
227             (begin
228               (print "Provided password " (multi-message-password mmsg))
229               (print "Host password " host-password)
230               (list #f 'remote)))))
231      (else
232       (list #f 'relay)))))
233
234
235 ;;; Sending/Delivering messages
236 ;;
237
238 (define (deliver-messages config messages)
239   (print "*** Attempting delivery of " (length messages) " mail items.")
240   (filter (lambda (msg) (not (deliver-message msg config)))
241           messages))
242
243 (define (deliver-message msg config)
244   (print "From: " (message-from msg))
245   (print "To: " (message-to msg))
246   (condition-case
247     (match (message-stamp msg)
248       ((#t 'local dest-dir) (deliver-message-local msg dest-dir))
249       ((#t 'remote) (deliver-message-remote msg config))
250       ((#f 'remote)
251        (print "* REMOTE DELIVERY NOT ALLOWED (auth failure)")
252        #t)
253       (else
254        (print "* DELIVERY NOT ALLOWED (relay forbidden)")
255        #t))
256     (o (exn)
257        (print "* DELIVERY FAILED")
258        (print-error-message o)
259        #t)))
260
261 ;; Local delivery
262
263 (define unique-file-name
264   (let ((counter 0))
265     (lambda ()
266       (set! counter (modulo (+ counter 1) 1000))
267       (conc (current-seconds) "_" counter))))
268
269 (define (deliver-message-local msg dest-dir)
270   (with-output-to-file (conc dest-dir "/" (unique-file-name))
271     (lambda ()
272       (print (message-text msg))))
273   (print "* MESSAGE DELIVERED (local)")
274   #t)
275
276
277 ;; Remote delivery
278
279 (define (get-domain-from-email email-string)
280   (car (string-split (cadr (string-split email-string "@")) ">")))
281
282 ;; This is a hack - there's no built-in interface to res_query()
283 ;; in chicken, so we have to resort to a system call to dig...
284 (define (get-mail-servers-for-domain domain)
285   (let* ((mx-lines (let-values (((in out id) (process (conc "dig " domain " mx +short"))))
286                      (with-input-from-port in read-lines)))
287          (mx-entries (map (lambda (l)
288                             (let ((s (string-split l)))
289                               (list (string->number (car s)) 
290                                     (string-drop-right (cadr s) 1)))) ; remove trailing "."
291                           mx-lines))
292          (sorted-mx-entries (map cadr (sort mx-entries (lambda (e f) (< (car e) (car f)))))))
293     (if (null? sorted-mx-entries)
294         (list domain) ; fall-back to email address domain if no mx entries
295         sorted-mx-entries))) ; otherwise pick the highest priority server
296
297 (define (deliver-message-remote msg config)
298   (let ((domain (get-domain-from-email (message-to msg))))
299     (let loop ((mail-servers (get-mail-servers-for-domain domain)))
300       (if (null? mail-servers)
301           (begin
302             (print "* REMOTE DELIVERY FAILED (Could not connect to any mail server)")
303             #f)
304           (condition-case
305               (let ((mail-server (car mail-servers)))
306                 (print "Attempting delivery to " mail-server)
307                 (let-values (((tcp-in tcp-out) (tcp-connect mail-server 25)))
308                   (let ((smtp-session (make-outgoing-smtp-session tcp-in tcp-out)))
309                     (let ((result (and
310                                    (smtp-session 'expect "220")
311                                    (smtp-session 'send "helo " (config-host config))
312                                    (smtp-session 'expect "250")
313                                    (smtp-session 'send "mail from:" (message-from msg))
314                                    (smtp-session 'expect "250")
315                                    (smtp-session 'send "rcpt to:" (message-to msg))
316                                    (smtp-session 'expect "250")
317                                    (smtp-session 'send "data")
318                                    (smtp-session 'expect "354")
319                                    (smtp-session 'send (message-text msg))
320                                    (smtp-session 'send ".")
321                                    (smtp-session 'expect "250" "5") ;Do not try again on rejects.
322                                    (smtp-session 'send "quit"))))
323                       (close-input-port tcp-in)
324                       (close-output-port tcp-out)
325                       (print "Connection closed.")
326                       (if result
327                           (print "* MESSAGE DELIVERED (remote)")
328                           (print "* REMOTE DELIVERY FAILED (unexpected server response)"))
329                       result))))
330             (o (exn)
331                (print-error-messsage o)
332                (print "* Failed to connect.  Trying next server.")
333                (loop (cdr mail-servers))))))))
334
335 (define (or-list l)
336   (fold (lambda (a b) (or a b)) #f l))
337
338 (define ((make-outgoing-smtp-session tcp-in tcp-out) . command)
339   (match command
340     (('expect codes ...)
341      (let loop ((result (read-line tcp-in)))
342        (if (and (> (string-length result) 3)
343                 (eq? (string-ref result 3) #\-))
344            (loop (read-line tcp-in)) ;status continues on next line
345            (begin
346              (print "Expecting one of " codes " got " result)
347              (or-list (map (lambda (code)
348                              (string-prefix? code result))
349                            codes))))))
350     (('send strings ...)
351      (print "Sending " (if (> (string-length (car strings)) 30)
352                            (string-take (car strings) 30)
353                            (car strings)))
354      (let ((processed-string
355             (string-translate* (conc (apply conc strings) "\n")
356                                '(("\n" . "\r\n")))))
357        (write-string processed-string #f tcp-out)))))
358
359
360 ;;; Command line argument parsing
361 ;;
362
363 (define (print-usage progname)
364   (print "Usage:\n"
365          progname " -h/--help\n"
366          progname " -v/--version\n"
367          progname " [-u/--user UID] [-g/--group GID] hostname [[port [spooldir]]\n"
368          "\n"
369          "The -u and -g options can be used to set the UID and GID of the process\n"
370          "following the creation of the TCP port listener (which often requires root)."))
371
372 (define (print-version)
373   (print lambdamail-version))
374
375 (define (main)
376   (let ((progname (pathname-file (car (argv))))
377         (config (make-config "" 25 "/var/spool/mail" '() '())))
378     (if (null? (cdr (argv)))
379         (print-usage progname)
380         (let loop ((args (cdr (argv))))
381           (let ((this-arg (car args))
382                 (rest-args (cdr args)))
383             (if (string-prefix? "-" this-arg)
384                 (cond
385                  ((or (equal? this-arg "-u")
386                       (equal? this-arg "--user"))
387                   (config-user-set! config (string->number (car rest-args)))
388                   (loop (cdr rest-args)))
389                  ((or (equal? this-arg "-g")
390                       (equal? this-arg "--group"))
391                   (config-group-set! config (string->number (car rest-args)))
392                   (loop (cdr rest-args)))
393                  ((or (equal? this-arg "-h")
394                       (equal? this-arg "--help"))
395                   (print-usage progname))
396                  ((or (equal? this-arg "-v")
397                       (equal? this-arg "--version"))
398                   (print-version))
399                  (else
400                   (print "Unknown option " this-arg "\n")
401                   (print-usage progname)))
402                 (begin
403                   (config-host-set! config this-arg)
404                   (unless (null? rest-args)
405                     (config-port-set! config (string->number (car rest-args)))
406                     (unless (null? (cdr rest-args))
407                       (config-spool-dir-set! config (cadr rest-args))))
408                   (run-server config))))))))
409
410 (main)
411
412 ;; (define (test)
413 ;;   (run-server (make-config "localhost" 2525 "spool" '() '())))
414
415 ;; (test)