EasSyncService.java revision 220686b40eb4cdeed35b1035dc3ad79842e4ce6e
1/* 2 * Copyright (C) 2008-2009 Marc Blank 3 * Licensed to The Android Open Source Project. 4 * 5 * Licensed under the Apache License, Version 2.0 (the "License"); 6 * you may not use this file except in compliance with the License. 7 * You may obtain a copy of the License at 8 * 9 * http://www.apache.org/licenses/LICENSE-2.0 10 * 11 * Unless required by applicable law or agreed to in writing, software 12 * distributed under the License is distributed on an "AS IS" BASIS, 13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 * See the License for the specific language governing permissions and 15 * limitations under the License. 16 */ 17 18package com.android.exchange; 19 20import com.android.emailcommon.mail.Address; 21import com.android.emailcommon.mail.MeetingInfo; 22import com.android.emailcommon.mail.MessagingException; 23import com.android.emailcommon.mail.PackedString; 24import com.android.emailcommon.provider.EmailContent.Account; 25import com.android.emailcommon.provider.EmailContent.AccountColumns; 26import com.android.emailcommon.provider.EmailContent.Attachment; 27import com.android.emailcommon.provider.EmailContent.AttachmentColumns; 28import com.android.emailcommon.provider.EmailContent.HostAuth; 29import com.android.emailcommon.provider.EmailContent.Mailbox; 30import com.android.emailcommon.provider.EmailContent.MailboxColumns; 31import com.android.emailcommon.provider.EmailContent.Message; 32import com.android.emailcommon.provider.EmailContent.MessageColumns; 33import com.android.emailcommon.provider.EmailContent.SyncColumns; 34import com.android.emailcommon.service.EmailServiceConstants; 35import com.android.emailcommon.service.EmailServiceProxy; 36import com.android.emailcommon.service.EmailServiceStatus; 37import com.android.emailcommon.service.PolicySet; 38import com.android.emailcommon.utility.AttachmentUtilities; 39import com.android.emailcommon.utility.Utility; 40import com.android.exchange.adapter.AbstractSyncAdapter; 41import com.android.exchange.adapter.AccountSyncAdapter; 42import com.android.exchange.adapter.CalendarSyncAdapter; 43import com.android.exchange.adapter.ContactsSyncAdapter; 44import com.android.exchange.adapter.EmailSyncAdapter; 45import com.android.exchange.adapter.FolderSyncParser; 46import com.android.exchange.adapter.GalParser; 47import com.android.exchange.adapter.MeetingResponseParser; 48import com.android.exchange.adapter.MoveItemsParser; 49import com.android.exchange.adapter.Parser.EasParserException; 50import com.android.exchange.adapter.PingParser; 51import com.android.exchange.adapter.ProvisionParser; 52import com.android.exchange.adapter.Serializer; 53import com.android.exchange.adapter.Tags; 54import com.android.exchange.provider.GalResult; 55import com.android.exchange.utility.CalendarUtilities; 56 57import org.apache.http.Header; 58import org.apache.http.HttpEntity; 59import org.apache.http.HttpResponse; 60import org.apache.http.HttpStatus; 61import org.apache.http.client.HttpClient; 62import org.apache.http.client.methods.HttpOptions; 63import org.apache.http.client.methods.HttpPost; 64import org.apache.http.client.methods.HttpRequestBase; 65import org.apache.http.conn.ClientConnectionManager; 66import org.apache.http.entity.ByteArrayEntity; 67import org.apache.http.entity.StringEntity; 68import org.apache.http.impl.client.DefaultHttpClient; 69import org.apache.http.params.BasicHttpParams; 70import org.apache.http.params.HttpConnectionParams; 71import org.apache.http.params.HttpParams; 72import org.xmlpull.v1.XmlPullParser; 73import org.xmlpull.v1.XmlPullParserException; 74import org.xmlpull.v1.XmlPullParserFactory; 75import org.xmlpull.v1.XmlSerializer; 76 77import android.content.ContentResolver; 78import android.content.ContentUris; 79import android.content.ContentValues; 80import android.content.Context; 81import android.content.Entity; 82import android.database.Cursor; 83import android.net.Uri; 84import android.os.Build; 85import android.os.Bundle; 86import android.os.RemoteException; 87import android.os.SystemClock; 88import android.provider.Calendar.Attendees; 89import android.provider.Calendar.Events; 90import android.text.TextUtils; 91import android.util.Base64; 92import android.util.Log; 93import android.util.Xml; 94 95import java.io.ByteArrayOutputStream; 96import java.io.File; 97import java.io.FileNotFoundException; 98import java.io.IOException; 99import java.io.InputStream; 100import java.io.OutputStream; 101import java.lang.Thread.State; 102import java.net.URI; 103import java.security.cert.CertificateException; 104import java.util.ArrayList; 105import java.util.HashMap; 106 107public class EasSyncService extends AbstractSyncService { 108 // DO NOT CHECK IN SET TO TRUE 109 public static final boolean DEBUG_GAL_SERVICE = false; 110 111 private static final String WHERE_ACCOUNT_KEY_AND_SERVER_ID = 112 MailboxColumns.ACCOUNT_KEY + "=? and " + MailboxColumns.SERVER_ID + "=?"; 113 private static final String WHERE_ACCOUNT_AND_SYNC_INTERVAL_PING = 114 MailboxColumns.ACCOUNT_KEY + "=? and " + MailboxColumns.SYNC_INTERVAL + 115 '=' + Mailbox.CHECK_INTERVAL_PING; 116 private static final String AND_FREQUENCY_PING_PUSH_AND_NOT_ACCOUNT_MAILBOX = " AND " + 117 MailboxColumns.SYNC_INTERVAL + " IN (" + Mailbox.CHECK_INTERVAL_PING + 118 ',' + Mailbox.CHECK_INTERVAL_PUSH + ") AND " + MailboxColumns.TYPE + "!=\"" + 119 Mailbox.TYPE_EAS_ACCOUNT_MAILBOX + '\"'; 120 private static final String WHERE_PUSH_HOLD_NOT_ACCOUNT_MAILBOX = 121 MailboxColumns.ACCOUNT_KEY + "=? and " + MailboxColumns.SYNC_INTERVAL + 122 '=' + Mailbox.CHECK_INTERVAL_PUSH_HOLD; 123 static private final int CHUNK_SIZE = 16*1024; 124 125 static private final String PING_COMMAND = "Ping"; 126 // Command timeout is the the time allowed for reading data from an open connection before an 127 // IOException is thrown. After a small added allowance, our watchdog alarm goes off (allowing 128 // us to detect a silently dropped connection). The allowance is defined below. 129 static private final int COMMAND_TIMEOUT = 30*SECONDS; 130 // Connection timeout is the time given to connect to the server before reporting an IOException 131 static private final int CONNECTION_TIMEOUT = 20*SECONDS; 132 // The extra time allowed beyond the COMMAND_TIMEOUT before which our watchdog alarm triggers 133 static private final int WATCHDOG_TIMEOUT_ALLOWANCE = 30*SECONDS; 134 135 // The amount of time the account mailbox will sleep if there are no pingable mailboxes 136 // This could happen if the sync time is set to "never"; we always want to check in from time 137 // to time, however, for folder list/policy changes 138 static private final int ACCOUNT_MAILBOX_SLEEP_TIME = 20*MINUTES; 139 static private final String ACCOUNT_MAILBOX_SLEEP_TEXT = 140 "Account mailbox sleeping for " + (ACCOUNT_MAILBOX_SLEEP_TIME / MINUTES) + "m"; 141 142 static private final String AUTO_DISCOVER_SCHEMA_PREFIX = 143 "http://schemas.microsoft.com/exchange/autodiscover/mobilesync/"; 144 static private final String AUTO_DISCOVER_PAGE = "/autodiscover/autodiscover.xml"; 145 static private final int AUTO_DISCOVER_REDIRECT_CODE = 451; 146 147 static private final int INTERNAL_SERVER_ERROR_CODE = 500; 148 149 static public final String EAS_12_POLICY_TYPE = "MS-EAS-Provisioning-WBXML"; 150 static public final String EAS_2_POLICY_TYPE = "MS-WAP-Provisioning-XML"; 151 152 static public final int MESSAGE_FLAG_MOVED_MESSAGE = 1 << Message.FLAG_SYNC_ADAPTER_SHIFT; 153 154 /** 155 * We start with an 8 minute timeout, and increase/decrease by 3 minutes at a time. There's 156 * no point having a timeout shorter than 5 minutes, I think; at that point, we can just let 157 * the ping exception out. The maximum I use is 17 minutes, which is really an empirical 158 * choice; too long and we risk silent connection loss and loss of push for that period. Too 159 * short and we lose efficiency/battery life. 160 * 161 * If we ever have to drop the ping timeout, we'll never increase it again. There's no point 162 * going into hysteresis; the NAT timeout isn't going to change without a change in connection, 163 * which will cause the sync service to be restarted at the starting heartbeat and going through 164 * the process again. 165 */ 166 static private final int PING_MINUTES = 60; // in seconds 167 static private final int PING_FUDGE_LOW = 10; 168 static private final int PING_STARTING_HEARTBEAT = (8*PING_MINUTES)-PING_FUDGE_LOW; 169 static private final int PING_HEARTBEAT_INCREMENT = 3*PING_MINUTES; 170 171 // Maximum number of times we'll allow a sync to "loop" with MoreAvailable true before 172 // forcing it to stop. This number has been determined empirically. 173 static private final int MAX_LOOPING_COUNT = 100; 174 175 static private final int PROTOCOL_PING_STATUS_COMPLETED = 1; 176 177 // The amount of time we allow for a thread to release its post lock after receiving an alert 178 static private final int POST_LOCK_TIMEOUT = 10*SECONDS; 179 180 // Fallbacks (in minutes) for ping loop failures 181 static private final int MAX_PING_FAILURES = 1; 182 static private final int PING_FALLBACK_INBOX = 5; 183 static private final int PING_FALLBACK_PIM = 25; 184 185 // MSFT's custom HTTP result code indicating the need to provision 186 static private final int HTTP_NEED_PROVISIONING = 449; 187 188 // The EAS protocol Provision status for "we implement all of the policies" 189 static private final String PROVISION_STATUS_OK = "1"; 190 // The EAS protocol Provision status meaning "we partially implement the policies" 191 static private final String PROVISION_STATUS_PARTIAL = "2"; 192 193 static /*package*/ final String DEVICE_TYPE = "Android"; 194 static private final String USER_AGENT = DEVICE_TYPE + '/' + Build.VERSION.RELEASE + '-' + 195 Eas.CLIENT_VERSION; 196 197 // Reasonable default 198 public String mProtocolVersion = Eas.DEFAULT_PROTOCOL_VERSION; 199 public Double mProtocolVersionDouble; 200 protected String mDeviceId = null; 201 /*package*/ String mAuthString = null; 202 /*package*/ String mCmdString = null; 203 public String mHostAddress; 204 public String mUserName; 205 public String mPassword; 206 private boolean mSsl = true; 207 private boolean mTrustSsl = false; 208 public ContentResolver mContentResolver; 209 private String[] mBindArguments = new String[2]; 210 private ArrayList<String> mPingChangeList; 211 // The HttpPost in progress 212 private volatile HttpPost mPendingPost = null; 213 // Our heartbeat when we are waiting for ping boxes to be ready 214 /*package*/ int mPingForceHeartbeat = 2*PING_MINUTES; 215 // The minimum heartbeat we will send 216 /*package*/ int mPingMinHeartbeat = (5*PING_MINUTES)-PING_FUDGE_LOW; 217 // The maximum heartbeat we will send 218 /*package*/ int mPingMaxHeartbeat = (17*PING_MINUTES)-PING_FUDGE_LOW; 219 // The ping time (in seconds) 220 /*package*/ int mPingHeartbeat = PING_STARTING_HEARTBEAT; 221 // The longest successful ping heartbeat 222 private int mPingHighWaterMark = 0; 223 // Whether we've ever lowered the heartbeat 224 /*package*/ boolean mPingHeartbeatDropped = false; 225 // Whether a POST was aborted due to alarm (watchdog alarm) 226 private boolean mPostAborted = false; 227 // Whether a POST was aborted due to reset 228 private boolean mPostReset = false; 229 // Whether or not the sync service is valid (usable) 230 public boolean mIsValid = true; 231 232 public EasSyncService(Context _context, Mailbox _mailbox) { 233 super(_context, _mailbox); 234 mContentResolver = _context.getContentResolver(); 235 if (mAccount == null) { 236 mIsValid = false; 237 return; 238 } 239 HostAuth ha = HostAuth.restoreHostAuthWithId(_context, mAccount.mHostAuthKeyRecv); 240 if (ha == null) { 241 mIsValid = false; 242 return; 243 } 244 mSsl = (ha.mFlags & HostAuth.FLAG_SSL) != 0; 245 mTrustSsl = (ha.mFlags & HostAuth.FLAG_TRUST_ALL) != 0; 246 } 247 248 private EasSyncService(String prefix) { 249 super(prefix); 250 } 251 252 public EasSyncService() { 253 this("EAS Validation"); 254 } 255 256 @Override 257 /** 258 * Try to wake up a sync thread that is waiting on an HttpClient POST and has waited past its 259 * socket timeout without having thrown an Exception 260 * 261 * @return true if the POST was successfully stopped; false if we've failed and interrupted 262 * the thread 263 */ 264 public boolean alarm() { 265 HttpPost post; 266 if (mThread == null) return true; 267 String threadName = mThread.getName(); 268 269 // Synchronize here so that we are guaranteed to have valid mPendingPost and mPostLock 270 // executePostWithTimeout (which executes the HttpPost) also uses this lock 271 synchronized(getSynchronizer()) { 272 // Get a reference to the current post lock 273 post = mPendingPost; 274 if (post != null) { 275 if (Eas.USER_LOG) { 276 URI uri = post.getURI(); 277 if (uri != null) { 278 String query = uri.getQuery(); 279 if (query == null) { 280 query = "POST"; 281 } 282 userLog(threadName, ": Alert, aborting ", query); 283 } else { 284 userLog(threadName, ": Alert, no URI?"); 285 } 286 } 287 // Abort the POST 288 mPostAborted = true; 289 post.abort(); 290 } else { 291 // If there's no POST, we're done 292 userLog("Alert, no pending POST"); 293 return true; 294 } 295 } 296 297 // Wait for the POST to finish 298 try { 299 Thread.sleep(POST_LOCK_TIMEOUT); 300 } catch (InterruptedException e) { 301 } 302 303 State s = mThread.getState(); 304 if (Eas.USER_LOG) { 305 userLog(threadName + ": State = " + s.name()); 306 } 307 308 synchronized (getSynchronizer()) { 309 // If the thread is still hanging around and the same post is pending, let's try to 310 // stop the thread with an interrupt. 311 if ((s != State.TERMINATED) && (mPendingPost != null) && (mPendingPost == post)) { 312 mStop = true; 313 mThread.interrupt(); 314 userLog("Interrupting..."); 315 // Let the caller know we had to interrupt the thread 316 return false; 317 } 318 } 319 // Let the caller know that the alarm was handled normally 320 return true; 321 } 322 323 @Override 324 public void reset() { 325 synchronized(getSynchronizer()) { 326 if (mPendingPost != null) { 327 URI uri = mPendingPost.getURI(); 328 if (uri != null) { 329 String query = uri.getQuery(); 330 if (query.startsWith("Cmd=Ping")) { 331 userLog("Reset, aborting Ping"); 332 mPostReset = true; 333 mPendingPost.abort(); 334 } 335 } 336 } 337 } 338 } 339 340 @Override 341 public void stop() { 342 mStop = true; 343 synchronized(getSynchronizer()) { 344 if (mPendingPost != null) { 345 mPendingPost.abort(); 346 } 347 } 348 } 349 350 /** 351 * Determine whether an HTTP code represents an authentication error 352 * @param code the HTTP code returned by the server 353 * @return whether or not the code represents an authentication error 354 */ 355 protected boolean isAuthError(int code) { 356 return (code == HttpStatus.SC_UNAUTHORIZED) || (code == HttpStatus.SC_FORBIDDEN); 357 } 358 359 /** 360 * Determine whether an HTTP code represents a provisioning error 361 * @param code the HTTP code returned by the server 362 * @return whether or not the code represents an provisioning error 363 */ 364 protected boolean isProvisionError(int code) { 365 return (code == HTTP_NEED_PROVISIONING) || (code == HttpStatus.SC_FORBIDDEN); 366 } 367 368 private void setupProtocolVersion(EasSyncService service, Header versionHeader) 369 throws MessagingException { 370 // The string is a comma separated list of EAS versions in ascending order 371 // e.g. 1.0,2.0,2.5,12.0,12.1 372 String supportedVersions = versionHeader.getValue(); 373 userLog("Server supports versions: ", supportedVersions); 374 String[] supportedVersionsArray = supportedVersions.split(","); 375 String ourVersion = null; 376 // Find the most recent version we support 377 for (String version: supportedVersionsArray) { 378 if (version.equals(Eas.SUPPORTED_PROTOCOL_EX2003) || 379 version.equals(Eas.SUPPORTED_PROTOCOL_EX2007) || 380 version.equals(Eas.SUPPORTED_PROTOCOL_EX2007_SP1)) { 381 ourVersion = version; 382 } 383 } 384 // If we don't support any of the servers supported versions, throw an exception here 385 // This will cause validation to fail 386 if (ourVersion == null) { 387 Log.w(TAG, "No supported EAS versions: " + supportedVersions); 388 throw new MessagingException(MessagingException.PROTOCOL_VERSION_UNSUPPORTED); 389 } else { 390 service.mProtocolVersion = ourVersion; 391 service.mProtocolVersionDouble = Eas.getProtocolVersionDouble(ourVersion); 392 if (service.mAccount != null) { 393 service.mAccount.mProtocolVersion = ourVersion; 394 } 395 } 396 } 397 398 @Override 399 public Bundle validateAccount(String hostAddress, String userName, String password, int port, 400 boolean ssl, boolean trustCertificates, Context context) { 401 Bundle bundle = new Bundle(); 402 int resultCode = MessagingException.NO_ERROR; 403 try { 404 userLog("Testing EAS: ", hostAddress, ", ", userName, ", ssl = ", ssl ? "1" : "0"); 405 EasSyncService svc = new EasSyncService("%TestAccount%"); 406 svc.mContext = context; 407 svc.mHostAddress = hostAddress; 408 svc.mUserName = userName; 409 svc.mPassword = password; 410 svc.mSsl = ssl; 411 svc.mTrustSsl = trustCertificates; 412 // We mustn't use the "real" device id or we'll screw up current accounts 413 // Any string will do, but we'll go for "validate" 414 svc.mDeviceId = "validate"; 415 HttpResponse resp = svc.sendHttpClientOptions(); 416 HttpEntity entity = resp.getEntity(); 417 try { 418 int code = resp.getStatusLine().getStatusCode(); 419 userLog("Validation (OPTIONS) response: " + code); 420 if (code == HttpStatus.SC_OK) { 421 // No exception means successful validation 422 Header commands = resp.getFirstHeader("MS-ASProtocolCommands"); 423 Header versions = resp.getFirstHeader("ms-asprotocolversions"); 424 // Make sure we've got the right protocol version set up 425 try { 426 if (commands == null || versions == null) { 427 userLog("OPTIONS response without commands or versions"); 428 // We'll treat this as a protocol exception 429 throw new MessagingException(0); 430 } 431 setupProtocolVersion(svc, versions); 432 } catch (MessagingException e) { 433 bundle.putInt(EmailServiceProxy.VALIDATE_BUNDLE_RESULT_CODE, 434 MessagingException.PROTOCOL_VERSION_UNSUPPORTED); 435 return bundle; 436 } 437 438 // Run second test here for provisioning failures using FolderSync 439 userLog("Try folder sync"); 440 // Send "0" as the sync key for new accounts; otherwise, use the current key 441 String syncKey = "0"; 442 Account existingAccount = 443 Utility.findExistingAccount(context, -1L, hostAddress, userName); 444 if (existingAccount != null && existingAccount.mSyncKey != null) { 445 syncKey = existingAccount.mSyncKey; 446 } 447 Serializer s = new Serializer(); 448 s.start(Tags.FOLDER_FOLDER_SYNC).start(Tags.FOLDER_SYNC_KEY).text(syncKey) 449 .end().end().done(); 450 resp = svc.sendHttpClientPost("FolderSync", s.toByteArray()); 451 code = resp.getStatusLine().getStatusCode(); 452 // We'll get one of the following responses if policies are required 453 if (code == HttpStatus.SC_FORBIDDEN || code == HTTP_NEED_PROVISIONING) { 454 // Get the policies and see if we are able to support them 455 ProvisionParser pp = svc.canProvision(); 456 if (pp != null) { 457 // Set the proper result code and save the PolicySet in our Bundle 458 resultCode = MessagingException.SECURITY_POLICIES_REQUIRED; 459 bundle.putParcelable(EmailServiceProxy.VALIDATE_BUNDLE_POLICY_SET, 460 pp.getPolicySet()); 461 } else 462 // If not, set the proper code (the account will not be created) 463 resultCode = MessagingException.SECURITY_POLICIES_UNSUPPORTED; 464 } else if (code == HttpStatus.SC_NOT_FOUND) { 465 // We get a 404 from OWA addresses (which are NOT EAS addresses) 466 resultCode = MessagingException.PROTOCOL_VERSION_UNSUPPORTED; 467 } else if (code != HttpStatus.SC_OK) { 468 // Fail generically with anything other than success 469 userLog("Unexpected response for FolderSync: ", code); 470 resultCode = MessagingException.UNSPECIFIED_EXCEPTION; 471 } else { 472 userLog("Validation successful"); 473 } 474 } else if (isAuthError(code)) { 475 userLog("Authentication failed"); 476 resultCode = MessagingException.AUTHENTICATION_FAILED; 477 } else if (code == INTERNAL_SERVER_ERROR_CODE) { 478 // For Exchange 2003, this could mean an authentication failure OR server error 479 userLog("Internal server error"); 480 resultCode = MessagingException.AUTHENTICATION_FAILED_OR_SERVER_ERROR; 481 } else { 482 // TODO Need to catch other kinds of errors (e.g. policy) For now, report code. 483 userLog("Validation failed, reporting I/O error: ", code); 484 resultCode = MessagingException.IOERROR; 485 } 486 } finally { 487 if (entity != null) { 488 entity.consumeContent(); 489 } 490 } 491 } catch (IOException e) { 492 Throwable cause = e.getCause(); 493 if (cause != null && cause instanceof CertificateException) { 494 userLog("CertificateException caught: ", e.getMessage()); 495 resultCode = MessagingException.GENERAL_SECURITY; 496 } 497 userLog("IOException caught: ", e.getMessage()); 498 resultCode = MessagingException.IOERROR; 499 } 500 bundle.putInt(EmailServiceProxy.VALIDATE_BUNDLE_RESULT_CODE, resultCode); 501 return bundle; 502 } 503 504 /** 505 * Gets the redirect location from the HTTP headers and uses that to modify the HttpPost so that 506 * it can be reused 507 * 508 * @param resp the HttpResponse that indicates a redirect (451) 509 * @param post the HttpPost that was originally sent to the server 510 * @return the HttpPost, updated with the redirect location 511 */ 512 private HttpPost getRedirect(HttpResponse resp, HttpPost post) { 513 Header locHeader = resp.getFirstHeader("X-MS-Location"); 514 if (locHeader != null) { 515 String loc = locHeader.getValue(); 516 // If we've gotten one and it shows signs of looking like an address, we try 517 // sending our request there 518 if (loc != null && loc.startsWith("http")) { 519 post.setURI(URI.create(loc)); 520 return post; 521 } 522 } 523 return null; 524 } 525 526 /** 527 * Send the POST command to the autodiscover server, handling a redirect, if necessary, and 528 * return the HttpResponse. If we get a 401 (unauthorized) error and we're using the 529 * full email address, try the bare user name instead (e.g. foo instead of foo@bar.com) 530 * 531 * @param client the HttpClient to be used for the request 532 * @param post the HttpPost we're going to send 533 * @param canRetry whether we can retry using the bare name on an authentication failure (401) 534 * @return an HttpResponse from the original or redirect server 535 * @throws IOException on any IOException within the HttpClient code 536 * @throws MessagingException 537 */ 538 private HttpResponse postAutodiscover(HttpClient client, HttpPost post, boolean canRetry) 539 throws IOException, MessagingException { 540 userLog("Posting autodiscover to: " + post.getURI()); 541 HttpResponse resp = executePostWithTimeout(client, post, COMMAND_TIMEOUT); 542 int code = resp.getStatusLine().getStatusCode(); 543 // On a redirect, try the new location 544 if (code == AUTO_DISCOVER_REDIRECT_CODE) { 545 post = getRedirect(resp, post); 546 if (post != null) { 547 userLog("Posting autodiscover to redirect: " + post.getURI()); 548 return executePostWithTimeout(client, post, COMMAND_TIMEOUT); 549 } 550 // 401 (Unauthorized) is for true auth errors when used in Autodiscover 551 } else if (code == HttpStatus.SC_UNAUTHORIZED) { 552 if (canRetry && mUserName.contains("@")) { 553 // Try again using the bare user name 554 int atSignIndex = mUserName.indexOf('@'); 555 mUserName = mUserName.substring(0, atSignIndex); 556 cacheAuthAndCmdString(); 557 userLog("401 received; trying username: ", mUserName); 558 // Recreate the basic authentication string and reset the header 559 post.removeHeaders("Authorization"); 560 post.setHeader("Authorization", mAuthString); 561 return postAutodiscover(client, post, false); 562 } 563 throw new MessagingException(MessagingException.AUTHENTICATION_FAILED); 564 // 403 (and others) we'll just punt on 565 } else if (code != HttpStatus.SC_OK) { 566 // We'll try the next address if this doesn't work 567 userLog("Code: " + code + ", throwing IOException"); 568 throw new IOException(); 569 } 570 return resp; 571 } 572 573 /** 574 * Use the Exchange 2007 AutoDiscover feature to try to retrieve server information using 575 * only an email address and the password 576 * 577 * @param userName the user's email address 578 * @param password the user's password 579 * @return a HostAuth ready to be saved in an Account or null (failure) 580 */ 581 public Bundle tryAutodiscover(String userName, String password) throws RemoteException { 582 XmlSerializer s = Xml.newSerializer(); 583 ByteArrayOutputStream os = new ByteArrayOutputStream(1024); 584 HostAuth hostAuth = new HostAuth(); 585 Bundle bundle = new Bundle(); 586 bundle.putInt(EmailServiceProxy.AUTO_DISCOVER_BUNDLE_ERROR_CODE, 587 MessagingException.NO_ERROR); 588 try { 589 // Build the XML document that's sent to the autodiscover server(s) 590 s.setOutput(os, "UTF-8"); 591 s.startDocument("UTF-8", false); 592 s.startTag(null, "Autodiscover"); 593 s.attribute(null, "xmlns", AUTO_DISCOVER_SCHEMA_PREFIX + "requestschema/2006"); 594 s.startTag(null, "Request"); 595 s.startTag(null, "EMailAddress").text(userName).endTag(null, "EMailAddress"); 596 s.startTag(null, "AcceptableResponseSchema"); 597 s.text(AUTO_DISCOVER_SCHEMA_PREFIX + "responseschema/2006"); 598 s.endTag(null, "AcceptableResponseSchema"); 599 s.endTag(null, "Request"); 600 s.endTag(null, "Autodiscover"); 601 s.endDocument(); 602 String req = os.toString(); 603 604 // Initialize the user name and password 605 mUserName = userName; 606 mPassword = password; 607 // Make sure the authentication string is recreated and cached 608 cacheAuthAndCmdString(); 609 610 // Split out the domain name 611 int amp = userName.indexOf('@'); 612 // The UI ensures that userName is a valid email address 613 if (amp < 0) { 614 throw new RemoteException(); 615 } 616 String domain = userName.substring(amp + 1); 617 618 // There are up to four attempts here; the two URLs that we're supposed to try per the 619 // specification, and up to one redirect for each (handled in postAutodiscover) 620 // Note: The expectation is that, of these four attempts, only a single server will 621 // actually be identified as the autodiscover server. For the identified server, 622 // we may also try a 2nd connection with a different format (bare name). 623 624 // Try the domain first and see if we can get a response 625 HttpPost post = new HttpPost("https://" + domain + AUTO_DISCOVER_PAGE); 626 setHeaders(post, false); 627 post.setHeader("Content-Type", "text/xml"); 628 post.setEntity(new StringEntity(req)); 629 HttpClient client = getHttpClient(COMMAND_TIMEOUT); 630 HttpResponse resp; 631 try { 632 resp = postAutodiscover(client, post, true /*canRetry*/); 633 } catch (IOException e1) { 634 userLog("IOException in autodiscover; trying alternate address"); 635 // We catch the IOException here because we have an alternate address to try 636 post.setURI(URI.create("https://autodiscover." + domain + AUTO_DISCOVER_PAGE)); 637 // If we fail here, we're out of options, so we let the outer try catch the 638 // IOException and return null 639 resp = postAutodiscover(client, post, true /*canRetry*/); 640 } 641 642 HttpEntity entity = resp.getEntity(); 643 try { 644 // Get the "final" code; if it's not 200, just return null 645 int code = resp.getStatusLine().getStatusCode(); 646 userLog("Code: " + code); 647 if (code != HttpStatus.SC_OK) return null; 648 649 InputStream is = entity.getContent(); 650 // The response to Autodiscover is regular XML (not WBXML) 651 // If we ever get an error in this process, we'll just punt and return null 652 XmlPullParserFactory factory = XmlPullParserFactory.newInstance(); 653 XmlPullParser parser = factory.newPullParser(); 654 parser.setInput(is, "UTF-8"); 655 int type = parser.getEventType(); 656 if (type == XmlPullParser.START_DOCUMENT) { 657 type = parser.next(); 658 if (type == XmlPullParser.START_TAG) { 659 String name = parser.getName(); 660 if (name.equals("Autodiscover")) { 661 hostAuth = new HostAuth(); 662 parseAutodiscover(parser, hostAuth); 663 // On success, we'll have a server address and login 664 if (hostAuth.mAddress != null) { 665 // Fill in the rest of the HostAuth 666 // We use the user name and password that were successful during 667 // the autodiscover process 668 hostAuth.mLogin = mUserName; 669 hostAuth.mPassword = mPassword; 670 hostAuth.mPort = 443; 671 hostAuth.mProtocol = "eas"; 672 hostAuth.mFlags = 673 HostAuth.FLAG_SSL | HostAuth.FLAG_AUTHENTICATE; 674 bundle.putParcelable( 675 EmailServiceProxy.AUTO_DISCOVER_BUNDLE_HOST_AUTH, hostAuth); 676 } else { 677 bundle.putInt(EmailServiceProxy.AUTO_DISCOVER_BUNDLE_ERROR_CODE, 678 MessagingException.UNSPECIFIED_EXCEPTION); 679 } 680 } 681 } 682 } 683 } catch (XmlPullParserException e1) { 684 // This would indicate an I/O error of some sort 685 // We will simply return null and user can configure manually 686 } finally { 687 if (entity != null) { 688 entity.consumeContent(); 689 } 690 } 691 // There's no reason at all for exceptions to be thrown, and it's ok if so. 692 // We just won't do auto-discover; user can configure manually 693 } catch (IllegalArgumentException e) { 694 bundle.putInt(EmailServiceProxy.AUTO_DISCOVER_BUNDLE_ERROR_CODE, 695 MessagingException.UNSPECIFIED_EXCEPTION); 696 } catch (IllegalStateException e) { 697 bundle.putInt(EmailServiceProxy.AUTO_DISCOVER_BUNDLE_ERROR_CODE, 698 MessagingException.UNSPECIFIED_EXCEPTION); 699 } catch (IOException e) { 700 userLog("IOException in Autodiscover", e); 701 bundle.putInt(EmailServiceProxy.AUTO_DISCOVER_BUNDLE_ERROR_CODE, 702 MessagingException.IOERROR); 703 } catch (MessagingException e) { 704 bundle.putInt(EmailServiceProxy.AUTO_DISCOVER_BUNDLE_ERROR_CODE, 705 MessagingException.AUTHENTICATION_FAILED); 706 } 707 return bundle; 708 } 709 710 void parseServer(XmlPullParser parser, HostAuth hostAuth) 711 throws XmlPullParserException, IOException { 712 boolean mobileSync = false; 713 while (true) { 714 int type = parser.next(); 715 if (type == XmlPullParser.END_TAG && parser.getName().equals("Server")) { 716 break; 717 } else if (type == XmlPullParser.START_TAG) { 718 String name = parser.getName(); 719 if (name.equals("Type")) { 720 if (parser.nextText().equals("MobileSync")) { 721 mobileSync = true; 722 } 723 } else if (mobileSync && name.equals("Url")) { 724 String url = parser.nextText().toLowerCase(); 725 // This will look like https://<server address>/Microsoft-Server-ActiveSync 726 // We need to extract the <server address> 727 if (url.startsWith("https://") && 728 url.endsWith("/microsoft-server-activesync")) { 729 int lastSlash = url.lastIndexOf('/'); 730 hostAuth.mAddress = url.substring(8, lastSlash); 731 userLog("Autodiscover, server: " + hostAuth.mAddress); 732 } 733 } 734 } 735 } 736 } 737 738 void parseSettings(XmlPullParser parser, HostAuth hostAuth) 739 throws XmlPullParserException, IOException { 740 while (true) { 741 int type = parser.next(); 742 if (type == XmlPullParser.END_TAG && parser.getName().equals("Settings")) { 743 break; 744 } else if (type == XmlPullParser.START_TAG) { 745 String name = parser.getName(); 746 if (name.equals("Server")) { 747 parseServer(parser, hostAuth); 748 } 749 } 750 } 751 } 752 753 void parseAction(XmlPullParser parser, HostAuth hostAuth) 754 throws XmlPullParserException, IOException { 755 while (true) { 756 int type = parser.next(); 757 if (type == XmlPullParser.END_TAG && parser.getName().equals("Action")) { 758 break; 759 } else if (type == XmlPullParser.START_TAG) { 760 String name = parser.getName(); 761 if (name.equals("Error")) { 762 // Should parse the error 763 } else if (name.equals("Redirect")) { 764 Log.d(TAG, "Redirect: " + parser.nextText()); 765 } else if (name.equals("Settings")) { 766 parseSettings(parser, hostAuth); 767 } 768 } 769 } 770 } 771 772 void parseUser(XmlPullParser parser, HostAuth hostAuth) 773 throws XmlPullParserException, IOException { 774 while (true) { 775 int type = parser.next(); 776 if (type == XmlPullParser.END_TAG && parser.getName().equals("User")) { 777 break; 778 } else if (type == XmlPullParser.START_TAG) { 779 String name = parser.getName(); 780 if (name.equals("EMailAddress")) { 781 String addr = parser.nextText(); 782 userLog("Autodiscover, email: " + addr); 783 } else if (name.equals("DisplayName")) { 784 String dn = parser.nextText(); 785 userLog("Autodiscover, user: " + dn); 786 } 787 } 788 } 789 } 790 791 void parseResponse(XmlPullParser parser, HostAuth hostAuth) 792 throws XmlPullParserException, IOException { 793 while (true) { 794 int type = parser.next(); 795 if (type == XmlPullParser.END_TAG && parser.getName().equals("Response")) { 796 break; 797 } else if (type == XmlPullParser.START_TAG) { 798 String name = parser.getName(); 799 if (name.equals("User")) { 800 parseUser(parser, hostAuth); 801 } else if (name.equals("Action")) { 802 parseAction(parser, hostAuth); 803 } 804 } 805 } 806 } 807 808 void parseAutodiscover(XmlPullParser parser, HostAuth hostAuth) 809 throws XmlPullParserException, IOException { 810 while (true) { 811 int type = parser.nextTag(); 812 if (type == XmlPullParser.END_TAG && parser.getName().equals("Autodiscover")) { 813 break; 814 } else if (type == XmlPullParser.START_TAG && parser.getName().equals("Response")) { 815 parseResponse(parser, hostAuth); 816 } 817 } 818 } 819 820 /** 821 * Contact the GAL and obtain a list of matching accounts 822 * @param context caller's context 823 * @param accountId the account Id to search 824 * @param filter the characters entered so far 825 * @return a result record or null for no data 826 * 827 * TODO: shorter timeout for interactive lookup 828 * TODO: make watchdog actually work (it doesn't understand our service w/Mailbox == 0) 829 * TODO: figure out why sendHttpClientPost() hangs - possibly pool exhaustion 830 */ 831 static public GalResult searchGal(Context context, long accountId, String filter, int limit) { 832 // Try to get the cached account from ExchangeService (saves a database access) 833 Account acct = ExchangeService.getAccountById(accountId); 834 if (acct == null) { 835 // ExchangeService isn't running; get the account directly from EmailProvider 836 acct = Account.restoreAccountWithId(context, accountId); 837 } 838 if (acct != null) { 839 HostAuth ha = HostAuth.restoreHostAuthWithId(context, acct.mHostAuthKeyRecv); 840 EasSyncService svc = new EasSyncService("%GalLookupk%"); 841 try { 842 // If there's no protocol version set up, we haven't successfully started syncing 843 // so we can't use GAL yet 844 String protocolVersion = acct.mProtocolVersion; 845 if (protocolVersion == null) { 846 return null; 847 } else { 848 svc.mProtocolVersion = protocolVersion; 849 svc.mProtocolVersionDouble = Eas.getProtocolVersionDouble(protocolVersion); 850 } 851 svc.mContext = context; 852 svc.mHostAddress = ha.mAddress; 853 svc.mUserName = ha.mLogin; 854 svc.mPassword = ha.mPassword; 855 svc.mSsl = (ha.mFlags & HostAuth.FLAG_SSL) != 0; 856 svc.mTrustSsl = (ha.mFlags & HostAuth.FLAG_TRUST_ALL) != 0; 857 svc.mDeviceId = ExchangeService.getDeviceId(context); 858 svc.mAccount = acct; 859 Serializer s = new Serializer(); 860 s.start(Tags.SEARCH_SEARCH).start(Tags.SEARCH_STORE); 861 s.data(Tags.SEARCH_NAME, "GAL").data(Tags.SEARCH_QUERY, filter); 862 s.start(Tags.SEARCH_OPTIONS); 863 s.data(Tags.SEARCH_RANGE, "0-" + Integer.toString(limit - 1)); 864 s.end().end().end().done(); 865 if (DEBUG_GAL_SERVICE) svc.userLog("GAL lookup starting for " + ha.mAddress); 866 HttpResponse resp = svc.sendHttpClientPost("Search", s.toByteArray()); 867 HttpEntity entity = resp.getEntity(); 868 try { 869 int code = resp.getStatusLine().getStatusCode(); 870 if (code == HttpStatus.SC_OK) { 871 InputStream is = entity.getContent(); 872 try { 873 GalParser gp = new GalParser(is, svc); 874 if (gp.parse()) { 875 if (DEBUG_GAL_SERVICE) svc.userLog("GAL lookup OK: " + ha.mAddress); 876 return gp.getGalResult(); 877 } else { 878 if (DEBUG_GAL_SERVICE) svc.userLog("GAL lookup: no matches"); 879 } 880 } finally { 881 is.close(); 882 } 883 } else { 884 svc.userLog("GAL lookup returned " + code); 885 } 886 } finally { 887 if (entity != null) { 888 entity.consumeContent(); 889 } 890 } 891 } catch (IOException e) { 892 // GAL is non-critical; we'll just go on 893 svc.userLog("GAL lookup exception " + e); 894 } 895 } 896 return null; 897 } 898 899 private void doStatusCallback(long messageId, long attachmentId, int status) { 900 try { 901 ExchangeService.callback().loadAttachmentStatus(messageId, attachmentId, status, 0); 902 } catch (RemoteException e) { 903 // No danger if the client is no longer around 904 } 905 } 906 907 private void doProgressCallback(long messageId, long attachmentId, int progress) { 908 try { 909 ExchangeService.callback().loadAttachmentStatus(messageId, attachmentId, 910 EmailServiceStatus.IN_PROGRESS, progress); 911 } catch (RemoteException e) { 912 // No danger if the client is no longer around 913 } 914 } 915 916 public File createUniqueFileInternal(String dir, String filename) { 917 File directory; 918 if (dir == null) { 919 directory = mContext.getFilesDir(); 920 } else { 921 directory = new File(dir); 922 } 923 if (!directory.exists()) { 924 directory.mkdirs(); 925 } 926 File file = new File(directory, filename); 927 if (!file.exists()) { 928 return file; 929 } 930 // Get the extension of the file, if any. 931 int index = filename.lastIndexOf('.'); 932 String name = filename; 933 String extension = ""; 934 if (index != -1) { 935 name = filename.substring(0, index); 936 extension = filename.substring(index); 937 } 938 for (int i = 2; i < Integer.MAX_VALUE; i++) { 939 file = new File(directory, name + '-' + i + extension); 940 if (!file.exists()) { 941 return file; 942 } 943 } 944 return null; 945 } 946 947 /** 948 * Loads an attachment, based on the PartRequest passed in. The PartRequest is basically our 949 * wrapper for Attachment 950 * @param req the part (attachment) to be retrieved 951 * @throws IOException 952 */ 953 protected void loadAttachment(PartRequest req) throws IOException { 954 Attachment att = req.mAttachment; 955 Message msg = Message.restoreMessageWithId(mContext, att.mMessageKey); 956 if (msg == null) { 957 doStatusCallback(att.mMessageKey, att.mId, EmailServiceStatus.MESSAGE_NOT_FOUND); 958 return; 959 } else { 960 doProgressCallback(msg.mId, att.mId, 0); 961 } 962 963 String cmd = "GetAttachment&AttachmentName=" + att.mLocation; 964 HttpResponse res = sendHttpClientPost(cmd, null, COMMAND_TIMEOUT); 965 HttpEntity entity = res.getEntity(); 966 967 try { 968 int status = res.getStatusLine().getStatusCode(); 969 if (status == HttpStatus.SC_OK) { 970 int len = (int)entity.getContentLength(); 971 InputStream is = entity.getContent(); 972 OutputStream os = null; 973 Uri attachmentUri = AttachmentUtilities.getAttachmentUri(att.mAccountKey, att.mId); 974 String fileName = null; 975 try { 976 os = mContentResolver.openOutputStream(attachmentUri); 977 userLog("Attachment filename retrieved as: " + fileName); 978 } catch (FileNotFoundException e) { 979 userLog("Can't get attachment; write file not found?"); 980 } 981 if (os != null) { 982 // len > 0 means that Content-Length was set in the headers 983 // len < 0 means "chunked" transfer-encoding 984 if (len != 0) { 985 try { 986 mPendingRequest = req; 987 byte[] bytes = new byte[CHUNK_SIZE]; 988 int length = len; 989 // Loop terminates 1) when EOF is reached or 2) IOException occurs 990 // One of these is guaranteed to occur 991 int totalRead = 0; 992 userLog("Attachment content-length: ", len); 993 while (true) { 994 int read = is.read(bytes, 0, CHUNK_SIZE); 995 996 // read < 0 means that EOF was reached 997 if (read < 0) { 998 userLog("Attachment load reached EOF, totalRead: ", totalRead); 999 break; 1000 } 1001 1002 // Keep track of how much we've read for progress callback 1003 totalRead += read; 1004 1005 // Write these bytes out 1006 os.write(bytes, 0, read); 1007 1008 // We can't report percentages if this is chunked; the 1009 // length of incoming data is unknown 1010 if (length > 0) { 1011 // Belt and suspenders check to prevent runaway reading 1012 if (totalRead > length) { 1013 errorLog("totalRead is greater than attachment length?"); 1014 break; 1015 } 1016 int pct = (totalRead * 100) / length; 1017 doProgressCallback(msg.mId, att.mId, pct); 1018 } 1019 } 1020 } finally { 1021 mPendingRequest = null; 1022 } 1023 } 1024 os.flush(); 1025 os.close(); 1026 1027 // EmailProvider will throw an exception if update an unsaved attachment 1028 if (att.isSaved()) { 1029 ContentValues cv = new ContentValues(); 1030 cv.put(AttachmentColumns.CONTENT_URI, attachmentUri.toString()); 1031 att.update(mContext, cv); 1032 doStatusCallback(msg.mId, att.mId, EmailServiceStatus.SUCCESS); 1033 } 1034 } 1035 } else { 1036 doStatusCallback(msg.mId, att.mId, EmailServiceStatus.MESSAGE_NOT_FOUND); 1037 } 1038 } finally { 1039 if (entity != null) { 1040 entity.consumeContent(); 1041 } 1042 } 1043 } 1044 1045 /** 1046 * Send an email responding to a Message that has been marked as a meeting request. The message 1047 * will consist a little bit of event information and an iCalendar attachment 1048 * @param msg the meeting request email 1049 */ 1050 private void sendMeetingResponseMail(Message msg, int response) { 1051 // Get the meeting information; we'd better have some... 1052 PackedString meetingInfo = new PackedString(msg.mMeetingInfo); 1053 if (meetingInfo == null) return; 1054 1055 // This will come as "First Last" <box@server.blah>, so we use Address to 1056 // parse it into parts; we only need the email address part for the ics file 1057 Address[] addrs = Address.parse(meetingInfo.get(MeetingInfo.MEETING_ORGANIZER_EMAIL)); 1058 // It shouldn't be possible, but handle it anyway 1059 if (addrs.length != 1) return; 1060 String organizerEmail = addrs[0].getAddress(); 1061 1062 String dtStamp = meetingInfo.get(MeetingInfo.MEETING_DTSTAMP); 1063 String dtStart = meetingInfo.get(MeetingInfo.MEETING_DTSTART); 1064 String dtEnd = meetingInfo.get(MeetingInfo.MEETING_DTEND); 1065 1066 // What we're doing here is to create an Entity that looks like an Event as it would be 1067 // stored by CalendarProvider 1068 ContentValues entityValues = new ContentValues(); 1069 Entity entity = new Entity(entityValues); 1070 1071 // Fill in times, location, title, and organizer 1072 entityValues.put("DTSTAMP", 1073 CalendarUtilities.convertEmailDateTimeToCalendarDateTime(dtStamp)); 1074 entityValues.put(Events.DTSTART, Utility.parseEmailDateTimeToMillis(dtStart)); 1075 entityValues.put(Events.DTEND, Utility.parseEmailDateTimeToMillis(dtEnd)); 1076 entityValues.put(Events.EVENT_LOCATION, meetingInfo.get(MeetingInfo.MEETING_LOCATION)); 1077 entityValues.put(Events.TITLE, meetingInfo.get(MeetingInfo.MEETING_TITLE)); 1078 entityValues.put(Events.ORGANIZER, organizerEmail); 1079 1080 // Add ourselves as an attendee, using our account email address 1081 ContentValues attendeeValues = new ContentValues(); 1082 attendeeValues.put(Attendees.ATTENDEE_RELATIONSHIP, 1083 Attendees.RELATIONSHIP_ATTENDEE); 1084 attendeeValues.put(Attendees.ATTENDEE_EMAIL, mAccount.mEmailAddress); 1085 entity.addSubValue(Attendees.CONTENT_URI, attendeeValues); 1086 1087 // Add the organizer 1088 ContentValues organizerValues = new ContentValues(); 1089 organizerValues.put(Attendees.ATTENDEE_RELATIONSHIP, 1090 Attendees.RELATIONSHIP_ORGANIZER); 1091 organizerValues.put(Attendees.ATTENDEE_EMAIL, organizerEmail); 1092 entity.addSubValue(Attendees.CONTENT_URI, organizerValues); 1093 1094 // Create a message from the Entity we've built. The message will have fields like 1095 // to, subject, date, and text filled in. There will also be an "inline" attachment 1096 // which is in iCalendar format 1097 int flag; 1098 switch(response) { 1099 case EmailServiceConstants.MEETING_REQUEST_ACCEPTED: 1100 flag = Message.FLAG_OUTGOING_MEETING_ACCEPT; 1101 break; 1102 case EmailServiceConstants.MEETING_REQUEST_DECLINED: 1103 flag = Message.FLAG_OUTGOING_MEETING_DECLINE; 1104 break; 1105 case EmailServiceConstants.MEETING_REQUEST_TENTATIVE: 1106 default: 1107 flag = Message.FLAG_OUTGOING_MEETING_TENTATIVE; 1108 break; 1109 } 1110 Message outgoingMsg = 1111 CalendarUtilities.createMessageForEntity(mContext, entity, flag, 1112 meetingInfo.get(MeetingInfo.MEETING_UID), mAccount); 1113 // Assuming we got a message back (we might not if the event has been deleted), send it 1114 if (outgoingMsg != null) { 1115 EasOutboxService.sendMessage(mContext, mAccount.mId, outgoingMsg); 1116 } 1117 } 1118 1119 /** 1120 * Responds to a move request. The MessageMoveRequest is basically our 1121 * wrapper for the MoveItems service call 1122 * @param req the request (message id and "to" mailbox id) 1123 * @throws IOException 1124 */ 1125 protected void messageMoveRequest(MessageMoveRequest req) throws IOException { 1126 // Retrieve the message and mailbox; punt if either are null 1127 Message msg = Message.restoreMessageWithId(mContext, req.mMessageId); 1128 if (msg == null) return; 1129 Cursor c = mContentResolver.query(ContentUris.withAppendedId(Message.UPDATED_CONTENT_URI, 1130 msg.mId), new String[] {MessageColumns.MAILBOX_KEY}, null, null, null); 1131 Mailbox srcMailbox = null; 1132 try { 1133 if (!c.moveToNext()) return; 1134 srcMailbox = Mailbox.restoreMailboxWithId(mContext, c.getLong(0)); 1135 } finally { 1136 c.close(); 1137 } 1138 if (srcMailbox == null) return; 1139 Mailbox dstMailbox = Mailbox.restoreMailboxWithId(mContext, req.mMailboxId); 1140 if (dstMailbox == null) return; 1141 Serializer s = new Serializer(); 1142 s.start(Tags.MOVE_MOVE_ITEMS).start(Tags.MOVE_MOVE); 1143 s.data(Tags.MOVE_SRCMSGID, msg.mServerId); 1144 s.data(Tags.MOVE_SRCFLDID, srcMailbox.mServerId); 1145 s.data(Tags.MOVE_DSTFLDID, dstMailbox.mServerId); 1146 s.end().end().done(); 1147 HttpResponse res = sendHttpClientPost("MoveItems", s.toByteArray()); 1148 HttpEntity entity = res.getEntity(); 1149 try { 1150 int status = res.getStatusLine().getStatusCode(); 1151 if (status == HttpStatus.SC_OK) { 1152 int len = (int) entity.getContentLength(); 1153 InputStream is = res.getEntity().getContent(); 1154 if (len != 0) { 1155 MoveItemsParser p = new MoveItemsParser(is, this); 1156 p.parse(); 1157 int statusCode = p.getStatusCode(); 1158 ContentValues cv = new ContentValues(); 1159 if (statusCode == MoveItemsParser.STATUS_CODE_REVERT) { 1160 // Restore the old mailbox id 1161 cv.put(MessageColumns.MAILBOX_KEY, srcMailbox.mServerId); 1162 mContentResolver.update( 1163 ContentUris.withAppendedId(Message.CONTENT_URI, req.mMessageId), 1164 cv, null, null); 1165 } else if (statusCode == MoveItemsParser.STATUS_CODE_SUCCESS) { 1166 // Update with the new server id 1167 cv.put(SyncColumns.SERVER_ID, p.getNewServerId()); 1168 cv.put(Message.FLAGS, msg.mFlags | MESSAGE_FLAG_MOVED_MESSAGE); 1169 mContentResolver.update( 1170 ContentUris.withAppendedId(Message.CONTENT_URI, req.mMessageId), 1171 cv, null, null); 1172 } 1173 if (statusCode == MoveItemsParser.STATUS_CODE_SUCCESS 1174 || statusCode == MoveItemsParser.STATUS_CODE_REVERT) { 1175 // If we revert or succeed, we no longer need the update information 1176 // OR the now-duplicate email (the new copy will be synced down) 1177 mContentResolver.delete(ContentUris.withAppendedId( 1178 Message.UPDATED_CONTENT_URI, req.mMessageId), null, null); 1179 } else { 1180 // In this case, we're retrying, so do nothing. The request will be 1181 // handled next sync 1182 } 1183 } 1184 } else if (isAuthError(status)) { 1185 throw new EasAuthenticationException(); 1186 } else { 1187 userLog("Move items request failed, code: " + status); 1188 throw new IOException(); 1189 } 1190 } finally { 1191 if (entity != null) { 1192 entity.consumeContent(); 1193 } 1194 } 1195 } 1196 1197 /** 1198 * Responds to a meeting request. The MeetingResponseRequest is basically our 1199 * wrapper for the meetingResponse service call 1200 * @param req the request (message id and response code) 1201 * @throws IOException 1202 */ 1203 protected void sendMeetingResponse(MeetingResponseRequest req) throws IOException { 1204 // Retrieve the message and mailbox; punt if either are null 1205 Message msg = Message.restoreMessageWithId(mContext, req.mMessageId); 1206 if (msg == null) return; 1207 Mailbox mailbox = Mailbox.restoreMailboxWithId(mContext, msg.mMailboxKey); 1208 if (mailbox == null) return; 1209 Serializer s = new Serializer(); 1210 s.start(Tags.MREQ_MEETING_RESPONSE).start(Tags.MREQ_REQUEST); 1211 s.data(Tags.MREQ_USER_RESPONSE, Integer.toString(req.mResponse)); 1212 s.data(Tags.MREQ_COLLECTION_ID, mailbox.mServerId); 1213 s.data(Tags.MREQ_REQ_ID, msg.mServerId); 1214 s.end().end().done(); 1215 HttpResponse res = sendHttpClientPost("MeetingResponse", s.toByteArray()); 1216 HttpEntity entity = res.getEntity(); 1217 try { 1218 int status = res.getStatusLine().getStatusCode(); 1219 if (status == HttpStatus.SC_OK) { 1220 int len = (int)entity.getContentLength(); 1221 if (len != 0) { 1222 InputStream is = res.getEntity().getContent(); 1223 new MeetingResponseParser(is, this).parse(); 1224 String meetingInfo = msg.mMeetingInfo; 1225 if (meetingInfo != null) { 1226 String responseRequested = new PackedString(meetingInfo).get( 1227 MeetingInfo.MEETING_RESPONSE_REQUESTED); 1228 // If there's no tag, or a non-zero tag, we send the response mail 1229 if ("0".equals(responseRequested)) { 1230 return; 1231 } 1232 } 1233 sendMeetingResponseMail(msg, req.mResponse); 1234 } 1235 } else if (isAuthError(status)) { 1236 throw new EasAuthenticationException(); 1237 } else { 1238 userLog("Meeting response request failed, code: " + status); 1239 throw new IOException(); 1240 } 1241 } finally { 1242 if (entity != null) { 1243 entity.consumeContent(); 1244 } 1245 } 1246 } 1247 1248 /** 1249 * Using mUserName and mPassword, create and cache mAuthString and mCacheString, which are used 1250 * in all HttpPost commands. This should be called if these strings are null, or if mUserName 1251 * and/or mPassword are changed 1252 */ 1253 private void cacheAuthAndCmdString() { 1254 String safeUserName = Uri.encode(mUserName); 1255 String cs = mUserName + ':' + mPassword; 1256 mAuthString = "Basic " + Base64.encodeToString(cs.getBytes(), Base64.NO_WRAP); 1257 mCmdString = "&User=" + safeUserName + "&DeviceId=" + mDeviceId + 1258 "&DeviceType=" + DEVICE_TYPE; 1259 } 1260 1261 /*package*/ String makeUriString(String cmd, String extra) throws IOException { 1262 // Cache the authentication string and the command string 1263 if (mAuthString == null || mCmdString == null) { 1264 cacheAuthAndCmdString(); 1265 } 1266 String us = (mSsl ? (mTrustSsl ? "httpts" : "https") : "http") + "://" + mHostAddress + 1267 "/Microsoft-Server-ActiveSync"; 1268 if (cmd != null) { 1269 us += "?Cmd=" + cmd + mCmdString; 1270 } 1271 if (extra != null) { 1272 us += extra; 1273 } 1274 return us; 1275 } 1276 1277 /** 1278 * Set standard HTTP headers, using a policy key if required 1279 * @param method the method we are going to send 1280 * @param usePolicyKey whether or not a policy key should be sent in the headers 1281 */ 1282 /*package*/ void setHeaders(HttpRequestBase method, boolean usePolicyKey) { 1283 method.setHeader("Authorization", mAuthString); 1284 method.setHeader("MS-ASProtocolVersion", mProtocolVersion); 1285 method.setHeader("Connection", "keep-alive"); 1286 method.setHeader("User-Agent", USER_AGENT); 1287 if (usePolicyKey) { 1288 // If there's an account in existence, use its key; otherwise (we're creating the 1289 // account), send "0". The server will respond with code 449 if there are policies 1290 // to be enforced 1291 String key = "0"; 1292 if (mAccount != null) { 1293 String accountKey = mAccount.mSecuritySyncKey; 1294 if (!TextUtils.isEmpty(accountKey)) { 1295 key = accountKey; 1296 } 1297 } 1298 method.setHeader("X-MS-PolicyKey", key); 1299 } 1300 } 1301 1302 private ClientConnectionManager getClientConnectionManager() { 1303 return ExchangeService.getClientConnectionManager(); 1304 } 1305 1306 private HttpClient getHttpClient(int timeout) { 1307 HttpParams params = new BasicHttpParams(); 1308 HttpConnectionParams.setConnectionTimeout(params, CONNECTION_TIMEOUT); 1309 HttpConnectionParams.setSoTimeout(params, timeout); 1310 HttpConnectionParams.setSocketBufferSize(params, 8192); 1311 HttpClient client = new DefaultHttpClient(getClientConnectionManager(), params); 1312 return client; 1313 } 1314 1315 protected HttpResponse sendHttpClientPost(String cmd, byte[] bytes) throws IOException { 1316 return sendHttpClientPost(cmd, new ByteArrayEntity(bytes), COMMAND_TIMEOUT); 1317 } 1318 1319 protected HttpResponse sendHttpClientPost(String cmd, HttpEntity entity) throws IOException { 1320 return sendHttpClientPost(cmd, entity, COMMAND_TIMEOUT); 1321 } 1322 1323 protected HttpResponse sendPing(byte[] bytes, int heartbeat) throws IOException { 1324 Thread.currentThread().setName(mAccount.mDisplayName + ": Ping"); 1325 if (Eas.USER_LOG) { 1326 userLog("Send ping, timeout: " + heartbeat + "s, high: " + mPingHighWaterMark + 's'); 1327 } 1328 return sendHttpClientPost(PING_COMMAND, new ByteArrayEntity(bytes), (heartbeat+5)*SECONDS); 1329 } 1330 1331 /** 1332 * Convenience method for executePostWithTimeout for use other than with the Ping command 1333 */ 1334 protected HttpResponse executePostWithTimeout(HttpClient client, HttpPost method, int timeout) 1335 throws IOException { 1336 return executePostWithTimeout(client, method, timeout, false); 1337 } 1338 1339 /** 1340 * Handle executing an HTTP POST command with proper timeout, watchdog, and ping behavior 1341 * @param client the HttpClient 1342 * @param method the HttpPost 1343 * @param timeout the timeout before failure, in ms 1344 * @param isPingCommand whether the POST is for the Ping command (requires wakelock logic) 1345 * @return the HttpResponse 1346 * @throws IOException 1347 */ 1348 protected HttpResponse executePostWithTimeout(HttpClient client, HttpPost method, int timeout, 1349 boolean isPingCommand) throws IOException { 1350 synchronized(getSynchronizer()) { 1351 mPendingPost = method; 1352 long alarmTime = timeout + WATCHDOG_TIMEOUT_ALLOWANCE; 1353 if (isPingCommand) { 1354 ExchangeService.runAsleep(mMailboxId, alarmTime); 1355 } else { 1356 ExchangeService.setWatchdogAlarm(mMailboxId, alarmTime); 1357 } 1358 } 1359 try { 1360 return client.execute(method); 1361 } finally { 1362 synchronized(getSynchronizer()) { 1363 if (isPingCommand) { 1364 ExchangeService.runAwake(mMailboxId); 1365 } else { 1366 ExchangeService.clearWatchdogAlarm(mMailboxId); 1367 } 1368 mPendingPost = null; 1369 } 1370 } 1371 } 1372 1373 protected HttpResponse sendHttpClientPost(String cmd, HttpEntity entity, int timeout) 1374 throws IOException { 1375 HttpClient client = getHttpClient(timeout); 1376 boolean isPingCommand = cmd.equals(PING_COMMAND); 1377 1378 // Split the mail sending commands 1379 String extra = null; 1380 boolean msg = false; 1381 if (cmd.startsWith("SmartForward&") || cmd.startsWith("SmartReply&")) { 1382 int cmdLength = cmd.indexOf('&'); 1383 extra = cmd.substring(cmdLength); 1384 cmd = cmd.substring(0, cmdLength); 1385 msg = true; 1386 } else if (cmd.startsWith("SendMail&")) { 1387 msg = true; 1388 } 1389 1390 String us = makeUriString(cmd, extra); 1391 HttpPost method = new HttpPost(URI.create(us)); 1392 // Send the proper Content-Type header 1393 // If entity is null (e.g. for attachments), don't set this header 1394 if (msg) { 1395 method.setHeader("Content-Type", "message/rfc822"); 1396 } else if (entity != null) { 1397 method.setHeader("Content-Type", "application/vnd.ms-sync.wbxml"); 1398 } 1399 setHeaders(method, !cmd.equals(PING_COMMAND)); 1400 method.setEntity(entity); 1401 return executePostWithTimeout(client, method, timeout, isPingCommand); 1402 } 1403 1404 protected HttpResponse sendHttpClientOptions() throws IOException { 1405 HttpClient client = getHttpClient(COMMAND_TIMEOUT); 1406 String us = makeUriString("OPTIONS", null); 1407 HttpOptions method = new HttpOptions(URI.create(us)); 1408 setHeaders(method, false); 1409 return client.execute(method); 1410 } 1411 1412 String getTargetCollectionClassFromCursor(Cursor c) { 1413 int type = c.getInt(Mailbox.CONTENT_TYPE_COLUMN); 1414 if (type == Mailbox.TYPE_CONTACTS) { 1415 return "Contacts"; 1416 } else if (type == Mailbox.TYPE_CALENDAR) { 1417 return "Calendar"; 1418 } else { 1419 return "Email"; 1420 } 1421 } 1422 1423 /** 1424 * Negotiate provisioning with the server. First, get policies form the server and see if 1425 * the policies are supported by the device. Then, write the policies to the account and 1426 * tell SecurityPolicy that we have policies in effect. Finally, see if those policies are 1427 * active; if so, acknowledge the policies to the server and get a final policy key that we 1428 * use in future EAS commands and write this key to the account. 1429 * @return whether or not provisioning has been successful 1430 * @throws IOException 1431 */ 1432 private boolean tryProvision() throws IOException { 1433 // First, see if provisioning is even possible, i.e. do we support the policies required 1434 // by the server 1435 ProvisionParser pp = canProvision(); 1436 if (pp != null) { 1437 // Get the policies from ProvisionParser 1438 PolicySet ps = pp.getPolicySet(); 1439 // Update the account with a null policyKey (the key we've gotten is 1440 // temporary and cannot be used for syncing) 1441 ps.writeAccount(mAccount, null, true, mContext); 1442 // Make sure that SecurityPolicy is up-to-date 1443 SecurityPolicyDelegate.updatePolicies(mContext, mAccount.mId); 1444 if (pp.getRemoteWipe()) { 1445 // We've gotten a remote wipe command 1446 ExchangeService.alwaysLog("!!! Remote wipe request received"); 1447 // Start by setting the account to security hold 1448 SecurityPolicyDelegate.setAccountHoldFlag(mContext, mAccount, true); 1449 // Force a stop to any running syncs for this account (except this one) 1450 ExchangeService.stopNonAccountMailboxSyncsForAccount(mAccount.mId); 1451 1452 // If we're not the admin, we can't do the wipe, so just return 1453 if (!SecurityPolicyDelegate.isActiveAdmin(mContext)) { 1454 ExchangeService.alwaysLog("!!! Not device admin; can't wipe"); 1455 return false; 1456 } 1457 1458 // First, we've got to acknowledge it, but wrap the wipe in try/catch so that 1459 // we wipe the device regardless of any errors in acknowledgment 1460 try { 1461 ExchangeService.alwaysLog("!!! Acknowledging remote wipe to server"); 1462 acknowledgeRemoteWipe(pp.getPolicyKey()); 1463 } catch (Exception e) { 1464 // Because remote wipe is such a high priority task, we don't want to 1465 // circumvent it if there's an exception in acknowledgment 1466 } 1467 // Then, tell SecurityPolicy to wipe the device 1468 ExchangeService.alwaysLog("!!! Executing remote wipe"); 1469 SecurityPolicyDelegate.remoteWipe(mContext); 1470 return false; 1471 } else if (SecurityPolicyDelegate.isActive(mContext, ps)) { 1472 // See if the required policies are in force; if they are, acknowledge the policies 1473 // to the server and get the final policy key 1474 String policyKey = acknowledgeProvision(pp.getPolicyKey(), PROVISION_STATUS_OK); 1475 if (policyKey != null) { 1476 // Write the final policy key to the Account and say we've been successful 1477 ps.writeAccount(mAccount, policyKey, true, mContext); 1478 // Release any mailboxes that might be in a security hold 1479 ExchangeService.releaseSecurityHold(mAccount); 1480 return true; 1481 } 1482 } else { 1483 // Notify that we are blocked because of policies 1484 SecurityPolicyDelegate.policiesRequired(mContext, mAccount.mId); 1485 } 1486 } 1487 return false; 1488 } 1489 1490 private String getPolicyType() { 1491 return (mProtocolVersionDouble >= 1492 Eas.SUPPORTED_PROTOCOL_EX2007_DOUBLE) ? EAS_12_POLICY_TYPE : EAS_2_POLICY_TYPE; 1493 } 1494 1495 /** 1496 * Obtain a set of policies from the server and determine whether those policies are supported 1497 * by the device. 1498 * @return the ProvisionParser (holds policies and key) if we receive policies and they are 1499 * supported by the device; null otherwise 1500 * @throws IOException 1501 */ 1502 private ProvisionParser canProvision() throws IOException { 1503 Serializer s = new Serializer(); 1504 s.start(Tags.PROVISION_PROVISION).start(Tags.PROVISION_POLICIES); 1505 s.start(Tags.PROVISION_POLICY).data(Tags.PROVISION_POLICY_TYPE, getPolicyType()) 1506 .end().end().end().done(); 1507 HttpResponse resp = sendHttpClientPost("Provision", s.toByteArray()); 1508 HttpEntity entity = resp.getEntity(); 1509 try { 1510 int code = resp.getStatusLine().getStatusCode(); 1511 if (code == HttpStatus.SC_OK) { 1512 InputStream is = entity.getContent(); 1513 ProvisionParser pp = new ProvisionParser(is, this); 1514 if (pp.parse()) { 1515 // The PolicySet in the ProvisionParser will have the requirements for all KNOWN 1516 // policies. If others are required, hasSupportablePolicySet will be false 1517 if (pp.hasSupportablePolicySet()) { 1518 // If the policies are supportable (in this context, meaning there are no 1519 // completely unimplemented policies required), return the parser itself 1520 return pp; 1521 } else { 1522 // Try to acknowledge using the "partial" status (i.e. we can partially 1523 // accommodate the required policies). The server will agree to this if the 1524 // "allow non-provisionable devices" setting is enabled on the server 1525 String policyKey = acknowledgeProvision(pp.getPolicyKey(), 1526 PROVISION_STATUS_PARTIAL); 1527 // Return either the parser (success) or null (failure) 1528 if (policyKey != null) { 1529 pp.clearUnsupportedPolicies(); 1530 return pp; 1531 } else { 1532 return null; 1533 } 1534 } 1535 } 1536 } 1537 } finally { 1538 if (entity != null) { 1539 entity.consumeContent(); 1540 } 1541 } 1542 // On failures, simply return null 1543 return null; 1544 } 1545 1546 /** 1547 * Acknowledge that we support the policies provided by the server, and that these policies 1548 * are in force. 1549 * @param tempKey the initial (temporary) policy key sent by the server 1550 * @return the final policy key, which can be used for syncing 1551 * @throws IOException 1552 */ 1553 private void acknowledgeRemoteWipe(String tempKey) throws IOException { 1554 acknowledgeProvisionImpl(tempKey, PROVISION_STATUS_OK, true); 1555 } 1556 1557 private String acknowledgeProvision(String tempKey, String result) throws IOException { 1558 return acknowledgeProvisionImpl(tempKey, result, false); 1559 } 1560 1561 private String acknowledgeProvisionImpl(String tempKey, String status, 1562 boolean remoteWipe) throws IOException { 1563 Serializer s = new Serializer(); 1564 s.start(Tags.PROVISION_PROVISION).start(Tags.PROVISION_POLICIES); 1565 s.start(Tags.PROVISION_POLICY); 1566 1567 // Use the proper policy type, depending on EAS version 1568 s.data(Tags.PROVISION_POLICY_TYPE, getPolicyType()); 1569 1570 s.data(Tags.PROVISION_POLICY_KEY, tempKey); 1571 s.data(Tags.PROVISION_STATUS, status); 1572 s.end().end(); // PROVISION_POLICY, PROVISION_POLICIES 1573 if (remoteWipe) { 1574 s.start(Tags.PROVISION_REMOTE_WIPE); 1575 s.data(Tags.PROVISION_STATUS, PROVISION_STATUS_OK); 1576 s.end(); 1577 } 1578 s.end().done(); // PROVISION_PROVISION 1579 HttpResponse resp = sendHttpClientPost("Provision", s.toByteArray()); 1580 HttpEntity entity = resp.getEntity(); 1581 try { 1582 int code = resp.getStatusLine().getStatusCode(); 1583 if (code == HttpStatus.SC_OK) { 1584 InputStream is = entity.getContent(); 1585 ProvisionParser pp = new ProvisionParser(is, this); 1586 if (pp.parse()) { 1587 // Return the final policy key from the ProvisionParser 1588 return pp.getPolicyKey(); 1589 } 1590 } 1591 } finally { 1592 if (entity != null) { 1593 entity.consumeContent(); 1594 } 1595 } 1596 // On failures, return null 1597 return null; 1598 } 1599 1600 /** 1601 * Performs FolderSync 1602 * 1603 * @throws IOException 1604 * @throws EasParserException 1605 */ 1606 public void runAccountMailbox() throws IOException, EasParserException { 1607 // Initialize exit status to success 1608 mExitStatus = EXIT_DONE; 1609 try { 1610 try { 1611 ExchangeService.callback() 1612 .syncMailboxListStatus(mAccount.mId, EmailServiceStatus.IN_PROGRESS, 0); 1613 } catch (RemoteException e1) { 1614 // Don't care if this fails 1615 } 1616 1617 // Don't run if we're being held 1618 if ((mAccount.mFlags & Account.FLAGS_SECURITY_HOLD) != 0) { 1619 mExitStatus = EXIT_SECURITY_FAILURE; 1620 return; 1621 } 1622 1623 if (mAccount.mSyncKey == null) { 1624 mAccount.mSyncKey = "0"; 1625 userLog("Account syncKey INIT to 0"); 1626 ContentValues cv = new ContentValues(); 1627 cv.put(AccountColumns.SYNC_KEY, mAccount.mSyncKey); 1628 mAccount.update(mContext, cv); 1629 } 1630 1631 boolean firstSync = mAccount.mSyncKey.equals("0"); 1632 if (firstSync) { 1633 userLog("Initial FolderSync"); 1634 } 1635 1636 // When we first start up, change all mailboxes to push. 1637 ContentValues cv = new ContentValues(); 1638 cv.put(Mailbox.SYNC_INTERVAL, Mailbox.CHECK_INTERVAL_PUSH); 1639 if (mContentResolver.update(Mailbox.CONTENT_URI, cv, 1640 WHERE_ACCOUNT_AND_SYNC_INTERVAL_PING, 1641 new String[] {Long.toString(mAccount.mId)}) > 0) { 1642 ExchangeService.kick("change ping boxes to push"); 1643 } 1644 1645 // Determine our protocol version, if we haven't already and save it in the Account 1646 // Also re-check protocol version at least once a day (in case of upgrade) 1647 if (mAccount.mProtocolVersion == null || 1648 ((System.currentTimeMillis() - mMailbox.mSyncTime) > DAYS)) { 1649 userLog("Determine EAS protocol version"); 1650 HttpResponse resp = sendHttpClientOptions(); 1651 int code = resp.getStatusLine().getStatusCode(); 1652 userLog("OPTIONS response: ", code); 1653 if (code == HttpStatus.SC_OK) { 1654 Header header = resp.getFirstHeader("MS-ASProtocolCommands"); 1655 userLog(header.getValue()); 1656 header = resp.getFirstHeader("ms-asprotocolversions"); 1657 try { 1658 setupProtocolVersion(this, header); 1659 } catch (MessagingException e) { 1660 // Since we've already validated, this can't really happen 1661 // But if it does, we'll rethrow this... 1662 throw new IOException(); 1663 } 1664 // Save the protocol version 1665 cv.clear(); 1666 // Save the protocol version in the account; if we're using 12.0 or greater, 1667 // set the flag for support of SmartForward 1668 cv.put(Account.PROTOCOL_VERSION, mProtocolVersion); 1669 if (mProtocolVersionDouble >= 12.0) { 1670 cv.put(Account.FLAGS, 1671 mAccount.mFlags | Account.FLAGS_SUPPORTS_SMART_FORWARD); 1672 } 1673 mAccount.update(mContext, cv); 1674 cv.clear(); 1675 // Save the sync time of the account mailbox to current time 1676 cv.put(Mailbox.SYNC_TIME, System.currentTimeMillis()); 1677 mMailbox.update(mContext, cv); 1678 } else { 1679 errorLog("OPTIONS command failed; throwing IOException"); 1680 throw new IOException(); 1681 } 1682 } 1683 1684 // Change all pushable boxes to push when we start the account mailbox 1685 if (mAccount.mSyncInterval == Account.CHECK_INTERVAL_PUSH) { 1686 cv.clear(); 1687 cv.put(Mailbox.SYNC_INTERVAL, Mailbox.CHECK_INTERVAL_PUSH); 1688 if (mContentResolver.update(Mailbox.CONTENT_URI, cv, 1689 ExchangeService.WHERE_IN_ACCOUNT_AND_PUSHABLE, 1690 new String[] {Long.toString(mAccount.mId)}) > 0) { 1691 userLog("Push account; set pushable boxes to push..."); 1692 } 1693 } 1694 1695 while (!mStop) { 1696 userLog("Sending Account syncKey: ", mAccount.mSyncKey); 1697 Serializer s = new Serializer(); 1698 s.start(Tags.FOLDER_FOLDER_SYNC).start(Tags.FOLDER_SYNC_KEY) 1699 .text(mAccount.mSyncKey).end().end().done(); 1700 HttpResponse resp = sendHttpClientPost("FolderSync", s.toByteArray()); 1701 HttpEntity entity = resp.getEntity(); 1702 try { 1703 if (mStop) break; 1704 int code = resp.getStatusLine().getStatusCode(); 1705 if (code == HttpStatus.SC_OK) { 1706 int len = (int)entity.getContentLength(); 1707 if (len != 0) { 1708 InputStream is = entity.getContent(); 1709 // Returns true if we need to sync again 1710 if (new FolderSyncParser(is, new AccountSyncAdapter(this)) 1711 .parse()) { 1712 continue; 1713 } 1714 } 1715 } else if (isProvisionError(code)) { 1716 // If the sync error is a provisioning failure (perhaps policies changed), 1717 // let's try the provisioning procedure 1718 // Provisioning must only be attempted for the account mailbox - trying to 1719 // provision any other mailbox may result in race conditions and the 1720 // creation of multiple policy keys. 1721 if (!tryProvision()) { 1722 // Set the appropriate failure status 1723 mExitStatus = EXIT_SECURITY_FAILURE; 1724 return; 1725 } else { 1726 // If we succeeded, try again... 1727 continue; 1728 } 1729 } else if (isAuthError(code)) { 1730 mExitStatus = EXIT_LOGIN_FAILURE; 1731 return; 1732 } else { 1733 userLog("FolderSync response error: ", code); 1734 } 1735 } finally { 1736 if (entity != null) { 1737 entity.consumeContent(); 1738 } 1739 } 1740 1741 // Change all push/hold boxes to push 1742 cv.clear(); 1743 cv.put(Mailbox.SYNC_INTERVAL, Account.CHECK_INTERVAL_PUSH); 1744 if (mContentResolver.update(Mailbox.CONTENT_URI, cv, 1745 WHERE_PUSH_HOLD_NOT_ACCOUNT_MAILBOX, 1746 new String[] {Long.toString(mAccount.mId)}) > 0) { 1747 userLog("Set push/hold boxes to push..."); 1748 } 1749 1750 try { 1751 ExchangeService.callback() 1752 .syncMailboxListStatus(mAccount.mId, mExitStatus, 0); 1753 } catch (RemoteException e1) { 1754 // Don't care if this fails 1755 } 1756 1757 // Before each run of the pingLoop, if this Account has a PolicySet, make sure it's 1758 // active; otherwise, clear out the key/flag. This should cause a provisioning 1759 // error on the next POST, and start the security sequence over again 1760 String key = mAccount.mSecuritySyncKey; 1761 if (!TextUtils.isEmpty(key)) { 1762 PolicySet ps = new PolicySet(mAccount); 1763 if (!SecurityPolicyDelegate.isActive(mContext, ps)) { 1764 cv.clear(); 1765 cv.put(AccountColumns.SECURITY_FLAGS, 0); 1766 cv.putNull(AccountColumns.SECURITY_SYNC_KEY); 1767 long accountId = mAccount.mId; 1768 mContentResolver.update(ContentUris.withAppendedId( 1769 Account.CONTENT_URI, accountId), cv, null, null); 1770 SecurityPolicyDelegate.policiesRequired(mContext, accountId); 1771 } 1772 } 1773 1774 // Wait for push notifications. 1775 String threadName = Thread.currentThread().getName(); 1776 try { 1777 runPingLoop(); 1778 } catch (StaleFolderListException e) { 1779 // We break out if we get told about a stale folder list 1780 userLog("Ping interrupted; folder list requires sync..."); 1781 } catch (IllegalHeartbeatException e) { 1782 // If we're sending an illegal heartbeat, reset either the min or the max to 1783 // that heartbeat 1784 resetHeartbeats(e.mLegalHeartbeat); 1785 } finally { 1786 Thread.currentThread().setName(threadName); 1787 } 1788 } 1789 } catch (IOException e) { 1790 // We catch this here to send the folder sync status callback 1791 // A folder sync failed callback will get sent from run() 1792 try { 1793 if (!mStop) { 1794 // NOTE: The correct status is CONNECTION_ERROR, but the UI displays this, and 1795 // it's not really appropriate for EAS as this is not unexpected for a ping and 1796 // connection errors are retried in any case 1797 ExchangeService.callback() 1798 .syncMailboxListStatus(mAccount.mId, 1799 EmailServiceStatus.SUCCESS, 0); 1800 } 1801 } catch (RemoteException e1) { 1802 // Don't care if this fails 1803 } 1804 throw e; 1805 } 1806 } 1807 1808 /** 1809 * Reset either our minimum or maximum ping heartbeat to a heartbeat known to be legal 1810 * @param legalHeartbeat a known legal heartbeat (from the EAS server) 1811 */ 1812 /*package*/ void resetHeartbeats(int legalHeartbeat) { 1813 userLog("Resetting min/max heartbeat, legal = " + legalHeartbeat); 1814 // We are here because the current heartbeat (mPingHeartbeat) is invalid. Depending on 1815 // whether the argument is above or below the current heartbeat, we can infer the need to 1816 // change either the minimum or maximum heartbeat 1817 if (legalHeartbeat > mPingHeartbeat) { 1818 // The legal heartbeat is higher than the ping heartbeat; therefore, our minimum was 1819 // too low. We respond by raising either or both of the minimum heartbeat or the 1820 // force heartbeat to the argument value 1821 if (mPingMinHeartbeat < legalHeartbeat) { 1822 mPingMinHeartbeat = legalHeartbeat; 1823 } 1824 if (mPingForceHeartbeat < legalHeartbeat) { 1825 mPingForceHeartbeat = legalHeartbeat; 1826 } 1827 // If our minimum is now greater than the max, bring them together 1828 if (mPingMinHeartbeat > mPingMaxHeartbeat) { 1829 mPingMaxHeartbeat = legalHeartbeat; 1830 } 1831 } else if (legalHeartbeat < mPingHeartbeat) { 1832 // The legal heartbeat is lower than the ping heartbeat; therefore, our maximum was 1833 // too high. We respond by lowering the maximum to the argument value 1834 mPingMaxHeartbeat = legalHeartbeat; 1835 // If our maximum is now less than the minimum, bring them together 1836 if (mPingMaxHeartbeat < mPingMinHeartbeat) { 1837 mPingMinHeartbeat = legalHeartbeat; 1838 } 1839 } 1840 // Set current heartbeat to the legal heartbeat 1841 mPingHeartbeat = legalHeartbeat; 1842 // Allow the heartbeat logic to run 1843 mPingHeartbeatDropped = false; 1844 } 1845 1846 private void pushFallback(long mailboxId) { 1847 Mailbox mailbox = Mailbox.restoreMailboxWithId(mContext, mailboxId); 1848 if (mailbox == null) { 1849 return; 1850 } 1851 ContentValues cv = new ContentValues(); 1852 int mins = PING_FALLBACK_PIM; 1853 if (mailbox.mType == Mailbox.TYPE_INBOX) { 1854 mins = PING_FALLBACK_INBOX; 1855 } 1856 cv.put(Mailbox.SYNC_INTERVAL, mins); 1857 mContentResolver.update(ContentUris.withAppendedId(Mailbox.CONTENT_URI, mailboxId), 1858 cv, null, null); 1859 errorLog("*** PING ERROR LOOP: Set " + mailbox.mDisplayName + " to " + mins + " min sync"); 1860 ExchangeService.kick("push fallback"); 1861 } 1862 1863 /** 1864 * Simplistic attempt to determine a NAT timeout, based on experience with various carriers 1865 * and networks. The string "reset by peer" is very common in these situations, so we look for 1866 * that specifically. We may add additional tests here as more is learned. 1867 * @param message 1868 * @return whether this message is likely associated with a NAT failure 1869 */ 1870 private boolean isLikelyNatFailure(String message) { 1871 if (message == null) return false; 1872 if (message.contains("reset by peer")) { 1873 return true; 1874 } 1875 return false; 1876 } 1877 1878 private void runPingLoop() throws IOException, StaleFolderListException, 1879 IllegalHeartbeatException { 1880 int pingHeartbeat = mPingHeartbeat; 1881 userLog("runPingLoop"); 1882 // Do push for all sync services here 1883 long endTime = System.currentTimeMillis() + (30*MINUTES); 1884 HashMap<String, Integer> pingErrorMap = new HashMap<String, Integer>(); 1885 ArrayList<String> readyMailboxes = new ArrayList<String>(); 1886 ArrayList<String> notReadyMailboxes = new ArrayList<String>(); 1887 int pingWaitCount = 0; 1888 long inboxId = -1; 1889 1890 while ((System.currentTimeMillis() < endTime) && !mStop) { 1891 // Count of pushable mailboxes 1892 int pushCount = 0; 1893 // Count of mailboxes that can be pushed right now 1894 int canPushCount = 0; 1895 // Count of uninitialized boxes 1896 int uninitCount = 0; 1897 1898 Serializer s = new Serializer(); 1899 Cursor c = mContentResolver.query(Mailbox.CONTENT_URI, Mailbox.CONTENT_PROJECTION, 1900 MailboxColumns.ACCOUNT_KEY + '=' + mAccount.mId + 1901 AND_FREQUENCY_PING_PUSH_AND_NOT_ACCOUNT_MAILBOX, null, null); 1902 notReadyMailboxes.clear(); 1903 readyMailboxes.clear(); 1904 // Look for an inbox, and remember its id 1905 if (inboxId == -1) { 1906 inboxId = Mailbox.findMailboxOfType(mContext, mAccount.mId, Mailbox.TYPE_INBOX); 1907 } 1908 try { 1909 // Loop through our pushed boxes seeing what is available to push 1910 while (c.moveToNext()) { 1911 pushCount++; 1912 // Two requirements for push: 1913 // 1) ExchangeService tells us the mailbox is syncable (not running/not stopped) 1914 // 2) The syncKey isn't "0" (i.e. it's synced at least once) 1915 long mailboxId = c.getLong(Mailbox.CONTENT_ID_COLUMN); 1916 int pingStatus = ExchangeService.pingStatus(mailboxId); 1917 String mailboxName = c.getString(Mailbox.CONTENT_DISPLAY_NAME_COLUMN); 1918 if (pingStatus == ExchangeService.PING_STATUS_OK) { 1919 String syncKey = c.getString(Mailbox.CONTENT_SYNC_KEY_COLUMN); 1920 if ((syncKey == null) || syncKey.equals("0")) { 1921 // We can't push until the initial sync is done 1922 pushCount--; 1923 uninitCount++; 1924 continue; 1925 } 1926 1927 if (canPushCount++ == 0) { 1928 // Initialize the Ping command 1929 s.start(Tags.PING_PING) 1930 .data(Tags.PING_HEARTBEAT_INTERVAL, 1931 Integer.toString(pingHeartbeat)) 1932 .start(Tags.PING_FOLDERS); 1933 } 1934 1935 String folderClass = getTargetCollectionClassFromCursor(c); 1936 s.start(Tags.PING_FOLDER) 1937 .data(Tags.PING_ID, c.getString(Mailbox.CONTENT_SERVER_ID_COLUMN)) 1938 .data(Tags.PING_CLASS, folderClass) 1939 .end(); 1940 readyMailboxes.add(mailboxName); 1941 } else if ((pingStatus == ExchangeService.PING_STATUS_RUNNING) || 1942 (pingStatus == ExchangeService.PING_STATUS_WAITING)) { 1943 notReadyMailboxes.add(mailboxName); 1944 } else if (pingStatus == ExchangeService.PING_STATUS_UNABLE) { 1945 pushCount--; 1946 userLog(mailboxName, " in error state; ignore"); 1947 continue; 1948 } 1949 } 1950 } finally { 1951 c.close(); 1952 } 1953 1954 if (Eas.USER_LOG) { 1955 if (!notReadyMailboxes.isEmpty()) { 1956 userLog("Ping not ready for: " + notReadyMailboxes); 1957 } 1958 if (!readyMailboxes.isEmpty()) { 1959 userLog("Ping ready for: " + readyMailboxes); 1960 } 1961 } 1962 1963 // If we've waited 10 seconds or more, just ping with whatever boxes are ready 1964 // But use a shorter than normal heartbeat 1965 boolean forcePing = !notReadyMailboxes.isEmpty() && (pingWaitCount > 5); 1966 1967 if ((canPushCount > 0) && ((canPushCount == pushCount) || forcePing)) { 1968 // If all pingable boxes are ready for push, send Ping to the server 1969 s.end().end().done(); 1970 pingWaitCount = 0; 1971 mPostReset = false; 1972 mPostAborted = false; 1973 1974 // If we've been stopped, this is a good time to return 1975 if (mStop) return; 1976 1977 long pingTime = SystemClock.elapsedRealtime(); 1978 try { 1979 // Send the ping, wrapped by appropriate timeout/alarm 1980 if (forcePing) { 1981 userLog("Forcing ping after waiting for all boxes to be ready"); 1982 } 1983 HttpResponse res = 1984 sendPing(s.toByteArray(), forcePing ? mPingForceHeartbeat : pingHeartbeat); 1985 HttpEntity entity = res.getEntity(); 1986 1987 try { 1988 int code = res.getStatusLine().getStatusCode(); 1989 userLog("Ping response: ", code); 1990 1991 // Return immediately if we've been asked to stop during the ping 1992 if (mStop) { 1993 userLog("Stopping pingLoop"); 1994 return; 1995 } 1996 1997 if (code == HttpStatus.SC_OK) { 1998 // Make sure to clear out any pending sync errors 1999 ExchangeService.removeFromSyncErrorMap(mMailboxId); 2000 int len = (int)entity.getContentLength(); 2001 InputStream is = entity.getContent(); 2002 if (len != 0) { 2003 int pingResult = parsePingResult(is, mContentResolver, 2004 pingErrorMap); 2005 // If our ping completed (status = 1), and wasn't forced and we're 2006 // not at the maximum, try increasing timeout by two minutes 2007 if (pingResult == PROTOCOL_PING_STATUS_COMPLETED && !forcePing) { 2008 if (pingHeartbeat > mPingHighWaterMark) { 2009 mPingHighWaterMark = pingHeartbeat; 2010 userLog("Setting high water mark at: ", mPingHighWaterMark); 2011 } 2012 if ((pingHeartbeat < mPingMaxHeartbeat) && 2013 !mPingHeartbeatDropped) { 2014 pingHeartbeat += PING_HEARTBEAT_INCREMENT; 2015 if (pingHeartbeat > mPingMaxHeartbeat) { 2016 pingHeartbeat = mPingMaxHeartbeat; 2017 } 2018 userLog("Increase ping heartbeat to ", pingHeartbeat, "s"); 2019 } 2020 } 2021 } else { 2022 userLog("Ping returned empty result; throwing IOException"); 2023 throw new IOException(); 2024 } 2025 } else if (isAuthError(code)) { 2026 mExitStatus = EXIT_LOGIN_FAILURE; 2027 userLog("Authorization error during Ping: ", code); 2028 throw new IOException(); 2029 } 2030 } finally { 2031 if (entity != null) { 2032 entity.consumeContent(); 2033 } 2034 } 2035 } catch (IOException e) { 2036 String message = e.getMessage(); 2037 // If we get the exception that is indicative of a NAT timeout and if we 2038 // haven't yet "fixed" the timeout, back off by two minutes and "fix" it 2039 boolean hasMessage = message != null; 2040 userLog("IOException runPingLoop: " + (hasMessage ? message : "[no message]")); 2041 if (mPostReset) { 2042 // Nothing to do in this case; this is ExchangeService telling us to try 2043 // another ping. 2044 } else if (mPostAborted || isLikelyNatFailure(message)) { 2045 long pingLength = SystemClock.elapsedRealtime() - pingTime; 2046 if ((pingHeartbeat > mPingMinHeartbeat) && 2047 (pingHeartbeat > mPingHighWaterMark)) { 2048 pingHeartbeat -= PING_HEARTBEAT_INCREMENT; 2049 mPingHeartbeatDropped = true; 2050 if (pingHeartbeat < mPingMinHeartbeat) { 2051 pingHeartbeat = mPingMinHeartbeat; 2052 } 2053 userLog("Decreased ping heartbeat to ", pingHeartbeat, "s"); 2054 } else if (mPostAborted) { 2055 // There's no point in throwing here; this can happen in two cases 2056 // 1) An alarm, which indicates minutes without activity; no sense 2057 // backing off 2058 // 2) ExchangeService abort, due to sync of mailbox. Again, we want to 2059 // keep on trying to ping 2060 userLog("Ping aborted; retry"); 2061 } else if (pingLength < 2000) { 2062 userLog("Abort or NAT type return < 2 seconds; throwing IOException"); 2063 throw e; 2064 } else { 2065 userLog("NAT type IOException"); 2066 } 2067 } else if (hasMessage && message.contains("roken pipe")) { 2068 // The "broken pipe" error (uppercase or lowercase "b") seems to be an 2069 // internal error, so let's not throw an exception (which leads to delays) 2070 // but rather simply run through the loop again 2071 } else { 2072 throw e; 2073 } 2074 } 2075 } else if (forcePing) { 2076 // In this case, there aren't any boxes that are pingable, but there are boxes 2077 // waiting (for IOExceptions) 2078 userLog("pingLoop waiting 60s for any pingable boxes"); 2079 sleep(60*SECONDS, true); 2080 } else if (pushCount > 0) { 2081 // If we want to Ping, but can't just yet, wait a little bit 2082 // TODO Change sleep to wait and use notify from ExchangeService when a sync ends 2083 sleep(2*SECONDS, false); 2084 pingWaitCount++; 2085 //userLog("pingLoop waited 2s for: ", (pushCount - canPushCount), " box(es)"); 2086 } else if (uninitCount > 0) { 2087 // In this case, we're doing an initial sync of at least one mailbox. Since this 2088 // is typically a one-time case, I'm ok with trying again every 10 seconds until 2089 // we're in one of the other possible states. 2090 userLog("pingLoop waiting for initial sync of ", uninitCount, " box(es)"); 2091 sleep(10*SECONDS, true); 2092 } else if (inboxId == -1) { 2093 // In this case, we're still syncing mailboxes, so sleep for only a short time 2094 sleep(45*SECONDS, true); 2095 } else { 2096 // We've got nothing to do, so we'll check again in 20 minutes at which time 2097 // we'll update the folder list, check for policy changes and/or remote wipe, etc. 2098 // Let the device sleep in the meantime... 2099 userLog(ACCOUNT_MAILBOX_SLEEP_TEXT); 2100 sleep(ACCOUNT_MAILBOX_SLEEP_TIME, true); 2101 } 2102 } 2103 2104 // Save away the current heartbeat 2105 mPingHeartbeat = pingHeartbeat; 2106 } 2107 2108 private void sleep(long ms, boolean runAsleep) { 2109 if (runAsleep) { 2110 ExchangeService.runAsleep(mMailboxId, ms+(5*SECONDS)); 2111 } 2112 try { 2113 Thread.sleep(ms); 2114 } catch (InterruptedException e) { 2115 // Doesn't matter whether we stop early; it's the thought that counts 2116 } finally { 2117 if (runAsleep) { 2118 ExchangeService.runAwake(mMailboxId); 2119 } 2120 } 2121 } 2122 2123 private int parsePingResult(InputStream is, ContentResolver cr, 2124 HashMap<String, Integer> errorMap) 2125 throws IOException, StaleFolderListException, IllegalHeartbeatException { 2126 PingParser pp = new PingParser(is, this); 2127 if (pp.parse()) { 2128 // True indicates some mailboxes need syncing... 2129 // syncList has the serverId's of the mailboxes... 2130 mBindArguments[0] = Long.toString(mAccount.mId); 2131 mPingChangeList = pp.getSyncList(); 2132 for (String serverId: mPingChangeList) { 2133 mBindArguments[1] = serverId; 2134 Cursor c = cr.query(Mailbox.CONTENT_URI, Mailbox.CONTENT_PROJECTION, 2135 WHERE_ACCOUNT_KEY_AND_SERVER_ID, mBindArguments, null); 2136 try { 2137 if (c.moveToFirst()) { 2138 2139 /** 2140 * Check the boxes reporting changes to see if there really were any... 2141 * We do this because bugs in various Exchange servers can put us into a 2142 * looping behavior by continually reporting changes in a mailbox, even when 2143 * there aren't any. 2144 * 2145 * This behavior is seemingly random, and therefore we must code defensively 2146 * by backing off of push behavior when it is detected. 2147 * 2148 * One known cause, on certain Exchange 2003 servers, is acknowledged by 2149 * Microsoft, and the server hotfix for this case can be found at 2150 * http://support.microsoft.com/kb/923282 2151 */ 2152 2153 // Check the status of the last sync 2154 String status = c.getString(Mailbox.CONTENT_SYNC_STATUS_COLUMN); 2155 int type = ExchangeService.getStatusType(status); 2156 // This check should always be true... 2157 if (type == ExchangeService.SYNC_PING) { 2158 int changeCount = ExchangeService.getStatusChangeCount(status); 2159 if (changeCount > 0) { 2160 errorMap.remove(serverId); 2161 } else if (changeCount == 0) { 2162 // This means that a ping reported changes in error; we keep a count 2163 // of consecutive errors of this kind 2164 String name = c.getString(Mailbox.CONTENT_DISPLAY_NAME_COLUMN); 2165 Integer failures = errorMap.get(serverId); 2166 if (failures == null) { 2167 userLog("Last ping reported changes in error for: ", name); 2168 errorMap.put(serverId, 1); 2169 } else if (failures > MAX_PING_FAILURES) { 2170 // We'll back off of push for this box 2171 pushFallback(c.getLong(Mailbox.CONTENT_ID_COLUMN)); 2172 continue; 2173 } else { 2174 userLog("Last ping reported changes in error for: ", name); 2175 errorMap.put(serverId, failures + 1); 2176 } 2177 } 2178 } 2179 2180 // If there were no problems with previous sync, we'll start another one 2181 ExchangeService.startManualSync(c.getLong(Mailbox.CONTENT_ID_COLUMN), 2182 ExchangeService.SYNC_PING, null); 2183 } 2184 } finally { 2185 c.close(); 2186 } 2187 } 2188 } 2189 return pp.getSyncStatus(); 2190 } 2191 2192 /** 2193 * Common code to sync E+PIM data 2194 * 2195 * @param target an EasMailbox, EasContacts, or EasCalendar object 2196 */ 2197 public void sync(AbstractSyncAdapter target) throws IOException { 2198 Mailbox mailbox = target.mMailbox; 2199 2200 boolean moreAvailable = true; 2201 int loopingCount = 0; 2202 while (!mStop && (moreAvailable || hasPendingRequests())) { 2203 // If we have no connectivity, just exit cleanly. ExchangeService will start us up again 2204 // when connectivity has returned 2205 if (!hasConnectivity()) { 2206 userLog("No connectivity in sync; finishing sync"); 2207 mExitStatus = EXIT_DONE; 2208 return; 2209 } 2210 2211 // Every time through the loop we check to see if we're still syncable 2212 if (!target.isSyncable()) { 2213 mExitStatus = EXIT_DONE; 2214 return; 2215 } 2216 2217 // Now, handle various requests 2218 while (true) { 2219 Request req = null; 2220 2221 if (mRequestQueue.isEmpty()) { 2222 break; 2223 } else { 2224 req = mRequestQueue.peek(); 2225 } 2226 2227 // Our two request types are PartRequest (loading attachment) and 2228 // MeetingResponseRequest (respond to a meeting request) 2229 if (req instanceof PartRequest) { 2230 loadAttachment((PartRequest)req); 2231 } else if (req instanceof MeetingResponseRequest) { 2232 sendMeetingResponse((MeetingResponseRequest)req); 2233 } else if (req instanceof MessageMoveRequest) { 2234 messageMoveRequest((MessageMoveRequest)req); 2235 } 2236 2237 // If there's an exception handling the request, we'll throw it 2238 // Otherwise, we remove the request 2239 mRequestQueue.remove(); 2240 } 2241 2242 // Don't sync if we've got nothing to do 2243 if (!moreAvailable) { 2244 continue; 2245 } 2246 2247 Serializer s = new Serializer(); 2248 2249 String className = target.getCollectionName(); 2250 String syncKey = target.getSyncKey(); 2251 userLog("sync, sending ", className, " syncKey: ", syncKey); 2252 s.start(Tags.SYNC_SYNC) 2253 .start(Tags.SYNC_COLLECTIONS) 2254 .start(Tags.SYNC_COLLECTION); 2255 // The "Class" element is removed in EAS 12.1 and later versions 2256 if (mProtocolVersionDouble < Eas.SUPPORTED_PROTOCOL_EX2007_SP1_DOUBLE) { 2257 s.data(Tags.SYNC_CLASS, className); 2258 } 2259 s.data(Tags.SYNC_SYNC_KEY, syncKey) 2260 .data(Tags.SYNC_COLLECTION_ID, mailbox.mServerId); 2261 2262 // Start with the default timeout 2263 int timeout = COMMAND_TIMEOUT; 2264 if (!syncKey.equals("0")) { 2265 // EAS doesn't allow GetChanges in an initial sync; sending other options 2266 // appears to cause the server to delay its response in some cases, and this delay 2267 // can be long enough to result in an IOException and total failure to sync. 2268 // Therefore, we don't send any options with the initial sync. 2269 // Set the truncation amount, body preference, lookback, etc. 2270 target.sendSyncOptions(mProtocolVersionDouble, s); 2271 } else { 2272 // Use enormous timeout for initial sync, which empirically can take a while longer 2273 timeout = 120*SECONDS; 2274 } 2275 // Send our changes up to the server 2276 target.sendLocalChanges(s); 2277 2278 s.end().end().end().done(); 2279 HttpResponse resp = sendHttpClientPost("Sync", new ByteArrayEntity(s.toByteArray()), 2280 timeout); 2281 HttpEntity entity = resp.getEntity(); 2282 try { 2283 int code = resp.getStatusLine().getStatusCode(); 2284 if (code == HttpStatus.SC_OK) { 2285 // In EAS 12.1, we can get "empty" sync responses, which indicate that there are 2286 // no changes in the mailbox; handle that case here 2287 Header header = resp.getFirstHeader("content-length"); 2288 if (header != null && header.getValue().equals("0")) { 2289 // If this happens, exit cleanly, and change the interval from push to ping 2290 // if necessary 2291 userLog("Empty sync response; finishing"); 2292 if (mMailbox.mSyncInterval == Mailbox.CHECK_INTERVAL_PUSH) { 2293 userLog("Changing mailbox from push to ping"); 2294 ContentValues cv = new ContentValues(); 2295 cv.put(Mailbox.SYNC_INTERVAL, Mailbox.CHECK_INTERVAL_PING); 2296 mContentResolver.update( 2297 ContentUris.withAppendedId(Mailbox.CONTENT_URI, mMailbox.mId), 2298 cv, null, null); 2299 } 2300 if (mRequestQueue.isEmpty()) { 2301 mExitStatus = EXIT_DONE; 2302 return; 2303 } else { 2304 continue; 2305 } 2306 } 2307 InputStream is = entity.getContent(); 2308 if (is != null) { 2309 moreAvailable = target.parse(is); 2310 if (target.isLooping()) { 2311 loopingCount++; 2312 userLog("** Looping: " + loopingCount); 2313 // After the maximum number of loops, we'll set moreAvailable to false 2314 // and allow the sync loop to terminate 2315 if (moreAvailable && (loopingCount > MAX_LOOPING_COUNT)) { 2316 userLog("** Looping force stopped"); 2317 moreAvailable = false; 2318 } 2319 } else { 2320 loopingCount = 0; 2321 } 2322 target.cleanup(); 2323 } else { 2324 userLog("Empty input stream in sync command response"); 2325 } 2326 } else { 2327 userLog("Sync response error: ", code); 2328 if (isProvisionError(code)) { 2329 mExitStatus = EXIT_SECURITY_FAILURE; 2330 } else if (isAuthError(code)) { 2331 mExitStatus = EXIT_LOGIN_FAILURE; 2332 } else { 2333 mExitStatus = EXIT_IO_ERROR; 2334 } 2335 return; 2336 } 2337 } finally { 2338 if (entity != null) { 2339 entity.consumeContent(); 2340 } 2341 } 2342 } 2343 mExitStatus = EXIT_DONE; 2344 } 2345 2346 protected boolean setupService() { 2347 // Make sure account and mailbox are always the latest from the database 2348 mAccount = Account.restoreAccountWithId(mContext, mAccount.mId); 2349 if (mAccount == null) return false; 2350 mMailbox = Mailbox.restoreMailboxWithId(mContext, mMailbox.mId); 2351 if (mMailbox == null) return false; 2352 mThread = Thread.currentThread(); 2353 android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_BACKGROUND); 2354 TAG = mThread.getName(); 2355 2356 HostAuth ha = HostAuth.restoreHostAuthWithId(mContext, mAccount.mHostAuthKeyRecv); 2357 if (ha == null) return false; 2358 mHostAddress = ha.mAddress; 2359 mUserName = ha.mLogin; 2360 mPassword = ha.mPassword; 2361 2362 // Set up our protocol version from the Account 2363 mProtocolVersion = mAccount.mProtocolVersion; 2364 // If it hasn't been set up, start with default version 2365 if (mProtocolVersion == null) { 2366 mProtocolVersion = Eas.DEFAULT_PROTOCOL_VERSION; 2367 } 2368 mProtocolVersionDouble = Eas.getProtocolVersionDouble(mProtocolVersion); 2369 return true; 2370 } 2371 2372 /* (non-Javadoc) 2373 * @see java.lang.Runnable#run() 2374 */ 2375 public void run() { 2376 if (!setupService()) return; 2377 if (mSyncReason >= ExchangeService.SYNC_CALLBACK_START) { 2378 try { 2379 ExchangeService.callback().syncMailboxStatus(mMailboxId, 2380 EmailServiceStatus.IN_PROGRESS, 0); 2381 } catch (RemoteException e1) { 2382 // Don't care if this fails 2383 } 2384 } 2385 2386 // Whether or not we're the account mailbox 2387 try { 2388 mDeviceId = ExchangeService.getDeviceId(mContext); 2389 if ((mMailbox == null) || (mAccount == null)) { 2390 return; 2391 } else if (mMailbox.mType == Mailbox.TYPE_EAS_ACCOUNT_MAILBOX) { 2392 runAccountMailbox(); 2393 } else { 2394 AbstractSyncAdapter target; 2395 if (mMailbox.mType == Mailbox.TYPE_CONTACTS) { 2396 target = new ContactsSyncAdapter( this); 2397 } else if (mMailbox.mType == Mailbox.TYPE_CALENDAR) { 2398 target = new CalendarSyncAdapter(this); 2399 } else { 2400 target = new EmailSyncAdapter(this); 2401 } 2402 // We loop here because someone might have put a request in while we were syncing 2403 // and we've missed that opportunity... 2404 do { 2405 if (mRequestTime != 0) { 2406 userLog("Looping for user request..."); 2407 mRequestTime = 0; 2408 } 2409 sync(target); 2410 } while (mRequestTime != 0); 2411 } 2412 } catch (EasAuthenticationException e) { 2413 userLog("Caught authentication error"); 2414 mExitStatus = EXIT_LOGIN_FAILURE; 2415 } catch (IOException e) { 2416 String message = e.getMessage(); 2417 userLog("Caught IOException: ", (message == null) ? "No message" : message); 2418 mExitStatus = EXIT_IO_ERROR; 2419 } catch (Exception e) { 2420 userLog("Uncaught exception in EasSyncService", e); 2421 } finally { 2422 int status; 2423 2424 if (!mStop) { 2425 userLog("Sync finished"); 2426 ExchangeService.done(this); 2427 switch (mExitStatus) { 2428 case EXIT_IO_ERROR: 2429 status = EmailServiceStatus.CONNECTION_ERROR; 2430 break; 2431 case EXIT_DONE: 2432 status = EmailServiceStatus.SUCCESS; 2433 ContentValues cv = new ContentValues(); 2434 cv.put(Mailbox.SYNC_TIME, System.currentTimeMillis()); 2435 String s = "S" + mSyncReason + ':' + status + ':' + mChangeCount; 2436 cv.put(Mailbox.SYNC_STATUS, s); 2437 mContentResolver.update(ContentUris.withAppendedId(Mailbox.CONTENT_URI, 2438 mMailboxId), cv, null, null); 2439 break; 2440 case EXIT_LOGIN_FAILURE: 2441 status = EmailServiceStatus.LOGIN_FAILED; 2442 break; 2443 case EXIT_SECURITY_FAILURE: 2444 status = EmailServiceStatus.SECURITY_FAILURE; 2445 // Ask for a new folder list. This should wake up the account mailbox; a 2446 // security error in account mailbox should start the provisioning process 2447 ExchangeService.reloadFolderList(mContext, mAccount.mId, true); 2448 break; 2449 default: 2450 status = EmailServiceStatus.REMOTE_EXCEPTION; 2451 errorLog("Sync ended due to an exception."); 2452 break; 2453 } 2454 } else { 2455 userLog("Stopped sync finished."); 2456 status = EmailServiceStatus.SUCCESS; 2457 } 2458 2459 // Send a callback if this run was initiated by a service call 2460 if (mSyncReason >= ExchangeService.SYNC_CALLBACK_START) { 2461 try { 2462 // Unless the user specifically asked for a sync, we really don't want to report 2463 // connection issues, as they are likely to be transient. In this case, we 2464 // simply report success, so that the progress indicator terminates without 2465 // putting up an error banner 2466 if (mSyncReason != ExchangeService.SYNC_UI_REQUEST && 2467 status == EmailServiceStatus.CONNECTION_ERROR) { 2468 status = EmailServiceStatus.SUCCESS; 2469 } 2470 ExchangeService.callback().syncMailboxStatus(mMailboxId, status, 0); 2471 } catch (RemoteException e1) { 2472 // Don't care if this fails 2473 } 2474 } 2475 2476 // Make sure ExchangeService knows about this 2477 ExchangeService.kick("sync finished"); 2478 } 2479 } 2480} 2481