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)
19 srfi-1 srfi-13 matchable base64)
21 (define lambdamail-version "LambdaMail v1.7.0")
23 (define-record config host port spool-dir user group)
26 (time->string (seconds->local-time) "%d %b %Y %T %z"))
29 ;;; Server initialization
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))
38 (set! (current-user-id) uid))))
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) ")")
48 (server-loop listener config '())))
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))))
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 '() "" "" "" "" '()))
67 ;;; Receiving messages
70 (define (receive-messages listener config)
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)))
77 (set! messages (process-smtp (make-smtp-session in-port out-port config) config))
79 (print-error-message o)))
80 (print "Terminating connection.")
81 (close-input-port in-port)
82 (close-output-port out-port))
85 (define (make-smtp-session in-port out-port config)
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))
94 (define (smtp-command? cmd-string input-string)
95 (string-prefix? cmd-string (string-downcase input-string)))
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)))
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)))
108 (if (not (string? line))
109 '() ; Don't keep anything on unexpected termination.
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))
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)))
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"))
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)
161 ((smtp-command? "quit" line)
162 (smtp-session 'send "221 closing transmission channel")
164 ((string=? "" (string-trim line))
165 (loop mmsg received-messages))
167 (smtp-session 'send "502 command not implemented")
168 (loop mmsg received-messages)))))))
170 (define (make-single-recipient-messages mmsg smtp-session config)
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"
178 "\t" (time-stamp) "\n"
179 (multi-message-text mmsg))
180 (multi-message-user mmsg)
181 (multi-message-password mmsg)
183 (multi-message-tos mmsg)
184 (multi-message-stamps mmsg)))
187 ;;; Message stamping and validation
190 (define (get-local-addresses config)
191 (map (lambda (p) (cons
192 (conc "<" (car p) "@" (config-host config) ">")
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)
200 (filter directory-exists?
201 (glob (conc (config-spool-dir config) "/*"))))))
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)))
209 (list #t 'local (cadr local-dest)))
211 (let ((host-password (caddr local-src)))
212 (if (and (string=? (conc "<" (multi-message-user mmsg) "@" (config-host config) ">")
213 (multi-message-from mmsg))
215 (string=? (multi-message-password mmsg) host-password))
218 (print "Provided password " (multi-message-password mmsg))
219 (print "Host password " host-password)
220 (list #f 'remote)))))
225 ;;; Sending/Delivering messages
228 (define (deliver-messages config messages)
229 (print "*** Attempting delivery of " (length messages) " mail items.")
230 (filter (lambda (msg) (not (deliver-message msg config)))
233 (define (deliver-message msg config)
234 (print "From: " (message-from msg))
235 (print "To: " (message-to msg))
237 (match (message-stamp msg)
238 ((#t 'local dest-dir) (deliver-message-local msg dest-dir))
239 ((#t 'remote) (deliver-message-remote msg config))
241 (print "* REMOTE DELIVERY NOT ALLOWED (auth failure)")
244 (print "* DELIVERY NOT ALLOWED (relay forbidden)")
247 (print "* DELIVERY FAILED")
248 (print-error-message o)
253 (define unique-file-name
256 (set! counter (modulo (+ counter 1) 1000))
257 (conc (current-seconds) "_" counter))))
259 (define (deliver-message-local msg dest-dir)
260 (with-output-to-file (conc dest-dir "/" (unique-file-name))
262 (print (message-text msg))))
263 (print "* MESSAGE DELIVERED (local)")
269 (define (get-domain-from-email email-string)
270 (car (string-split (cadr (string-split email-string "@")) ">")))
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-servers-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 "."
282 (sorted-mx-entries (map cadr (sort mx-entries (lambda (e f) (< (car e) (car f)))))))
283 (if (null? sorted-mx-entries)
284 (list domain) ; fall-back to email address domain if no mx entries
285 sorted-mx-entries))) ; otherwise pick the highest priority server
287 (define (deliver-message-remote msg config)
288 (let ((domain (get-domain-from-email (message-to msg))))
289 (let loop ((mail-servers (get-mail-servers-for-domain domain)))
290 (if (null? mail-servers)
292 (print "* REMOTE DELIVERY FAILED (Could not connect to any mail server)")
295 (let ((mail-server (car mail-servers)))
296 (print "Attempting delivery to " mail-server)
297 (let-values (((tcp-in tcp-out) (tcp-connect mail-server 25)))
298 (let ((smtp-session (make-outgoing-smtp-session tcp-in tcp-out)))
300 (smtp-session 'expect "220")
301 (smtp-session 'send "helo " (config-host config))
302 (smtp-session 'expect "250")
303 (smtp-session 'send "mail from:" (message-from msg))
304 (smtp-session 'expect "250")
305 (smtp-session 'send "rcpt to:" (message-to msg))
306 (smtp-session 'expect "250")
307 (smtp-session 'send "data")
308 (smtp-session 'expect "354")
309 (smtp-session 'send (message-text msg))
310 (smtp-session 'send ".")
311 (smtp-session 'expect "250" "5") ;Do not try again on rejects.
312 (smtp-session 'send "quit"))))
313 (close-input-port tcp-in)
314 (close-output-port tcp-out)
315 (print "Connection closed.")
317 (print "* MESSAGE DELIVERED (remote)")
318 (print "* REMOTE DELIVERY FAILED (unexpected server response)"))
321 (print-error-messsage o)
322 (print "* Failed to connect. Trying next server.")
323 (loop (cdr mail-servers))))))))
326 (fold (lambda (a b) (or a b)) #f l))
328 (define ((make-outgoing-smtp-session tcp-in tcp-out) . command)
331 (let loop ((result (read-line tcp-in)))
332 (if (and (> (string-length result) 3)
333 (eq? (string-ref result 3) #\-))
334 (loop (read-line tcp-in)) ;status continues on next line
336 (print "Expecting one of " codes " got " result)
337 (or-list (map (lambda (code)
338 (string-prefix? code result))
341 (print "Sending " (if (> (string-length (car strings)) 30)
342 (string-take (car strings) 30)
344 (let ((processed-string
345 (string-translate* (conc (apply conc strings) "\n")
346 '(("\n" . "\r\n")))))
347 (write-string processed-string #f tcp-out)))))
350 ;;; Command line argument parsing
353 (define (print-usage progname)
355 progname " -h/--help\n"
356 progname " -v/--version\n"
357 progname " [-u/--user UID] [-g/--group GID] hostname [[port [spooldir]]\n"
359 "The -u and -g options can be used to set the UID and GID of the process\n"
360 "following the creation of the TCP port listener (which often requires root)."))
362 (define (print-version)
363 (print lambdamail-version))
366 (let ((progname (pathname-file (car (argv))))
367 (config (make-config "" 25 "/var/spool/mail" '() '())))
368 (if (null? (cdr (argv)))
369 (print-usage progname)
370 (let loop ((args (cdr (argv))))
371 (let ((this-arg (car args))
372 (rest-args (cdr args)))
373 (if (string-prefix? "-" this-arg)
375 ((or (equal? this-arg "-u")
376 (equal? this-arg "--user"))
377 (config-user-set! config (string->number (car rest-args)))
378 (loop (cdr rest-args)))
379 ((or (equal? this-arg "-g")
380 (equal? this-arg "--group"))
381 (config-group-set! config (string->number (car rest-args)))
382 (loop (cdr rest-args)))
383 ((or (equal? this-arg "-h")
384 (equal? this-arg "--help"))
385 (print-usage progname))
386 ((or (equal? this-arg "-v")
387 (equal? this-arg "--version"))
390 (print "Unknown option " this-arg "\n")
391 (print-usage progname)))
393 (config-host-set! config this-arg)
394 (unless (null? rest-args)
395 (config-port-set! config (string->number (car rest-args)))
396 (unless (null? (cdr rest-args))
397 (config-spool-dir-set! config (cadr rest-args))))
398 (run-server config))))))))
403 ;; (run-server (make-config "localhost" 2525 "spool" '() '())))