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