1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 package davmail.exchange;
20
21 import davmail.BundleMessage;
22 import davmail.Settings;
23 import davmail.exception.DavMailException;
24 import davmail.exception.HttpForbiddenException;
25 import davmail.exception.HttpNotFoundException;
26 import davmail.http.URIUtil;
27 import davmail.ui.NotificationDialog;
28 import davmail.util.StringUtil;
29 import org.apache.log4j.Logger;
30
31 import javax.mail.MessagingException;
32 import javax.mail.internet.InternetAddress;
33 import javax.mail.internet.InternetHeaders;
34 import javax.mail.internet.MimeMessage;
35 import javax.mail.internet.MimeMultipart;
36 import javax.mail.internet.MimePart;
37 import javax.mail.util.SharedByteArrayInputStream;
38 import javax.net.ssl.SSLException;
39 import java.io.ByteArrayOutputStream;
40 import java.io.File;
41 import java.io.IOException;
42 import java.io.InputStream;
43 import java.io.OutputStreamWriter;
44 import java.io.StringReader;
45 import java.net.NoRouteToHostException;
46 import java.net.SocketTimeoutException;
47 import java.net.UnknownHostException;
48 import java.nio.charset.StandardCharsets;
49 import java.nio.file.Files;
50 import java.nio.file.Paths;
51 import java.text.ParseException;
52 import java.text.SimpleDateFormat;
53 import java.util.ArrayList;
54 import java.util.Arrays;
55 import java.util.Calendar;
56 import java.util.Collections;
57 import java.util.Date;
58 import java.util.Enumeration;
59 import java.util.HashMap;
60 import java.util.HashSet;
61 import java.util.List;
62 import java.util.Locale;
63 import java.util.Map;
64 import java.util.Properties;
65 import java.util.ResourceBundle;
66 import java.util.Set;
67 import java.util.SimpleTimeZone;
68 import java.util.TimeZone;
69 import java.util.TreeMap;
70 import java.util.UUID;
71
72
73
74
75 public abstract class ExchangeSession {
76
77 protected static final Logger LOGGER = Logger.getLogger("davmail.exchange.ExchangeSession");
78
79
80
81
82 public static final SimpleTimeZone GMT_TIMEZONE = new SimpleTimeZone(0, "GMT");
83
84 protected static final int FREE_BUSY_INTERVAL = 15;
85
86 protected static final String PUBLIC_ROOT = "/public/";
87 protected static final String CALENDAR = "calendar";
88 protected static final String TASKS = "tasks";
89
90
91
92 public static final String CONTACTS = "contacts";
93 protected static final String ADDRESSBOOK = "addressbook";
94 protected static final String ARCHIVE = "Archive";
95 protected static final String INBOX = "INBOX";
96 protected static final String LOWER_CASE_INBOX = "inbox";
97 protected static final String MIXED_CASE_INBOX = "Inbox";
98 protected static final String SENT = "Sent";
99 protected static final String SENDMSG = "##DavMailSubmissionURI##";
100 protected static final String DRAFTS = "Drafts";
101 protected static final String TRASH = "Trash";
102 protected static final String JUNK = "Junk";
103 protected static final String UNSENT = "Unsent Messages";
104
105 protected static final List<String> SPECIAL = Arrays.asList(SENT, DRAFTS, TRASH, JUNK, ARCHIVE);
106
107
108 protected static final String REPLYTOSENDER = "102";
109 protected static final String REPLYTOALL = "103";
110 protected static final String FORWARD = "104";
111
112 protected static final String REPLIED_ICON = "261";
113 protected static final String FORWARDED_ICON = "262";
114
115 static {
116
117 System.setProperty("mail.mime.ignoreunknownencoding", "true");
118 System.setProperty("mail.mime.decodetext.strict", "false");
119 }
120
121 protected String publicFolderUrl;
122
123
124
125
126 protected String mailPath;
127 protected String rootPath;
128 protected String email;
129 protected String alias;
130
131
132
133
134 protected String currentMailboxPath;
135
136 protected String userName;
137
138 protected String serverVersion;
139
140 protected static final String YYYY_MM_DD_HH_MM_SS = "yyyy/MM/dd HH:mm:ss";
141 private static final String YYYYMMDD_T_HHMMSS_Z = "yyyyMMdd'T'HHmmss'Z'";
142 protected static final String YYYY_MM_DD_T_HHMMSS_Z = "yyyy-MM-dd'T'HH:mm:ss'Z'";
143 private static final String YYYY_MM_DD = "yyyy-MM-dd";
144 private static final String YYYY_MM_DD_T_HHMMSS_SSS_Z = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'";
145
146 public ExchangeSession() {
147
148 }
149
150
151
152
153
154 public abstract void close();
155
156
157
158
159
160
161
162 public abstract String formatSearchDate(Date date);
163
164
165
166
167
168
169 public static SimpleDateFormat getZuluDateFormat() {
170 SimpleDateFormat dateFormat = new SimpleDateFormat(YYYYMMDD_T_HHMMSS_Z, Locale.ENGLISH);
171 dateFormat.setTimeZone(GMT_TIMEZONE);
172 return dateFormat;
173 }
174
175 protected static SimpleDateFormat getVcardBdayFormat() {
176 SimpleDateFormat dateFormat = new SimpleDateFormat(YYYY_MM_DD, Locale.ENGLISH);
177 dateFormat.setTimeZone(GMT_TIMEZONE);
178 return dateFormat;
179 }
180
181 protected static SimpleDateFormat getExchangeDateFormat(String value) {
182 SimpleDateFormat dateFormat;
183 if (value.length() == 8) {
184 dateFormat = new SimpleDateFormat("yyyyMMdd", Locale.ENGLISH);
185 dateFormat.setTimeZone(GMT_TIMEZONE);
186 } else if (value.length() == 15) {
187 dateFormat = new SimpleDateFormat("yyyyMMdd'T'HHmmss", Locale.ENGLISH);
188 dateFormat.setTimeZone(GMT_TIMEZONE);
189 } else if (value.length() == 16) {
190 dateFormat = new SimpleDateFormat("yyyyMMdd'T'HHmmss'Z'", Locale.ENGLISH);
191 dateFormat.setTimeZone(GMT_TIMEZONE);
192 } else {
193 dateFormat = ExchangeSession.getExchangeZuluDateFormat();
194 }
195 return dateFormat;
196 }
197
198 protected static SimpleDateFormat getExchangeZuluDateFormat() {
199 SimpleDateFormat dateFormat = new SimpleDateFormat(YYYY_MM_DD_T_HHMMSS_Z, Locale.ENGLISH);
200 dateFormat.setTimeZone(GMT_TIMEZONE);
201 return dateFormat;
202 }
203
204 protected static SimpleDateFormat getExchangeZuluDateFormatMillisecond() {
205 SimpleDateFormat dateFormat = new SimpleDateFormat(YYYY_MM_DD_T_HHMMSS_SSS_Z, Locale.ENGLISH);
206 dateFormat.setTimeZone(GMT_TIMEZONE);
207 return dateFormat;
208 }
209
210 protected static Date parseDate(String dateString) throws ParseException {
211 SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
212 dateFormat.setTimeZone(GMT_TIMEZONE);
213 return dateFormat.parse(dateString);
214 }
215
216
217
218
219
220
221
222
223 public boolean isExpired() throws IOException {
224 boolean isExpired = false;
225 try {
226 getFolder("");
227 } catch (UnknownHostException | NoRouteToHostException |
228 SocketTimeoutException | SSLException exc) {
229
230 throw exc;
231 } catch (IOException e) {
232 isExpired = true;
233 }
234
235 return isExpired;
236 }
237
238 protected abstract void buildSessionInfo(java.net.URI uri) throws IOException;
239
240
241
242
243
244
245
246
247
248
249
250 public abstract Message createMessage(String folderPath, String messageName, HashMap<String, String> properties, MimeMessage mimeMessage) throws IOException;
251
252
253
254
255
256
257
258
259 public abstract void updateMessage(Message message, Map<String, String> properties) throws IOException;
260
261
262
263
264
265
266
267
268 public abstract void deleteMessage(Message message) throws IOException;
269
270
271
272
273
274
275
276
277 protected abstract byte[] getContent(Message message) throws IOException;
278
279 protected static final Set<String> POP_MESSAGE_ATTRIBUTES = new HashSet<>();
280
281 static {
282 POP_MESSAGE_ATTRIBUTES.add("uid");
283 POP_MESSAGE_ATTRIBUTES.add("imapUid");
284 POP_MESSAGE_ATTRIBUTES.add("messageSize");
285 }
286
287
288
289
290
291
292
293
294 public MessageList getAllMessageUidAndSize(String folderName) throws IOException {
295 return searchMessages(folderName, POP_MESSAGE_ATTRIBUTES, null);
296 }
297
298 protected static final Set<String> IMAP_MESSAGE_ATTRIBUTES = new HashSet<>();
299
300 static {
301 IMAP_MESSAGE_ATTRIBUTES.add("permanenturl");
302 IMAP_MESSAGE_ATTRIBUTES.add("urlcompname");
303 IMAP_MESSAGE_ATTRIBUTES.add("uid");
304 IMAP_MESSAGE_ATTRIBUTES.add("messageSize");
305 IMAP_MESSAGE_ATTRIBUTES.add("imapUid");
306 IMAP_MESSAGE_ATTRIBUTES.add("junk");
307 IMAP_MESSAGE_ATTRIBUTES.add("flagStatus");
308 IMAP_MESSAGE_ATTRIBUTES.add("messageFlags");
309 IMAP_MESSAGE_ATTRIBUTES.add("lastVerbExecuted");
310 IMAP_MESSAGE_ATTRIBUTES.add("read");
311 IMAP_MESSAGE_ATTRIBUTES.add("deleted");
312 IMAP_MESSAGE_ATTRIBUTES.add("date");
313 IMAP_MESSAGE_ATTRIBUTES.add("lastmodified");
314
315 IMAP_MESSAGE_ATTRIBUTES.add("contentclass");
316 IMAP_MESSAGE_ATTRIBUTES.add("keywords");
317 }
318
319 protected static final Set<String> UID_MESSAGE_ATTRIBUTES = new HashSet<>();
320
321 static {
322 UID_MESSAGE_ATTRIBUTES.add("uid");
323 }
324
325
326
327
328
329
330
331
332 public MessageList searchMessages(String folderPath) throws IOException {
333 return searchMessages(folderPath, IMAP_MESSAGE_ATTRIBUTES, null);
334 }
335
336
337
338
339
340
341
342
343
344 public MessageList searchMessages(String folderName, Condition condition) throws IOException {
345 return searchMessages(folderName, IMAP_MESSAGE_ATTRIBUTES, condition);
346 }
347
348
349
350
351
352
353
354
355
356
357 public abstract MessageList searchMessages(String folderName, Set<String> attributes, Condition condition) throws IOException;
358
359
360
361
362
363
364 public String getServerVersion() {
365 return serverVersion;
366 }
367
368 public enum Operator {
369 Or, And, Not, IsEqualTo,
370 IsGreaterThan, IsGreaterThanOrEqualTo,
371 IsLessThan, IsLessThanOrEqualTo,
372 IsNull, IsTrue, IsFalse,
373 Like, StartsWith, Contains
374 }
375
376
377
378
379 public interface Condition {
380
381
382
383
384
385 void appendTo(StringBuilder buffer);
386
387
388
389
390
391
392 boolean isEmpty();
393
394
395
396
397
398
399
400 boolean isMatch(ExchangeSession.Contact contact);
401 }
402
403
404
405
406 public abstract static class AttributeCondition implements Condition {
407 protected final String attributeName;
408 protected final Operator operator;
409 protected final String value;
410
411 protected AttributeCondition(String attributeName, Operator operator, String value) {
412 this.attributeName = attributeName;
413 this.operator = operator;
414 this.value = value;
415 }
416
417 public boolean isEmpty() {
418 return false;
419 }
420
421
422
423
424
425
426 public String getAttributeName() {
427 return attributeName;
428 }
429
430
431
432
433
434
435 public String getValue() {
436 return value;
437 }
438
439 }
440
441
442
443
444 public abstract static class MultiCondition implements Condition {
445 protected final Operator operator;
446 protected final List<Condition> conditions;
447
448 protected MultiCondition(Operator operator, Condition... conditions) {
449 this.operator = operator;
450 this.conditions = new ArrayList<>();
451 for (Condition condition : conditions) {
452 if (condition != null) {
453 this.conditions.add(condition);
454 }
455 }
456 }
457
458
459
460
461
462
463 public List<Condition> getConditions() {
464 return conditions;
465 }
466
467
468
469
470
471
472 public Operator getOperator() {
473 return operator;
474 }
475
476
477
478
479
480
481 public void add(Condition condition) {
482 if (condition != null) {
483 conditions.add(condition);
484 }
485 }
486
487 @Override
488 public boolean isEmpty() {
489 return getActualConditionCount() == 0;
490 }
491
492 protected int getActualConditionCount() {
493 int count = 0;
494 for (Condition condition : conditions) {
495 if (!condition.isEmpty()) {
496 count++;
497 }
498 }
499 return count;
500 }
501
502 public boolean isMatch(ExchangeSession.Contact contact) {
503 if (operator == Operator.And) {
504 for (Condition condition : conditions) {
505 if (!condition.isMatch(contact)) {
506 return false;
507 }
508 }
509 return true;
510 } else if (operator == Operator.Or) {
511 for (Condition condition : conditions) {
512 if (condition.isMatch(contact)) {
513 return true;
514 }
515 }
516 return false;
517 } else {
518 return false;
519 }
520 }
521
522 }
523
524
525
526
527 public abstract static class NotCondition implements Condition {
528 protected final Condition condition;
529
530 protected NotCondition(Condition condition) {
531 this.condition = condition;
532 }
533
534 public boolean isEmpty() {
535 return condition.isEmpty();
536 }
537
538 public boolean isMatch(ExchangeSession.Contact contact) {
539 return !condition.isMatch(contact);
540 }
541 }
542
543
544
545
546 public abstract static class MonoCondition implements Condition {
547 protected final String attributeName;
548 protected final Operator operator;
549
550 protected MonoCondition(String attributeName, Operator operator) {
551 this.attributeName = attributeName;
552 this.operator = operator;
553 }
554
555 public boolean isEmpty() {
556 return false;
557 }
558
559 public boolean isMatch(ExchangeSession.Contact contact) {
560 String actualValue = contact.get(attributeName);
561 return (operator == Operator.IsNull && actualValue == null) ||
562 (operator == Operator.IsFalse && "false".equals(actualValue)) ||
563 (operator == Operator.IsTrue && "true".equals(actualValue));
564 }
565 }
566
567
568
569
570
571
572
573 public abstract MultiCondition and(Condition... condition);
574
575
576
577
578
579
580
581 public abstract MultiCondition or(Condition... condition);
582
583
584
585
586
587
588
589 public abstract Condition not(Condition condition);
590
591
592
593
594
595
596
597
598 public abstract Condition isEqualTo(String attributeName, String value);
599
600
601
602
603
604
605
606
607 public abstract Condition isEqualTo(String attributeName, int value);
608
609
610
611
612
613
614
615
616 public abstract Condition headerIsEqualTo(String headerName, String value);
617
618
619
620
621
622
623
624
625 public abstract Condition gte(String attributeName, String value);
626
627
628
629
630
631
632
633
634 public abstract Condition gt(String attributeName, String value);
635
636
637
638
639
640
641
642
643 public abstract Condition lt(String attributeName, String value);
644
645
646
647
648
649
650
651
652 @SuppressWarnings({"UnusedDeclaration"})
653 public abstract Condition lte(String attributeName, String value);
654
655
656
657
658
659
660
661
662 public abstract Condition contains(String attributeName, String value);
663
664
665
666
667
668
669
670
671 public abstract Condition startsWith(String attributeName, String value);
672
673
674
675
676
677
678
679 public abstract Condition isNull(String attributeName);
680
681
682
683
684
685
686
687 public abstract Condition exists(String attributeName);
688
689
690
691
692
693
694
695 public abstract Condition isTrue(String attributeName);
696
697
698
699
700
701
702
703 public abstract Condition isFalse(String attributeName);
704
705
706
707
708
709
710
711
712
713
714 public List<Folder> getSubFolders(String folderName, boolean recursive, boolean wildcard) throws IOException {
715 MultiCondition folderCondition = and();
716 if (!Settings.getBooleanProperty("davmail.imapIncludeSpecialFolders", false)) {
717 folderCondition.add(or(isEqualTo("folderclass", "IPF.Note"),
718 isEqualTo("folderclass", "IPF.Note.Microsoft.Conversation"),
719 isNull("folderclass")));
720 }
721 if (wildcard) {
722 folderCondition.add(startsWith("displayname", folderName));
723 folderName = "";
724 }
725 List<Folder> results = getSubFolders(folderName, folderCondition,
726 recursive);
727
728 if (recursive && !getSubfolderPath(folderName).isEmpty()) {
729 results.add(getFolder(folderName));
730 }
731
732 return results;
733 }
734
735
736
737
738
739
740
741
742
743 public List<Folder> getSubCalendarFolders(String folderName, boolean recursive) throws IOException {
744 return getSubFolders(folderName, isEqualTo("folderclass", "IPF.Appointment"), recursive);
745 }
746
747
748
749
750
751
752
753
754
755 public List<Folder> getSubContactFolders(String folderName, boolean recursive) throws IOException {
756 return getSubFolders(folderName, isEqualTo("folderclass", "IPF.Contact"), recursive);
757 }
758
759
760
761
762
763
764
765
766 public String getSubfolderPath(String folderPath) {
767 String baseFolderPath = folderPath;
768 if (baseFolderPath.startsWith("/users/")) {
769 int index = baseFolderPath.indexOf('/', "/users/".length());
770 if (index >= 0) {
771 baseFolderPath = baseFolderPath.substring(index + 1);
772 }
773 }
774 return baseFolderPath;
775 }
776
777
778
779
780
781
782
783
784
785
786 public abstract List<Folder> getSubFolders(String folderName, Condition condition, boolean recursive) throws IOException;
787
788
789
790
791
792
793
794 public void purgeOldestTrashAndSentMessages() throws IOException {
795 int keepDelay = Settings.getIntProperty("davmail.keepDelay");
796 if (keepDelay != 0) {
797 purgeOldestFolderMessages(TRASH, keepDelay);
798 }
799
800 int sentKeepDelay = Settings.getIntProperty("davmail.sentKeepDelay");
801 if (sentKeepDelay != 0) {
802 purgeOldestFolderMessages(SENT, sentKeepDelay);
803 }
804 }
805
806 protected void purgeOldestFolderMessages(String folderPath, int keepDelay) throws IOException {
807 Calendar cal = Calendar.getInstance();
808 cal.add(Calendar.DAY_OF_MONTH, -keepDelay);
809 LOGGER.debug("Delete messages in " + folderPath + " not modified since " + cal.getTime());
810
811 MessageList messages = searchMessages(folderPath, UID_MESSAGE_ATTRIBUTES,
812 lt("lastmodified", formatSearchDate(cal.getTime())));
813
814 for (Message message : messages) {
815 message.delete();
816 }
817 }
818
819
820
821
822 protected void convertResentHeader(MimeMessage mimeMessage, String headerName) throws MessagingException {
823 String[] resentHeader = mimeMessage.getHeader("Resent-" + headerName);
824 if (resentHeader != null) {
825 mimeMessage.removeHeader("Resent-" + headerName);
826 mimeMessage.removeHeader(headerName);
827 for (String value : resentHeader) {
828 mimeMessage.addHeader(headerName, value);
829 }
830 }
831 }
832
833 protected String lastSentMessageId;
834 protected List<String> lastRcptToRecipients;
835
836
837
838
839
840
841
842
843
844
845 public void sendMessage(List<String> rcptToRecipients, MimeMessage mimeMessage) throws IOException, MessagingException {
846
847 String messageId = mimeMessage.getMessageID();
848 if (lastSentMessageId != null && lastSentMessageId.equals(messageId)) {
849
850 if (Settings.getBooleanProperty("davmail.smtpAllowDuplicateSend", false)) {
851 LOGGER.debug("Detected duplicate message id " + messageId + " but smtpAllowDuplicateSend is enabled, resending message");
852 } else if (lastRcptToRecipients != null && !lastRcptToRecipients.equals(rcptToRecipients)) {
853 LOGGER.debug("Detected duplicate message id " + messageId + " but recipients differ, resending message");
854 } else {
855 LOGGER.debug("Dropping message id " + messageId + ": already sent");
856 return;
857 }
858 }
859 LOGGER.debug("Sending message id " + messageId);
860
861 lastSentMessageId = messageId;
862 lastRcptToRecipients = rcptToRecipients;
863
864 convertResentHeader(mimeMessage, "From");
865 convertResentHeader(mimeMessage, "To");
866 convertResentHeader(mimeMessage, "Cc");
867 convertResentHeader(mimeMessage, "Bcc");
868 convertResentHeader(mimeMessage, "Message-Id");
869
870
871 if ("Exchange2003".equals(serverVersion) || Settings.getBooleanProperty("davmail.smtpStripFrom", false)) {
872 mimeMessage.removeHeader("From");
873 }
874
875
876 Set<String> visibleRecipients = new HashSet<>();
877 List<InternetAddress> recipients = getAllRecipients(mimeMessage);
878 for (InternetAddress address : recipients) {
879 visibleRecipients.add((address.getAddress().toLowerCase()));
880 }
881 for (String recipient : rcptToRecipients) {
882 if (!visibleRecipients.contains(recipient.toLowerCase())) {
883 mimeMessage.addRecipient(javax.mail.Message.RecipientType.BCC, new InternetAddress(recipient));
884 }
885 }
886 sendMessage(mimeMessage);
887
888 }
889
890 static final String[] RECIPIENT_HEADERS = {"to", "cc", "bcc"};
891
892 protected List<InternetAddress> getAllRecipients(MimeMessage mimeMessage) throws MessagingException {
893 List<InternetAddress> recipientList = new ArrayList<>();
894 for (String recipientHeader : RECIPIENT_HEADERS) {
895 final String recipientHeaderValue = mimeMessage.getHeader(recipientHeader, ",");
896 if (recipientHeaderValue != null) {
897
898 recipientList.addAll(Arrays.asList(InternetAddress.parseHeader(recipientHeaderValue, false)));
899 }
900
901 }
902 return recipientList;
903 }
904
905
906
907
908
909
910
911
912 public abstract void sendMessage(MimeMessage mimeMessage) throws IOException, MessagingException;
913
914
915
916
917
918
919
920
921
922
923 public ExchangeSession.Folder getFolder(String folderPath) throws IOException {
924 Folder folder = internalGetFolder(folderPath);
925 if (isMainCalendar(folderPath)) {
926 Folder taskFolder = internalGetFolder(TASKS);
927 folder.ctag += taskFolder.ctag;
928 }
929 return folder;
930 }
931
932 protected abstract Folder internalGetFolder(String folderName) throws IOException;
933
934
935
936
937
938
939
940
941 public boolean refreshFolder(Folder currentFolder) throws IOException {
942 Folder newFolder = getFolder(currentFolder.folderPath);
943 if (currentFolder.ctag == null || !currentFolder.ctag.equals(newFolder.ctag)
944
945 || !(currentFolder.messageCount == newFolder.messageCount)
946 ) {
947 if (LOGGER.isDebugEnabled()) {
948 LOGGER.debug("Contenttag or count changed on " + currentFolder.folderPath +
949 " ctag: " + currentFolder.ctag + " => " + newFolder.ctag +
950 " count: " + currentFolder.messageCount + " => " + newFolder.messageCount
951 + ", reloading messages");
952 }
953 currentFolder.hasChildren = newFolder.hasChildren;
954 currentFolder.noInferiors = newFolder.noInferiors;
955 currentFolder.unreadCount = newFolder.unreadCount;
956 currentFolder.ctag = newFolder.ctag;
957 currentFolder.etag = newFolder.etag;
958 if (newFolder.uidNext > currentFolder.uidNext) {
959 currentFolder.uidNext = newFolder.uidNext;
960 }
961 currentFolder.refreshMessages();
962 return true;
963 } else {
964 return false;
965 }
966 }
967
968
969
970
971
972
973
974 public void createMessageFolder(String folderName) throws IOException {
975 createFolder(folderName, "IPF.Note", null);
976 }
977
978
979
980
981
982
983
984
985
986 public int createCalendarFolder(String folderName, Map<String, String> properties) throws IOException {
987 return createFolder(folderName, "IPF.Appointment", properties);
988 }
989
990
991
992
993
994
995
996
997 public void createContactFolder(String folderName, Map<String, String> properties) throws IOException {
998 createFolder(folderName, "IPF.Contact", properties);
999 }
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010 public abstract int createFolder(String folderName, String folderClass, Map<String, String> properties) throws IOException;
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020 public abstract int updateFolder(String folderName, Map<String, String> properties) throws IOException;
1021
1022
1023
1024
1025
1026
1027
1028 public abstract void deleteFolder(String folderName) throws IOException;
1029
1030
1031
1032
1033
1034
1035
1036
1037 public abstract void copyMessage(Message message, String targetFolder) throws IOException;
1038
1039 public void copyMessages(List<Message> messages, String targetFolder) throws IOException {
1040 for (Message message : messages) {
1041 copyMessage(message, targetFolder);
1042 }
1043 }
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053 public abstract void moveMessage(Message message, String targetFolder) throws IOException;
1054
1055 public void moveMessages(List<Message> messages, String targetFolder) throws IOException {
1056 for (Message message : messages) {
1057 moveMessage(message, targetFolder);
1058 }
1059 }
1060
1061
1062
1063
1064
1065
1066
1067
1068 public abstract void moveFolder(String folderName, String targetName) throws IOException;
1069
1070
1071
1072
1073
1074
1075
1076
1077 public abstract void moveItem(String sourcePath, String targetPath) throws IOException;
1078
1079 protected abstract void moveToTrash(Message message) throws IOException;
1080
1081
1082
1083
1084
1085
1086
1087 public String convertKeywordToFlag(String value) {
1088
1089 Properties flagSettings = Settings.getSubProperties("davmail.imapFlags");
1090 Enumeration<?> flagSettingsEnum = flagSettings.propertyNames();
1091 while (flagSettingsEnum.hasMoreElements()) {
1092 String key = (String) flagSettingsEnum.nextElement();
1093 if (value.equalsIgnoreCase(flagSettings.getProperty(key))) {
1094 return key;
1095 }
1096 }
1097
1098 ResourceBundle flagBundle = ResourceBundle.getBundle("imapflags");
1099 Enumeration<String> flagBundleEnum = flagBundle.getKeys();
1100 while (flagBundleEnum.hasMoreElements()) {
1101 String key = flagBundleEnum.nextElement();
1102 if (value.equalsIgnoreCase(flagBundle.getString(key))) {
1103 return key;
1104 }
1105 }
1106
1107
1108 return value;
1109 }
1110
1111
1112
1113
1114
1115
1116
1117 public String convertFlagToKeyword(String value) {
1118
1119 Properties flagSettings = Settings.getSubProperties("davmail.imapFlags");
1120
1121 for (String key : flagSettings.stringPropertyNames()) {
1122 if (key.equalsIgnoreCase(value)) {
1123 return flagSettings.getProperty(key);
1124 }
1125 }
1126
1127
1128 ResourceBundle flagBundle = ResourceBundle.getBundle("imapflags");
1129 for (String key : flagBundle.keySet()) {
1130 if (key.equalsIgnoreCase(value)) {
1131 return flagBundle.getString(key);
1132 }
1133 }
1134
1135
1136 return value;
1137 }
1138
1139
1140
1141
1142
1143
1144
1145 public String convertFlagsToKeywords(HashSet<String> flags) {
1146 HashSet<String> keywordSet = new HashSet<>();
1147 for (String flag : flags) {
1148 keywordSet.add(decodeKeyword(convertFlagToKeyword(flag)));
1149 }
1150 return StringUtil.join(keywordSet, ",");
1151 }
1152
1153 protected String decodeKeyword(String keyword) {
1154 String result = keyword;
1155 if (keyword.contains("_x0028_") || keyword.contains("_x0029_")) {
1156 result = result.replace("_x0028_", "(")
1157 .replace("_x0029_", ")");
1158 }
1159 return result;
1160 }
1161
1162 protected String encodeKeyword(String keyword) {
1163 String result = keyword;
1164 if (keyword.indexOf('(') >= 0|| keyword.indexOf(')') >= 0) {
1165 result = result.replaceAll("\\(", "_x0028_")
1166 .replaceAll("\\)", "_x0029_" );
1167 }
1168 return result;
1169 }
1170
1171
1172
1173
1174 public class Folder {
1175
1176
1177
1178 public String folderPath;
1179
1180
1181
1182
1183 public String displayName;
1184
1185
1186
1187 public String folderClass;
1188
1189
1190
1191 public int messageCount;
1192
1193
1194
1195 public int unreadCount;
1196
1197
1198
1199 public boolean hasChildren;
1200
1201
1202
1203 public boolean noInferiors;
1204
1205
1206
1207 public String ctag;
1208
1209
1210
1211 public String etag;
1212
1213
1214
1215 public long uidNext;
1216
1217
1218
1219 public int recent;
1220
1221
1222
1223
1224 public ExchangeSession.MessageList messages;
1225
1226
1227
1228 private final HashMap<String, Long> permanentUrlToImapUidMap = new HashMap<>();
1229
1230
1231
1232
1233
1234
1235 public String getFlags() {
1236 String specialFlag = "";
1237 if (isSpecial()) {
1238 specialFlag = "\\" + folderPath + " ";
1239 }
1240 if (noInferiors) {
1241 return specialFlag + "\\NoInferiors";
1242 } else if (hasChildren) {
1243 return specialFlag + "\\HasChildren";
1244 } else {
1245 return specialFlag + "\\HasNoChildren";
1246 }
1247 }
1248
1249
1250
1251
1252
1253 public boolean isSpecial() {
1254 return SPECIAL.contains(folderPath);
1255 }
1256
1257
1258
1259
1260
1261
1262 public void loadMessages() throws IOException {
1263 messages = ExchangeSession.this.searchMessages(folderPath, null);
1264 fixUids(messages);
1265 computeAttributes();
1266 }
1267
1268 public void computeAttributes() {
1269 recent = 0;
1270 for (Message message : messages) {
1271 if (message.recent) {
1272 recent++;
1273 }
1274 }
1275 long computedUidNext = 1;
1276 if (!messages.isEmpty()) {
1277 computedUidNext = messages.get(messages.size() - 1).getImapUid() + 1;
1278 }
1279 if (computedUidNext > uidNext) {
1280 uidNext = computedUidNext;
1281 }
1282
1283 messageCount = messages.size();
1284
1285 buildImapFlagMap();
1286 }
1287
1288 public void refreshMessages() throws IOException {
1289 loadMessages();
1290 }
1291
1292
1293
1294
1295
1296
1297
1298
1299 public MessageList searchMessages(Condition condition) throws IOException {
1300 MessageList localMessages = ExchangeSession.this.searchMessages(folderPath, condition);
1301 fixUids(localMessages);
1302 return localMessages;
1303 }
1304
1305
1306
1307
1308
1309
1310 protected void fixUids(MessageList messages) {
1311 boolean sortNeeded = false;
1312 for (Message message : messages) {
1313 if (permanentUrlToImapUidMap.containsKey(message.getPermanentId())) {
1314 long previousUid = permanentUrlToImapUidMap.get(message.getPermanentId());
1315 if (message.getImapUid() != previousUid) {
1316 LOGGER.debug("Restoring IMAP uid " + message.getImapUid() + " -> " + previousUid + " for message " + message.getPermanentId());
1317 message.setImapUid(previousUid);
1318 sortNeeded = true;
1319 }
1320 } else {
1321
1322 permanentUrlToImapUidMap.put(message.getPermanentId(), message.getImapUid());
1323 }
1324 }
1325 if (sortNeeded) {
1326 Collections.sort(messages);
1327 }
1328 }
1329
1330
1331
1332
1333
1334
1335 public int count() {
1336 if (messages == null) {
1337 return messageCount;
1338 } else {
1339 return messages.size();
1340 }
1341 }
1342
1343
1344
1345
1346
1347
1348 public long getUidNext() {
1349 return uidNext;
1350 }
1351
1352
1353
1354
1355
1356
1357
1358 public Message get(int index) {
1359 return messages.get(index);
1360 }
1361
1362 private TreeMap<Long, String> imapFlagMap = new TreeMap<>();
1363
1364
1365
1366
1367
1368
1369 public TreeMap<Long, String> getImapFlagMap() {
1370 return imapFlagMap;
1371 }
1372
1373 public void buildImapFlagMap() {
1374 int previousMessageCount = imapFlagMap.size();
1375
1376 imapFlagMap = new TreeMap<>();
1377 for (ExchangeSession.Message message : messages) {
1378 imapFlagMap.put(message.getImapUid(), message.getImapFlags());
1379 }
1380 if (previousMessageCount != imapFlagMap.size()) {
1381 LOGGER.debug("imapFlagMap size: " + previousMessageCount + " -> " + imapFlagMap.size());
1382 }
1383 }
1384
1385
1386
1387
1388
1389
1390 public boolean isCalendar() {
1391 return "IPF.Appointment".equals(folderClass);
1392 }
1393
1394
1395
1396
1397
1398
1399 public boolean isContact() {
1400 return "IPF.Contact".equals(folderClass);
1401 }
1402
1403
1404
1405
1406
1407
1408 public boolean isTask() {
1409 return "IPF.Task".equals(folderClass);
1410 }
1411
1412
1413
1414
1415 public void clearCache() {
1416 messages.cachedMimeContent = null;
1417 messages.cachedMimeMessage = null;
1418 messages.cachedMessageImapUid = 0;
1419 }
1420 }
1421
1422
1423
1424
1425 public abstract class Message implements Comparable<Message> {
1426
1427
1428
1429 public MessageList messageList;
1430
1431
1432
1433 public String messageUrl;
1434
1435
1436
1437 public String permanentUrl;
1438
1439
1440
1441 public String uid;
1442
1443
1444
1445 public String contentClass;
1446
1447
1448
1449 public String keywords;
1450
1451
1452
1453 public long imapUid;
1454
1455
1456
1457 public int size;
1458
1459
1460
1461 public String date;
1462
1463
1464
1465
1466 public boolean read;
1467
1468
1469
1470 public boolean deleted;
1471
1472
1473
1474 public boolean junk;
1475
1476
1477
1478 public boolean flagged;
1479
1480
1481
1482 public boolean recent;
1483
1484
1485
1486 public boolean draft;
1487
1488
1489
1490 public boolean answered;
1491
1492
1493
1494 public boolean forwarded;
1495
1496
1497
1498
1499 protected byte[] mimeContent;
1500
1501
1502
1503
1504 protected MimeMessage mimeMessage;
1505
1506
1507
1508
1509
1510
1511
1512 public abstract String getPermanentId();
1513
1514
1515
1516
1517
1518
1519 public long getImapUid() {
1520 return imapUid;
1521 }
1522
1523
1524
1525
1526
1527
1528 public void setImapUid(long imapUid) {
1529 this.imapUid = imapUid;
1530 }
1531
1532
1533
1534
1535
1536
1537 public String getUid() {
1538 return uid;
1539 }
1540
1541
1542
1543
1544
1545
1546 public String getImapFlags() {
1547 StringBuilder buffer = new StringBuilder();
1548 if (read) {
1549 buffer.append("\\Seen ");
1550 }
1551 if (deleted) {
1552 buffer.append("\\Deleted ");
1553 }
1554 if (recent) {
1555 buffer.append("\\Recent ");
1556 }
1557 if (flagged) {
1558 buffer.append("\\Flagged ");
1559 }
1560 if (junk) {
1561 buffer.append("Junk ");
1562 }
1563 if (draft) {
1564 buffer.append("\\Draft ");
1565 }
1566 if (answered) {
1567 buffer.append("\\Answered ");
1568 }
1569 if (forwarded) {
1570 buffer.append("$Forwarded ");
1571 }
1572 if (keywords != null) {
1573 for (String keyword : keywords.split(",")) {
1574 buffer.append(encodeKeyword(convertKeywordToFlag(keyword))).append(" ");
1575 }
1576 }
1577 return buffer.toString().trim();
1578 }
1579
1580
1581
1582
1583
1584
1585
1586 public void loadMimeMessage() throws IOException, MessagingException {
1587 if (mimeMessage == null) {
1588
1589 if (this.imapUid == messageList.cachedMessageImapUid
1590
1591 && messageList.cachedMimeContent != null
1592 && messageList.cachedMimeMessage != null) {
1593 mimeContent = messageList.cachedMimeContent;
1594 mimeMessage = messageList.cachedMimeMessage;
1595 LOGGER.debug("Got message content for " + imapUid + " from cache");
1596 } else {
1597
1598 mimeContent = getContent(this);
1599 mimeMessage = new MimeMessage(null, new SharedByteArrayInputStream(mimeContent));
1600
1601 if (mimeMessage.getHeader("MAIL FROM") != null) {
1602
1603 byte[] mimeContentCopy = new byte[((SharedByteArrayInputStream) mimeMessage.getRawInputStream()).available()];
1604 int offset = mimeContent.length - mimeContentCopy.length;
1605
1606 System.arraycopy(mimeContent, offset, mimeContentCopy, 0, mimeContentCopy.length);
1607 mimeContent = mimeContentCopy;
1608 mimeMessage = new MimeMessage(null, new SharedByteArrayInputStream(mimeContent));
1609 }
1610 LOGGER.debug("Downloaded full message content for IMAP UID " + imapUid + " (" + mimeContent.length + " bytes)");
1611 }
1612 }
1613 }
1614
1615
1616
1617
1618
1619
1620
1621
1622 public MimeMessage getMimeMessage() throws IOException, MessagingException {
1623 loadMimeMessage();
1624 return mimeMessage;
1625 }
1626
1627 public Enumeration<?> getMatchingHeaderLinesFromHeaders(String[] headerNames) throws MessagingException {
1628 Enumeration<?> result = null;
1629 if (mimeMessage == null) {
1630
1631 InputStream headers = getMimeHeaders();
1632 if (headers != null) {
1633 InternetHeaders internetHeaders = new InternetHeaders(headers);
1634 if (internetHeaders.getHeader("Subject") == null) {
1635
1636 return null;
1637 }
1638 if (headerNames == null) {
1639 result = internetHeaders.getAllHeaderLines();
1640 } else {
1641 result = internetHeaders.getMatchingHeaderLines(headerNames);
1642 }
1643 }
1644 }
1645 return result;
1646 }
1647
1648 public Enumeration<?> getMatchingHeaderLines(String[] headerNames) throws MessagingException, IOException {
1649 Enumeration<?> result = getMatchingHeaderLinesFromHeaders(headerNames);
1650 if (result == null) {
1651 if (headerNames == null) {
1652 result = getMimeMessage().getAllHeaderLines();
1653 } else {
1654 result = getMimeMessage().getMatchingHeaderLines(headerNames);
1655 }
1656
1657 }
1658 return result;
1659 }
1660
1661 protected abstract InputStream getMimeHeaders();
1662
1663
1664
1665
1666
1667
1668
1669
1670 public int getMimeMessageSize() throws IOException, MessagingException {
1671 loadMimeMessage();
1672 return mimeContent.length;
1673 }
1674
1675
1676
1677
1678
1679
1680
1681
1682 public InputStream getRawInputStream() throws IOException, MessagingException {
1683 loadMimeMessage();
1684 return new SharedByteArrayInputStream(mimeContent);
1685 }
1686
1687
1688
1689
1690
1691
1692 public void dropMimeMessage() {
1693
1694 if (mimeMessage != null) {
1695 messageList.cachedMessageImapUid = imapUid;
1696 messageList.cachedMimeContent = mimeContent;
1697 messageList.cachedMimeMessage = mimeMessage;
1698 }
1699
1700 mimeMessage = null;
1701 mimeContent = null;
1702 }
1703
1704 public boolean isLoaded() {
1705
1706 if (imapUid == messageList.cachedMessageImapUid) {
1707 mimeContent = messageList.cachedMimeContent;
1708 mimeMessage = messageList.cachedMimeMessage;
1709 }
1710 return mimeMessage != null;
1711 }
1712
1713
1714
1715
1716
1717
1718 public void delete() throws IOException {
1719 deleteMessage(this);
1720 }
1721
1722
1723
1724
1725
1726
1727 public void moveToTrash() throws IOException {
1728 markRead();
1729
1730 ExchangeSession.this.moveToTrash(this);
1731 }
1732
1733
1734
1735
1736
1737
1738 public void markRead() throws IOException {
1739 HashMap<String, String> properties = new HashMap<>();
1740 properties.put("read", "1");
1741 updateMessage(this, properties);
1742 }
1743
1744
1745
1746
1747
1748
1749
1750 public int compareTo(Message message) {
1751 long compareValue = (imapUid - message.imapUid);
1752 if (compareValue > 0) {
1753 return 1;
1754 } else if (compareValue < 0) {
1755 return -1;
1756 } else {
1757 return 0;
1758 }
1759 }
1760
1761
1762
1763
1764
1765
1766
1767 @Override
1768 public boolean equals(Object message) {
1769 return message instanceof Message && imapUid == ((Message) message).imapUid;
1770 }
1771
1772
1773
1774
1775
1776
1777 @Override
1778 public int hashCode() {
1779 return Long.hashCode(imapUid);
1780 }
1781
1782 public String removeFlag(String flag) {
1783 if (keywords != null) {
1784 final String exchangeFlag = convertFlagToKeyword(flag);
1785 Set<String> keywordSet = new HashSet<>();
1786 String[] keywordArray = keywords.split(",");
1787 for (String value : keywordArray) {
1788 if (!value.equalsIgnoreCase(exchangeFlag)) {
1789 keywordSet.add(value);
1790 }
1791 }
1792 keywords = StringUtil.join(keywordSet, ",");
1793 }
1794 return keywords;
1795 }
1796
1797 public String addFlag(String flag) {
1798 final String exchangeFlag = convertFlagToKeyword(flag);
1799 HashSet<String> keywordSet = new HashSet<>();
1800 boolean hasFlag = false;
1801 if (keywords != null) {
1802 String[] keywordArray = keywords.split(",");
1803 for (String value : keywordArray) {
1804 keywordSet.add(value);
1805 if (value.equalsIgnoreCase(exchangeFlag)) {
1806 hasFlag = true;
1807 }
1808 }
1809 }
1810 if (!hasFlag) {
1811 keywordSet.add(exchangeFlag);
1812 }
1813 keywords = StringUtil.join(keywordSet, ",");
1814 return keywords;
1815 }
1816
1817 public String setFlags(HashSet<String> flags) {
1818 keywords = convertFlagsToKeywords(flags);
1819 return keywords;
1820 }
1821
1822 }
1823
1824
1825
1826
1827 public static class MessageList extends ArrayList<Message> {
1828
1829
1830
1831 protected transient MimeMessage cachedMimeMessage;
1832
1833
1834
1835 protected transient long cachedMessageImapUid;
1836
1837
1838
1839 protected transient byte[] cachedMimeContent;
1840
1841 @Override
1842 public boolean add(Message message) {
1843 message.messageList = this;
1844 return super.add(message);
1845 }
1846 }
1847
1848
1849
1850
1851 public abstract static class Item extends HashMap<String, String> {
1852 public String folderPath;
1853 protected String itemName;
1854 protected String permanentUrl;
1855
1856
1857
1858 public String displayName;
1859
1860
1861
1862 public String etag;
1863 protected String noneMatch;
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873 public Item(String folderPath, String itemName, String etag, String noneMatch) {
1874 this.folderPath = folderPath;
1875 this.itemName = itemName;
1876 this.etag = etag;
1877 this.noneMatch = noneMatch;
1878 }
1879
1880
1881
1882
1883 protected Item() {
1884 }
1885
1886
1887
1888
1889
1890
1891 public abstract String getContentType();
1892
1893
1894
1895
1896
1897
1898
1899 public abstract String getBody() throws IOException;
1900
1901
1902
1903
1904
1905
1906 public String getName() {
1907 return itemName;
1908 }
1909
1910
1911
1912
1913
1914
1915 public String getEtag() {
1916 return etag;
1917 }
1918
1919
1920
1921
1922
1923
1924 public void setHref(String href) {
1925 int index = href.lastIndexOf('/');
1926 if (index >= 0) {
1927 folderPath = href.substring(0, index);
1928 itemName = href.substring(index + 1);
1929 } else {
1930 throw new IllegalArgumentException(href);
1931 }
1932 }
1933
1934
1935
1936
1937
1938
1939 public String getHref() {
1940 return folderPath + '/' + itemName;
1941 }
1942
1943 public void setItemName(String itemName) {
1944 this.itemName = itemName;
1945 }
1946 }
1947
1948
1949
1950
1951 public abstract class Contact extends Item {
1952
1953 protected ArrayList<String> distributionListMembers = null;
1954 protected String vCardVersion;
1955
1956 public Contact(String folderPath, String itemName, Map<String, String> properties, String etag, String noneMatch) {
1957 super(folderPath, itemName.endsWith(".vcf") ? itemName.substring(0, itemName.length() - 3) + "EML" : itemName, etag, noneMatch);
1958 this.putAll(properties);
1959 }
1960
1961 protected Contact() {
1962 }
1963
1964 public void setVCardVersion(String vCardVersion) {
1965 this.vCardVersion = vCardVersion;
1966 }
1967
1968 public abstract ItemResult createOrUpdate() throws IOException;
1969
1970
1971
1972
1973
1974
1975 @Override
1976 public String getName() {
1977 String name = super.getName();
1978 if (name.endsWith(".EML")) {
1979 name = name.substring(0, name.length() - 3) + "vcf";
1980 }
1981 return name;
1982 }
1983
1984
1985
1986
1987
1988
1989 public void setName(String name) {
1990 this.itemName = name;
1991 }
1992
1993
1994
1995
1996
1997
1998 public String getUid() {
1999 String uid = getName();
2000 int dotIndex = uid.lastIndexOf('.');
2001 if (dotIndex > 0) {
2002 uid = uid.substring(0, dotIndex);
2003 }
2004 return URIUtil.encodePath(uid);
2005 }
2006
2007 @Override
2008 public String getContentType() {
2009 return "text/vcard";
2010 }
2011
2012 public void addMember(String member) {
2013 if (distributionListMembers == null) {
2014 distributionListMembers = new ArrayList<>();
2015 }
2016 distributionListMembers.add(member);
2017 }
2018
2019
2020 @Override
2021 public String getBody() {
2022
2023 VCardWriter writer = new VCardWriter();
2024 writer.startCard(vCardVersion);
2025 writer.appendProperty("UID", getUid());
2026
2027 String cn = get("cn");
2028 if (cn == null) {
2029 cn = get("displayname");
2030 }
2031 String sn = get("sn");
2032 if (sn == null) {
2033 sn = cn;
2034 }
2035 writer.appendProperty("FN", cn);
2036
2037 writer.appendProperty("N", sn, get("givenName"), get("middlename"), get("personaltitle"), get("namesuffix"));
2038
2039 if (distributionListMembers != null) {
2040 if ("3.0".equals(vCardVersion)) {
2041 writer.appendProperty("X-ADDRESSBOOKSERVER-KIND", "group");
2042 for (String member : distributionListMembers) {
2043 writer.appendProperty("X-ADDRESSBOOKSERVER-MEMBER", member);
2044 }
2045 } else {
2046 writer.appendProperty("KIND", "group");
2047 for (String member : distributionListMembers) {
2048 writer.appendProperty("MEMBER", member);
2049 }
2050 }
2051 }
2052
2053 writer.appendProperty("TEL;TYPE=cell", get("mobile"));
2054 writer.appendProperty("TEL;TYPE=work", get("telephoneNumber"));
2055 writer.appendProperty("TEL;TYPE=home", get("homePhone"));
2056 writer.appendProperty("TEL;TYPE=fax", get("facsimiletelephonenumber"));
2057 writer.appendProperty("TEL;TYPE=pager", get("pager"));
2058 writer.appendProperty("TEL;TYPE=car", get("othermobile"));
2059 writer.appendProperty("TEL;TYPE=home,fax", get("homefax"));
2060 writer.appendProperty("TEL;TYPE=isdn", get("internationalisdnnumber"));
2061 writer.appendProperty("TEL;TYPE=msg", get("otherTelephone"));
2062
2063 writer.appendProperty("TEL;TYPE=work", get("otherBusinessTelephoneNumber"));
2064 writer.appendProperty("TEL;TYPE=home", get("otherHomePhone"));
2065
2066
2067
2068
2069 writer.appendProperty("ADR;TYPE=home",
2070 get("homepostofficebox"), null, get("homeStreet"), get("homeCity"), get("homeState"), get("homePostalCode"), get("homeCountry"));
2071 writer.appendProperty("ADR;TYPE=work",
2072 get("postofficebox"), get("roomnumber"), get("street"), get("l"), get("st"), get("postalcode"), get("co"));
2073 writer.appendProperty("ADR;TYPE=other",
2074 get("otherpostofficebox"), null, get("otherstreet"), get("othercity"), get("otherstate"), get("otherpostalcode"), get("othercountry"));
2075
2076 writer.appendProperty("EMAIL;TYPE=work", get("smtpemail1"));
2077 writer.appendProperty("EMAIL;TYPE=home", get("smtpemail2"));
2078 writer.appendProperty("EMAIL;TYPE=other", get("smtpemail3"));
2079
2080 writer.appendProperty("ORG", get("o"), get("department"));
2081 writer.appendProperty("URL;TYPE=work", get("businesshomepage"));
2082 writer.appendProperty("URL;TYPE=home", get("personalHomePage"));
2083 writer.appendProperty("TITLE", get("title"));
2084 writer.appendProperty("NOTE", get("personalNotes"));
2085
2086 writer.appendProperty("CUSTOM1", get("extensionattribute1"));
2087 writer.appendProperty("CUSTOM2", get("extensionattribute2"));
2088 writer.appendProperty("CUSTOM3", get("extensionattribute3"));
2089 writer.appendProperty("CUSTOM4", get("extensionattribute4"));
2090
2091 writer.appendProperty("ROLE", get("profession"));
2092 writer.appendProperty("NICKNAME", get("nickname"));
2093 writer.appendProperty("X-AIM", get("im"));
2094
2095 writer.appendProperty("BDAY", convertZuluDateToBday(get("bday")));
2096 writer.appendProperty("ANNIVERSARY", convertZuluDateToBday(get("anniversary")));
2097
2098 String gender = get("gender");
2099 if ("1".equals(gender)) {
2100 writer.appendProperty("SEX", "2");
2101 } else if ("2".equals(gender)) {
2102 writer.appendProperty("SEX", "1");
2103 }
2104
2105 writer.appendProperty("CATEGORIES", get("keywords"));
2106
2107 writer.appendProperty("FBURL", get("fburl"));
2108
2109 if ("1".equals(get("private"))) {
2110 writer.appendProperty("CLASS", "PRIVATE");
2111 }
2112
2113 writer.appendProperty("X-ASSISTANT", get("secretarycn"));
2114 writer.appendProperty("X-MANAGER", get("manager"));
2115 writer.appendProperty("X-SPOUSE", get("spousecn"));
2116
2117 writer.appendProperty("REV", get("lastmodified"));
2118
2119 ContactPhoto contactPhoto = null;
2120
2121 if (Settings.getBooleanProperty("davmail.carddavReadPhoto", true)) {
2122 if (("true".equals(get("haspicture")))) {
2123 try {
2124 contactPhoto = getContactPhoto(this);
2125 } catch (IOException e) {
2126 LOGGER.warn("Unable to get photo from contact " + this.get("cn"));
2127 }
2128 }
2129
2130 if (contactPhoto == null) {
2131 contactPhoto = getADPhoto(get("smtpemail1"));
2132 }
2133 }
2134
2135 if (contactPhoto != null) {
2136 if ("3.0".equals(vCardVersion)) {
2137
2138 String photoType = contactPhoto.contentType;
2139 if (photoType != null && photoType.startsWith("image/")) {
2140 photoType = photoType.substring("image/".length()).toUpperCase();
2141 }
2142 writer.writeLine("PHOTO;ENCODING=b;TYPE=" + photoType + ":" + contactPhoto.content);
2143 } else {
2144
2145 writer.writeLine("PHOTO:data:" + contactPhoto.contentType + ";base64," + contactPhoto.content);
2146 }
2147 }
2148
2149 writer.appendProperty("KEY1;X509;ENCODING=BASE64", get("msexchangecertificate"));
2150 writer.appendProperty("KEY2;X509;ENCODING=BASE64", get("usersmimecertificate"));
2151
2152 writer.endCard();
2153 return writer.toString();
2154 }
2155 }
2156
2157
2158
2159
2160 public abstract class Event extends Item {
2161 protected String contentClass;
2162 protected String subject;
2163 protected VCalendar vCalendar;
2164 protected String startTimeZone;
2165
2166 public Event(String folderPath, String itemName, String contentClass, String itemBody, String etag, String noneMatch) throws IOException {
2167 super(folderPath, itemName, etag, noneMatch);
2168 this.contentClass = contentClass;
2169 fixICS(itemBody.getBytes(StandardCharsets.UTF_8), getCalendarEmail(folderPath), false);
2170
2171 if (vCalendar.isTodo() && this.itemName.endsWith(".ics")) {
2172 this.itemName = itemName.substring(0, itemName.length() - 3) + "EML";
2173 }
2174 }
2175
2176 protected Event() {
2177 }
2178
2179 @Override
2180 public String getContentType() {
2181 return "text/calendar;charset=UTF-8";
2182 }
2183
2184 @Override
2185 public String getBody() throws IOException {
2186 if (vCalendar == null) {
2187 fixICS(getEventContent(), getCalendarEmail(folderPath), true);
2188 }
2189 return vCalendar.toString();
2190 }
2191
2192 protected HttpNotFoundException buildHttpNotFoundException(Exception e) {
2193 String message = "Unable to get event " + getName() + " subject: " + subject + " at " + permanentUrl + ": " + e.getMessage();
2194 LOGGER.warn(message);
2195 return new HttpNotFoundException(message);
2196 }
2197
2198
2199
2200
2201
2202
2203
2204 public abstract byte[] getEventContent() throws IOException;
2205
2206 protected static final String TEXT_CALENDAR = "text/calendar";
2207 protected static final String APPLICATION_ICS = "application/ics";
2208
2209 protected boolean isCalendarContentType(String contentType) {
2210 return TEXT_CALENDAR.regionMatches(true, 0, contentType, 0, TEXT_CALENDAR.length()) ||
2211 APPLICATION_ICS.regionMatches(true, 0, contentType, 0, APPLICATION_ICS.length());
2212 }
2213
2214 protected MimePart getCalendarMimePart(MimeMultipart multiPart) throws IOException, MessagingException {
2215 MimePart bodyPart = null;
2216 for (int i = 0; i < multiPart.getCount(); i++) {
2217 String contentType = multiPart.getBodyPart(i).getContentType();
2218 if (isCalendarContentType(contentType)) {
2219 bodyPart = (MimePart) multiPart.getBodyPart(i);
2220 break;
2221 } else if (contentType.startsWith("multipart")) {
2222 Object content = multiPart.getBodyPart(i).getContent();
2223 if (content instanceof MimeMultipart) {
2224 bodyPart = getCalendarMimePart((MimeMultipart) content);
2225 }
2226 }
2227 }
2228
2229 return bodyPart;
2230 }
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240 protected byte[] getICS(InputStream mimeInputStream) throws IOException, MessagingException {
2241 byte[] result;
2242 MimeMessage mimeMessage = new MimeMessage(null, mimeInputStream);
2243 String[] contentClassHeader = mimeMessage.getHeader("Content-class");
2244
2245 if (contentClassHeader != null && contentClassHeader.length > 0 && "urn:content-classes:task".equals(contentClassHeader[0])) {
2246 return null;
2247 }
2248 Object mimeBody = mimeMessage.getContent();
2249 MimePart bodyPart = null;
2250 if (mimeBody instanceof MimeMultipart) {
2251 bodyPart = getCalendarMimePart((MimeMultipart) mimeBody);
2252 } else if (isCalendarContentType(mimeMessage.getContentType())) {
2253
2254 bodyPart = mimeMessage;
2255 }
2256
2257
2258 if (bodyPart != null) {
2259 try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
2260 bodyPart.getDataHandler().writeTo(baos);
2261 result = baos.toByteArray();
2262 }
2263 } else {
2264 try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
2265 mimeMessage.writeTo(baos);
2266 throw new DavMailException("EXCEPTION_INVALID_MESSAGE_CONTENT", new String(baos.toByteArray(), StandardCharsets.UTF_8));
2267 }
2268 }
2269 return result;
2270 }
2271
2272 protected void fixICS(byte[] icsContent, String calendarEmail, boolean fromServer) throws IOException {
2273 if (LOGGER.isDebugEnabled() && fromServer) {
2274 dumpIndex++;
2275 String icsBody = new String(icsContent, StandardCharsets.UTF_8);
2276 ICSCalendarValidator.ValidationResult vr = ICSCalendarValidator.validateWithDetails(icsBody);
2277 dumpICS(icsBody, true, false);
2278 LOGGER.debug("Vcalendar body ValidationResult: "+ vr.isValid() +" "+ vr.showReason());
2279 LOGGER.debug("Vcalendar body received from server:\n" + icsBody);
2280 }
2281 vCalendar = new VCalendar(icsContent, calendarEmail, getVTimezone());
2282 if (startTimeZone != null) {
2283 vCalendar.setStartTimeZone(startTimeZone);
2284 }
2285 vCalendar.fixVCalendar(fromServer);
2286 if (LOGGER.isDebugEnabled() && !fromServer) {
2287 String resultString = vCalendar.toString();
2288 ICSCalendarValidator.ValidationResult vr = ICSCalendarValidator.validateWithDetails(resultString);
2289 LOGGER.debug("Fixed Vcalendar body ValidationResult: "+ vr.isValid() +" "+ vr.showReason());
2290 LOGGER.debug("Fixed Vcalendar body to server:\n" + resultString);
2291 dumpICS(resultString, false, true);
2292 }
2293 }
2294
2295 protected void dumpICS(String icsBody, boolean fromServer, boolean after) {
2296 String logFileDirectory = Settings.getLogFileDirectory();
2297
2298
2299 int dumpMax = Settings.getIntProperty("davmail.dumpICS");
2300 if (dumpMax > 0) {
2301 if (dumpIndex > dumpMax) {
2302
2303 final int oldest = dumpIndex - dumpMax;
2304 try {
2305 File[] oldestFiles = (new File(logFileDirectory)).listFiles((dir, name) -> {
2306 if (name.endsWith(".ics")) {
2307 int dashIndex = name.indexOf('-');
2308 if (dashIndex > 0) {
2309 try {
2310 int fileIndex = Integer.parseInt(name.substring(0, dashIndex));
2311 return fileIndex < oldest;
2312 } catch (NumberFormatException nfe) {
2313
2314 }
2315 }
2316 }
2317 return false;
2318 });
2319 if (oldestFiles != null) {
2320 for (File file : oldestFiles) {
2321 if (!file.delete()) {
2322 LOGGER.warn("Unable to delete " + file.getAbsolutePath());
2323 }
2324 }
2325 }
2326 } catch (Exception ex) {
2327 LOGGER.warn("Error deleting ics dump: " + ex.getMessage());
2328 }
2329 }
2330
2331 StringBuilder filePath = new StringBuilder();
2332 filePath.append(logFileDirectory).append('/')
2333 .append(dumpIndex)
2334 .append(after ? "-to" : "-from")
2335 .append((after ^ fromServer) ? "-server" : "-client")
2336 .append(".ics");
2337 if ((icsBody != null) && (!icsBody.isEmpty())) {
2338 try (OutputStreamWriter writer = new OutputStreamWriter(Files.newOutputStream(Paths.get(filePath.toString())), StandardCharsets.UTF_8))
2339 {
2340 writer.write(icsBody);
2341 } catch (IOException e) {
2342 LOGGER.error(e);
2343 }
2344
2345
2346 }
2347 }
2348
2349 }
2350
2351
2352
2353
2354
2355
2356
2357 public byte[] createMimeContent() throws IOException {
2358 String boundary = UUID.randomUUID().toString();
2359 ByteArrayOutputStream baos = new ByteArrayOutputStream();
2360 MimeOutputStreamWriter writer = new MimeOutputStreamWriter(baos);
2361
2362 writer.writeHeader("Content-Transfer-Encoding", "7bit");
2363 writer.writeHeader("Content-class", contentClass);
2364
2365 writer.writeHeader("Date", new Date());
2366
2367
2368 String vEventSubject = vCalendar.getFirstVeventPropertyValue("SUMMARY");
2369 if (vEventSubject == null) {
2370 vEventSubject = BundleMessage.format("MEETING_REQUEST");
2371 }
2372
2373
2374
2375 String description = vCalendar.getFirstVeventPropertyValue("DESCRIPTION");
2376
2377
2378 if ("urn:content-classes:calendarmessage".equals(contentClass)) {
2379
2380 VCalendar.Recipients recipients = vCalendar.getRecipients(true);
2381 String to;
2382 String cc;
2383 String notificationSubject;
2384 if (email.equalsIgnoreCase(recipients.organizer)) {
2385
2386 to = recipients.attendees;
2387 cc = recipients.optionalAttendees;
2388 notificationSubject = subject;
2389 } else {
2390 String status = vCalendar.getAttendeeStatus();
2391
2392 to = recipients.organizer;
2393 cc = null;
2394 notificationSubject = (status != null) ? (BundleMessage.format(status) + vEventSubject) : subject;
2395 description = "";
2396 }
2397
2398
2399 if (Settings.getBooleanProperty("davmail.caldavEditNotifications")) {
2400
2401 NotificationDialog notificationDialog = new NotificationDialog(to,
2402 cc, notificationSubject, description);
2403 if (!notificationDialog.getSendNotification()) {
2404 LOGGER.debug("Notification canceled by user");
2405 return null;
2406 }
2407
2408 to = notificationDialog.getTo();
2409 cc = notificationDialog.getCc();
2410 notificationSubject = notificationDialog.getSubject();
2411 description = notificationDialog.getBody();
2412 }
2413
2414
2415 if ((to == null || to.isEmpty()) && (cc == null || cc.isEmpty())) {
2416 return null;
2417 }
2418
2419 writer.writeHeader("To", to);
2420 writer.writeHeader("Cc", cc);
2421 writer.writeHeader("Subject", notificationSubject);
2422
2423
2424 if (LOGGER.isDebugEnabled()) {
2425 StringBuilder logBuffer = new StringBuilder("Sending notification ");
2426 if (to != null) {
2427 logBuffer.append("to: ").append(to);
2428 }
2429 if (cc != null) {
2430 logBuffer.append("cc: ").append(cc);
2431 }
2432 LOGGER.debug(logBuffer.toString());
2433 }
2434 } else {
2435
2436 VCalendar.Recipients recipients = vCalendar.getRecipients(false);
2437
2438 if (recipients.attendees != null) {
2439 writer.writeHeader("To", recipients.attendees);
2440 } else {
2441
2442 writer.writeHeader("To", email);
2443 }
2444 writer.writeHeader("Cc", recipients.optionalAttendees);
2445
2446 if (recipients.organizer != null) {
2447 writer.writeHeader("From", recipients.organizer);
2448 } else {
2449 writer.writeHeader("From", email);
2450 }
2451 }
2452 if (vCalendar.getMethod() == null) {
2453 vCalendar.setPropertyValue("METHOD", "REQUEST");
2454 }
2455 writer.writeHeader("MIME-Version", "1.0");
2456 writer.writeHeader("Content-Type", "multipart/alternative;\r\n" +
2457 "\tboundary=\"----=_NextPart_" + boundary + '\"');
2458 writer.writeLn();
2459 writer.writeLn("This is a multi-part message in MIME format.");
2460 writer.writeLn();
2461 writer.writeLn("------=_NextPart_" + boundary);
2462
2463 if (description != null && !description.isEmpty()) {
2464 writer.writeHeader("Content-Type", "text/plain;\r\n" +
2465 "\tcharset=\"utf-8\"");
2466 writer.writeHeader("content-transfer-encoding", "8bit");
2467 writer.writeLn();
2468 writer.flush();
2469 baos.write(description.getBytes(StandardCharsets.UTF_8));
2470 writer.writeLn();
2471 writer.writeLn("------=_NextPart_" + boundary);
2472 }
2473 writer.writeHeader("Content-class", contentClass);
2474 writer.writeHeader("Content-Type", "text/calendar;\r\n" +
2475 "\tmethod=" + vCalendar.getMethod() + ";\r\n" +
2476 "\tcharset=\"utf-8\""
2477 );
2478 writer.writeHeader("Content-Transfer-Encoding", "8bit");
2479 writer.writeLn();
2480 writer.flush();
2481 baos.write(vCalendar.toString().getBytes(StandardCharsets.UTF_8));
2482 writer.writeLn();
2483 writer.writeLn("------=_NextPart_" + boundary + "--");
2484 writer.close();
2485 return baos.toByteArray();
2486 }
2487
2488
2489
2490
2491
2492
2493
2494 public abstract ItemResult createOrUpdate() throws IOException;
2495
2496 }
2497
2498 protected abstract Set<String> getItemProperties();
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508 public List<ExchangeSession.Contact> getAllContacts(String folderPath, boolean includeDistList) throws IOException {
2509 return searchContacts(folderPath, ExchangeSession.CONTACT_ATTRIBUTES, isEqualTo("outlookmessageclass", "IPM.Contact"), 0);
2510 }
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523 public abstract List<Contact> searchContacts(String folderPath, Set<String> attributes, Condition condition, int maxCount) throws IOException;
2524
2525
2526
2527
2528
2529
2530
2531
2532 public abstract List<Event> getEventMessages(String folderPath) throws IOException;
2533
2534
2535
2536
2537
2538
2539
2540
2541 public List<Event> getAllEvents(String folderPath) throws IOException {
2542 List<Event> results = searchEvents(folderPath, getCalendarItemCondition(getPastDelayCondition("dtstart")));
2543
2544 if (!Settings.getBooleanProperty("davmail.caldavDisableTasks", false) && isMainCalendar(folderPath)) {
2545
2546 results.addAll(searchTasksOnly(folderPath));
2547 }
2548
2549 return results;
2550 }
2551
2552 protected abstract Condition getCalendarItemCondition(Condition dateCondition);
2553
2554 protected Condition getPastDelayCondition(String attribute) {
2555 int caldavPastDelay = Settings.getIntProperty("davmail.caldavPastDelay");
2556 Condition dateCondition = null;
2557 if (caldavPastDelay != 0) {
2558 Calendar cal = Calendar.getInstance();
2559 cal.add(Calendar.DAY_OF_MONTH, -caldavPastDelay);
2560 dateCondition = gt(attribute, formatSearchDate(cal.getTime()));
2561 }
2562 return dateCondition;
2563 }
2564
2565 protected Condition getRangeCondition(String timeRangeStart, String timeRangeEnd) throws IOException {
2566 try {
2567 SimpleDateFormat parser = getZuluDateFormat();
2568 ExchangeSession.MultiCondition andCondition = and();
2569 if (timeRangeStart != null) {
2570 andCondition.add(gt("dtend", formatSearchDate(parser.parse(timeRangeStart))));
2571 }
2572 if (timeRangeEnd != null) {
2573 andCondition.add(lt("dtstart", formatSearchDate(parser.parse(timeRangeEnd))));
2574 }
2575 return andCondition;
2576 } catch (ParseException e) {
2577 throw new IOException(e + " " + e.getMessage());
2578 }
2579 }
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590 public List<Event> searchEvents(String folderPath, String timeRangeStart, String timeRangeEnd) throws IOException {
2591 Condition dateCondition = getRangeCondition(timeRangeStart, timeRangeEnd);
2592 Condition condition = getCalendarItemCondition(dateCondition);
2593
2594 return searchEvents(folderPath, condition);
2595 }
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606 public List<Event> searchEventsOnly(String folderPath, String timeRangeStart, String timeRangeEnd) throws IOException {
2607 Condition dateCondition = getRangeCondition(timeRangeStart, timeRangeEnd);
2608 return searchEvents(folderPath, getCalendarItemCondition(dateCondition));
2609 }
2610
2611
2612
2613
2614
2615
2616
2617
2618 public List<Event> searchTasksOnly(String folderPath) throws IOException {
2619
2620 String taskFolderPath = folderPath;
2621 if (isMainCalendar(folderPath)) {
2622 taskFolderPath = TASKS;
2623 }
2624 return searchEvents(taskFolderPath, and(isEqualTo("outlookmessageclass", "IPM.Task"),
2625 or(isNull("datecompleted"), getPastDelayCondition("datecompleted"))));
2626 }
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636 public List<Event> searchEvents(String folderPath, Condition filter) throws IOException {
2637
2638 Condition privateCondition = null;
2639 if (isSharedFolder(folderPath) && Settings.getBooleanProperty("davmail.excludePrivateEvents", true)) {
2640 LOGGER.debug("Shared or public calendar: exclude private events");
2641 privateCondition = isEqualTo("sensitivity", 0);
2642 }
2643
2644 return searchEvents(folderPath, getItemProperties(),
2645 and(filter, privateCondition));
2646 }
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657 public abstract List<Event> searchEvents(String folderPath, Set<String> attributes, Condition condition) throws IOException;
2658
2659
2660
2661
2662
2663
2664
2665 protected String convertItemNameToEML(String itemName) {
2666 if (itemName.endsWith(".vcf")) {
2667 return itemName.substring(0, itemName.length() - 3) + "EML";
2668 } else {
2669 return itemName;
2670 }
2671 }
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681 public abstract Item getItem(String folderPath, String itemName) throws IOException;
2682
2683
2684
2685
2686 public static class ContactPhoto {
2687
2688
2689
2690 public String contentType;
2691
2692
2693
2694 public String content;
2695 }
2696
2697
2698
2699
2700
2701
2702
2703
2704 public abstract ContactPhoto getContactPhoto(Contact contact) throws IOException;
2705
2706
2707
2708
2709
2710
2711
2712 public ContactPhoto getADPhoto(String email) {
2713 return null;
2714 }
2715
2716
2717
2718
2719
2720
2721
2722
2723 public abstract void deleteItem(String folderPath, String itemName) throws IOException;
2724
2725
2726
2727
2728
2729
2730
2731
2732 public abstract void processItem(String folderPath, String itemName) throws IOException;
2733
2734
2735 private static int dumpIndex;
2736
2737
2738
2739
2740 public static class ItemResult {
2741
2742
2743
2744 public int status;
2745
2746
2747
2748 public String etag;
2749
2750
2751
2752 public String itemName;
2753 }
2754
2755
2756
2757
2758
2759
2760
2761
2762 public abstract int sendEvent(String icsBody) throws IOException;
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775 public ItemResult createOrUpdateItem(String folderPath, String itemName, String itemBody, String etag, String noneMatch) throws IOException {
2776 if (itemBody.startsWith("BEGIN:VCALENDAR")) {
2777 if (Settings.getBooleanProperty("davmail.caldavReadonly", false)) {
2778 throw new HttpForbiddenException("Calendar is read-only");
2779 }
2780 return internalCreateOrUpdateEvent(folderPath, itemName, "urn:content-classes:appointment", itemBody, etag, noneMatch);
2781 } else if (itemBody.startsWith("BEGIN:VCARD")) {
2782 return createOrUpdateContact(folderPath, itemName, itemBody, etag, noneMatch);
2783 } else {
2784 throw new IOException(BundleMessage.format("EXCEPTION_INVALID_MESSAGE_CONTENT", itemBody));
2785 }
2786 }
2787
2788 static final String[] VCARD_N_PROPERTIES = {"sn", "givenName", "middlename", "personaltitle", "namesuffix"};
2789 static final String[] VCARD_ADR_HOME_PROPERTIES = {"homepostofficebox", null, "homeStreet", "homeCity", "homeState", "homePostalCode", "homeCountry"};
2790 static final String[] VCARD_ADR_WORK_PROPERTIES = {"postofficebox", "roomnumber", "street", "l", "st", "postalcode", "co"};
2791 static final String[] VCARD_ADR_OTHER_PROPERTIES = {"otherpostofficebox", null, "otherstreet", "othercity", "otherstate", "otherpostalcode", "othercountry"};
2792 static final String[] VCARD_ORG_PROPERTIES = {"o", "department"};
2793
2794 protected void convertContactProperties(Map<String, String> properties, String[] contactProperties, List<String> values) {
2795 for (int i = 0; i < values.size() && i < contactProperties.length; i++) {
2796 if (contactProperties[i] != null) {
2797 properties.put(contactProperties[i], values.get(i));
2798 }
2799 }
2800 }
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812 protected static String getContactPhoneField(VProperty property, Map<String, String> properties) {
2813 if (property.hasParam("TYPE", "cell") || property.hasParam("X-GROUP", "cell")) {
2814 return "mobile";
2815 } else if (property.hasParam("TYPE", "fax")) {
2816 return property.hasParam("TYPE", "home") ? "homefax" : "facsimiletelephonenumber";
2817 } else if (property.hasParam("TYPE", "pager")) {
2818 return "pager";
2819 } else if (property.hasParam("TYPE", "car")) {
2820 return "othermobile";
2821 } else if (property.hasParam("TYPE", "work") || property.hasParam("X-GROUP", "work")) {
2822 return firstAvailable(properties, "telephoneNumber", "otherBusinessTelephoneNumber");
2823 } else if (property.hasParam("TYPE", "home") || property.hasParam("X-GROUP", "home")) {
2824 return firstAvailable(properties, "homePhone", "otherHomePhone");
2825 } else {
2826 return "otherTelephone";
2827 }
2828 }
2829
2830 private static String firstAvailable(Map<String, String> properties, String primary, String secondary) {
2831 if (!properties.containsKey(primary)) {
2832 return primary;
2833 } else if (!properties.containsKey(secondary)) {
2834 return secondary;
2835 } else {
2836 return null;
2837 }
2838 }
2839
2840 protected ItemResult createOrUpdateContact(String folderPath, String itemName, String itemBody, String etag, String noneMatch) throws IOException {
2841
2842 Map<String, String> properties = new HashMap<>();
2843
2844 VObject vcard = new VObject(new ICSBufferedReader(new StringReader(itemBody)));
2845 if ("group".equalsIgnoreCase(vcard.getPropertyValue("KIND"))) {
2846 properties.put("outlookmessageclass", "IPM.DistList");
2847 properties.put("displayname", vcard.getPropertyValue("FN"));
2848 properties.put("personalNotes", vcard.getPropertyValue("NOTE"));
2849 } else {
2850 properties.put("outlookmessageclass", "IPM.Contact");
2851
2852 for (VProperty property : vcard.getProperties()) {
2853 if ("FN".equals(property.getKey())) {
2854 properties.put("cn", property.getValue());
2855 properties.put("subject", property.getValue());
2856 properties.put("fileas", property.getValue());
2857
2858 } else if ("N".equals(property.getKey())) {
2859 convertContactProperties(properties, VCARD_N_PROPERTIES, property.getValues());
2860 } else if ("NICKNAME".equals(property.getKey())) {
2861 properties.put("nickname", property.getValue());
2862 } else if ("TEL".equals(property.getKey())) {
2863 String phoneField = getContactPhoneField(property, properties);
2864 if (phoneField != null) {
2865 properties.put(phoneField, property.getValue());
2866 } else {
2867 LOGGER.warn("Ignore additional phone number " + property.getValue());
2868 }
2869 } else if ("ADR".equals(property.getKey())) {
2870
2871 if (property.hasParam("TYPE", "home")) {
2872 convertContactProperties(properties, VCARD_ADR_HOME_PROPERTIES, property.getValues());
2873 } else if (property.hasParam("TYPE", "work")) {
2874 convertContactProperties(properties, VCARD_ADR_WORK_PROPERTIES, property.getValues());
2875
2876 } else {
2877 convertContactProperties(properties, VCARD_ADR_OTHER_PROPERTIES, property.getValues());
2878 }
2879 } else if ("EMAIL".equals(property.getKey())) {
2880 if (property.hasParam("TYPE", "home")) {
2881 properties.put("email2", property.getValue());
2882 properties.put("smtpemail2", property.getValue());
2883 } else if (property.hasParam("TYPE", "other")) {
2884 properties.put("email3", property.getValue());
2885 properties.put("smtpemail3", property.getValue());
2886 } else {
2887 properties.put("email1", property.getValue());
2888 properties.put("smtpemail1", property.getValue());
2889 }
2890 } else if ("ORG".equals(property.getKey())) {
2891 convertContactProperties(properties, VCARD_ORG_PROPERTIES, property.getValues());
2892 } else if ("URL".equals(property.getKey())) {
2893 if (property.hasParam("TYPE", "work")) {
2894 properties.put("businesshomepage", property.getValue());
2895 } else if (property.hasParam("TYPE", "home")) {
2896 properties.put("personalHomePage", property.getValue());
2897 } else {
2898
2899 properties.put("personalHomePage", property.getValue());
2900 }
2901 } else if ("TITLE".equals(property.getKey())) {
2902 properties.put("title", property.getValue());
2903 } else if ("NOTE".equals(property.getKey())) {
2904 properties.put("personalNotes", property.getValue());
2905 } else if ("CUSTOM1".equals(property.getKey())) {
2906 properties.put("extensionattribute1", property.getValue());
2907 } else if ("CUSTOM2".equals(property.getKey())) {
2908 properties.put("extensionattribute2", property.getValue());
2909 } else if ("CUSTOM3".equals(property.getKey())) {
2910 properties.put("extensionattribute3", property.getValue());
2911 } else if ("CUSTOM4".equals(property.getKey())) {
2912 properties.put("extensionattribute4", property.getValue());
2913 } else if ("ROLE".equals(property.getKey())) {
2914 properties.put("profession", property.getValue());
2915 } else if ("X-AIM".equals(property.getKey())) {
2916 properties.put("im", property.getValue());
2917 } else if ("BDAY".equals(property.getKey())) {
2918 properties.put("bday", convertBDayToZulu(property.getValue()));
2919 } else if ("ANNIVERSARY".equals(property.getKey()) || "X-ANNIVERSARY".equals(property.getKey())) {
2920 properties.put("anniversary", convertBDayToZulu(property.getValue()));
2921 } else if ("CATEGORIES".equals(property.getKey())) {
2922 properties.put("keywords", property.getValue());
2923 } else if ("CLASS".equals(property.getKey())) {
2924 if ("PUBLIC".equals(property.getValue())) {
2925 properties.put("sensitivity", "0");
2926 properties.put("private", "false");
2927 } else {
2928 properties.put("sensitivity", "2");
2929 properties.put("private", "true");
2930 }
2931 } else if ("SEX".equals(property.getKey())) {
2932 String propertyValue = property.getValue();
2933 if ("1".equals(propertyValue)) {
2934 properties.put("gender", "2");
2935 } else if ("2".equals(propertyValue)) {
2936 properties.put("gender", "1");
2937 }
2938 } else if ("FBURL".equals(property.getKey())) {
2939 properties.put("fburl", property.getValue());
2940 } else if ("X-ASSISTANT".equals(property.getKey())) {
2941 properties.put("secretarycn", property.getValue());
2942 } else if ("X-MANAGER".equals(property.getKey())) {
2943 properties.put("manager", property.getValue());
2944 } else if ("X-SPOUSE".equals(property.getKey())) {
2945 properties.put("spousecn", property.getValue());
2946 } else if ("PHOTO".equals(property.getKey())) {
2947 String value = property.getValue();
2948 if ("data:image/jpeg".equals(value) && property.values.size() > 1) {
2949 value = property.getValues().get(1);
2950 if (value.startsWith("base64,")) {
2951 value = value.substring(7);
2952 }
2953 }
2954 properties.put("photo", value);
2955 properties.put("haspicture", "true");
2956 } else if ("KEY1".equals(property.getKey())) {
2957 properties.put("msexchangecertificate", property.getValue());
2958 } else if ("KEY2".equals(property.getKey())) {
2959 properties.put("usersmimecertificate", property.getValue());
2960 }
2961 }
2962 LOGGER.debug("Create or update contact " + itemName + ": " + properties);
2963
2964 for (String key : CONTACT_ATTRIBUTES) {
2965 if (!"imapUid".equals(key) && !"etag".equals(key) && !"urlcompname".equals(key) && !"uid".equals(key)
2966 && !"lastmodified".equals(key) && !"sensitivity".equals(key)
2967 && !"haspicture".equals(key)
2968 && !"usersmimecertificate".equals(key) && !"msexchangecertificate".equals(key)
2969 && !properties.containsKey(key)) {
2970 properties.put(key, null);
2971 }
2972 }
2973 }
2974
2975 Contact contact = buildContact(folderPath, itemName, properties, etag, noneMatch);
2976 for (VProperty property : vcard.getProperties()) {
2977 if ("MEMBER".equals(property.getKey())) {
2978 String member = property.getValue();
2979 if (member.startsWith("urn:uuid:")) {
2980 Item item = getItem(folderPath, member.substring(9) + ".EML");
2981 if (item != null) {
2982 if (item.get("smtpemail1") != null) {
2983 member = "mailto:" + item.get("smtpemail1");
2984 } else if (item.get("smtpemail2") != null) {
2985 member = "mailto:" + item.get("smtpemail2");
2986 } else if (item.get("smtpemail3") != null) {
2987 member = "mailto:" + item.get("smtpemail3");
2988 }
2989 }
2990 }
2991 contact.addMember(member);
2992 }
2993 }
2994 return contact.createOrUpdate();
2995 }
2996
2997 protected String convertZuluDateToBday(String value) {
2998 String result = null;
2999 if (value != null && !value.isEmpty()) {
3000 try {
3001 SimpleDateFormat parser = ExchangeSession.getZuluDateFormat();
3002 Calendar cal = Calendar.getInstance();
3003 cal.setTime(parser.parse(value));
3004 cal.add(Calendar.HOUR_OF_DAY, 12);
3005 result = ExchangeSession.getVcardBdayFormat().format(cal.getTime());
3006 } catch (ParseException e) {
3007 LOGGER.warn("Invalid date: " + value);
3008 }
3009 }
3010 return result;
3011 }
3012
3013 protected String convertBDayToZulu(String value) {
3014 String result = null;
3015 if (value != null && !value.isEmpty()) {
3016 try {
3017 SimpleDateFormat parser;
3018 if (value.length() == 8) {
3019 parser = new SimpleDateFormat("yyyyMMdd", Locale.ENGLISH);
3020 parser.setTimeZone(GMT_TIMEZONE);
3021 } else if (value.length() == 10) {
3022 parser = ExchangeSession.getVcardBdayFormat();
3023 } else if (value.length() == 15) {
3024 parser = new SimpleDateFormat("yyyyMMdd'T'HHmmss", Locale.ENGLISH);
3025 parser.setTimeZone(GMT_TIMEZONE);
3026 } else {
3027 parser = ExchangeSession.getExchangeZuluDateFormat();
3028 }
3029 result = ExchangeSession.getExchangeZuluDateFormatMillisecond().format(parser.parse(value));
3030 } catch (ParseException e) {
3031 LOGGER.warn("Invalid date: " + value);
3032 }
3033 }
3034
3035 return result;
3036 }
3037
3038
3039 protected abstract Contact buildContact(String folderPath, String itemName, Map<String, String> properties, String etag, String noneMatch) throws IOException;
3040
3041 protected abstract ItemResult internalCreateOrUpdateEvent(String folderPath, String itemName, String contentClass, String icsBody, String etag, String noneMatch) throws IOException;
3042
3043
3044
3045
3046
3047
3048 public String getAliasFromLogin() {
3049
3050 if (this.userName.indexOf('@') >= 0) {
3051 return null;
3052 }
3053 String result = this.userName;
3054
3055 int index = Math.max(result.indexOf('\\'), result.indexOf('/'));
3056 if (index >= 0) {
3057 result = result.substring(index + 1);
3058 }
3059 return result;
3060 }
3061
3062
3063
3064
3065
3066
3067
3068 public abstract boolean isSharedFolder(String folderPath);
3069
3070
3071
3072
3073
3074
3075
3076 public abstract boolean isMainCalendar(String folderPath) throws IOException;
3077
3078 protected static final String MAILBOX_BASE = "/cn=";
3079
3080
3081
3082
3083
3084
3085 public String getEmail() {
3086 return email;
3087 }
3088
3089
3090
3091
3092
3093
3094 protected abstract String getCalendarEmail(String folderPath) throws IOException;
3095
3096
3097
3098
3099
3100
3101 public String getAlias() {
3102 return alias;
3103 }
3104
3105
3106
3107
3108
3109
3110
3111 public boolean supportsPeopleSearch() {
3112 return false;
3113 }
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124 public abstract Map<String, Contact> galFind(Condition condition, Set<String> returningAttributes, int sizeLimit) throws IOException;
3125
3126
3127
3128
3129 public static final Set<String> CONTACT_ATTRIBUTES = new HashSet<>();
3130
3131 static {
3132 CONTACT_ATTRIBUTES.add("uid");
3133 CONTACT_ATTRIBUTES.add("imapUid");
3134 CONTACT_ATTRIBUTES.add("etag");
3135 CONTACT_ATTRIBUTES.add("urlcompname");
3136
3137 CONTACT_ATTRIBUTES.add("extensionattribute1");
3138 CONTACT_ATTRIBUTES.add("extensionattribute2");
3139 CONTACT_ATTRIBUTES.add("extensionattribute3");
3140 CONTACT_ATTRIBUTES.add("extensionattribute4");
3141 CONTACT_ATTRIBUTES.add("bday");
3142 CONTACT_ATTRIBUTES.add("anniversary");
3143 CONTACT_ATTRIBUTES.add("businesshomepage");
3144 CONTACT_ATTRIBUTES.add("personalHomePage");
3145 CONTACT_ATTRIBUTES.add("cn");
3146 CONTACT_ATTRIBUTES.add("co");
3147 CONTACT_ATTRIBUTES.add("department");
3148 CONTACT_ATTRIBUTES.add("smtpemail1");
3149 CONTACT_ATTRIBUTES.add("smtpemail2");
3150 CONTACT_ATTRIBUTES.add("smtpemail3");
3151 CONTACT_ATTRIBUTES.add("facsimiletelephonenumber");
3152 CONTACT_ATTRIBUTES.add("givenName");
3153 CONTACT_ATTRIBUTES.add("internationalisdnnumber");
3154 CONTACT_ATTRIBUTES.add("homeCity");
3155 CONTACT_ATTRIBUTES.add("homeCountry");
3156 CONTACT_ATTRIBUTES.add("homefax");
3157 CONTACT_ATTRIBUTES.add("homePhone");
3158 CONTACT_ATTRIBUTES.add("homePostalCode");
3159 CONTACT_ATTRIBUTES.add("homeState");
3160 CONTACT_ATTRIBUTES.add("homeStreet");
3161 CONTACT_ATTRIBUTES.add("homepostofficebox");
3162 CONTACT_ATTRIBUTES.add("l");
3163 CONTACT_ATTRIBUTES.add("manager");
3164 CONTACT_ATTRIBUTES.add("mobile");
3165 CONTACT_ATTRIBUTES.add("namesuffix");
3166 CONTACT_ATTRIBUTES.add("nickname");
3167 CONTACT_ATTRIBUTES.add("o");
3168 CONTACT_ATTRIBUTES.add("pager");
3169 CONTACT_ATTRIBUTES.add("personaltitle");
3170 CONTACT_ATTRIBUTES.add("postalcode");
3171 CONTACT_ATTRIBUTES.add("postofficebox");
3172 CONTACT_ATTRIBUTES.add("profession");
3173 CONTACT_ATTRIBUTES.add("roomnumber");
3174 CONTACT_ATTRIBUTES.add("secretarycn");
3175 CONTACT_ATTRIBUTES.add("sn");
3176 CONTACT_ATTRIBUTES.add("spousecn");
3177 CONTACT_ATTRIBUTES.add("st");
3178 CONTACT_ATTRIBUTES.add("street");
3179 CONTACT_ATTRIBUTES.add("telephoneNumber");
3180 CONTACT_ATTRIBUTES.add("title");
3181 CONTACT_ATTRIBUTES.add("description");
3182 CONTACT_ATTRIBUTES.add("personalNotes");
3183 CONTACT_ATTRIBUTES.add("im");
3184 CONTACT_ATTRIBUTES.add("middlename");
3185 CONTACT_ATTRIBUTES.add("lastmodified");
3186 CONTACT_ATTRIBUTES.add("otherstreet");
3187 CONTACT_ATTRIBUTES.add("otherstate");
3188 CONTACT_ATTRIBUTES.add("otherpostofficebox");
3189 CONTACT_ATTRIBUTES.add("otherpostalcode");
3190 CONTACT_ATTRIBUTES.add("othercountry");
3191 CONTACT_ATTRIBUTES.add("othercity");
3192 CONTACT_ATTRIBUTES.add("haspicture");
3193 CONTACT_ATTRIBUTES.add("keywords");
3194 CONTACT_ATTRIBUTES.add("othermobile");
3195 CONTACT_ATTRIBUTES.add("otherBusinessTelephoneNumber");
3196 CONTACT_ATTRIBUTES.add("otherHomePhone");
3197 CONTACT_ATTRIBUTES.add("otherTelephone");
3198 CONTACT_ATTRIBUTES.add("gender");
3199 CONTACT_ATTRIBUTES.add("private");
3200 CONTACT_ATTRIBUTES.add("sensitivity");
3201 CONTACT_ATTRIBUTES.add("fburl");
3202 CONTACT_ATTRIBUTES.add("msexchangecertificate");
3203 CONTACT_ATTRIBUTES.add("usersmimecertificate");
3204 }
3205
3206 protected static final Set<String> DISTRIBUTION_LIST_ATTRIBUTES = new HashSet<>();
3207
3208 static {
3209 DISTRIBUTION_LIST_ATTRIBUTES.add("imapUid");
3210 DISTRIBUTION_LIST_ATTRIBUTES.add("etag");
3211 DISTRIBUTION_LIST_ATTRIBUTES.add("urlcompname");
3212
3213 DISTRIBUTION_LIST_ATTRIBUTES.add("cn");
3214 DISTRIBUTION_LIST_ATTRIBUTES.add("members");
3215 }
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227 protected abstract String getFreeBusyData(String attendee, String start, String end, int interval) throws IOException;
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238 public FreeBusy getFreebusy(String attendee, String startDateValue, String endDateValue) throws IOException {
3239
3240 attendee = VCalendar.replaceIcal4Principal(attendee);
3241
3242
3243 if (attendee == null || attendee.indexOf('@') < 0 || attendee.charAt(attendee.length() - 1) == '@') {
3244 return null;
3245 }
3246
3247 if (attendee.startsWith("mailto:") || attendee.startsWith("MAILTO:")) {
3248 attendee = attendee.substring("mailto:".length());
3249 }
3250
3251 SimpleDateFormat exchangeZuluDateFormat = getExchangeZuluDateFormat();
3252 SimpleDateFormat icalDateFormat = getZuluDateFormat();
3253
3254 Date startDate;
3255 Date endDate;
3256 try {
3257 if (startDateValue.length() == 8) {
3258 startDate = parseDate(startDateValue);
3259 } else {
3260 startDate = icalDateFormat.parse(startDateValue);
3261 }
3262 if (endDateValue.length() == 8) {
3263 endDate = parseDate(endDateValue);
3264 } else {
3265 endDate = icalDateFormat.parse(endDateValue);
3266 }
3267 } catch (ParseException e) {
3268 throw new DavMailException("EXCEPTION_INVALID_DATES", e.getMessage());
3269 }
3270
3271 FreeBusy freeBusy = null;
3272 String fbdata = getFreeBusyData(attendee, exchangeZuluDateFormat.format(startDate), exchangeZuluDateFormat.format(endDate), FREE_BUSY_INTERVAL);
3273 if (fbdata != null) {
3274 freeBusy = new FreeBusy(icalDateFormat, startDate, fbdata);
3275 }
3276
3277 if (freeBusy != null && freeBusy.knownAttendee) {
3278 return freeBusy;
3279 } else {
3280 return null;
3281 }
3282 }
3283
3284
3285
3286
3287
3288 public static final class FreeBusy {
3289 final SimpleDateFormat icalParser;
3290 boolean knownAttendee = true;
3291 static final HashMap<Character, String> FBTYPES = new HashMap<>();
3292
3293 static {
3294 FBTYPES.put('1', "BUSY-TENTATIVE");
3295 FBTYPES.put('2', "BUSY");
3296 FBTYPES.put('3', "BUSY-UNAVAILABLE");
3297 }
3298
3299 final HashMap<String, StringBuilder> busyMap = new HashMap<>();
3300
3301 StringBuilder getBusyBuffer(char type) {
3302 String fbType = FBTYPES.get(type);
3303 return busyMap.computeIfAbsent(fbType, k -> new StringBuilder());
3304 }
3305
3306 void startBusy(char type, Calendar currentCal) {
3307 if (type == '4') {
3308 knownAttendee = false;
3309 } else if (type != '0') {
3310 StringBuilder busyBuffer = getBusyBuffer(type);
3311 if (busyBuffer.length() > 0) {
3312 busyBuffer.append(',');
3313 }
3314 busyBuffer.append(icalParser.format(currentCal.getTime()));
3315 }
3316 }
3317
3318 void endBusy(char type, Calendar currentCal) {
3319 if (type != '0' && type != '4') {
3320 getBusyBuffer(type).append('/').append(icalParser.format(currentCal.getTime()));
3321 }
3322 }
3323
3324 FreeBusy(SimpleDateFormat icalParser, Date startDate, String fbdata) {
3325 this.icalParser = icalParser;
3326 if (!fbdata.isEmpty()) {
3327 Calendar currentCal = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
3328 currentCal.setTime(startDate);
3329
3330 startBusy(fbdata.charAt(0), currentCal);
3331 for (int i = 1; i < fbdata.length() && knownAttendee; i++) {
3332 currentCal.add(Calendar.MINUTE, FREE_BUSY_INTERVAL);
3333 char previousState = fbdata.charAt(i - 1);
3334 char currentState = fbdata.charAt(i);
3335 if (previousState != currentState) {
3336 endBusy(previousState, currentCal);
3337 startBusy(currentState, currentCal);
3338 }
3339 }
3340 currentCal.add(Calendar.MINUTE, FREE_BUSY_INTERVAL);
3341 endBusy(fbdata.charAt(fbdata.length() - 1), currentCal);
3342 }
3343 }
3344
3345
3346
3347
3348
3349
3350 public void appendTo(StringBuilder buffer) {
3351 for (Map.Entry<String, StringBuilder> entry : busyMap.entrySet()) {
3352 buffer.append("FREEBUSY;FBTYPE=").append(entry.getKey())
3353 .append(':').append(entry.getValue()).append((char) 13).append((char) 10);
3354 }
3355 }
3356 }
3357
3358 protected VObject vTimezone;
3359
3360
3361
3362
3363
3364
3365 public VObject getVTimezone() {
3366 if (vTimezone == null) {
3367
3368 loadVtimezone();
3369 }
3370 return vTimezone;
3371 }
3372
3373 public String getTimezoneId() {
3374 return getVTimezone().getPropertyValue("TZID");
3375 }
3376
3377 public void clearVTimezone() {
3378 vTimezone = null;
3379 }
3380
3381 protected abstract void loadVtimezone();
3382
3383 protected static final Map<String, String> importanceToPriorityMap = new HashMap<>();
3384
3385 static {
3386 importanceToPriorityMap.put("High", "1");
3387 importanceToPriorityMap.put("Normal", "5");
3388 importanceToPriorityMap.put("Low", "9");
3389 }
3390
3391 protected static final Map<String, String> priorityToImportanceMap = new HashMap<>();
3392
3393 static {
3394
3395 priorityToImportanceMap.put("0", "Normal");
3396
3397 priorityToImportanceMap.put("1", "High");
3398 priorityToImportanceMap.put("2", "High");
3399 priorityToImportanceMap.put("3", "High");
3400 priorityToImportanceMap.put("4", "Normal");
3401 priorityToImportanceMap.put("5", "Normal");
3402 priorityToImportanceMap.put("6", "Normal");
3403 priorityToImportanceMap.put("7", "Low");
3404 priorityToImportanceMap.put("8", "Low");
3405 priorityToImportanceMap.put("9", "Low");
3406 }
3407
3408 protected String convertPriorityFromExchange(String exchangeImportanceValue) {
3409 String value = null;
3410 if (exchangeImportanceValue != null) {
3411 value = importanceToPriorityMap.get(exchangeImportanceValue);
3412 }
3413 return value;
3414 }
3415
3416 protected String convertPriorityToExchange(String vTodoPriorityValue) {
3417 String value = null;
3418 if (vTodoPriorityValue != null) {
3419 value = priorityToImportanceMap.get(vTodoPriorityValue);
3420 }
3421 return value;
3422 }
3423
3424
3425
3426
3427
3428
3429 protected String convertClassFromExchange(String sensitivity) {
3430 String eventClass;
3431 if ("private".equals(sensitivity)) {
3432 eventClass = "PRIVATE";
3433 } else if ("confidential".equals(sensitivity)) {
3434 eventClass = "CONFIDENTIAL";
3435 } else if ("personal".equals(sensitivity)) {
3436 eventClass = "PRIVATE";
3437 } else {
3438
3439 eventClass = "PUBLIC";
3440 }
3441 return eventClass;
3442 }
3443
3444 }