First successful remote delivery.
[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 (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 ;;; Receiving messages
60 ;;
61
62 (define (receive-messages listener config)
63   (let ((messages '()))
64     (let-values (((in-port out-port) (tcp-accept listener)))
65       (let-values (((local-ip remote-ip) (tcp-addresses in-port)))
66         (print "Accepted connection from " remote-ip " on " (time-stamp)))
67       (condition-case
68           (set! messages (process-smtp (make-smtp-session in-port out-port config) config))
69         (o (exn)
70            (print-error-message o)))
71       (print "Terminating connection.")
72       (close-input-port in-port)
73       (close-output-port out-port))
74     messages))
75
76 (define (make-smtp-session in-port out-port config)
77   (let ((user "")
78         (password ""))
79     (lambda command
80       (match command
81         (('get-line) (read-line in-port))
82         (('send strings ...) (write-line (conc (apply conc strings) "\r") out-port))
83         (('set-user! u) (set! user u))
84         (('set-password! p) (set! password p))
85         (('user) user)
86         (('password) password)))))
87
88 (define (smtp-command? cmd-string input-string)
89   (string-prefix? cmd-string (string-downcase input-string)))
90
91 (define (smtp-command-args cmd-string input-string)
92   (if (> (string-length input-string) (string-length cmd-string))
93       (string-trim (string-drop input-string (string-length cmd-string)))
94       ""))
95
96 (define (process-smtp smtp-session config)
97   (smtp-session 'send "220 " (config-host config) lambdamail-version)
98   (let loop ((msg (make-empty-message))
99              (received-messages '()))
100     (let ((line (smtp-session 'get-line)))
101       (when (string? line)
102         (print "got " line)
103         (cond
104          ((smtp-command? "helo" line)
105           (smtp-session 'send "250 ok")
106           (loop msg received-messages))
107          ((smtp-command? "ehlo" line)
108           (smtp-session 'send
109                         "250-" (config-host config)
110                         " Hello " (smtp-command-args "ehlo" line))
111           (smtp-session 'send "250 AUTH PLAIN")
112           ;; (smtp-session 'send "250 STARTTLS")
113           (loop msg received-messages))
114          ((smtp-command? "auth plain" line)
115           (let* ((auth-string (smtp-command-args "auth plain" line))
116                  (auth-decoded (base64-decode auth-string))
117                  (auth-list (string-split auth-decoded "\x00"))
118                  (user (car auth-list))
119                  (password (cadr auth-list)))
120             (smtp-session 'set-user! user)
121             (smtp-session 'set-password! password)
122             (print "Attempted login, user: " user ", password: " password)
123             (smtp-session 'send "235 authentication successful")
124             (loop msg received-messages)))
125          ((smtp-command? "mail from:" line)
126           (message-from-set! msg (smtp-command-args "mail from:" line))
127           (smtp-session 'send "250 ok")
128           (loop msg received-messages))
129          ((smtp-command? "rcpt to:" line)
130           (message-to-set! msg (smtp-command-args "rcpt to:" line))
131           (smtp-session 'send "250 ok")
132           (loop msg received-messages))
133          ((smtp-command? "data" line)
134           (smtp-session 'send "354 intermediate")
135           (let text-loop ((text (conc "Received: from " (smtp-session 'helo)
136                                       " by " (config-host)
137                                       " for " (message-from msg)
138                                       "; " (time-stamp))))
139             (let ((text-line (smtp-session 'get-line)))
140               (if (string=? "." text-line)
141                   (message-text-set! msg text)
142                   (text-loop (conc text text-line "\n")))))
143           (message-user-set! msg (smtp-session 'user))
144           (message-password-set! msg (smtp-session 'password))
145           (smtp-session 'send "250 ok")
146           (loop (make-empty-message) (cons msg received-messages)))
147          ((smtp-command? "quit" line)
148           (smtp-session 'send "221 closing transmission channel")
149           received-messages)
150          ((string=? "" (string-trim line))
151           (loop msg received-messages))
152          (else
153           (smtp-session 'send "502 command not implemented")
154           (loop msg received-messages)))))))
155
156
157 ;;; Sending/Delivering messages
158 ;;
159
160 (define (deliver-messages config messages)
161   (print "Attempting delivery of " (length messages) " mail items.")
162   (filter (lambda (msg) (not (deliver-message msg config)))
163           messages))
164
165 (define (deliver-message msg config)
166   (condition-case
167       (begin
168         (let* ((local-addresses (get-local-addresses config))
169                (dest (assoc (message-to msg) local-addresses))
170                (orig (assoc (message-from msg) local-addresses)))
171           (cond
172            (dest
173             (let ((dest-dir (cadr dest)))
174               (deliver-message-local msg dest-file))
175             (print "Message DELIVERED (local):"))
176            (orig
177             (let ((password (caddr orig)))
178               (if (and
179                    (string=? (conc "<" (message-user msg) "@" (config-host config) ">")
180                              (message-from msg))
181                    password
182                    (string=? (message-password msg) password))
183                   (begin
184                     (deliver-message-remote msg config)
185                     (print "Message DELIVERED (remote):"))
186                   (print "Message DELIVERY REJECTED (auth failure):"))))
187            (else
188             (print "Message DELIVERY REJECTED (relay forbidden):"))))
189         (print " * From: " (message-from msg))
190         (print " * To: " (message-to msg))
191         #t)
192     (o (exn)
193        (print "Message delivery failed.")
194        (print-error-message o))))
195
196 ;; Local delivery
197
198 (define (get-local-addresses config)
199   (map (lambda (p) (cons
200                     (conc "<" (car p) "@" (config-host config) ">")
201                     (cdr p)))
202        (map (lambda (file)
203               (list (pathname-file file) file
204                     (let ((password-file (conc file ".auth")))
205                       (if (file-exists? password-file)
206                           (with-input-from-file password-file read-line)
207                           #f))))
208             (filter directory-exists?
209                     (glob (conc (config-spool-dir config) "/*"))))))
210
211 (define (deliver-message-local msg dest-dir)
212   (with-output-to-file (conc dest-dir "/" (current-seconds))
213     (lambda ()
214       (print (message-text msg)))))
215
216
217 ;; Remote delivery
218
219 (define (get-host-from-email email-string)
220   (car (string-split (cadr (string-split email-string "@")) ">")))
221
222 (define (deliver-message-remote msg config)
223   (let ((host (get-host-from-email (message-to msg))))
224     (print "Attempting delivery to host " host)
225     (let-values (((tcp-in tcp-out) (tcp-connect host 2525)))
226       (let ((smtp-session (make-outgoing-smtp-session tcp-in tcp-out)))
227         (let ((result (and
228                        (smtp-session 'expect "220")
229                        (smtp-session 'send "helo " (config-host config))
230                        (smtp-session 'expect "250")
231                        (smtp-session 'send "mail from:" (message-from msg))
232                        (smtp-session 'expect "250")
233                        (smtp-session 'send "rcpt to:" (message-to msg))
234                        (smtp-session 'expect "250")
235                        (smtp-session 'send "data")
236                        (smtp-session 'expect "354")
237                        (smtp-session 'send (message-text msg))
238                        (smtp-session 'send ".")
239                        (smtp-session 'expect "250")
240                        (smtp-session 'send "quit"))))
241           (close-input-port tcp-in)
242           (close-output-port tcp-out)
243           result)))))
244
245 (define ((make-outgoing-smtp-session tcp-in tcp-out) . command)
246   (match command
247     (('expect code)
248      (let ((result (read-line tcp-in)))
249        (print "Expecting " code " got " result)
250        (string-prefix? code result)))
251     (('send strings ...)
252      (print "Sending " (car strings) (if (> (length strings) 1) " ... (truncated)" ""))
253      (let ((processed-string
254             (string-translate* (conc (apply conc strings) "\n")
255                                '(("\n" . "\r\n")))))
256        (write-string processed-string #f tcp-out)))))
257
258 ;;; Command line argument parsing
259 ;;
260
261 (define (print-usage progname)
262   (print "Usage:\n"
263          progname " -h/--help\n"
264          progname " [-u/--user UID] [-g/--group GID] hostname [[port [spooldir]]\n"
265          "\n"
266          "The -u and -g options can be used to set the UID and GID of the process\n"
267          "following the creation of the TCP port listener (which often requires root)."))
268
269 (define (main)
270   (let ((progname (pathname-file (car (argv))))
271         (config (make-config "" 25 "/var/spool/mail" '() '())))
272     (if (null? (cdr (argv)))
273         (print-usage progname)
274         (let loop ((args (cdr (argv))))
275           (let ((this-arg (car args))
276                 (rest-args (cdr args)))
277             (if (string-prefix? "-" this-arg)
278                 (cond
279                  ((or (equal? this-arg "-u")
280                       (equal? this-arg "--user"))
281                   (config-user-set! config (string->number (car rest-args)))
282                   (loop (cdr rest-args)))
283                  ((or (equal? this-arg "-g")
284                       (equal? this-arg "--group"))
285                   (config-group-set! config (string->number (car rest-args)))
286                   (loop (cdr rest-args)))
287                  ((or (equal? this-arg "-h")
288                       (equal? this-arg "--help"))
289                   (print-usage progname))
290                  (else
291                   (print "Unknown option " this-arg "\n")
292                   (print-usage progname)))
293                 (begin
294                   (config-host-set! config this-arg)
295                   (unless (null? rest-args)
296                     (config-port-set! config (string->number (car rest-args)))
297                     (unless (null? (cdr rest-args))
298                       (config-spool-dir-set! config (cadr rest-args))))
299                   (run-server config))))))))
300
301 (main)
302
303 ;; (define (test)
304 ;;   (run-server (make-config "localhost" 2525 "spool" '() '())))