View Javadoc
1   /*
2    * DavMail POP/IMAP/SMTP/CalDav/LDAP Exchange Gateway
3    * Copyright (C) 2009  Mickael Guessant
4    *
5    * This program is free software; you can redistribute it and/or
6    * modify it under the terms of the GNU General Public License
7    * as published by the Free Software Foundation; either version 2
8    * of the License, or (at your option) any later version.
9    *
10   * This program is distributed in the hope that it will be useful,
11   * but WITHOUT ANY WARRANTY; without even the implied warranty of
12   * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13   * GNU General Public License for more details.
14   *
15   * You should have received a copy of the GNU General Public License
16   * along with this program; if not, write to the Free Software
17   * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
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   * Create ExchangeSession instances.
53   */
54  public final class ExchangeSessionFactory {
55      /**
56       * Serialize session creation for different users in workstation mode, to avoid multiple concurrent
57       * interactive authentications. Not held while accessing the session pool.
58       */
59      private static final Object CREATION_LOCK = new Object();
60      /**
61       * Session pool. Guarded by itself.
62       */
63      private static final Map<PoolKey, ExchangeSession> POOL_MAP = new HashMap<>();
64      /**
65       * Incremented by shutdown, to detect session creations started before a shutdown.
66       * Guarded by POOL_MAP.
67       */
68      private static int shutdownGeneration;
69      /**
70       * Session creations in progress, by key. Guarded by itself.
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      * Run at most one session creation at a time for a given key, and share its result with concurrent callers.
104      * <p>
105      * With an interactive authentication (device code, valid for several minutes), concurrent connections
106      * for the same user must wait for one authentication instead of each starting their own.
107      * If the creation fails, callers that were waiting get the same failure instead of each retrying in turn.
108      * Results are not cached here: a call made after completion starts a new creation (the session pool
109      * is checked first, see {@link #getOrCreateSession}).
110      *
111      * @param key         session key
112      * @param sessionMode configured davmail.mode, may be null
113      * @return created session
114      * @throws Exception on creation failure, or InterruptedIOException if interrupted while waiting
115      */
116     static ExchangeSession singleFlightGetOrCreateSession(PoolKey key, String sessionMode) throws Exception {
117         CompletableFuture<ExchangeSession> future;
118         boolean owner = false;
119         // create a future if no session creation in progress
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                 // unregister before completing, so a later caller starts a new creation instead of joining a failed one
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             // owner failed with an Error
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      * Create authenticated Exchange session
170      *
171      * @param userName user login
172      * @param password user password
173      * @return authenticated session
174      * @throws IOException on error
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      * Build the session pool key, the same way for every lookup.
183      * In O365 mode the URL is forced, whatever the caller or davmail.url say.
184      *
185      * @param mode     configured davmail.mode, may be null
186      * @param baseUrl  OWA base URL
187      * @param userName user login
188      * @param password user password
189      * @return pool key
190      */
191     private static PoolKey buildPoolKey(String mode, String baseUrl, String userName, String password) {
192         if (Settings.O365.equals(mode)) {
193             // force url with O365
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         // prepend default windows domain prefix
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      * Create authenticated Exchange session
211      *
212      * @param baseUrl  OWA base URL
213      * @param userName user login
214      * @param password user password
215      * @return authenticated session
216      * @throws IOException on error
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                 // only the thread that actually removes the expired session closes it: another thread may already
234                 // have replaced it with a new session, which must stay in the pool
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                 // one session creation at a time for a given user: concurrent connections wait for the
247                 // same authentication (device code can take minutes) instead of each starting their own.
248                 // The created session is published to the pool by getOrCreateSession.
249                 session = singleFlightGetOrCreateSession(poolKey, mode);
250             }
251             // session opened; future failure will mean network down
252             configChecked = true;
253             // Reset so next time a problem occurs message is sent once
254             errorSent = false;
255         } catch (DavMailException | InterruptedIOException | IllegalStateException | NullPointerException exc) {
256             // not a network problem: no network down handling for a cancelled wait
257             throw exc;
258         } catch (Exception exc) {
259             handleNetworkDown(exc);
260         }
261         return session;
262     }
263 
264     /**
265      * Get session from pool or create it, runs as the single session creation for this user.
266      * Pool is checked again: a previous creation for the same user may have completed
267      * after the caller checked the pool.
268      *
269      * @param poolKey session key
270      * @param mode    configured davmail.mode, may be null
271      * @return session
272      * @throws Exception on error
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                 // serialize session creation in workstation mode to avoid multiple OTP requests
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         // publish before ending this creation, so a new caller can not start a duplicate one,
303         // unless shutdown was called during the creation: the session must not outlive the shutdown
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      * Check if the pool holds a session for the same URL and user, authenticated with another password.
327      * Passwords are only compared, never logged.
328      *
329      * @param poolKey session key
330      * @return true if a session with a different password exists
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      * Create a new session, called by at most one thread at a time for a given user.
346      *
347      * @param poolKey session key
348      * @param mode    configured davmail.mode, may be null
349      * @return new authenticated session
350      * @throws Exception on error
351      */
352     private static ExchangeSession createSession(PoolKey poolKey, String mode) throws Exception {
353         ExchangeSession session;
354         // convert old setting
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         // check for overridden authenticator
363         String authenticatorClass = Settings.getProperty("davmail.authenticator");
364         if (authenticatorClass == null && mode.startsWith("O365")) {
365             // set authenticator class based on authentication mode
366             String authentication = Settings.getProperty("davmail.authentication");
367             authenticatorClass = getAuthenticatorClass(authentication);
368             if (authenticatorClass == null) {
369                 // fallback to legacy modes
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             // new mode
389                 Settings.EXCHANGE_EWS.equals(mode)
390                         // legacy
391                         || Settings.EWS.equals(mode) || Settings.O365.equals(mode)
392                         // direct EWS even if mode is different
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             // Legacy Exchange 2003 WebDav mode
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             // do not leak a session that will never be published to the pool
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      * Check if whitelist is empty or email is allowed.
467      * userWhiteList is a comma-separated list of values.
468      * \@company.com means all domain users are allowed
469      *
470      * @param email user email
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      * Get a non-expired session.
489      * If the current session is not expired, return current session, else try to create a new session
490      *
491      * @param currentSession current session
492      * @param userName       user login
493      * @param password       user password
494      * @return authenticated session
495      * @throws IOException on error
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                 // expired session, remove from cache unless already replaced by another thread
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      * Send a request to Exchange server to check current settings.
524      *
525      * @throws IOException if unable to access Exchange server
526      */
527     public static void checkConfig() throws IOException {
528         String url;
529         if (Settings.isGraphEnabled()) {
530             // In Graph mode, check the Graph endpoint instead of the legacy EWS endpoint
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             // get webMail root url (will not follow redirects)
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             // session opened; future failure will mean network down
550             configChecked = true;
551             // Reset so next time a problem occurs message is sent once
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             // log full stack trace for unknown errors
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                 // Mark that an error has been sent so you only get one
574                 // error in a row (not a repeating string of errors).
575                 errorSent = true;
576                 ExchangeSession.LOGGER.error(message);
577                 throw new DavMailException("EXCEPTION_DAVMAIL_CONFIGURATION", message);
578             }
579         }
580     }
581 
582     /**
583      * Get user password from session pool for SASL authentication
584      *
585      * @param userName Exchange username
586      * @return user password
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      * Check if at least one network interface is up and active (i.e., has an address)
602      *
603      * @return true if network available
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      * Reset config check status and clear session pool.
626      * Session creations in progress are cancelled: their session is closed instead of being added to the pool.
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         // close outside the monitor, close() may perform network I/O
638         for (ExchangeSession session : sessions) {
639             session.close();
640         }
641     }
642 }