-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathbic.el
2639 lines (2488 loc) · 102 KB
/
bic.el
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
;;; bic.el --- Best IMAP Client -*- lexical-binding: t; -*-
;; Copyright (C) 2014 Magnus Henoch
;; Author: Magnus Henoch <[email protected]>
;; Keywords: mail
;; Package-Version: 0.0.1
;; Package-Requires: ((emacs "25") (fsm "0.2.1") (srv "0.2"))
;; URL: https://github.com/legoscia/bic
;; This program 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 of the License, or
;; (at your option) any later version.
;; This program 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
;; GNU General Public License for more details.
;; You should have received a copy of the GNU General Public License
;; along with this program. If not, see <http://www.gnu.org/licenses/>.
;;; Commentary:
;; BIC is the Best IMAP Client. No configuration necessary: just type
;; M-x bic to get started.
;;
;; Key bindings are similar to Gnus. Type C-h m to see available key
;; bindings in the current buffer. (There are three types of buffers:
;; the mailbox tree buffer, mailbox buffers, and the message buffer.)
;;
;; BIC is built on the following principles:
;;
;; - asynchronicity
;; - minimal configuration
;; - offline is online
;; - osmosis
;;
;; For more information, including a list of known problems, see the
;; README.org file. If you are viewing this text from within the
;; package system, you can find the README file at this URL:
;; https://github.com/legoscia/bic#readme
;;
;; Experience reports, bug reports and feature requests are very
;; welcome! Please submit them as issues here:
;; https://github.com/legoscia/bic/issues
;;; Code:
(require 'fsm)
(require 'srv)
(require 'bic-core)
(require 'cl-lib)
(require 'utf7)
(require 'gnus)
(require 'gnus-art)
(require 'gnus-range)
(require 'gnus-srvr)
(require 'hex-util)
(require 'avl-tree)
(declare-function bic-mailbox-tree "bic-mailbox-tree")
(defgroup bic nil
"Settings for the Best IMAP Client."
:group 'mail)
(defvar bic-running-accounts ())
(defvar bic-account-state-table (make-hash-table :test 'equal)
"Hash table mapping accounts to a state keyword.
Possible values are :connected, :disconnected, and :deactivated.")
(defvar bic-account-state-update-functions ()
"List of functions called when account state changes.
The functions are called with two argument, the name of the
account, and the new state. Possible states are the values of
`bic-account-state-table'.
When an account FSM is stopped, these functions are called with
nil as the new state.")
(defvar bic-account-mailbox-table (make-hash-table :test 'equal)
"Hash table of hash tables containing mailbox state.
The keys are account names, and the values are hash tables whose
keys are mailbox names and whose values are plists containing
mailbox state.")
(defvar bic-account-mailbox-update-functions ()
"List of functions called when mailbox state changes.
The functions are called with three arguments: the name of the
account, the name of the mailbox, and the new state plist.
If the second and third arguments are nil, it means that the
mailbox list has been renewed, and the new list can be retrieved
from `bic-account-mailbox-table'.")
(defvar bic-data-directory (locate-user-emacs-file "bic"))
(defvar bic-backlog-days 30
"Messages no more than this old will be fetched.")
(defvar bic-reconnect-interval 5
"Attempt to reconnect after this many seconds.")
(defvar bic-command-timeout 30
"Time in seconds allowed for server to respond to commands.
If no data has been received during this time, the connection is
considered dead.")
(defvar-local bic--current-account nil)
(defvar-local bic--current-mailbox nil)
(defvar-local bic--dir nil)
(defconst bic--pending-flags-prefixes '("+" "-")
"Possible markers in pending flags files.")
(defconst bic--pending-flags-prefixes-regexp
(regexp-opt bic--pending-flags-prefixes))
;;;###autoload
(defun bic (&optional new-account)
"Start BIC.
If there are no configured accounts, or if a prefix argument is
given (setting NEW-ACCOUNT to non-nil), prompt for email address.
Otherwise, start BIC for all known addresses."
(interactive "P")
(let ((accounts (and (file-directory-p bic-data-directory)
(directory-files bic-data-directory nil "@"))))
(if (or new-account (null accounts))
(progn
(call-interactively #'bic-add-account)
(bic-mailbox-tree))
(mapc #'bic-add-account
(cl-remove-if #'bic--find-account accounts))
(bic-mailbox-tree))))
;;;###autoload
(defun bic-add-account (address)
"Add ADDRESS to the list of accounts in BIC.
IMAP server details will be requested interactively."
(interactive "sEmail address: ")
(if (bic--find-account address)
(user-error "%s already running" address)
(push (start-bic-account address) bic-running-accounts)))
(defun bic-deactivate (account)
"Temporarily deactivate ACCOUNT.
Close any existing connection, and don't attempt to reconnect
until reactivated with `bic-activate'."
(interactive (list (bic--read-running-account)))
(fsm-send (bic--find-account account) :deactivate))
(defun bic-deactivate-all ()
"Temporarily deactivate all accounts.
Close any existing connections, and don't attempt to reconnect
until reactivated with `bic-activate' or `bic-activate-all'."
(interactive)
(dolist (a bic-running-accounts)
(fsm-send a :deactivate)))
(defun bic-activate (account)
"Reactivate ACCOUNT.
Attempt to reconnect to an account previously disabled with
`bic-deactivate'."
(interactive (list (bic--read-running-account)))
(fsm-send (bic--find-account account) :activate))
(defun bic-activate-all ()
"Reactivate all accounts.
Attempt to reconnect any accounts previously disabled with
`bic-deactivate' or `bic-deactivate-all'."
(interactive)
(dolist (a bic-running-accounts)
(fsm-send a :activate)))
(defun bic-stop (account)
"Stop the BIC state machine for ACCOUNT.
If you want to keep using BIC, but stop it from attempting to
reconnect to a certain account, use `bic-deactivate' instead."
(interactive (list (bic--read-running-account)))
(fsm-send (bic--find-account account) :stop))
(defun bic-stop-all ()
"Stop the BIC state machines for all accounts.
See `bic-stop'."
(interactive)
(dolist (a bic-running-accounts)
(fsm-send a :stop)))
(defun bic--read-running-account ()
"Read the name of a running account from the minibuffer."
(if (null bic-running-accounts)
(user-error "No accounts available")
(completing-read "Account: "
(mapcar
(lambda (fsm)
(plist-get (fsm-get-state-data fsm) :address))
bic-running-accounts)
nil t)))
(defun bic--find-account (account)
"Find active FSM for ACCOUNT.
ACCOUNT is a string of the form \"username@server\"."
(cl-find-if (lambda (state-data)
(string= account (plist-get state-data :address)))
bic-running-accounts
:key #'fsm-get-state-data))
(define-state-machine bic-account
:start ((address)
"Start using an IMAP account."
(bic--update-account-state address :disconnected)
(let* ((dir (expand-file-name address bic-data-directory))
(state-data (list
:address address
:dir dir
:overview-per-mailbox (make-hash-table :test 'equal)
:uid-tree-per-mailbox (make-hash-table :test 'equal)
:flags-per-mailbox (make-hash-table :test 'equal))))
(if (file-directory-p dir)
(list :existing state-data)
(list :no-data state-data)))))
(define-enter-state bic-account nil
(fsm state-data)
(pcase (plist-get state-data :connection)
((and connection (pred identity))
(fsm-send connection :stop)))
(setq bic-running-accounts (delq fsm bic-running-accounts))
;; Need to delete all mailbox buffers, since they reference hash
;; tables that are about to go stale.
(dolist (buffer (buffer-list))
(with-current-buffer buffer
(when (and (derived-mode-p 'bic-mailbox-mode)
(string= bic--current-account (plist-get state-data :address)))
(kill-buffer buffer))))
(bic--update-account-state (plist-get state-data :address) nil)
(list state-data nil))
(define-state bic-account nil
(_fsm _state-data _event _callback)
;; Nothing to do here.
nil)
(define-enter-state bic-account :no-data
(fsm state-data)
;; We know nothing about this account. Let's try to figure out the
;; mail server hostname.
;;
;; First, look for SRV records, as described in RFC 6186.
;;
;; We don't follow the specifications precisely when it comes to
;; verifying certificates for hostnames found through SRV, but
;; that's because noone else does.
(let* ((address (plist-get state-data :address))
(domain-name (substring address (1+ (cl-position ?@ address))))
(imaps-srv-results (srv-lookup (concat "_imaps._tcp." domain-name)))
(srv-candidate nil)
(candidates nil))
;; Empty hostname means "service not available".
(setq imaps-srv-results (cl-delete "" imaps-srv-results :key 'car))
(if imaps-srv-results
;; Strictly speaking, we should go through all results in
;; priority order, and pick the first one that works, but
;; since the hosts are unlikely to have SRV-ID (RFC 4985)
;; fields in their certificates (and since we don't have
;; methods to retrieve those fields), we would have to ask the
;; user to confirm every single host, which would be
;; confusing. So let's pick the first one for now.
(setq srv-candidate (list
(caar imaps-srv-results)
(cdar imaps-srv-results)
:plaintls))
;; No IMAPS service advertised. What about plain IMAP
;; (hopefully with STARTTLS)?
(let ((imap-srv-results (srv-lookup (concat "_imap._tcp." domain-name))))
(setq imap-srv-results (cl-delete "" imap-srv-results :key 'car))
(when imap-srv-results
(setq srv-candidate (list
(caar imap-srv-results)
(cdar imap-srv-results)
:starttls)))))
;; Ask user if SRV result is okay.
(when srv-candidate
(when (yes-or-no-p
(format "Use %s:%d as IMAP server? "
(car srv-candidate)
(cadr srv-candidate)))
(setq candidates (list srv-candidate))))
(unless candidates
(let* ((response (read-string
(format "IMAP server for %s (hostname or hostname:port): "
address)))
(colon-pos (cl-position ?: response)))
(if colon-pos
;; User specified port
(let ((hostname (substring response 0 colon-pos))
(port (string-to-number (substring response (1+ colon-pos)))))
;; For ports 143 and 993, we know what to expect.
(cl-case port
(143
(push (list hostname port :starttls) candidates))
(993
(push (list hostname port :plaintls) candidates))
(t
;; For other ports, try both plain TLS and STARTTLS.
(push (list hostname port :starttls) candidates)
(push (list hostname port :plaintls) candidates))))
;; No port specified. Try both 143 and 993.
(push (list response 143 :starttls) candidates)
(push (list response 993 :plaintls) candidates))))
(plist-put state-data :candidates candidates)
(plist-put state-data :username (bic--ask-for-username address))
(fsm-send fsm :try-connect)
(list state-data nil)))
(defun bic--ask-for-username (address)
"Ask the user what username to use for ADDRESS.
RFC 6186 suggests using the full email address, or if that doesn't
work, the \"local-part\" of the email address. We don't attempt
authentication with those two usernames as described in the RFC,
but ask the user to pick one option."
(let ((user-part (substring address 0 (cl-position ?@ address))))
(pcase (widget-choose
"IMAP username"
(list (cons (concat "Authenticate as " address) address)
(cons (concat "Authenticate as " user-part) user-part)
(cons "Use a different username" :other)))
((and (pred stringp) username)
username)
(`:other
(read-string "Enter IMAP username: ")))))
(define-state bic-account :no-data
(fsm state-data event _callback)
(pcase event
(:try-connect
;; Now we have a number of connection candidates. Let's connect
;; to all of them and pick the one that answers first.
(let ((candidate-connections
(mapcar
(lambda (candidate)
(pcase-let ((`(,hostname ,port ,connection-type) candidate))
(cons
(start-bic-connection
(plist-get state-data :username)
hostname
connection-type
port
(lambda (connection status)
(fsm-send fsm (list status connection)))
:auth-wait
(apply-partially #'bic--untagged-callback fsm))
candidate)))
(plist-get state-data :candidates))))
(plist-put state-data :candidate-connections candidate-connections)
(list :no-data state-data)))
((and (guard (not (plist-get state-data :connection)))
`(:auth-wait ,chosen-connection))
;; One of our candidate connections is ready to begin
;; authentication, and we haven't chosen a different connection
;; already.
(let* ((candidate-connections (plist-get state-data :candidate-connections))
(chosen-candidate (cdr (assq chosen-connection candidate-connections)))
(other-connections
(remq chosen-connection (mapcar 'car candidate-connections))))
(plist-put state-data :chosen-candidate chosen-candidate)
(plist-put state-data :connection chosen-connection)
;; Close `other-connections':
(dolist (other-connection other-connections)
(fsm-send other-connection :stop))
(fsm-send chosen-connection :proceed)
(list :no-data state-data)))
(`((:disconnected ,keyword ,reason) ,bad-connection)
(let* ((candidate-connections (plist-get state-data :candidate-connections))
(bad-candidate (cdr (assq bad-connection candidate-connections))))
(message "Connection to %s:%d failed: %s (%s)"
(cl-first bad-candidate) (cl-second bad-candidate)
reason keyword)
(setq candidate-connections
(cl-remove bad-connection candidate-connections :key 'car))
(plist-put state-data :candidate-connections candidate-connections)
(if candidate-connections
;; We are still waiting to hear from some other connection.
(list :no-data state-data)
(message "Cannot connect to server for %s, and not enough data for offline operation"
(plist-get state-data :address))
(list nil state-data))))
(`(:authenticated ,_)
;; That's good enough for now; let's create the directory.
;; Mail directories should not be group- or world-readable.
(with-file-modes #o700
(make-directory (plist-get state-data :dir) t))
;; Let's save the hostname+port+type combo that was successful.
(pcase-let ((`(,hostname ,port ,connection-type)
(plist-get state-data :chosen-candidate)))
(bic--write-string-to-file
(concat
(cl-ecase connection-type
(:starttls "imap")
(:plaintls "imaps"))
"://"
(url-hexify-string (plist-get state-data :username))
"@"
hostname
;; Only include port if it's not the default port
(pcase (cons connection-type port)
(`(:starttls . 143) "")
(`(:plaintls . 993) "")
(_ (format ":%d" port)))
"\n")
(expand-file-name "connection-info" (plist-get state-data :dir))))
(list :connected state-data))
(:stop
(let ((candidate-connections (mapcar #'car (plist-get state-data :candidate-connections))))
(dolist (connection candidate-connections)
(fsm-send connection :stop)))
(list nil state-data))))
(define-enter-state bic-account :existing
(fsm state-data)
;; Let's try connecting, but we do have some offline data, and can
;; use that if we can't connect.
(let* ((dir (plist-get state-data :dir))
(connection-url
(with-temp-buffer
(insert-file-contents-literally (expand-file-name "connection-info" dir))
(goto-char (point-min))
(buffer-substring (point-min) (point-at-eol))))
(parsed-url (url-generic-parse-url connection-url))
(username (url-unhex-string (url-user parsed-url)))
(server (url-host parsed-url))
(connection
(start-bic-connection
username
server
(pcase (url-type parsed-url)
("imap" :starttls)
("imaps" :plaintls)
(bad-type (error "Invalid URL protocol `%s'" bad-type)))
(pcase (url-port parsed-url)
(0 nil)
(port port))
(lambda (connection status)
(fsm-send fsm (list status connection)))
nil
(apply-partially #'bic--untagged-callback fsm))))
(let ((mailboxes (bic--directory-directories dir "[^.]")))
(bic--store-initial-mailbox-list
(plist-get state-data :address)
(mapcar
(lambda (mailbox-dir-name)
(let ((mailbox (bic--unsanitize-mailbox-name mailbox-dir-name))
(attributes-file
(expand-file-name
"attributes"
(expand-file-name mailbox-dir-name dir))))
(list
mailbox
:attributes
(when (file-exists-p attributes-file)
(with-temp-buffer
(insert-file-contents-literally attributes-file)
(split-string (buffer-string) "\n"))))))
mailboxes)))
(plist-put state-data :connection connection)
(plist-put state-data :username username)
(plist-put state-data :server server)
;; After 60 seconds, consider connection attempt failed.
(list state-data 60)))
(define-state bic-account :existing
(_fsm state-data event callback)
(let ((our-connection (plist-get state-data :connection)))
(pcase event
(`((:disconnected ,keyword ,reason) ,(pred (eq our-connection)))
(cond
((memq keyword '(:authentication-failed :authentication-abort))
(warn "Authentication failure: %s\nDeactivating account `%s'. To retry, type M-x bic-activate."
reason (plist-get state-data :address))
(list :disconnected (plist-put state-data :deactivated t)))
(t
;; We used to display a message here, but that can be rather
;; annoying if you're starting BIC without a network
;; connection. Just check the mailbox tree view to see if
;; you're connected or not.
(list :disconnected state-data))))
(:timeout
;; Ditto.
(fsm-send our-connection :stop)
(plist-put state-data :connection nil)
(list :disconnected state-data))
(`(:authenticated ,(pred (eq our-connection)))
(list :connected state-data))
(`(:flags ,mailbox ,full-uid ,flags-to-add ,flags-to-remove)
(bic--write-pending-flags mailbox full-uid flags-to-add flags-to-remove state-data)
(list :existing state-data :keep))
(`(:get-mailbox-tables ,mailbox)
(let ((overview-table (bic--read-overview state-data mailbox))
(flags-table (bic--read-flags-table state-data mailbox))
(uid-tree (gethash mailbox (plist-get state-data :uid-tree-per-mailbox))))
(funcall callback (list overview-table flags-table uid-tree)))
(list :existing state-data :keep))
(:deactivate
(plist-put state-data :deactivated t)
(fsm-send our-connection :stop)
(plist-put state-data :connection nil)
(list :disconnected state-data))
(:stop
(list nil state-data)))))
(define-enter-state bic-account :connected
(fsm state-data)
(bic--update-account-state (plist-get state-data :address) :connected)
(plist-put state-data :selected nil)
(plist-put state-data :selecting nil)
;; Find pending flag changes
(let* ((default-directory (plist-get state-data :dir))
(pending-flags-files
;; Because of the way we remove entries from pending flags
;; files, we might leave files of size 1 that should be
;; ignored.
(cl-remove-if-not
(lambda (pending-flags-file)
(pcase (nth 7 (file-attributes pending-flags-file))
(`nil
(warn "Cannot open pending flags file `%s'" pending-flags-file)
nil)
(size
(> size 1))))
(file-expand-wildcards "*/pending-flags")))
(mailboxes-with-pending-flags
(mapcar
(lambda (pending-flags-file)
(bic--unsanitize-mailbox-name
(directory-file-name
(file-name-directory pending-flags-file))))
pending-flags-files))
(pending-flags-tasks (mapcar (lambda (mailbox)
(list mailbox :pending-flags))
mailboxes-with-pending-flags))
(want-subscribed-files (file-expand-wildcards "*/want-subscribed"))
(want-subscribed-mailboxes
(mapcar
(lambda (want-subscribed-file)
(bic--unsanitize-mailbox-name
(directory-file-name
(file-name-directory want-subscribed-file))))
want-subscribed-files))
(want-subscribed-tasks
(mapcar (lambda (mailbox) (list :any-mailbox :subscribe mailbox))
want-subscribed-mailboxes)))
;; NB: Overwriting any existing tasks from previous connections.
(plist-put state-data :tasks (append pending-flags-tasks
want-subscribed-tasks))
(plist-put state-data :current-task nil))
(let ((c (plist-get state-data :connection)))
;; If the server supports ID, ask for its identity. Ignore the
;; answer; it's just for the transcript.
(when (bic-connection--has-capability "ID" c)
(bic-command c
;; We're anonymous ourselves so far.
"ID NIL"
#'ignore
'((0 "ID" ignore))))
(when (bic-connection--has-capability "NOTIFY" c)
(bic-command
c
(concat
"NOTIFY SET (selected-delayed (MessageNew MessageExpunge FlagChange))"
" (subscribed (MessageNew MessageExpunge FlagChange))"
" (personal (MailboxName SubscriptionChange))")
(lambda (notify-response)
(pcase notify-response
(`(,(or :no :bad) ,response ,_response-lines)
(warn "Cannot enable NOTIFY for %s: %s"
(plist-get state-data :address)
(plist-get response :text)))))))
;; Get list of mailboxes
(bic-command c
(cond
((bic-connection--has-capability "LIST-EXTENDED" c)
(concat
"LIST \"\" \"*\" RETURN (SUBSCRIBED"
(when (bic-connection--has-capability "LIST-STATUS" c)
(concat " STATUS ("
(bic--interesting-status-items c)
")"))
(when (bic-connection--has-capability "SPECIAL-USE" c)
" SPECIAL-USE")
")"))
(t
"LIST \"\" \"*\""))
(lambda (response)
(fsm-send fsm (list :list-response response)))
'((0 "LIST" :keep)
(0 "STATUS" :keep))))
(list state-data nil))
(define-state bic-account :connected
(fsm state-data event callback)
(pcase event
(`(:list-response ,list-response)
(pcase list-response
(`(:ok ,_ ,list-data)
(bic--handle-list-response fsm state-data list-data)
;; TODO: open extra connection(s), start downloading interesting
;; messages from interesting mailboxes
;; XXX: do we _really_ want an extra connection?.. We could
;; probably do that later.
(bic--maybe-next-task fsm state-data)
(list :connected state-data nil))
;; TODO: handle LIST error
))
(`(:lsub-response ,lsub-response)
(pcase lsub-response
(`(:ok ,_ ,lsub-data)
(bic--handle-lsub-response fsm state-data lsub-data)
(bic--maybe-next-task fsm state-data)
(list :connected state-data nil))
;; TODO: handle LSUB error
))
(`(:select-response ,mailbox-name ,select-response)
(when (string= mailbox-name (plist-get state-data :selecting))
(plist-put state-data :selecting nil))
(pcase select-response
(`(:ok ,_ ,select-data)
(bic--handle-select-response state-data mailbox-name select-data)
;; Check if we're doing a task here
(pcase (plist-get state-data :current-task)
((and `(,(pred (string= mailbox-name)) . ,_)
current-task)
(bic--do-task fsm state-data current-task))
(current-task
(when current-task
;; This shouldn't happen
(warn "doing nothing about %S" current-task))
(bic--maybe-next-task fsm state-data)))
(list :connected state-data nil))
(`(,(or :no :bad) ,response ,_response-lines)
(warn "Cannot select %s for %s: %s"
mailbox-name (plist-get state-data :address)
(or (plist-get response :text)
(plist-get response :code)
""))
(plist-put state-data :selected nil)
;; Check if we were trying to select this mailbox for the
;; current task.
(pcase (plist-get state-data :current-task)
(`(,(pred (string= mailbox-name)) . ,_)
(plist-put state-data :current-task nil)
(bic--maybe-next-task fsm state-data)))
(list :connected state-data nil))))
(`(:untagged-response ,untagged-response)
;; XXX: check :selecting and :selected
(let ((selecting (plist-get state-data :selecting))
(selected (plist-get state-data :selected)))
(pcase untagged-response
(`("STATUS" ,mailbox-name ,status-att-list)
(bic--handle-status-response
fsm state-data mailbox-name status-att-list
:queue-sync-tasks t)
(list :connected state-data nil))
((guard selecting)
(warn "Cannot handle untagged response %S: is it for '%s' or '%s'?"
untagged-response selecting selected)
nil)
(`(,seq-no "EXPUNGE")
;; A somewhat complicated dance to ensure that after receiving
;; EXPUNGE responses, we'll exit IDLE, and run the expunge task
;; once and only once, with all received message sequence
;; numbers. Thus we build the task using `nconc', and add
;; it with `bic--queue-task-if-new', which skips duplicate
;; tasks.
(let ((expunge-task (plist-get state-data :expunge-task)))
(when (or (null expunge-task)
(not (string= (car expunge-task) selected)))
(setq expunge-task (list selected :expunge-messages))
(plist-put state-data :expunge-task expunge-task))
(nconc expunge-task (list seq-no))
(bic--queue-task-if-new state-data expunge-task)
(bic--maybe-next-task fsm state-data)
;; TODO: decrement "EXISTS" value for current mailbox
(list :connected state-data nil)))
(`(,_ "RECENT")
;; We don't really care about the \Recent flag. Assuming
;; that the server always sends EXISTS along with RECENT,
;; we can ignore this.
(list :connected state-data nil))
(`(,how-many "EXISTS")
(plist-put (cdr (assoc selected (plist-get state-data :mailboxes)))
:exists (string-to-number how-many))
;; TODO: just fetch new messages, as we know their
;; sequence numbers.
(fsm-send
fsm
`(:queue-task
(,selected :sync-mailbox
,@(unless (eq :unlimited-sync
(bic--mailbox-sync-level state-data selected))
'(:limit 100)))))
(list :connected state-data nil))
(`(,_ "FETCH" ,_msg-att)
;; XXX: this is ugly. In bic--handle-fetch-response, we
;; check the UIDVALIDITY value of the mailbox, but here we
;; don't have any reliable value, so we just fetch the
;; stored value, rendering the check meaningless.
(let* ((mailbox-plist (cdr (assoc selected (plist-get state-data :mailboxes))))
(mailbox-uidvalidity (plist-get mailbox-plist :uidvalidity)))
(bic--handle-fetch-response state-data selected untagged-response mailbox-uidvalidity))
(list :connected state-data nil))
(_
(warn "Unexpected untagged response %S" untagged-response)
nil))))
(`(:early-fetch-response ,selected-mailbox ,msg ,uidvalidity)
(bic--handle-fetch-response state-data selected-mailbox msg uidvalidity)
(list :connected state-data))
(`(:get-mailbox-tables ,mailbox)
(let ((overview-table (bic--read-overview state-data mailbox))
(flags-table (bic--read-flags-table state-data mailbox))
(uid-tree (gethash mailbox (plist-get state-data :uid-tree-per-mailbox))))
(funcall callback (list overview-table flags-table uid-tree)))
(list :connected state-data))
(`(:task-finished ,task)
;; Check that this actually is the task we think we're doing
;; right now.
(if (not (eq task (plist-get state-data :current-task)))
(warn "Task %S finished while doing task %S"
task (plist-get state-data :current-task))
(plist-put state-data :current-task nil)
(bic--cancel-command-timeout-timer state-data)
(bic--maybe-next-task fsm state-data))
(list :connected state-data))
(`(:flags ,mailbox ,full-uid ,flags-to-add ,flags-to-remove)
(bic--write-pending-flags mailbox full-uid flags-to-add flags-to-remove state-data)
(bic--queue-task-if-new state-data (list mailbox :pending-flags))
(bic--maybe-next-task fsm state-data)
(list :connected state-data))
(`(:copy ,from-mailbox ,to-mailbox ,full-uid)
;; TODO: offline-friendly
(bic--queue-task-if-new state-data (list from-mailbox :copy to-mailbox full-uid))
(list :connected state-data))
(`(:sync-level ,mailbox ,new-sync-level)
;; Update sync level and maybe send subscribe command.
(when (bic--set-sync-level state-data mailbox new-sync-level)
(bic--queue-task-if-new
state-data
(list :any-mailbox :subscribe mailbox))
(bic--maybe-next-task fsm state-data))
(list :connected state-data))
(`(:queue-task ,new-task)
(bic--queue-task-if-new state-data new-task)
(bic--maybe-next-task fsm state-data)
(list :connected state-data))
(`(:idle-timeout ,idle-gensym)
;; 29 minutes have passed. Break our IDLE command, to ensure the
;; server doesn't close the connection.
(pcase (plist-get state-data :current-task)
(`(:idle ,(pred (eq idle-gensym)) ,_idle-timer)
(bic--idle-done fsm state-data)))
(list :connected state-data))
(`(:idle-done-timeout ,idle-gensym)
(pcase (plist-get state-data :current-task)
(`(:idle-done ,(pred (eq idle-gensym)) ,_idle-timer)
(message "Timeout while leaving IDLE; connection for %s considered lost"
(plist-get state-data :address))
(fsm-send (plist-get state-data :connection) :stop)
(list :disconnected state-data))
(_
;; Timer message received out of order; ignore.
(list :connected state-data))))
(`(:idle-response (,idle-type ,idle-extra ,idle-responses) ,idle-gensym)
;; An IDLE command has finished, for whatever reason.
(unless (eq idle-type :ok)
(warn "IDLE response not OK: %S %S" idle-type idle-extra))
(when idle-responses
(warn "Unhandled responses while idle: %S" idle-responses))
(pcase (plist-get state-data :current-task)
;; XXX: "or" correct?
(`(,(or :idle :idle-done) ,(pred (eq idle-gensym)) ,idle-timer)
(cancel-timer idle-timer)
(plist-put state-data :current-task nil)))
(bic--maybe-next-task fsm state-data)
(list :connected state-data))
(`(:command-timeout ,command-timeout-gensym ,time)
(cond
((not (eq command-timeout-gensym (plist-get state-data :command-timeout-gensym)))
;; This timeout event doesn't correspond to the command we're
;; currently executing. Ignore it.
(list :connected state-data))
((time-less-p time
(bic-connection--latest-received (plist-get state-data :connection)))
;; The connection has received data since this timer was
;; created, so we know for sure that it was alive not long ago.
;; Start a new timer.
(bic--start-command-timeout-timer fsm state-data)
(list :connected state-data))
(t
;; We've sent a command to the server, and waited
;; `bic-command-timeout' seconds, but we haven't received a
;; single byte from the server. Probably the connection is
;; dead without the OS telling us that.
(message "Timeout while waiting for data; connection for %s considered lost"
(plist-get state-data :address))
(fsm-send (plist-get state-data :connection) :stop)
(list :disconnected state-data))))
(`(:ensure-up-to-date ,mailbox . ,options)
(bic--queue-task-if-new
state-data
`(,mailbox :sync-mailbox
,@(unless (eq :unlimited-sync (bic--mailbox-sync-level state-data mailbox))
'(:limit 100))
:verbose ,(plist-get options :verbose)))
(bic--maybe-next-task fsm state-data)
(list :connected state-data))
(:activate
;; Nothing to do.
(list :connected state-data))
(:deactivate
(plist-put state-data :deactivated t)
;; Ask server to disconnect - but exit IDLE first, if needed.
(plist-put state-data :tasks (list (list :any-mailbox :logout)))
(bic--maybe-next-task fsm state-data)
(list :connected state-data))
(`((:disconnected ,_keyword ,_reason) ,connection)
(cond
((eq connection (plist-get state-data :connection))
(message "Disconnected from IMAP server!")
(plist-put state-data :connection nil)
;; TODO: check if we have enough data for offline operation.
(list :disconnected state-data))
(t
;; Not ours.
(list :connected state-data))))
(:stop
(list nil state-data))))
(define-enter-state bic-account :disconnected
(fsm state-data)
(bic--update-account-state
(plist-get state-data :address)
(if (plist-get state-data :deactivated)
:deactivated
:disconnected))
(unless (plist-get state-data :deactivated)
(run-with-timer
bic-reconnect-interval nil
#'fsm-send fsm :reconnect))
(list state-data nil))
(define-state bic-account :disconnected
(fsm state-data event callback)
(pcase event
(`(:get-mailbox-tables ,mailbox)
(let ((overview-table (bic--read-overview state-data mailbox))
(flags-table (bic--read-flags-table state-data mailbox))
(uid-tree (gethash mailbox (plist-get state-data :uid-tree-per-mailbox))))
(funcall callback (list overview-table flags-table uid-tree)))
(list :disconnected state-data))
(`(:flags ,mailbox ,full-uid ,flags-to-add ,flags-to-remove)
(bic--write-pending-flags mailbox full-uid flags-to-add flags-to-remove state-data)
(list :disconnected state-data))
(`(:sync-level ,mailbox ,new-sync-level)
;; Update sync level; we may have to send subscribe commands when
;; we are connected.
(bic--set-sync-level state-data mailbox new-sync-level)
(list :disconnected state-data))
(:reconnect
(if (plist-get state-data :deactivated)
;; User asked us not to reconnect.
(list :disconnected state-data)
(list :existing state-data)))
(:activate
(plist-put state-data :deactivated nil)
(bic--update-account-state (plist-get state-data :address) :disconnected)
(fsm-send fsm :reconnect)
(list :disconnected state-data))
(:deactivate
(plist-put state-data :deactivated t)
(bic--update-account-state (plist-get state-data :address) :deactivated)
(list :disconnected state-data))
(:stop
(list nil state-data))))
(defun bic--untagged-callback (fsm untagged-response)
;; checkdoc-order: nil
"Pass a received UNTAGGED-RESPONSE to FSM.
This function is meant to be given as UNTAGGED-CALLBACK to
`start-bic-connection'."
(fsm-send fsm (list :untagged-response untagged-response)))
(defun bic--update-account-state (account new-state)
"Update ACCOUNT to NEW-STATE, and call hooks.
Update the entry in `bic-account-state-table', or create a new
entry if needed, and call `bic-account-state-update-functions'.
Possible values for NEW-STATE are :connected, :disconnected,
and :deactivated, or nil if the account state machine has been
stopped."
(let ((old-state (gethash account bic-account-state-table)))
(unless (eq old-state new-state)
(if (null new-state)
(remhash account bic-account-state-table)
(puthash account new-state bic-account-state-table))
;; Run in timer, to isolate errors.
(run-with-timer
0.1 nil
#'run-hook-with-args 'bic-account-state-update-functions
account new-state))))
(defconst bic-filename-invalid-characters '(?< ?> ?: ?\" ?/ ?\\ ?| ?? ?* ?_)
"Characters not allowed inside a file name component.
This is different from `file-name-invalid-regexp', which checks
an entire file name.
It also includes underscore, which is used as an escape character.")
(defun bic--sanitize-mailbox-name (mailbox-name)
"Convert MAILBOX-NAME to a directory name.
MAILBOX-NAME is decoded from UTF-7, and characters in
`bic-filename-invalid-characters' are escaped. Hopefully this
should consistently give a valid directory name."
(let ((decoded (utf7-decode mailbox-name t))
(sanitized-to 0)
i sanitized-segments)
(while (setq i (cl-position-if
(lambda (c) (memq c bic-filename-invalid-characters))
decoded
:start sanitized-to))
(push (substring decoded sanitized-to i) sanitized-segments)
(push (format "_%x_" (aref decoded i)) sanitized-segments)
(setq sanitized-to (1+ i)))
(push (substring decoded sanitized-to) sanitized-segments)
(apply #'concat (nreverse sanitized-segments))))
(defun bic--unsanitize-mailbox-name (directory-name)
"Convert DIRECTORY-NAME to a UTF-7 mailbox name.
This is the reverse of `bic--sanitize-mailbox-name'."
(let ((i 0) segments)
(while (string-match "_\\([[:xdigit:]]+\\)_" directory-name i)
(push (substring directory-name i (match-beginning 0)) segments)
(push (string (string-to-number (match-string 1 directory-name) 16)) segments)
(setq i (match-end 0)))
(push (substring directory-name i) segments)
(utf7-encode (apply 'concat (nreverse segments)) t)))
(defun bic--mailbox-dir (state-data mailbox-name)
"Return the directory for the given mailbox.
Use the base directory in STATE-DATA, and append the sanitized
version of MAILBOX-NAME."
(expand-file-name
(bic--sanitize-mailbox-name mailbox-name)
(plist-get state-data :dir)))
(defun bic--handle-list-response (fsm state-data list-data)
"Handle a response to a LIST command.
FSM and STATE-DATA are the account state machine and state data.
LIST-DATA is a list of \"LIST\" and \"STATUS\" response lines,
each line having been parsed into a list of tokens."
(let* ((old-mailboxes (plist-get state-data :mailboxes))
;; If the server supports LIST-EXTENDED, then we will have
;; asked for mailbox subscription information.
(subscription-return
(bic-connection--has-capability "LIST-EXTENDED" (plist-get state-data :connection)))
(status-return
(bic-connection--has-capability "LIST-STATUS" (plist-get state-data :connection)))
mailboxes status-responses)
;; XXX: do we really always overwrite mailbox information?
;; Need to reverse responses, so we get LIST before STATUS.
(dolist (x (nreverse list-data))
(pcase x
(`("LIST" ,attributes ,_separator ,mailbox-name)
;; If we weren't asking for subscription information,
;; keep previous subscription status.
(let* ((old-attributes
(unless subscription-return
(plist-get (cdr (assoc mailbox-name old-mailboxes)) :attributes)))
(subscription-attribute
(when (cl-member "\\Subscribed" old-attributes :test #'cl-equalp)
(list "\\Subscribed"))))
(push
(list mailbox-name
:attributes (append subscription-attribute attributes))
mailboxes)))
;; Need to buffer STATUS responses here, as we haven't