pop3.el 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930
  1. ;;; pop3.el --- Post Office Protocol (RFC 1460) interface
  2. ;; Copyright (C) 1996-2015 Free Software Foundation, Inc.
  3. ;; Author: Richard L. Pieri <ratinox@peorth.gweep.net>
  4. ;; Maintainer: emacs-devel@gnu.org
  5. ;; Keywords: mail
  6. ;; This file is part of GNU Emacs.
  7. ;; GNU Emacs is free software: you can redistribute it and/or modify
  8. ;; it under the terms of the GNU General Public License as published by
  9. ;; the Free Software Foundation, either version 3 of the License, or
  10. ;; (at your option) any later version.
  11. ;; GNU Emacs is distributed in the hope that it will be useful,
  12. ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. ;; GNU General Public License for more details.
  15. ;; You should have received a copy of the GNU General Public License
  16. ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
  17. ;;; Commentary:
  18. ;; Most of the standard Post Office Protocol version 3 (RFC 1460) commands
  19. ;; are implemented. The LIST command has not been implemented due to lack
  20. ;; of actual usefulness.
  21. ;; The optional POP3 command TOP has not been implemented.
  22. ;; This program was inspired by Kyle E. Jones's vm-pop program.
  23. ;;; Code:
  24. (eval-when-compile (require 'cl))
  25. (eval-and-compile
  26. ;; In Emacs 24, `open-protocol-stream' is an autoloaded alias for
  27. ;; `make-network-stream'.
  28. (unless (fboundp 'open-protocol-stream)
  29. (require 'proto-stream)))
  30. (require 'mail-utils)
  31. (defvar parse-time-months)
  32. (defgroup pop3 nil
  33. "Post Office Protocol."
  34. :group 'mail
  35. :group 'mail-source)
  36. (defcustom pop3-maildrop (or (user-login-name)
  37. (getenv "LOGNAME")
  38. (getenv "USER"))
  39. "*POP3 maildrop."
  40. :version "22.1" ;; Oort Gnus
  41. :type 'string
  42. :group 'pop3)
  43. (defcustom pop3-mailhost (or (getenv "MAILHOST") ;; nil -> mismatch
  44. "pop3")
  45. "*POP3 mailhost."
  46. :version "22.1" ;; Oort Gnus
  47. :type 'string
  48. :group 'pop3)
  49. (defcustom pop3-port 110
  50. "*POP3 port."
  51. :version "22.1" ;; Oort Gnus
  52. :type 'number
  53. :group 'pop3)
  54. (defcustom pop3-password-required t
  55. "*Non-nil if a password is required when connecting to POP server."
  56. :version "22.1" ;; Oort Gnus
  57. :type 'boolean
  58. :group 'pop3)
  59. ;; Should this be customizable?
  60. (defvar pop3-password nil
  61. "*Password to use when connecting to POP server.")
  62. (defcustom pop3-authentication-scheme 'pass
  63. "*POP3 authentication scheme.
  64. Defaults to `pass', for the standard USER/PASS authentication. The other
  65. valid value is `apop'."
  66. :type '(choice (const :tag "Normal user/password" pass)
  67. (const :tag "APOP" apop))
  68. :version "22.1" ;; Oort Gnus
  69. :group 'pop3)
  70. (defcustom pop3-stream-length 100
  71. "How many messages should be requested at one time.
  72. The lower the number, the more latency-sensitive the fetching
  73. will be. If your pop3 server doesn't support streaming at all,
  74. set this to 1."
  75. :type 'number
  76. :version "24.1"
  77. :group 'pop3)
  78. (defcustom pop3-leave-mail-on-server nil
  79. "Non-nil if the mail is to be left on the POP server after fetching.
  80. Mails once fetched will never be fetched again by the UIDL control.
  81. If this is neither nil nor a number, all mails will be left on the
  82. server. If this is a number, leave mails on the server for this many
  83. days since you first checked new mails. If this is nil, mails will be
  84. deleted on the server right after fetching.
  85. Gnus users should use the `:leave' keyword in a mail source to direct
  86. the behavior per server, rather than directly modifying this value.
  87. Note that POP servers maintain no state information between sessions,
  88. so what the client believes is there and what is actually there may
  89. not match up. If they do not, then you may get duplicate mails or
  90. the whole thing can fall apart and leave you with a corrupt mailbox."
  91. :version "24.4"
  92. :type '(choice (const :tag "Don't leave mails" nil)
  93. (const :tag "Leave all mails" t)
  94. (number :tag "Leave mails for this many days" :value 14))
  95. :group 'pop3)
  96. (defcustom pop3-uidl-file "~/.pop3-uidl"
  97. "File used to save UIDL."
  98. :version "24.4"
  99. :type 'file
  100. :group 'pop3)
  101. (defcustom pop3-uidl-file-backup '(0 9)
  102. "How to backup the UIDL file `pop3-uidl-file' when updating.
  103. If it is a list of numbers, the first one binds `kept-old-versions' and
  104. the other binds `kept-new-versions' to keep number of oldest and newest
  105. versions. Otherwise, the value binds `version-control' (which see).
  106. Note: Backup will take place whenever you check new mails on a server.
  107. So, you may lose the backup files having been saved before a trouble
  108. if you set it so as to make too few backups whereas you have access to
  109. many servers."
  110. :version "24.4"
  111. :type '(choice (group :tag "Keep versions" :format "\n%v" :indent 3
  112. (number :tag "oldest")
  113. (number :tag "newest"))
  114. (sexp :format "%v"
  115. :match (lambda (widget value)
  116. (condition-case nil
  117. (not (and (numberp (car value))
  118. (numberp (car (cdr value)))))
  119. (error t)))))
  120. :group 'pop3)
  121. (defvar pop3-timestamp nil
  122. "Timestamp returned when initially connected to the POP server.
  123. Used for APOP authentication.")
  124. (defvar pop3-read-point nil)
  125. (defvar pop3-debug nil)
  126. ;; Borrowed from nnheader-accept-process-output in nnheader.el. See the
  127. ;; comments there for explanations about the values.
  128. (eval-and-compile
  129. (if (and (fboundp 'nnheader-accept-process-output)
  130. (boundp 'nnheader-read-timeout))
  131. (defalias 'pop3-accept-process-output 'nnheader-accept-process-output)
  132. ;; Borrowed from `nnheader.el':
  133. (defvar pop3-read-timeout
  134. (if (string-match "windows-nt\\|os/2\\|cygwin"
  135. (symbol-name system-type))
  136. 1.0
  137. 0.01)
  138. "How long pop3 should wait between checking for the end of output.
  139. Shorter values mean quicker response, but are more CPU intensive.")
  140. (defun pop3-accept-process-output (process)
  141. (accept-process-output
  142. process
  143. (truncate pop3-read-timeout)
  144. (truncate (* (- pop3-read-timeout
  145. (truncate pop3-read-timeout))
  146. 1000))))))
  147. (defvar pop3-uidl)
  148. ;; List of UIDLs of existing messages at present in the server:
  149. ;; ("UIDL1" "UIDL2" "UIDL3"...)
  150. (defvar pop3-uidl-saved)
  151. ;; Locally saved UIDL data; an alist of the server, the user, and the UIDL
  152. ;; and timestamp pairs:
  153. ;; (("SERVER_A" ("USER_A1" "UIDL1" TIMESTAMP1 "UIDL2" TIMESTAMP2...)
  154. ;; ("USER_A2" "UIDL1" TIMESTAMP1 "UIDL2" TIMESTAMP2...)
  155. ;; ...)
  156. ;; ("SERVER_B" ("USER_B1" "UIDL1" TIMESTAMP1 "UIDL2" TIMESTAMP2...)
  157. ;; ("USER_B2" "UIDL1" TIMESTAMP1 "UIDL2" TIMESTAMP2...)
  158. ;; ...))
  159. ;; Where TIMESTAMP is the most significant two digits of an Emacs time,
  160. ;; i.e. the return value of `current-time'.
  161. ;;;###autoload
  162. (defun pop3-movemail (file)
  163. "Transfer contents of a maildrop to the specified FILE.
  164. Use streaming commands."
  165. (let ((process (pop3-open-server pop3-mailhost pop3-port))
  166. messages total-size
  167. pop3-uidl
  168. pop3-uidl-saved)
  169. (pop3-logon process)
  170. (if pop3-leave-mail-on-server
  171. (setq messages (pop3-uidl-stat process)
  172. total-size (cadr messages)
  173. messages (car messages))
  174. (let ((size (pop3-stat process)))
  175. (dotimes (i (car size)) (push (1+ i) messages))
  176. (setq messages (nreverse messages)
  177. total-size (cadr size))))
  178. (when messages
  179. (with-current-buffer (process-buffer process)
  180. (pop3-send-streaming-command process "RETR" messages total-size)
  181. (pop3-write-to-file file messages)
  182. (unless pop3-leave-mail-on-server
  183. (pop3-send-streaming-command process "DELE" messages nil))))
  184. (if pop3-leave-mail-on-server
  185. (when (prog1 (pop3-uidl-dele process) (pop3-quit process))
  186. (pop3-uidl-save))
  187. (pop3-quit process)
  188. ;; Remove UIDL data for the account that got not to leave mails.
  189. (setq pop3-uidl-saved (pop3-uidl-load))
  190. (let ((elt (assoc pop3-maildrop
  191. (cdr (assoc pop3-mailhost pop3-uidl-saved)))))
  192. (when elt
  193. (setcdr elt nil)
  194. (pop3-uidl-save))))
  195. t))
  196. (defun pop3-send-streaming-command (process command messages total-size)
  197. (erase-buffer)
  198. (let ((count (length messages))
  199. (i 1)
  200. (start-point (point-min))
  201. (waited-for 0))
  202. (while messages
  203. (process-send-string process (format "%s %d\r\n" command (pop messages)))
  204. ;; Only do 100 messages at a time to avoid pipe stalls.
  205. (when (zerop (% i pop3-stream-length))
  206. (setq start-point
  207. (pop3-wait-for-messages process pop3-stream-length
  208. total-size start-point))
  209. (incf waited-for pop3-stream-length))
  210. (incf i))
  211. (pop3-wait-for-messages process (- count waited-for)
  212. total-size start-point)))
  213. (defun pop3-wait-for-messages (process count total-size start-point)
  214. (while (> count 0)
  215. (goto-char start-point)
  216. (while (or (and (re-search-forward "^\\+OK" nil t)
  217. (or (not total-size)
  218. (re-search-forward "^\\.\r?\n" nil t)))
  219. (re-search-forward "^-ERR " nil t))
  220. (decf count)
  221. (setq start-point (point)))
  222. (unless (memq (process-status process) '(open run))
  223. (error "pop3 process died"))
  224. (when total-size
  225. (let ((size 0))
  226. (goto-char (point-min))
  227. (while (re-search-forward "^\\+OK.*\n" nil t)
  228. (setq size (+ size (- (point))
  229. (if (re-search-forward "^\\.\r?\n" nil 'move)
  230. (match-beginning 0)
  231. (point)))))
  232. (message "pop3 retrieved %dKB (%d%%)"
  233. (truncate (/ size 1000))
  234. (truncate (* (/ (* size 1.0) total-size) 100)))))
  235. (pop3-accept-process-output process))
  236. start-point)
  237. (defun pop3-write-to-file (file messages)
  238. (let ((pop-buffer (current-buffer))
  239. (start (point-min))
  240. beg end
  241. temp-buffer)
  242. (with-temp-buffer
  243. (setq temp-buffer (current-buffer))
  244. (with-current-buffer pop-buffer
  245. (goto-char (point-min))
  246. (while (re-search-forward "^\\+OK" nil t)
  247. (forward-line 1)
  248. (setq beg (point))
  249. (when (re-search-forward "^\\.\r?\n" nil t)
  250. (setq start (point))
  251. (forward-line -1)
  252. (setq end (point)))
  253. (with-current-buffer temp-buffer
  254. (goto-char (point-max))
  255. (let ((hstart (point)))
  256. (insert-buffer-substring pop-buffer beg end)
  257. (pop3-clean-region hstart (point))
  258. (goto-char (point-max))
  259. (pop3-munge-message-separator hstart (point))
  260. (when pop3-leave-mail-on-server
  261. (pop3-uidl-add-xheader hstart (pop messages)))
  262. (goto-char (point-max))))))
  263. (let ((coding-system-for-write 'binary))
  264. (goto-char (point-min))
  265. ;; Check whether something inserted a newline at the start and
  266. ;; delete it.
  267. (when (eolp)
  268. (delete-char 1))
  269. (write-region (point-min) (point-max) file nil 'nomesg)))))
  270. (defun pop3-logon (process)
  271. (let ((pop3-password pop3-password))
  272. ;; for debugging only
  273. (if pop3-debug (switch-to-buffer (process-buffer process)))
  274. ;; query for password
  275. (if (and pop3-password-required (not pop3-password))
  276. (setq pop3-password
  277. (read-passwd (format "Password for %s: " pop3-maildrop))))
  278. (cond ((equal 'apop pop3-authentication-scheme)
  279. (pop3-apop process pop3-maildrop))
  280. ((equal 'pass pop3-authentication-scheme)
  281. (pop3-user process pop3-maildrop)
  282. (pop3-pass process))
  283. (t (error "Invalid POP3 authentication scheme")))))
  284. (defun pop3-get-message-count ()
  285. "Return the number of messages in the maildrop."
  286. (let* ((process (pop3-open-server pop3-mailhost pop3-port))
  287. message-count
  288. (pop3-password pop3-password))
  289. ;; for debugging only
  290. (if pop3-debug (switch-to-buffer (process-buffer process)))
  291. ;; query for password
  292. (if (and pop3-password-required (not pop3-password))
  293. (setq pop3-password
  294. (read-passwd (format "Password for %s: " pop3-maildrop))))
  295. (cond ((equal 'apop pop3-authentication-scheme)
  296. (pop3-apop process pop3-maildrop))
  297. ((equal 'pass pop3-authentication-scheme)
  298. (pop3-user process pop3-maildrop)
  299. (pop3-pass process))
  300. (t (error "Invalid POP3 authentication scheme")))
  301. (setq message-count (car (pop3-stat process)))
  302. (pop3-quit process)
  303. message-count))
  304. (defun pop3-uidl-stat (process)
  305. "Return a list of unread message numbers and total size."
  306. (pop3-send-command process "UIDL")
  307. (let (err messages size)
  308. (if (condition-case code
  309. (progn
  310. (pop3-read-response process)
  311. t)
  312. (error (setq err (error-message-string code))
  313. nil))
  314. (let ((start pop3-read-point)
  315. saved list)
  316. (with-current-buffer (process-buffer process)
  317. (while (not (re-search-forward "^\\.\r\n" nil t))
  318. (unless (memq (process-status process) '(open run))
  319. (error "pop3 server closed the connection"))
  320. (pop3-accept-process-output process)
  321. (goto-char start))
  322. (setq pop3-read-point (point-marker)
  323. pop3-uidl nil)
  324. (while (progn (forward-line -1) (>= (point) start))
  325. (when (looking-at "[0-9]+ \\([^\n\r ]+\\)")
  326. (push (match-string 1) pop3-uidl)))
  327. (when pop3-uidl
  328. (setq pop3-uidl-saved (pop3-uidl-load)
  329. saved (cdr (assoc pop3-maildrop
  330. (cdr (assoc pop3-mailhost
  331. pop3-uidl-saved)))))
  332. (let ((i (length pop3-uidl)))
  333. (while (> i 0)
  334. (unless (member (nth (1- i) pop3-uidl) saved)
  335. (push i messages))
  336. (decf i)))
  337. (when messages
  338. (setq list (pop3-list process)
  339. size 0)
  340. (dolist (msg messages)
  341. (setq size (+ size (cdr (assq msg list)))))
  342. (list messages size)))))
  343. (message "%s doesn't support UIDL (%s), so we try a regressive way..."
  344. pop3-mailhost err)
  345. (sit-for 1)
  346. (setq size (pop3-stat process))
  347. (dotimes (i (car size)) (push (1+ i) messages))
  348. (setcar size (nreverse messages))
  349. size)))
  350. (defun pop3-uidl-dele (process)
  351. "Delete messages according to `pop3-leave-mail-on-server'.
  352. Return non-nil if it is necessary to update the local UIDL file."
  353. (let* ((ctime (current-time))
  354. (srvr (assoc pop3-mailhost pop3-uidl-saved))
  355. (saved (assoc pop3-maildrop (cdr srvr)))
  356. i uidl mod new tstamp dele)
  357. (setcdr (cdr ctime) nil)
  358. ;; Add new messages to the data to be saved.
  359. (cond ((and pop3-uidl saved)
  360. (setq i (1- (length pop3-uidl)))
  361. (while (>= i 0)
  362. (unless (member (setq uidl (nth i pop3-uidl)) (cdr saved))
  363. (push ctime new)
  364. (push uidl new))
  365. (decf i)))
  366. (pop3-uidl
  367. (setq new (apply 'nconc (mapcar (lambda (elt) (list elt ctime))
  368. pop3-uidl)))))
  369. (when new (setq mod t))
  370. ;; List expirable messages and delete them from the data to be saved.
  371. (setq ctime (when (numberp pop3-leave-mail-on-server)
  372. (/ (+ (* (car ctime) 65536.0) (cadr ctime)) 86400))
  373. i (1- (length saved)))
  374. (while (> i 0)
  375. (if (member (setq uidl (nth (1- i) saved)) pop3-uidl)
  376. (progn
  377. (setq tstamp (nth i saved))
  378. (if (and ctime
  379. (> (- ctime (/ (+ (* (car tstamp) 65536.0) (cadr tstamp))
  380. 86400))
  381. pop3-leave-mail-on-server))
  382. ;; Mails to delete.
  383. (progn
  384. (setq mod t)
  385. (push uidl dele))
  386. ;; Mails to keep.
  387. (push tstamp new)
  388. (push uidl new)))
  389. ;; Mails having been deleted in the server.
  390. (setq mod t))
  391. (decf i 2))
  392. (cond (saved
  393. (setcdr saved new))
  394. (srvr
  395. (setcdr (last srvr) (list (cons pop3-maildrop new))))
  396. (t
  397. (add-to-list 'pop3-uidl-saved
  398. (list pop3-mailhost (cons pop3-maildrop new))
  399. t)))
  400. ;; Actually delete the messages in the server.
  401. (when dele
  402. (setq uidl nil
  403. i (length pop3-uidl))
  404. (while (> i 0)
  405. (when (member (nth (1- i) pop3-uidl) dele)
  406. (push i uidl))
  407. (decf i))
  408. (when uidl
  409. (pop3-send-streaming-command process "DELE" uidl nil)))
  410. mod))
  411. (defun pop3-uidl-load ()
  412. "Load saved UIDL."
  413. (when (file-exists-p pop3-uidl-file)
  414. (with-temp-buffer
  415. (condition-case code
  416. (progn
  417. (insert-file-contents pop3-uidl-file)
  418. (goto-char (point-min))
  419. (read (current-buffer)))
  420. (error
  421. (message "Error while loading %s (%s)"
  422. pop3-uidl-file (error-message-string code))
  423. (sit-for 1)
  424. nil)))))
  425. (defun pop3-uidl-save ()
  426. "Save UIDL."
  427. (with-temp-buffer
  428. (if pop3-uidl-saved
  429. (progn
  430. (insert "(")
  431. (dolist (srvr pop3-uidl-saved)
  432. (when (cdr srvr)
  433. (insert "(\"" (pop srvr) "\"\n ")
  434. (dolist (elt srvr)
  435. (when (cdr elt)
  436. (insert "(\"" (pop elt) "\"\n ")
  437. (while elt
  438. (insert (format "\"%s\" %s\n " (pop elt) (pop elt))))
  439. (delete-char -4)
  440. (insert ")\n ")))
  441. (delete-char -3)
  442. (if (eq (char-before) ?\))
  443. (insert ")\n ")
  444. (goto-char (1+ (point-at-bol)))
  445. (delete-region (point) (point-max)))))
  446. (when (eq (char-before) ? )
  447. (delete-char -2))
  448. (insert ")\n"))
  449. (insert "()\n"))
  450. (let ((buffer-file-name pop3-uidl-file)
  451. (delete-old-versions t)
  452. (kept-new-versions kept-new-versions)
  453. (kept-old-versions kept-old-versions)
  454. (version-control version-control))
  455. (if (consp pop3-uidl-file-backup)
  456. (setq kept-new-versions (cadr pop3-uidl-file-backup)
  457. kept-old-versions (car pop3-uidl-file-backup)
  458. version-control t)
  459. (setq version-control pop3-uidl-file-backup))
  460. (save-buffer))))
  461. (defun pop3-uidl-add-xheader (start msgno)
  462. "Add X-UIDL header."
  463. (let ((case-fold-search t))
  464. (save-restriction
  465. (narrow-to-region start (progn
  466. (goto-char start)
  467. (search-forward "\n\n" nil 'move)
  468. (1- (point))))
  469. (goto-char start)
  470. (while (re-search-forward "^x-uidl:" nil t)
  471. (while (progn
  472. (forward-line 1)
  473. (memq (char-after) '(?\t ? ))))
  474. (delete-region (match-beginning 0) (point)))
  475. (goto-char (point-max))
  476. (insert "X-UIDL: " (nth (1- msgno) pop3-uidl) "\n"))))
  477. (defcustom pop3-stream-type nil
  478. "*Transport security type for POP3 connections.
  479. This may be either nil (plain connection), `ssl' (use an
  480. SSL/TSL-secured stream) or `starttls' (use the starttls mechanism
  481. to turn on TLS security after opening the stream). However, if
  482. this is nil, `ssl' is assumed for connections to port
  483. 995 (pop3s)."
  484. :version "23.1" ;; No Gnus
  485. :group 'pop3
  486. :type '(choice (const :tag "Plain" nil)
  487. (const :tag "SSL/TLS" ssl)
  488. (const starttls)))
  489. (eval-and-compile
  490. (if (fboundp 'set-process-query-on-exit-flag)
  491. (defalias 'pop3-set-process-query-on-exit-flag
  492. 'set-process-query-on-exit-flag)
  493. (defalias 'pop3-set-process-query-on-exit-flag
  494. 'process-kill-without-query)))
  495. (defun pop3-open-server (mailhost port)
  496. "Open TCP connection to MAILHOST on PORT.
  497. Returns the process associated with the connection."
  498. (let ((coding-system-for-read 'binary)
  499. (coding-system-for-write 'binary)
  500. result)
  501. (with-current-buffer
  502. (get-buffer-create (concat " trace of POP session to "
  503. mailhost))
  504. (erase-buffer)
  505. (setq pop3-read-point (point-min))
  506. (setq result
  507. (open-protocol-stream
  508. "POP" (current-buffer) mailhost port
  509. :type (cond
  510. ((or (eq pop3-stream-type 'ssl)
  511. (and (not pop3-stream-type)
  512. (member port '(995 "pop3s"))))
  513. 'tls)
  514. (t
  515. (or pop3-stream-type 'network)))
  516. :warn-unless-encrypted t
  517. :capability-command "CAPA\r\n"
  518. :end-of-command "^\\(-ERR\\|+OK\\).*\n"
  519. :end-of-capability "^\\.\r?\n\\|^-ERR"
  520. :success "^\\+OK.*\n"
  521. :return-list t
  522. :starttls-function
  523. (lambda (capabilities)
  524. (and (string-match "\\bSTLS\\b" capabilities)
  525. "STLS\r\n"))))
  526. (when result
  527. (let ((response (plist-get (cdr result) :greeting)))
  528. (setq pop3-timestamp
  529. (substring response (or (string-match "<" response) 0)
  530. (+ 1 (or (string-match ">" response) -1)))))
  531. (pop3-set-process-query-on-exit-flag (car result) nil)
  532. (erase-buffer)
  533. (car result)))))
  534. ;; Support functions
  535. (defun pop3-send-command (process command)
  536. (set-buffer (process-buffer process))
  537. (goto-char (point-max))
  538. ;; (if (= (aref command 0) ?P)
  539. ;; (insert "PASS <omitted>\r\n")
  540. ;; (insert command "\r\n"))
  541. (setq pop3-read-point (point))
  542. (goto-char (point-max))
  543. (process-send-string process (concat command "\r\n")))
  544. (defun pop3-read-response (process &optional return)
  545. "Read the response from the server.
  546. Return the response string if optional second argument is non-nil."
  547. (let ((case-fold-search nil)
  548. match-end)
  549. (with-current-buffer (process-buffer process)
  550. (goto-char pop3-read-point)
  551. (while (and (memq (process-status process) '(open run))
  552. (not (search-forward "\r\n" nil t)))
  553. (pop3-accept-process-output process)
  554. (goto-char pop3-read-point))
  555. (setq match-end (point))
  556. (goto-char pop3-read-point)
  557. (if (looking-at "-ERR")
  558. (error "%s" (buffer-substring (point) (- match-end 2)))
  559. (if (not (looking-at "+OK"))
  560. (progn (setq pop3-read-point match-end) nil)
  561. (setq pop3-read-point match-end)
  562. (if return
  563. (buffer-substring (point) match-end)
  564. t)
  565. )))))
  566. (defun pop3-clean-region (start end)
  567. (setq end (set-marker (make-marker) end))
  568. (save-excursion
  569. (goto-char start)
  570. (while (and (< (point) end) (search-forward "\r\n" end t))
  571. (replace-match "\n" t t))
  572. (goto-char start)
  573. (while (and (< (point) end) (re-search-forward "^\\." end t))
  574. (replace-match "" t t)
  575. (forward-char)))
  576. (set-marker end nil))
  577. ;; Copied from message-make-date.
  578. (defun pop3-make-date (&optional now)
  579. "Make a valid date header.
  580. If NOW, use that time instead."
  581. (require 'parse-time)
  582. (let* ((now (or now (current-time)))
  583. (zone (nth 8 (decode-time now)))
  584. (sign "+"))
  585. (when (< zone 0)
  586. (setq sign "-")
  587. (setq zone (- zone)))
  588. (concat
  589. (format-time-string "%d" now)
  590. ;; The month name of the %b spec is locale-specific. Pfff.
  591. (format " %s "
  592. (capitalize (car (rassoc (nth 4 (decode-time now))
  593. parse-time-months))))
  594. (format-time-string "%Y %H:%M:%S " now)
  595. ;; We do all of this because XEmacs doesn't have the %z spec.
  596. (format "%s%02d%02d" sign (/ zone 3600) (/ (% zone 3600) 60)))))
  597. (defun pop3-munge-message-separator (start end)
  598. "Check to see if a message separator exists. If not, generate one."
  599. (save-excursion
  600. (save-restriction
  601. (narrow-to-region start end)
  602. (goto-char (point-min))
  603. (if (not (or (looking-at "From .?") ; Unix mail
  604. (looking-at "\001\001\001\001\n") ; MMDF
  605. (looking-at "BABYL OPTIONS:") ; Babyl
  606. ))
  607. (let* ((from (mail-strip-quoted-names (mail-fetch-field "From")))
  608. (tdate (mail-fetch-field "Date"))
  609. (date (split-string (or (and tdate
  610. (not (string= "" tdate))
  611. tdate)
  612. (pop3-make-date))
  613. " "))
  614. (From_))
  615. ;; sample date formats I have seen
  616. ;; Date: Tue, 9 Jul 1996 09:04:21 -0400 (EDT)
  617. ;; Date: 08 Jul 1996 23:22:24 -0400
  618. ;; should be
  619. ;; Tue Jul 9 09:04:21 1996
  620. ;; Fixme: This should use timezone on the date field contents.
  621. (setq date
  622. (cond ((not date)
  623. "Tue Jan 1 00:00:0 1900")
  624. ((string-match "[A-Z]" (nth 0 date))
  625. (format "%s %s %s %s %s"
  626. (nth 0 date) (nth 2 date) (nth 1 date)
  627. (nth 4 date) (nth 3 date)))
  628. (t
  629. ;; this really needs to be better but I don't feel
  630. ;; like writing a date to day converter.
  631. (format "Sun %s %s %s %s"
  632. (nth 1 date) (nth 0 date)
  633. (nth 3 date) (nth 2 date)))
  634. ))
  635. (setq From_ (format "\nFrom %s %s\n" from date))
  636. (while (string-match "," From_)
  637. (setq From_ (concat (substring From_ 0 (match-beginning 0))
  638. (substring From_ (match-end 0)))))
  639. (goto-char (point-min))
  640. (insert From_)
  641. (if (search-forward "\n\n" nil t)
  642. nil
  643. (goto-char (point-max))
  644. (insert "\n"))
  645. (let ((size (- (point-max) (point))))
  646. (forward-line -1)
  647. (insert (format "Content-Length: %s\n" size)))
  648. )))))
  649. ;; The Command Set
  650. ;; AUTHORIZATION STATE
  651. (defun pop3-user (process user)
  652. "Send USER information to POP3 server."
  653. (pop3-send-command process (format "USER %s" user))
  654. (let ((response (pop3-read-response process t)))
  655. (if (not (and response (string-match "+OK" response)))
  656. (error "USER %s not valid" user))))
  657. (defun pop3-pass (process)
  658. "Send authentication information to the server."
  659. (pop3-send-command process (format "PASS %s" pop3-password))
  660. (let ((response (pop3-read-response process t)))
  661. (if (not (and response (string-match "+OK" response)))
  662. (pop3-quit process))))
  663. (defun pop3-apop (process user)
  664. "Send alternate authentication information to the server."
  665. (let ((pass pop3-password))
  666. (if (and pop3-password-required (not pass))
  667. (setq pass
  668. (read-passwd (format "Password for %s: " pop3-maildrop))))
  669. (if pass
  670. (let ((hash (md5 (concat pop3-timestamp pass) nil nil 'binary)))
  671. (pop3-send-command process (format "APOP %s %s" user hash))
  672. (let ((response (pop3-read-response process t)))
  673. (if (not (and response (string-match "+OK" response)))
  674. (pop3-quit process)))))
  675. ))
  676. ;; TRANSACTION STATE
  677. (defun pop3-stat (process)
  678. "Return the number of messages in the maildrop and the maildrop's size."
  679. (pop3-send-command process "STAT")
  680. (let ((response (pop3-read-response process t)))
  681. (list (string-to-number (nth 1 (split-string response " ")))
  682. (string-to-number (nth 2 (split-string response " "))))
  683. ))
  684. (defun pop3-list (process &optional msg)
  685. "If MSG is nil, return an alist of (MESSAGE-ID . SIZE) pairs.
  686. Otherwise, return the size of the message-id MSG"
  687. (pop3-send-command process (if msg
  688. (format "LIST %d" msg)
  689. "LIST"))
  690. (let ((response (pop3-read-response process t)))
  691. (if msg
  692. (string-to-number (nth 2 (split-string response " ")))
  693. (let ((start pop3-read-point) end)
  694. (with-current-buffer (process-buffer process)
  695. (while (not (re-search-forward "^\\.\r\n" nil t))
  696. (pop3-accept-process-output process)
  697. (goto-char start))
  698. (setq pop3-read-point (point-marker))
  699. (goto-char (match-beginning 0))
  700. (setq end (point-marker))
  701. (mapcar #'(lambda (s) (let ((split (split-string s " ")))
  702. (cons (string-to-number (nth 0 split))
  703. (string-to-number (nth 1 split)))))
  704. (split-string (buffer-substring start end) "\r\n" t)))))))
  705. (defun pop3-retr (process msg crashbuf)
  706. "Retrieve message-id MSG to buffer CRASHBUF."
  707. (pop3-send-command process (format "RETR %s" msg))
  708. (pop3-read-response process)
  709. (let ((start pop3-read-point) end)
  710. (with-current-buffer (process-buffer process)
  711. (while (not (re-search-forward "^\\.\r\n" nil t))
  712. (unless (memq (process-status process) '(open run))
  713. (error "pop3 server closed the connection"))
  714. (pop3-accept-process-output process)
  715. (goto-char start))
  716. (setq pop3-read-point (point-marker))
  717. ;; this code does not seem to work for some POP servers...
  718. ;; and I cannot figure out why not.
  719. ;; (goto-char (match-beginning 0))
  720. ;; (backward-char 2)
  721. ;; (if (not (looking-at "\r\n"))
  722. ;; (insert "\r\n"))
  723. ;; (re-search-forward "\\.\r\n")
  724. (goto-char (match-beginning 0))
  725. (setq end (point-marker))
  726. (pop3-clean-region start end)
  727. (pop3-munge-message-separator start end)
  728. (with-current-buffer crashbuf
  729. (erase-buffer))
  730. (copy-to-buffer crashbuf start end)
  731. (delete-region start end)
  732. )))
  733. (defun pop3-dele (process msg)
  734. "Mark message-id MSG as deleted."
  735. (pop3-send-command process (format "DELE %s" msg))
  736. (pop3-read-response process))
  737. (defun pop3-noop (process msg)
  738. "No-operation."
  739. (pop3-send-command process "NOOP")
  740. (pop3-read-response process))
  741. (defun pop3-last (process)
  742. "Return highest accessed message-id number for the session."
  743. (pop3-send-command process "LAST")
  744. (let ((response (pop3-read-response process t)))
  745. (string-to-number (nth 1 (split-string response " ")))
  746. ))
  747. (defun pop3-rset (process)
  748. "Remove all delete marks from current maildrop."
  749. (pop3-send-command process "RSET")
  750. (pop3-read-response process))
  751. ;; UPDATE
  752. (defun pop3-quit (process)
  753. "Close connection to POP3 server.
  754. Tell server to remove all messages marked as deleted, unlock the maildrop,
  755. and close the connection."
  756. (pop3-send-command process "QUIT")
  757. (pop3-read-response process t)
  758. (if process
  759. (with-current-buffer (process-buffer process)
  760. (goto-char (point-max))
  761. (delete-process process))))
  762. ;; Summary of POP3 (Post Office Protocol version 3) commands and responses
  763. ;;; AUTHORIZATION STATE
  764. ;; Initial TCP connection
  765. ;; Arguments: none
  766. ;; Restrictions: none
  767. ;; Possible responses:
  768. ;; +OK [POP3 server ready]
  769. ;; USER name
  770. ;; Arguments: a server specific user-id (required)
  771. ;; Restrictions: authorization state [after unsuccessful USER or PASS
  772. ;; Possible responses:
  773. ;; +OK [valid user-id]
  774. ;; -ERR [invalid user-id]
  775. ;; PASS string
  776. ;; Arguments: a server/user-id specific password (required)
  777. ;; Restrictions: authorization state, after successful USER
  778. ;; Possible responses:
  779. ;; +OK [maildrop locked and ready]
  780. ;; -ERR [invalid password]
  781. ;; -ERR [unable to lock maildrop]
  782. ;; STLS (RFC 2595)
  783. ;; Arguments: none
  784. ;; Restrictions: Only permitted in AUTHORIZATION state.
  785. ;; Possible responses:
  786. ;; +OK
  787. ;; -ERR
  788. ;;; TRANSACTION STATE
  789. ;; STAT
  790. ;; Arguments: none
  791. ;; Restrictions: transaction state
  792. ;; Possible responses:
  793. ;; +OK nn mm [# of messages, size of maildrop]
  794. ;; LIST [msg]
  795. ;; Arguments: a message-id (optional)
  796. ;; Restrictions: transaction state; msg must not be deleted
  797. ;; Possible responses:
  798. ;; +OK [scan listing follows]
  799. ;; -ERR [no such message]
  800. ;; RETR msg
  801. ;; Arguments: a message-id (required)
  802. ;; Restrictions: transaction state; msg must not be deleted
  803. ;; Possible responses:
  804. ;; +OK [message contents follow]
  805. ;; -ERR [no such message]
  806. ;; DELE msg
  807. ;; Arguments: a message-id (required)
  808. ;; Restrictions: transaction state; msg must not be deleted
  809. ;; Possible responses:
  810. ;; +OK [message deleted]
  811. ;; -ERR [no such message]
  812. ;; NOOP
  813. ;; Arguments: none
  814. ;; Restrictions: transaction state
  815. ;; Possible responses:
  816. ;; +OK
  817. ;; LAST
  818. ;; Arguments: none
  819. ;; Restrictions: transaction state
  820. ;; Possible responses:
  821. ;; +OK nn [highest numbered message accessed]
  822. ;; RSET
  823. ;; Arguments: none
  824. ;; Restrictions: transaction state
  825. ;; Possible responses:
  826. ;; +OK [all delete marks removed]
  827. ;; UIDL [msg]
  828. ;; Arguments: a message-id (optional)
  829. ;; Restrictions: transaction state; msg must not be deleted
  830. ;; Possible responses:
  831. ;; +OK [uidl listing follows]
  832. ;; -ERR [no such message]
  833. ;;; UPDATE STATE
  834. ;; QUIT
  835. ;; Arguments: none
  836. ;; Restrictions: none
  837. ;; Possible responses:
  838. ;; +OK [TCP connection closed]
  839. (provide 'pop3)
  840. ;;; pop3.el ends here