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.DavMailAuthenticationException;
24 import davmail.exception.DavMailException;
25 import davmail.exception.WebdavNotAvailableException;
26 import davmail.exchange.auth.ExchangeAuthenticator;
27 import davmail.exchange.auth.ExchangeFormAuthenticator;
28 import davmail.exchange.dav.DavExchangeSession;
29 import davmail.exchange.ews.EwsExchangeSession;
30 import davmail.exchange.graph.GraphExchangeSession;
31 import davmail.http.HttpClientAdapter;
32 import davmail.http.request.GetRequest;
33 import org.apache.http.HttpStatus;
34 import org.apache.http.client.methods.CloseableHttpResponse;
35
36 import java.awt.*;
37 import java.io.IOException;
38 import java.io.InterruptedIOException;
39 import java.net.NetworkInterface;
40 import java.net.SocketException;
41 import java.net.UnknownHostException;
42 import java.util.ArrayList;
43 import java.util.Enumeration;
44 import java.util.HashMap;
45 import java.util.List;
46 import java.util.Map;
47 import java.util.Objects;
48 import java.util.concurrent.CompletableFuture;
49 import java.util.concurrent.ExecutionException;
50
51
52
53
54 public final class ExchangeSessionFactory {
55
56
57
58
59 private static final Object CREATION_LOCK = new Object();
60
61
62
63 private static final Map<PoolKey, ExchangeSession> POOL_MAP = new HashMap<>();
64
65
66
67
68 private static int shutdownGeneration;
69
70
71
72 private static final Map<PoolKey, CompletableFuture<ExchangeSession>> SESSION_CREATORS = new HashMap<>();
73 private static volatile boolean configChecked;
74 private static volatile boolean errorSent;
75
76 static class PoolKey {
77 final String url;
78 final String userName;
79 final String password;
80
81 PoolKey(String url, String userName, String password) {
82 this.url = url;
83 this.userName = convertUserName(userName);
84 this.password = password;
85 }
86
87 @Override
88 public boolean equals(Object object) {
89 return object == this ||
90 object instanceof PoolKey &&
91 ((PoolKey) object).url.equals(this.url) &&
92 ((PoolKey) object).userName.equals(this.userName) &&
93 ((PoolKey) object).password.equals(this.password);
94 }
95
96 @Override
97 public int hashCode() {
98 return Objects.hash(url, userName, password);
99 }
100 }
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116 static ExchangeSession singleFlightGetOrCreateSession(PoolKey key, String sessionMode) throws Exception {
117 CompletableFuture<ExchangeSession> future;
118 boolean owner = false;
119
120 synchronized (SESSION_CREATORS) {
121 future = SESSION_CREATORS.get(key);
122 if (future == null) {
123 future = new CompletableFuture<>();
124 SESSION_CREATORS.put(key, future);
125 owner = true;
126 }
127 }
128
129 if (owner) {
130 ExchangeSession session;
131 try {
132 session = getOrCreateSession(key, sessionMode);
133 } catch (Throwable t) {
134
135 removeSessionCreator(key);
136 future.completeExceptionally(t);
137 throw t;
138 }
139 removeSessionCreator(key);
140 future.complete(session);
141 return session;
142 }
143
144 try {
145 return future.get();
146 } catch (InterruptedException e) {
147 Thread.currentThread().interrupt();
148 throw new InterruptedIOException("Interrupted waiting for concurrent session creation");
149 } catch (ExecutionException e) {
150 Throwable cause = e.getCause();
151 if (cause instanceof Exception) {
152 throw (Exception) cause;
153 }
154
155 throw new IllegalStateException("Concurrent session creation failed", cause);
156 }
157 }
158
159 private static void removeSessionCreator(PoolKey key) {
160 synchronized (SESSION_CREATORS) {
161 SESSION_CREATORS.remove(key);
162 }
163 }
164
165 private ExchangeSessionFactory() {
166 }
167
168
169
170
171
172
173
174
175
176 public static ExchangeSession getInstance(String userName, String password) throws IOException {
177 String baseUrl = Settings.getProperty("davmail.url", Settings.getO365Url());
178 return getInstance(baseUrl, userName, password);
179 }
180
181
182
183
184
185
186
187
188
189
190
191 private static PoolKey buildPoolKey(String mode, String baseUrl, String userName, String password) {
192 if (Settings.O365.equals(mode)) {
193
194 baseUrl = Settings.getO365Url();
195 }
196 return new PoolKey(baseUrl, userName, password);
197 }
198
199 private static String convertUserName(String userName) {
200 String result = userName;
201
202 String defaultDomain = Settings.getProperty("davmail.defaultDomain");
203 if (defaultDomain != null && userName.indexOf('\\') < 0 && userName.indexOf('@') < 0) {
204 result = defaultDomain + '\\' + userName;
205 }
206 return result;
207 }
208
209
210
211
212
213
214
215
216
217
218 public static ExchangeSession getInstance(String baseUrl, String userName, String password) throws IOException {
219 ExchangeSession session = null;
220 try {
221 String mode = Settings.getProperty("davmail.mode");
222 PoolKey poolKey = buildPoolKey(mode, baseUrl, userName, password);
223
224 synchronized (POOL_MAP) {
225 session = POOL_MAP.get(poolKey);
226 }
227 if (session != null) {
228 ExchangeSession.LOGGER.debug("Got session " + session + " from cache");
229 }
230
231 if (session != null && session.isExpired()) {
232 ExchangeSession.LOGGER.debug("Session " + session + " for user " + session.userName + " expired");
233
234
235 boolean removed;
236 synchronized (POOL_MAP) {
237 removed = POOL_MAP.remove(poolKey, session);
238 }
239 if (removed) {
240 session.close();
241 }
242 session = null;
243 }
244
245 if (session == null) {
246
247
248
249 session = singleFlightGetOrCreateSession(poolKey, mode);
250 }
251
252 configChecked = true;
253
254 errorSent = false;
255 } catch (DavMailException | InterruptedIOException | IllegalStateException | NullPointerException exc) {
256
257 throw exc;
258 } catch (Exception exc) {
259 handleNetworkDown(exc);
260 }
261 return session;
262 }
263
264
265
266
267
268
269
270
271
272
273
274 private static ExchangeSession getOrCreateSession(PoolKey poolKey, String mode) throws Exception {
275 int startGeneration;
276 synchronized (POOL_MAP) {
277 ExchangeSession cached = POOL_MAP.get(poolKey);
278 if (cached != null) {
279 return cached;
280 }
281 startGeneration = shutdownGeneration;
282 }
283
284 ExchangeSession session;
285 try {
286 if (Settings.getBooleanProperty("davmail.server")) {
287 session = createSession(poolKey, mode);
288 } else {
289
290 synchronized (CREATION_LOCK) {
291 session = createSession(poolKey, mode);
292 }
293 }
294 } catch (DavMailAuthenticationException e) {
295 if (hasSessionWithDifferentPassword(poolKey)) {
296 ExchangeSession.LOGGER.warn("Authentication failed for user " + poolKey.userName
297 + ", but a session exists for this user with a different password: "
298 + "a client may be configured with an outdated password");
299 }
300 throw e;
301 }
302
303
304 boolean published = false;
305 boolean otherPassword = false;
306 synchronized (POOL_MAP) {
307 if (shutdownGeneration == startGeneration) {
308 otherPassword = hasSessionWithDifferentPassword(poolKey);
309 POOL_MAP.put(poolKey, session);
310 published = true;
311 }
312 }
313 if (published) {
314 if (otherPassword) {
315 ExchangeSession.LOGGER.warn("User " + poolKey.userName + " authenticated with a password different "
316 + "from the one of an existing session: the password may have been changed, "
317 + "check that all clients use the new password");
318 }
319 return session;
320 }
321 session.close();
322 throw new InterruptedIOException("Session creation cancelled by shutdown");
323 }
324
325
326
327
328
329
330
331
332 private static boolean hasSessionWithDifferentPassword(PoolKey poolKey) {
333 synchronized (POOL_MAP) {
334 for (PoolKey other : POOL_MAP.keySet()) {
335 if (other.url.equals(poolKey.url) && other.userName.equals(poolKey.userName)
336 && !other.password.equals(poolKey.password)) {
337 return true;
338 }
339 }
340 }
341 return false;
342 }
343
344
345
346
347
348
349
350
351
352 private static ExchangeSession createSession(PoolKey poolKey, String mode) throws Exception {
353 ExchangeSession session;
354
355 if (mode == null) {
356 if ("false".equals(Settings.getProperty("davmail.enableEws"))) {
357 mode = Settings.WEBDAV;
358 } else {
359 mode = Settings.EWS;
360 }
361 }
362
363 String authenticatorClass = Settings.getProperty("davmail.authenticator");
364 if (authenticatorClass == null && mode.startsWith("O365")) {
365
366 String authentication = Settings.getProperty("davmail.authentication");
367 authenticatorClass = getAuthenticatorClass(authentication);
368 if (authenticatorClass == null) {
369
370 authenticatorClass = getAuthenticatorClass(mode);
371 }
372 }
373
374 if (authenticatorClass != null) {
375 ExchangeAuthenticator authenticator = (ExchangeAuthenticator) Class.forName(authenticatorClass)
376 .getDeclaredConstructor().newInstance();
377 authenticator.setUsername(poolKey.userName);
378 authenticator.setPassword(poolKey.password);
379 authenticator.authenticate();
380
381 if (Settings.isGraphEnabled()) {
382 session = new GraphExchangeSession(authenticator.getHttpClientAdapter(), authenticator.getToken(), poolKey.userName);
383 } else {
384 session = new EwsExchangeSession(authenticator.getExchangeUri(), authenticator.getToken(), poolKey.userName);
385 }
386
387 } else if (
388
389 Settings.EXCHANGE_EWS.equals(mode)
390
391 || Settings.EWS.equals(mode) || Settings.O365.equals(mode)
392
393 || poolKey.url.toLowerCase().endsWith("/ews/exchange.asmx")
394 || poolKey.url.toLowerCase().endsWith("/ews/services.wsdl")) {
395 if (poolKey.url.toLowerCase().endsWith("/ews/exchange.asmx")
396 || poolKey.url.toLowerCase().endsWith("/ews/services.wsdl")) {
397 ExchangeSession.LOGGER.debug("Direct EWS authentication");
398 session = new EwsExchangeSession(poolKey.url, poolKey.userName, poolKey.password);
399 } else {
400 ExchangeSession.LOGGER.debug("OWA authentication in EWS mode");
401 ExchangeFormAuthenticator exchangeFormAuthenticator = new ExchangeFormAuthenticator();
402 exchangeFormAuthenticator.setUrl(poolKey.url);
403 exchangeFormAuthenticator.setUsername(poolKey.userName);
404 exchangeFormAuthenticator.setPassword(poolKey.password);
405 exchangeFormAuthenticator.authenticate();
406 session = new EwsExchangeSession(exchangeFormAuthenticator.getHttpClientAdapter(),
407 exchangeFormAuthenticator.getExchangeUri(), exchangeFormAuthenticator.getUsername());
408 }
409 } else {
410
411 ExchangeFormAuthenticator exchangeFormAuthenticator = new ExchangeFormAuthenticator();
412 exchangeFormAuthenticator.setUrl(poolKey.url);
413 exchangeFormAuthenticator.setUsername(poolKey.userName);
414 exchangeFormAuthenticator.setPassword(poolKey.password);
415 exchangeFormAuthenticator.authenticate();
416 try {
417 session = new DavExchangeSession(exchangeFormAuthenticator.getHttpClientAdapter(),
418 exchangeFormAuthenticator.getExchangeUri(),
419 exchangeFormAuthenticator.getUsername());
420 } catch (WebdavNotAvailableException e) {
421 if (Settings.AUTO.equals(mode)) {
422 ExchangeSession.LOGGER.debug(e.getMessage() + ", retry with EWS");
423 session = new EwsExchangeSession(poolKey.url, poolKey.userName, poolKey.password);
424 } else {
425 throw e;
426 }
427 }
428 }
429 try {
430 checkWhiteList(session.getEmail());
431 } catch (Throwable t) {
432
433 session.close();
434 throw t;
435 }
436 ExchangeSession.LOGGER.debug("Created new session " + session + " for user " + poolKey.userName);
437 return session;
438 }
439
440 private static String getAuthenticatorClass(String authentication) throws DavMailException {
441 String authenticatorClass = null;
442 if (authentication != null) {
443 switch (authentication) {
444 case Settings.O365_INTERACTIVE:
445 authenticatorClass = "davmail.exchange.auth.O365InteractiveAuthenticator";
446 if (GraphicsEnvironment.isHeadless()) {
447 throw new DavMailException("EXCEPTION_DAVMAIL_CONFIGURATION", "O365Interactive not supported in headless mode");
448 }
449 break;
450 case Settings.O365_MANUAL:
451 authenticatorClass = "davmail.exchange.auth.O365ManualAuthenticator";
452 break;
453 case Settings.O365_DEVICECODE:
454 authenticatorClass = "davmail.exchange.auth.O365DeviceCodeAuthenticator";
455 break;
456 case Settings.O365_TRANSPARENT:
457 case Settings.O365_MODERN:
458 authenticatorClass = "davmail.exchange.auth.O365Authenticator";
459 break;
460 }
461 }
462 return authenticatorClass;
463 }
464
465
466
467
468
469
470
471
472 private static void checkWhiteList(String email) throws DavMailAuthenticationException {
473 String whiteListString = Settings.getProperty("davmail.userWhiteList");
474 if (whiteListString != null && !whiteListString.isEmpty()) {
475 for (String whiteListValue : whiteListString.split(",")) {
476 if (whiteListValue.startsWith("@") && email.endsWith(whiteListValue)) {
477 return;
478 } else if (email.equalsIgnoreCase(whiteListValue)) {
479 return;
480 }
481 }
482 ExchangeSession.LOGGER.warn(email + " not allowed by whitelist");
483 throw new DavMailAuthenticationException("EXCEPTION_AUTHENTICATION_FAILED");
484 }
485 }
486
487
488
489
490
491
492
493
494
495
496
497 public static ExchangeSession getInstance(ExchangeSession currentSession, String userName, String password)
498 throws IOException {
499 ExchangeSession session = currentSession;
500 try {
501 if (session.isExpired()) {
502 ExchangeSession.LOGGER.debug("Session " + session + " expired, trying to open a new one");
503 session = null;
504 String baseUrl = Settings.getProperty("davmail.url", Settings.getO365Url());
505 PoolKey poolKey = buildPoolKey(Settings.getProperty("davmail.mode"), baseUrl, userName, password);
506
507 synchronized (POOL_MAP) {
508 POOL_MAP.remove(poolKey, currentSession);
509 }
510 session = getInstance(userName, password);
511 }
512 } catch (DavMailAuthenticationException exc) {
513 ExchangeSession.LOGGER.debug("Unable to reopen session", exc);
514 throw exc;
515 } catch (Exception exc) {
516 ExchangeSession.LOGGER.debug("Unable to reopen session", exc);
517 handleNetworkDown(exc);
518 }
519 return session;
520 }
521
522
523
524
525
526
527 public static void checkConfig() throws IOException {
528 String url;
529 if (Settings.isGraphEnabled()) {
530
531 url = Settings.getGraphUrl();
532 } else {
533 url = Settings.getProperty("davmail.url", Settings.getO365Url());
534 }
535 if (url == null || (!url.startsWith("http://") && !url.startsWith("https://"))) {
536 throw new DavMailException("LOG_INVALID_URL", url);
537 }
538 try (
539 HttpClientAdapter httpClientAdapter = new HttpClientAdapter(url);
540 CloseableHttpResponse response = httpClientAdapter.execute(new GetRequest(url))
541 ) {
542
543 int status = response.getStatusLine().getStatusCode();
544 ExchangeSession.LOGGER.debug("Test configuration status: " + status);
545 if (status != HttpStatus.SC_OK && status != HttpStatus.SC_UNAUTHORIZED
546 && !HttpClientAdapter.isRedirect(status)) {
547 throw new DavMailException("EXCEPTION_CONNECTION_FAILED", url, status);
548 }
549
550 configChecked = true;
551
552 errorSent = false;
553 } catch (Exception exc) {
554 handleNetworkDown(exc);
555 }
556
557 }
558
559 private static void handleNetworkDown(Exception exc) throws DavMailException {
560 if (!checkNetwork() || configChecked) {
561 ExchangeSession.LOGGER.warn(BundleMessage.formatLog("EXCEPTION_NETWORK_DOWN"));
562
563 if (!((exc instanceof UnknownHostException) || (exc instanceof NetworkDownException))) {
564 ExchangeSession.LOGGER.debug(exc, exc);
565 }
566 throw new NetworkDownException("EXCEPTION_NETWORK_DOWN");
567 } else {
568 BundleMessage message = new BundleMessage("EXCEPTION_CONNECT", exc.getClass().getName(), exc.getMessage());
569 if (errorSent) {
570 ExchangeSession.LOGGER.warn(message);
571 throw new NetworkDownException("EXCEPTION_DAVMAIL_CONFIGURATION", message);
572 } else {
573
574
575 errorSent = true;
576 ExchangeSession.LOGGER.error(message);
577 throw new DavMailException("EXCEPTION_DAVMAIL_CONFIGURATION", message);
578 }
579 }
580 }
581
582
583
584
585
586
587
588 public static String getUserPassword(String userName) {
589 String fullUserName = convertUserName(userName);
590 synchronized (POOL_MAP) {
591 for (PoolKey poolKey : POOL_MAP.keySet()) {
592 if (poolKey.userName.equals(fullUserName)) {
593 return poolKey.password;
594 }
595 }
596 }
597 return null;
598 }
599
600
601
602
603
604
605 static boolean checkNetwork() {
606 boolean up = false;
607 Enumeration<NetworkInterface> enumeration;
608 try {
609 enumeration = NetworkInterface.getNetworkInterfaces();
610 while (!up && enumeration.hasMoreElements()) {
611 NetworkInterface networkInterface = enumeration.nextElement();
612 up = networkInterface.isUp() && !networkInterface.isLoopback()
613 && networkInterface.getInetAddresses().hasMoreElements();
614 if (up) {
615 ExchangeSession.LOGGER.debug(networkInterface.getDisplayName() + " is up");
616 }
617 }
618 } catch (SocketException exc) {
619 ExchangeSession.LOGGER.error("DavMail configuration exception: \n Error listing network interfaces " + exc.getMessage(), exc);
620 }
621 return up;
622 }
623
624
625
626
627
628 public static void shutdown() {
629 configChecked = false;
630 errorSent = false;
631 List<ExchangeSession> sessions;
632 synchronized (POOL_MAP) {
633 shutdownGeneration++;
634 sessions = new ArrayList<>(POOL_MAP.values());
635 POOL_MAP.clear();
636 }
637
638 for (ExchangeSession session : sessions) {
639 session.close();
640 }
641 }
642 }