1 ;; Super-basic bell-and-whistle-free SMTP server.
3 ;; Intended for a single-user system
14 (chicken process-context)
15 (chicken process-context posix)
18 srfi-1 srfi-13 matchable base64)
20 (define lambdamail-version "LambdaMail v1.2.0")
22 (define-record config host port spool-dir user group)
23 (define-record message to from text user password)
24 (define (make-empty-message) (make-message "" "" "" "" ""))
27 (time->string (seconds->local-time) "%d %b %Y %T %z"))
30 ;;; Server initialization
33 (define (drop-privs config)
34 (let ((uid (config-user config))
35 (gid (config-group config)))
36 (if (not (null? gid)) ; Group first, since only root can switch groups.
37 (set! (current-group-id) gid))
39 (set! (current-user-id) uid))))
41 (define (run-server config)
42 (set-buffering-mode! (current-output-port) #:line)
43 (let ((listener (tcp-listen (config-port config) 10 "::")))
44 (print lambdamail-version
45 " listening on port " (config-port config) " ...")
46 (print "(Host name: " (config-host config)
47 ", Spool dir: " (config-spool-dir config) ")")
49 (server-loop listener config '())))
55 (define (server-loop listener config undelivered-messages)
56 (let* ((messages (append (receive-messages listener config) undelivered-messages)))
57 (server-loop listener config (deliver-messages config messages))))
60 ;;; Receiving messages
63 (define (receive-messages listener config)
65 (print "*** Waiting for incoming mail")
66 (let-values (((in-port out-port) (tcp-accept listener)))
67 (let-values (((local-ip remote-ip) (tcp-addresses in-port)))
68 (print "Accepted connection from " remote-ip " on " (time-stamp)))
70 (set! messages (process-smtp (make-smtp-session in-port out-port config) config))
72 (print-error-message o)))
73 (print "Terminating connection.")
74 (close-input-port in-port)
75 (close-output-port out-port))
78 (define (make-smtp-session in-port out-port config)
84 (('get-line) (read-line in-port))
85 (('send strings ...) (write-line (conc (apply conc strings) "\r") out-port))
86 (('set-user! u) (set! user u))
87 (('set-password! p) (set! password p))
88 (('set-helo! h) (set! helo h))
90 (('password) password)
93 (define (smtp-command? cmd-string input-string)
94 (string-prefix? cmd-string (string-downcase input-string)))
96 (define (smtp-command-args cmd-string input-string)
97 (if (> (string-length input-string) (string-length cmd-string))
98 (string-trim (string-drop input-string (string-length cmd-string)))
101 (define (process-smtp smtp-session config)
102 (smtp-session 'send "220 " (config-host config) " " lambdamail-version)
103 (let loop ((msg (make-empty-message))
104 (received-messages '()))
105 (let ((line (smtp-session 'get-line)))
107 (if (not (string? line))
108 '() ; Don't keep anything on unexpected termination.
110 ((smtp-command? "helo" line)
111 (smtp-session 'set-helo! (smtp-command-args "helo" line))
112 (smtp-session 'send "250 ok")
113 (loop msg received-messages))
114 ((smtp-command? "ehlo" line)
115 (smtp-session 'set-helo! (smtp-command-args "helo" line))
117 "250-" (config-host config)
118 " Hello " (smtp-command-args "ehlo" line))
119 (smtp-session 'send "250 AUTH PLAIN")
120 ;; (smtp-session 'send "250 STARTTLS")
121 (loop msg received-messages))
122 ((smtp-command? "auth plain" line)
123 (let* ((auth-string (smtp-command-args "auth plain" line))
124 (auth-decoded (base64-decode auth-string))
125 (auth-list (string-split auth-decoded "\x00"))
126 (user (car auth-list))
127 (password (cadr auth-list)))
128 (smtp-session 'set-user! user)
129 (smtp-session 'set-password! password)
130 (print "Attempted login, user: " user ", password: " password)
131 (smtp-session 'send "235 authentication successful")
132 (loop msg received-messages)))
133 ((smtp-command? "mail from:" line)
134 (message-from-set! msg (smtp-command-args "mail from:" line))
135 (smtp-session 'send "250 ok")
136 (loop msg received-messages))
137 ((smtp-command? "rcpt to:" line)
138 (message-to-set! msg (smtp-command-args "rcpt to:" line))
139 (smtp-session 'send "250 ok")
140 (loop msg received-messages))
141 ((smtp-command? "data" line)
142 (smtp-session 'send "354 intermediate")
143 (let text-loop ((text (conc "Received: from " (smtp-session 'helo) "\n"
144 "\tby " (config-host config) "\n"
145 "\tfor " (message-to msg) ";\n"
146 "\t" (time-stamp) "\n")))
147 (let ((text-line (smtp-session 'get-line)))
148 (if (string=? "." text-line)
149 (message-text-set! msg text)
150 (text-loop (conc text text-line "\n")))))
151 (message-user-set! msg (smtp-session 'user))
152 (message-password-set! msg (smtp-session 'password))
153 (smtp-session 'send "250 ok")
154 (loop (make-empty-message) (cons msg received-messages)))
155 ((smtp-command? "quit" line)
156 (smtp-session 'send "221 closing transmission channel")
158 ((string=? "" (string-trim line))
159 (loop msg received-messages))
161 (smtp-session 'send "502 command not implemented")
162 (loop msg received-messages)))))))
165 ;;; Sending/Delivering messages
168 (define (deliver-messages config messages)
169 (print "*** Attempting delivery of " (length messages) " mail items.")
170 (filter (lambda (msg) (not (deliver-message msg config)))
173 (define (deliver-message msg config)
174 (print "From: " (message-from msg))
175 (print "To: " (message-to msg))
177 (let* ((local-addresses (get-local-addresses config))
178 (dest (assoc (message-to msg) local-addresses))
179 (orig (assoc (message-from msg) local-addresses)))
182 (let ((dest-dir (cadr dest)))
183 (deliver-message-local msg dest-dir)))
185 (let ((password (caddr orig)))
186 (if (and (string=? (conc "<" (message-user msg) "@" (config-host config) ">")
189 (string=? (message-password msg) password))
190 (deliver-message-remote msg config)
192 (print "* REMOTE DELIVERY NOT ALLOWED (auth failure)")
195 (print "* REMOTE DELIVERY REJECTED (relay forbidden)")
198 (print "* DELIVERY FAILED")
199 (print-error-message o)
205 (define (get-local-addresses config)
206 (map (lambda (p) (cons
207 (conc "<" (car p) "@" (config-host config) ">")
210 (list (pathname-file file) file
211 (let ((password-file (conc file ".auth")))
212 (if (file-exists? password-file)
213 (with-input-from-file password-file read-line)
215 (filter directory-exists?
216 (glob (conc (config-spool-dir config) "/*"))))))
218 (define (deliver-message-local msg dest-dir)
219 (with-output-to-file (conc dest-dir "/" (current-seconds))
221 (print (message-text msg))))
222 (print "* MESSAGE DELIVERED (local)")
228 (define (get-domain-from-email email-string)
229 (car (string-split (cadr (string-split email-string "@")) ">")))
231 ;; This is a hack - there's no built-in interface to res_query()
232 ;; in chicken, so we have to resort to a system call to dig...
233 (define (get-mail-server-for-domain domain)
234 (let* ((mx-lines (let-values (((in out id) (process (conc "dig " domain " mx +short"))))
235 (with-input-from-port in read-lines)))
236 (mx-entries (map (lambda (l)
237 (let ((s (string-split l)))
238 (list (string->number (car s))
239 (string-drop-right (cadr s) 1)))) ; remove trailing "."
241 (sorted-mx-entries (sort mx-entries (lambda (e f) (< (car e) (car f))))))
242 (if (null? sorted-mx-entries)
243 domain ; fall-back to email address domain if no mx entries
244 (cadar sorted-mx-entries)))) ; otherwise pick the highest priority server
246 (define (deliver-message-remote msg config)
247 (let* ((domain (get-domain-from-email (message-to msg)))
248 (mail-server (get-mail-server-for-domain domain)))
249 (print "Attempting delivery to " mail-server)
250 (let-values (((tcp-in tcp-out) (tcp-connect mail-server 25)))
251 (let ((smtp-session (make-outgoing-smtp-session tcp-in tcp-out)))
253 (smtp-session 'expect "2")
254 (smtp-session 'send "helo " (config-host config))
255 (smtp-session 'expect "2")
256 (smtp-session 'send "mail from:" (message-from msg))
257 (smtp-session 'expect "2")
258 (smtp-session 'send "rcpt to:" (message-to msg))
259 (smtp-session 'expect "2")
260 (smtp-session 'send "data")
261 (smtp-session 'expect "354")
262 (smtp-session 'send (message-text msg))
263 (smtp-session 'send ".")
264 (smtp-session 'expect "2" "5") ;Do not try again on rejects.
265 (smtp-session 'send "quit"))))
266 (close-input-port tcp-in)
267 (close-output-port tcp-out)
268 (print "Connection closed.")
270 (print "* MESSAGE DELIVERED (remote)")
271 (print "* REMOTE DELIVERY FAILED (unexpected server response)"))
275 (fold (lambda (a b) (or a b)) #f l))
277 (define ((make-outgoing-smtp-session tcp-in tcp-out) . command)
280 (let ((result (read-line tcp-in)))
281 (print "Expecting one of " codes " got " result)
282 (or-list (map (lambda (code) (string-prefix? code result)) codes))))
284 (print "Sending " (if (> (string-length (car strings)) 30)
285 (string-take (car strings) 30)
287 (let ((processed-string
288 (string-translate* (conc (apply conc strings) "\n")
289 '(("\n" . "\r\n")))))
290 (write-string processed-string #f tcp-out)))))
293 ;;; Command line argument parsing
296 (define (print-usage progname)
298 progname " -h/--help\n"
299 progname " -v/--version\n"
300 progname " [-u/--user UID] [-g/--group GID] hostname [[port [spooldir]]\n"
302 "The -u and -g options can be used to set the UID and GID of the process\n"
303 "following the creation of the TCP port listener (which often requires root)."))
305 (define (print-version)
306 (print lambdamail-version))
309 (let ((progname (pathname-file (car (argv))))
310 (config (make-config "" 25 "/var/spool/mail" '() '())))
311 (if (null? (cdr (argv)))
312 (print-usage progname)
313 (let loop ((args (cdr (argv))))
314 (let ((this-arg (car args))
315 (rest-args (cdr args)))
316 (if (string-prefix? "-" this-arg)
318 ((or (equal? this-arg "-u")
319 (equal? this-arg "--user"))
320 (config-user-set! config (string->number (car rest-args)))
321 (loop (cdr rest-args)))
322 ((or (equal? this-arg "-g")
323 (equal? this-arg "--group"))
324 (config-group-set! config (string->number (car rest-args)))
325 (loop (cdr rest-args)))
326 ((or (equal? this-arg "-h")
327 (equal? this-arg "--help"))
328 (print-usage progname))
329 ((or (equal? this-arg "-v")
330 (equal? this-arg "--version"))
333 (print "Unknown option " this-arg "\n")
334 (print-usage progname)))
336 (config-host-set! config this-arg)
337 (unless (null? rest-args)
338 (config-port-set! config (string->number (car rest-args)))
339 (unless (null? (cdr rest-args))
340 (config-spool-dir-set! config (cadr rest-args))))
341 (run-server config))))))))
346 ;; (run-server (make-config "localhost" 2525 "spool" '() '())))