* shr.el (shr-insert): Don't insert double spaces.
[gnus] / lisp / sieve-manage.el
index 894f144..c542632 100644 (file)
@@ -1,26 +1,24 @@
 ;;; sieve-manage.el --- Implementation of the managesive protocol in elisp
 
-;; Copyright (C) 2001, 2002, 2003, 2004, 2005,
-;;   2006, 2007 Free Software Foundation, Inc.
+;; Copyright (C) 2001, 2002, 2003, 2004, 2005, 2006, 2007,
+;;   2008, 2009, 2010  Free Software Foundation, Inc.
 
 ;; Author: Simon Josefsson <simon@josefsson.org>
 
 ;; This file is part of GNU Emacs.
 
-;; GNU Emacs is free software; you can redistribute it and/or modify
+;; GNU Emacs is free software: you can redistribute it and/or modify
 ;; it under the terms of the GNU General Public License as published by
-;; the Free Software Foundation; either version 3, or (at your option)
-;; any later version.
+;; the Free Software Foundation, either version 3 of the License, or
+;; (at your option) any later version.
 
 ;; GNU Emacs is distributed in the hope that it will be useful,
 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
-;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.         See the
+;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 ;; GNU General Public License for more details.
 
 ;; You should have received a copy of the GNU General Public License
-;; along with GNU Emacs; see the file COPYING.  If not, write to the
-;; Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
-;; Boston, MA 02110-1301, USA.
+;; along with GNU Emacs.  If not, see <http://www.gnu.org/licenses/>.
 
 ;;; Commentary:
 
@@ -45,7 +43,6 @@
 ;; `sieve-manage-close'
 ;; close a server connection.
 ;;
-;; `sieve-manage-authenticate'
 ;; `sieve-manage-listscripts'
 ;; `sieve-manage-deletescript'
 ;; `sieve-manage-getscript'
 ;;
 ;; and that's it.  Example of a managesieve session in *scratch*:
 ;;
-;; (setq my-buf (sieve-manage-open "my.server.com"))
-;; " *sieve* my.server.com:2000*"
+;; (with-current-buffer (sieve-manage-open "mail.example.com")
+;;   (sieve-manage-authenticate)
+;;   (sieve-manage-listscripts))
 ;;
-;; (sieve-manage-authenticate "myusername" "mypassword" my-buf)
-;; 'auth
-;;
-;; (sieve-manage-listscripts my-buf)
-;; ("vacation" "testscript" ("splitmail") "badscript")
+;; => ((active . "main") "vacation")
 ;;
 ;; References:
 ;;
 (eval-and-compile
   (unless (fboundp 'declare-function) (defmacro declare-function (&rest r))))
 
-(if (featurep 'xemacs)
-    (or (load "password-cache" t)
-        ;; Not all XEmacs versions support `noerror' arg of `require'.
-       (require 'password))
-  (or (require 'password-cache nil t)
-      (require 'password)))
+(if (locate-library "password-cache")
+    (require 'password-cache)
+  (require 'password))
 
 (eval-when-compile
   (require 'sasl)
   (require 'starttls))
-(eval-and-compile
-  (autoload 'sasl-find-mechanism "sasl")
-  (autoload 'starttls-open-stream "starttls"))
+(autoload 'sasl-find-mechanism "sasl")
+(autoload 'starttls-open-stream "starttls")
+(autoload 'auth-source-user-or-password "auth-source")
 
 ;; User customizable variables:
 
   :type 'string
   :group 'sieve-manage)
 
-(defcustom sieve-manage-default-user (user-login-name)
-  "Default username to use."
-  :type 'string
-  :group 'sieve-manage)
-
 (defcustom sieve-manage-server-eol "\r\n"
   "The EOL string sent from the server."
   :type 'string
@@ -168,27 +154,28 @@ for doing the actual authentication."
   :type 'integer
   :group 'sieve-manage)
 
+(defcustom sieve-manage-default-stream 'network
+  "Default stream type to use for `sieve-manage'.
+Must be a name of a stream in `sieve-manage-stream-alist'."
+  :type 'symbol
+  :group 'sieve-manage)
+
 ;; Internal variables:
 
 (defconst sieve-manage-local-variables '(sieve-manage-server
                                         sieve-manage-port
                                         sieve-manage-auth
                                         sieve-manage-stream
-                                        sieve-manage-username
-                                        sieve-manage-password
                                         sieve-manage-process
                                         sieve-manage-client-eol
                                         sieve-manage-server-eol
                                         sieve-manage-capability))
-(defconst sieve-manage-default-stream 'network)
 (defconst sieve-manage-coding-system-for-read 'binary)
 (defconst sieve-manage-coding-system-for-write 'binary)
 (defvar sieve-manage-stream nil)
 (defvar sieve-manage-auth nil)
 (defvar sieve-manage-server nil)
 (defvar sieve-manage-port nil)
-(defvar sieve-manage-username nil)
-(defvar sieve-manage-password nil)
 (defvar sieve-manage-state 'closed
   "Managesieve state.
 Valid states are `closed', `initial', `nonauth', and `auth'.")
@@ -197,65 +184,10 @@ Valid states are `closed', `initial', `nonauth', and `auth'.")
 
 ;; Internal utility functions
 
-(defsubst sieve-manage-disable-multibyte ()
+(defmacro sieve-manage-disable-multibyte ()
   "Enable multibyte in the current buffer."
-  (when (fboundp 'set-buffer-multibyte)
-    (set-buffer-multibyte nil)))
-
-(declare-function password-read         "password-cache" (prompt &optional key))
-(declare-function password-cache-add    "password-cache" (key password))
-(declare-function password-cache-remove "password-cache" (key))
-
-;; Uses the dynamically bound `reason' variable.
-(defvar reason)
-(defun sieve-manage-interactive-login (buffer loginfunc)
-  "Login to server in BUFFER.
-LOGINFUNC is passed a username and a password, it should return t if
-it was successful authenticating itself to the server, nil otherwise.
-Returns t if login was successful, nil otherwise."
-  (with-current-buffer buffer
-    (make-local-variable 'sieve-manage-username)
-    (make-local-variable 'sieve-manage-password)
-    (let (user passwd ret reason passwd-key)
-      (condition-case ()
-         (while (or (not user) (not passwd))
-           (setq user (or sieve-manage-username
-                          (read-from-minibuffer
-                           (concat "Managesieve username for "
-                                   sieve-manage-server ": ")
-                           (or user sieve-manage-default-user)))
-                 passwd-key (concat "managesieve:" user "@" sieve-manage-server
-                                    ":" sieve-manage-port)
-                 passwd (or sieve-manage-password
-                            (password-read (concat "Managesieve password for "
-                                                   user "@" sieve-manage-server
-                                                   ": ")
-                                           passwd-key)))
-           (when (y-or-n-p "Store password for this session? ")
-             (password-cache-add passwd-key (copy-sequence passwd)))
-           (when (and user passwd)
-             (if (funcall loginfunc user passwd)
-                 (setq ret t
-                       sieve-manage-username user)
-               (if reason
-                   (message "Login failed (reason given: %s)..." reason)
-                 (message "Login failed..."))
-               (password-cache-remove passwd-key)
-               (setq sieve-manage-password nil)
-               (setq passwd nil)
-               (setq reason nil)
-               (sit-for 1))))
-       (quit (with-current-buffer buffer
-               (password-cache-remove passwd-key)
-               (setq user nil
-                     passwd nil
-                     sieve-manage-password nil)))
-       (error (with-current-buffer buffer
-                (password-cache-remove passwd-key)
-                (setq user nil
-                      passwd nil
-                      sieve-manage-password nil))))
-      ret)))
+  (unless (featurep 'xemacs)
+    '(set-buffer-multibyte nil)))
 
 (defun sieve-manage-erase (&optional p buffer)
   (let ((buffer (or buffer (current-buffer))))
@@ -310,15 +242,14 @@ Returns t if login was successful, nil otherwise."
       (when (memq (process-status process) '(open run))
        process))))
 
-(defun imap-starttls-p (buffer)
-  ;;  (and (imap-capability 'STARTTLS buffer)
+(defun sieve-manage-starttls-p (buffer)
   (condition-case ()
       (progn
        (require 'starttls)
        (call-process "starttls"))
     (error nil)))
 
-(defun imap-starttls-open (name buffer server port)
+(defun sieve-manage-starttls-open (name buffer server port)
   (let* ((port (or port sieve-manage-default-port))
         (coding-system-for-read sieve-manage-coding-system-for-read)
         (coding-system-for-write sieve-manage-coding-system-for-write)
@@ -338,70 +269,72 @@ Returns t if login was successful, nil otherwise."
       process)))
 
 ;; Authenticators
-
 (defun sieve-sasl-auth (buffer mech)
   "Login to server using the SASL MECH method."
   (message "sieve: Authenticating using %s..." mech)
-  (if (sieve-manage-interactive-login 
-       buffer
-       (lambda (user passwd)
-        (let (client step tag data rsp)
-          (setq client (sasl-make-client (sasl-find-mechanism (list mech))
-                                         user "sieve" sieve-manage-server))
-          (setq sasl-read-passphrase (function (lambda (prompt) passwd)))
-          (setq step (sasl-next-step client nil))
-          (setq tag
-                (sieve-manage-send
-                 (concat
-                  "AUTHENTICATE \""
-                  mech
-                  "\""
-                  (and (sasl-step-data step)
-                       (concat
-                        " \""
-                        (base64-encode-string
-                         (sasl-step-data step)
-                         'no-line-break)
-                        "\"")))))
-          (catch 'done
-            (while t
-              (setq rsp nil)
-              (goto-char (point-min))
-              (while (null (or (progn
-                                 (setq rsp (sieve-manage-is-string))
-                                 (if (not (and rsp (looking-at
-                                                    sieve-manage-server-eol)))
-                                     (setq rsp nil)
-                                   (goto-char (match-end 0))
-                                   rsp))
-                               (setq rsp (sieve-manage-is-okno))))
-                (accept-process-output sieve-manage-process 1)
-                (goto-char (point-min)))
-              (sieve-manage-erase)
-              (when (sieve-manage-ok-p rsp)
-                (when (string-match "^SASL \"\\([^\"]+\\)\"" (cadr rsp))
-                  (sasl-step-set-data
-                   step (base64-decode-string (match-string 1 (cadr rsp)))))
-                (if (and (setq step (sasl-next-step client step))
-                         (setq data (sasl-step-data step)))
-                    ;; We got data for server but it's finished
-                    (error "Server not ready for SASL data: %s" data)
-                  ;; The authentication process is finished.
-                  (throw 'done t)))
-              (unless (stringp rsp)
-                (apply 'error "Server aborted SASL authentication: %s %s %s"
-                       rsp))
-              (sasl-step-set-data step (base64-decode-string rsp))
-              (setq step (sasl-next-step client step))
-              (sieve-manage-send
-               (if (sasl-step-data step)
-                   (concat "\""
-                           (base64-encode-string (sasl-step-data step)
-                                                 'no-line-break)
-                           "\"")
-                 "")))))))
-      (message "sieve: Authenticating using %s...done" mech)
-    (message "sieve: Authenticating using %s...failed" mech)))
+  (with-current-buffer buffer
+    (let* ((user-password (auth-source-user-or-password
+                           '("login" "password")
+                           sieve-manage-server
+                           "sieve" nil t))
+           (client (sasl-make-client (sasl-find-mechanism (list mech))
+                                     (car user-password) "sieve" sieve-manage-server))
+           (sasl-read-passphrase
+            ;; We *need* to copy the password, because sasl will modify it
+            ;; somehow.
+            `(lambda (prompt) ,(copy-sequence (cadr user-password))))
+           (step (sasl-next-step client nil))
+           (tag (sieve-manage-send
+                 (concat
+                  "AUTHENTICATE \""
+                  mech
+                  "\""
+                  (and (sasl-step-data step)
+                       (concat
+                        " \""
+                        (base64-encode-string
+                         (sasl-step-data step)
+                         'no-line-break)
+                        "\"")))))
+           data rsp)
+      (catch 'done
+        (while t
+          (setq rsp nil)
+          (goto-char (point-min))
+          (while (null (or (progn
+                             (setq rsp (sieve-manage-is-string))
+                             (if (not (and rsp (looking-at
+                                                sieve-manage-server-eol)))
+                                 (setq rsp nil)
+                               (goto-char (match-end 0))
+                               rsp))
+                           (setq rsp (sieve-manage-is-okno))))
+            (accept-process-output sieve-manage-process 1)
+            (goto-char (point-min)))
+          (sieve-manage-erase)
+          (when (sieve-manage-ok-p rsp)
+            (when (and (cadr rsp)
+                       (string-match "^SASL \"\\([^\"]+\\)\"" (cadr rsp)))
+              (sasl-step-set-data
+               step (base64-decode-string (match-string 1 (cadr rsp)))))
+            (if (and (setq step (sasl-next-step client step))
+                     (setq data (sasl-step-data step)))
+                ;; We got data for server but it's finished
+                (error "Server not ready for SASL data: %s" data)
+              ;; The authentication process is finished.
+              (throw 'done t)))
+          (unless (stringp rsp)
+            (error "Server aborted SASL authentication: %s" (caddr rsp)))
+          (sasl-step-set-data step (base64-decode-string rsp))
+          (setq step (sasl-next-step client step))
+          (sieve-manage-send
+           (if (sasl-step-data step)
+               (concat "\""
+                       (base64-encode-string (sasl-step-data step)
+                                             'no-line-break)
+                       "\"")
+             ""))))
+      (message "sieve: Login using %s...done" mech))))
 
 (defun sieve-manage-cram-md5-p (buffer)
   (sieve-manage-capability "SASL" "CRAM-MD5" buffer))
@@ -449,14 +382,14 @@ Returns t if login was successful, nil otherwise."
 
 (defun sieve-manage-open (server &optional port stream auth buffer)
   "Open a network connection to a managesieve SERVER (string).
-Optional variable PORT is port number (integer) on remote server.
-Optional variable STREAM is any of `sieve-manage-streams' (a symbol).
-Optional variable AUTH indicates authenticator to use, see
-`sieve-manage-authenticators' for available authenticators.  If nil, chooses
-the best stream the server is capable of.
-Optional variable BUFFER is buffer (buffer, or string naming buffer)
+Optional argument PORT is port number (integer) on remote server.
+Optional argument STREAM is any of `sieve-manage-streams' (a symbol).
+Optional argument AUTH indicates authenticator to use, see
+`sieve-manage-authenticators' for available authenticators.
+If nil, chooses the best stream the server is capable of.
+Optional argument BUFFER is buffer (buffer, or string naming buffer)
 to work in."
-  (setq buffer (or buffer (format " *sieve* %s:%d" server (or port 2000))))
+  (setq buffer (or buffer (format " *sieve* %s:%d" server (or port sieve-manage-default-port))))
   (with-current-buffer (get-buffer-create buffer)
     (mapc 'make-local-variable sieve-manage-local-variables)
     (sieve-manage-disable-multibyte)
@@ -513,6 +446,17 @@ to work in."
       (sieve-manage-erase)
       buffer)))
 
+(defun sieve-manage-authenticate (&optional buffer)
+  "Authenticate on server in BUFFER.
+Return `sieve-manage-state' value."
+  (with-current-buffer (or buffer (current-buffer))
+    (if (eq sieve-manage-state 'nonauth)
+        (when (funcall (nth 2 (assq sieve-manage-auth
+                                    sieve-manage-authenticator-alist))
+                       (current-buffer))
+          (setq sieve-manage-state 'auth))
+      sieve-manage-state)))
+
 (defun sieve-manage-opened (&optional buffer)
   "Return non-nil if connection to managesieve server in BUFFER is open.
 If BUFFER is nil then the current buffer is used."
@@ -536,32 +480,19 @@ If BUFFER is nil, the current buffer is used."
     (sieve-manage-erase)
     t))
 
-(defun sieve-manage-authenticate (&optional user passwd buffer)
-  "Authenticate to server in BUFFER, using current buffer if nil.
-It uses the authenticator specified when opening the server.  If the
-authenticator requires username/passwords, they are queried from the
-user and optionally stored in the buffer.  If USER and/or PASSWD is
-specified, the user will not be questioned and the username and/or
-password is remembered in the buffer."
-  (with-current-buffer (or buffer (current-buffer))
-    (if (not (eq sieve-manage-state 'nonauth))
-       (eq sieve-manage-state 'auth)
-      (make-local-variable 'sieve-manage-username)
-      (make-local-variable 'sieve-manage-password)
-      (if user (setq sieve-manage-username user))
-      (if passwd (setq sieve-manage-password passwd))
-      (if (funcall (nth 2 (assq sieve-manage-auth
-                               sieve-manage-authenticator-alist)) buffer)
-         (setq sieve-manage-state 'auth)))))
-
 (defun sieve-manage-capability (&optional name value buffer)
+  "Check if capability NAME of server BUFFER match VALUE.
+If it does, return the server value of NAME. If not returns nil.
+If VALUE is nil, do not check VALUE and return server value.
+If NAME is nil, return the full server list of capabilities."
   (with-current-buffer (or buffer (current-buffer))
     (if (null name)
        sieve-manage-capability
-      (if (null value)
-         (nth 1 (assoc name sieve-manage-capability))
-       (when (string-match value (nth 1 (assoc name sieve-manage-capability)))
-         (nth 1 (assoc name sieve-manage-capability)))))))
+      (let ((server-value (cadr (assoc name sieve-manage-capability))))
+        (when (or (null value)
+                  (and server-value
+                       (string-match value server-value)))
+          server-value)))))
 
 (defun sieve-manage-listscripts (&optional buffer)
   (with-current-buffer (or buffer (current-buffer))
@@ -573,15 +504,14 @@ password is remembered in the buffer."
     (sieve-manage-send (format "HAVESPACE \"%s\" %s" name size))
     (sieve-manage-parse-okno)))
 
-(eval-and-compile
-  (if (fboundp 'string-bytes)
-      (defalias 'sieve-string-bytes 'string-bytes)
-    (defalias 'sieve-string-bytes 'length)))
-
 (defun sieve-manage-putscript (name content &optional buffer)
   (with-current-buffer (or buffer (current-buffer))
     (sieve-manage-send (format "PUTSCRIPT \"%s\" {%d+}%s%s" name
-                              (sieve-string-bytes content)
+                               ;; Here we assume that the coding-system will
+                               ;; replace each char with a single byte.
+                               ;; This is always the case if `content' is
+                               ;; a unibyte string.
+                              (length content)
                               sieve-manage-client-eol content))
     (sieve-manage-parse-okno)))
 
@@ -644,7 +574,7 @@ password is remembered in the buffer."
                  sieve-manage-capability))
        (push (list str) sieve-manage-capability))
       (forward-line)))
-  (when (re-search-forward (concat "^OK" sieve-manage-server-eol) nil t)
+  (when (re-search-forward (concat "^OK.*" sieve-manage-server-eol) nil t)
     (setq sieve-manage-state 'nonauth)))
 
 (defalias 'sieve-manage-parse-greeting-1 'sieve-manage-parse-capability-1)
@@ -654,7 +584,7 @@ password is remembered in the buffer."
         (prog1
             (match-string 1)
           (goto-char (match-end 0))))
-       ((looking-at (concat "{\\([0-9]+\\)}" sieve-manage-server-eol))
+       ((looking-at (concat "{\\([0-9]+\\+?\\)}" sieve-manage-server-eol))
         (let ((pos (match-end 0))
               (len (string-to-number (match-string 1))))
           (if (< (point-max) (+ pos len))
@@ -709,5 +639,4 @@ password is remembered in the buffer."
 
 (provide 'sieve-manage)
 
-;;; arch-tag: 321c4640-1371-4495-9baf-8ccb71dd5bd1
 ;; sieve-manage.el ends here