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? "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)")
128 (smtp-session 'send "220 Ready to start TLS")
130 ;; TODO: initiate TLS handshake using (ssl-start*)
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)))
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"))
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)
171 ((smtp-command? "quit" line)
172 (smtp-session 'send "221 closing transmission channel")
174 ((string=? "" (string-trim line))
175 (loop mmsg received-messages))
177 (smtp-session 'send "502 command not implemented")
178 (loop mmsg received-messages)))))))
180 (define (make-single-recipient-messages mmsg smtp-session config)
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"
188 "\t" (time-stamp) "\n"
189 (multi-message-text mmsg))
190 (multi-message-user mmsg)
191 (multi-message-password mmsg)
193 (multi-message-tos mmsg)
194 (multi-message-stamps mmsg)))
197 ;;; Message stamping and validation
200 (define (get-local-addresses config)
201 (map (lambda (p) (cons
202 (conc "<" (car p) "@" (config-host config) ">")
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)
210 (filter directory-exists?
211 (glob (conc (config-spool-dir config) "/*"))))))
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)))
219 (list #t 'local (cadr local-dest)))
221 (let ((host-password (caddr local-src)))
222 (if (and (string=? (conc "<" (multi-message-user mmsg) "@" (config-host config) ">")
223 (multi-message-from mmsg))
225 (string=? (multi-message-password mmsg) host-password))
228 (print "Provided password " (multi-message-password mmsg))
229 (print "Host password " host-password)
230 (list #f 'remote)))))
235 ;;; Sending/Delivering messages
238 (define (deliver-messages config messages)
239 (print "*** Attempting delivery of " (length messages) " mail items.")
240 (filter (lambda (msg) (not (deliver-message msg config)))
243 (define (deliver-message msg config)
244 (print "From: " (message-from msg))
245 (print "To: " (message-to msg))
247 (match (message-stamp msg)
248 ((#t 'local dest-dir) (deliver-message-local msg dest-dir))
249 ((#t 'remote) (deliver-message-remote msg config))
251 (print "* REMOTE DELIVERY NOT ALLOWED (auth failure)")
254 (print "* DELIVERY NOT ALLOWED (relay forbidden)")
257 (print "* DELIVERY FAILED")
258 (print-error-message o)
263 (define unique-file-name
266 (set! counter (modulo (+ counter 1) 1000))
267 (conc (current-seconds) "_" counter))))
269 (define (deliver-message-local msg dest-dir)
270 (with-output-to-file (conc dest-dir "/" (unique-file-name))
272 (print (message-text msg))))
273 (print "* MESSAGE DELIVERED (local)")
279 (define (get-domain-from-email email-string)
280 (car (string-split (cadr (string-split email-string "@")) ">")))
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 "."
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
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)
302 (print "* REMOTE DELIVERY FAILED (Could not connect to any mail server)")
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)))
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.")
327 (print "* MESSAGE DELIVERED (remote)")
328 (print "* REMOTE DELIVERY FAILED (unexpected server response)"))
331 (print-error-messsage o)
332 (print "* Failed to connect. Trying next server.")
333 (loop (cdr mail-servers))))))))
336 (fold (lambda (a b) (or a b)) #f l))
338 (define ((make-outgoing-smtp-session tcp-in tcp-out) . command)
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
346 (print "Expecting one of " codes " got " result)
347 (or-list (map (lambda (code)
348 (string-prefix? code result))
351 (print "Sending " (if (> (string-length (car strings)) 30)
352 (string-take (car strings) 30)
354 (let ((processed-string
355 (string-translate* (conc (apply conc strings) "\n")
356 '(("\n" . "\r\n")))))
357 (write-string processed-string #f tcp-out)))))
360 ;;; Command line argument parsing
363 (define (print-usage progname)
365 progname " -h/--help\n"
366 progname " -v/--version\n"
367 progname " [-u/--user UID] [-g/--group GID] hostname [[port [spooldir]]\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)."))
372 (define (print-version)
373 (print lambdamail-version))
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)
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"))
400 (print "Unknown option " this-arg "\n")
401 (print-usage progname)))
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))))))))
413 ;; (run-server (make-config "localhost" 2525 "spool" '() '())))