Home | History | Annotate | Download | only in exchange
      1 /*
      2  * Copyright (C) 2011 The Android Open Source Project
      3  *
      4  * Licensed under the Apache License, Version 2.0 (the "License");
      5  * you may not use this file except in compliance with the License.
      6  * You may obtain a copy of the License at
      7  *
      8  *      http://www.apache.org/licenses/LICENSE-2.0
      9  *
     10  * Unless required by applicable law or agreed to in writing, software
     11  * distributed under the License is distributed on an "AS IS" BASIS,
     12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     13  * See the License for the specific language governing permissions and
     14  * limitations under the License.
     15  */
     16 
     17 package com.android.exchange;
     18 
     19 import android.content.ContentResolver;
     20 import android.content.ContentUris;
     21 import android.content.ContentValues;
     22 import android.content.Context;
     23 import android.database.Cursor;
     24 import android.net.TrafficStats;
     25 import android.os.RemoteException;
     26 import android.os.SystemClock;
     27 import android.provider.CalendarContract;
     28 import android.provider.ContactsContract;
     29 import android.text.TextUtils;
     30 import android.util.Log;
     31 
     32 import com.android.emailcommon.TrafficFlags;
     33 import com.android.emailcommon.mail.MessagingException;
     34 import com.android.emailcommon.provider.Account;
     35 import com.android.emailcommon.provider.EmailContent;
     36 import com.android.emailcommon.provider.EmailContent.AccountColumns;
     37 import com.android.emailcommon.provider.EmailContent.HostAuthColumns;
     38 import com.android.emailcommon.provider.EmailContent.MailboxColumns;
     39 import com.android.emailcommon.provider.HostAuth;
     40 import com.android.emailcommon.provider.Mailbox;
     41 import com.android.emailcommon.provider.Policy;
     42 import com.android.emailcommon.provider.ProviderUnavailableException;
     43 import com.android.emailcommon.service.EmailServiceStatus;
     44 import com.android.emailcommon.service.PolicyServiceProxy;
     45 import com.android.exchange.CommandStatusException.CommandStatus;
     46 import com.android.exchange.adapter.AccountSyncAdapter;
     47 import com.android.exchange.adapter.FolderSyncParser;
     48 import com.android.exchange.adapter.Parser.EasParserException;
     49 import com.android.exchange.adapter.PingParser;
     50 import com.android.exchange.adapter.Serializer;
     51 import com.android.exchange.adapter.Tags;
     52 import com.android.exchange.provider.MailboxUtilities;
     53 import com.google.common.annotations.VisibleForTesting;
     54 
     55 import org.apache.http.Header;
     56 import org.apache.http.HttpStatus;
     57 import org.apache.http.entity.ByteArrayEntity;
     58 
     59 import java.io.IOException;
     60 import java.io.InputStream;
     61 import java.util.ArrayList;
     62 import java.util.HashMap;
     63 
     64 /**
     65  * AccountMailbox handles sync for the EAS "account mailbox"; this includes sync of the mailbox list
     66  * as well as management of mailbox push (using the EAS "Ping" command
     67  */
     68 public class EasAccountService extends EasSyncService {
     69     private static final String WHERE_ACCOUNT_AND_SYNC_INTERVAL_PING =
     70         MailboxColumns.ACCOUNT_KEY + "=? and " + MailboxColumns.SYNC_INTERVAL +
     71         '=' + Mailbox.CHECK_INTERVAL_PING;
     72     private static final String AND_FREQUENCY_PING_PUSH_AND_NOT_ACCOUNT_MAILBOX = " AND " +
     73         MailboxColumns.SYNC_INTERVAL + " IN (" + Mailbox.CHECK_INTERVAL_PING +
     74         ',' + Mailbox.CHECK_INTERVAL_PUSH + ") AND " + MailboxColumns.TYPE + "!=\"" +
     75         Mailbox.TYPE_EAS_ACCOUNT_MAILBOX + '\"';
     76     private static final String WHERE_PUSH_HOLD_NOT_ACCOUNT_MAILBOX =
     77         MailboxColumns.ACCOUNT_KEY + "=? and " + MailboxColumns.SYNC_INTERVAL +
     78         '=' + Mailbox.CHECK_INTERVAL_PUSH_HOLD;
     79     private static final String WHERE_ACCOUNT_KEY_AND_SERVER_ID =
     80         MailboxColumns.ACCOUNT_KEY + "=? and " + MailboxColumns.SERVER_ID + "=?";
     81 
     82     /**
     83      * We start with an 8 minute timeout, and increase/decrease by 3 minutes at a time.  There's
     84      * no point having a timeout shorter than 5 minutes, I think; at that point, we can just let
     85      * the ping exception out.  The maximum I use is 17 minutes, which is really an empirical
     86      * choice; too long and we risk silent connection loss and loss of push for that period.  Too
     87      * short and we lose efficiency/battery life.
     88      *
     89      * If we ever have to drop the ping timeout, we'll never increase it again.  There's no point
     90      * going into hysteresis; the NAT timeout isn't going to change without a change in connection,
     91      * which will cause the sync service to be restarted at the starting heartbeat and going through
     92      * the process again.
     93      */
     94     static private final int PING_MINUTES = 60; // in seconds
     95     static private final int PING_FUDGE_LOW = 10;
     96     static private final int PING_STARTING_HEARTBEAT = (8*PING_MINUTES)-PING_FUDGE_LOW;
     97     static private final int PING_HEARTBEAT_INCREMENT = 3*PING_MINUTES;
     98 
     99     static private final int PROTOCOL_PING_STATUS_COMPLETED = 1;
    100     static private final int PROTOCOL_PING_STATUS_BAD_PARAMETERS = 3;
    101     static private final int PROTOCOL_PING_STATUS_RETRY = 8;
    102 
    103     // Fallbacks (in minutes) for ping loop failures
    104     static private final int MAX_PING_FAILURES = 1;
    105     static private final int PING_FALLBACK_INBOX = 5;
    106     static private final int PING_FALLBACK_PIM = 25;
    107 
    108     // The amount of time the account mailbox will sleep if there are no pingable mailboxes
    109     // This could happen if the sync time is set to "never"; we always want to check in from time
    110     // to time, however, for folder list/policy changes
    111     static private final int ACCOUNT_MAILBOX_SLEEP_TIME = 20*MINUTES;
    112     static private final String ACCOUNT_MAILBOX_SLEEP_TEXT =
    113         "Account mailbox sleeping for " + (ACCOUNT_MAILBOX_SLEEP_TIME / MINUTES) + "m";
    114 
    115     // Our heartbeat when we are waiting for ping boxes to be ready
    116     /*package*/ int mPingForceHeartbeat = 2*PING_MINUTES;
    117     // The minimum heartbeat we will send
    118     /*package*/ int mPingMinHeartbeat = (5*PING_MINUTES)-PING_FUDGE_LOW;
    119     // The maximum heartbeat we will send
    120     /*package*/ int mPingMaxHeartbeat = (17*PING_MINUTES)-PING_FUDGE_LOW;
    121     // The ping time (in seconds)
    122     /*package*/ int mPingHeartbeat = PING_STARTING_HEARTBEAT;
    123     // The longest successful ping heartbeat
    124     private int mPingHighWaterMark = 0;
    125     // Whether we've ever lowered the heartbeat
    126     /*package*/ boolean mPingHeartbeatDropped = false;
    127 
    128     private final String[] mBindArguments = new String[2];
    129     private ArrayList<String> mPingChangeList;
    130 
    131     protected EasAccountService(Context _context, Mailbox _mailbox) {
    132         super(_context, _mailbox);
    133     }
    134 
    135     @VisibleForTesting
    136     protected EasAccountService() {
    137     }
    138 
    139     @Override
    140     public void run() {
    141         mExitStatus = EXIT_DONE;
    142         try {
    143             // Make sure account and mailbox are still valid
    144             if (!setupService()) return;
    145             // If we've been stopped, we're done
    146             if (mStop) return;
    147 
    148             try {
    149                 mDeviceId = ExchangeService.getDeviceId(mContext);
    150                 int trafficFlags = TrafficFlags.getSyncFlags(mContext, mAccount);
    151                 TrafficStats.setThreadStatsTag(trafficFlags | TrafficFlags.DATA_EMAIL);
    152                 if ((mMailbox == null) || (mAccount == null)) {
    153                     return;
    154                 } else {
    155                     sync();
    156                 }
    157             } catch (EasAuthenticationException e) {
    158                 userLog("Caught authentication error");
    159                 mExitStatus = EXIT_LOGIN_FAILURE;
    160             } catch (IOException e) {
    161                 String message = e.getMessage();
    162                 userLog("Caught IOException: ", (message == null) ? "No message" : message);
    163                 mExitStatus = EXIT_IO_ERROR;
    164             } catch (Exception e) {
    165                 userLog("Uncaught exception in AccountMailboxService", e);
    166             } finally {
    167                 ExchangeService.done(this);
    168                 if (!mStop) {
    169                     userLog("Sync finished");
    170                     switch (mExitStatus) {
    171                         case EXIT_SECURITY_FAILURE:
    172                             // Ask for a new folder list. This should wake up the account mailbox; a
    173                             // security error in account mailbox should start provisioning
    174                             ExchangeService.reloadFolderList(mContext, mAccount.mId, true);
    175                             break;
    176                         case EXIT_EXCEPTION:
    177                             errorLog("Sync ended due to an exception.");
    178                             break;
    179                     }
    180                 } else {
    181                     userLog("Stopped sync finished.");
    182                 }
    183 
    184                 // Make sure ExchangeService knows about this
    185                 ExchangeService.kick("sync finished");
    186             }
    187         } catch (ProviderUnavailableException e) {
    188             Log.e(TAG, "EmailProvider unavailable; sync ended prematurely");
    189         }
    190     }
    191 
    192     /**
    193      * If possible, update the account to the new server address; report result
    194      * @param resp the EasResponse from the current POST
    195      * @return whether or not the redirect is handled and the POST should be retried
    196      */
    197     private boolean canHandleAccountMailboxRedirect(EasResponse resp) {
    198         userLog("AccountMailbox redirect error");
    199         HostAuth ha =
    200                 HostAuth.restoreHostAuthWithId(mContext, mAccount.mHostAuthKeyRecv);
    201         if (ha != null && getValidateRedirect(resp, ha)) {
    202             // Update the account's HostAuth with new values
    203             ContentValues haValues = new ContentValues();
    204             haValues.put(HostAuthColumns.ADDRESS, ha.mAddress);
    205             ha.update(mContext, haValues);
    206             return true;
    207         }
    208         return false;
    209     }
    210 
    211     /**
    212      * Performs FolderSync
    213      *
    214      * @throws IOException
    215      * @throws EasParserException
    216      */
    217     public void sync() throws IOException, EasParserException {
    218          // Check that the account's mailboxes are consistent
    219         MailboxUtilities.checkMailboxConsistency(mContext, mAccount.mId);
    220         // Initialize exit status to success
    221         try {
    222             try {
    223                 ExchangeService.callback()
    224                     .syncMailboxListStatus(mAccount.mId, EmailServiceStatus.IN_PROGRESS, 0);
    225             } catch (RemoteException e1) {
    226                 // Don't care if this fails
    227             }
    228 
    229             if (mAccount.mSyncKey == null) {
    230                 mAccount.mSyncKey = "0";
    231                 userLog("Account syncKey INIT to 0");
    232                 ContentValues cv = new ContentValues();
    233                 cv.put(AccountColumns.SYNC_KEY, mAccount.mSyncKey);
    234                 mAccount.update(mContext, cv);
    235             }
    236 
    237             boolean firstSync = mAccount.mSyncKey.equals("0");
    238             if (firstSync) {
    239                 userLog("Initial FolderSync");
    240             }
    241 
    242             // When we first start up, change all mailboxes to push.
    243             ContentValues cv = new ContentValues();
    244             cv.put(Mailbox.SYNC_INTERVAL, Mailbox.CHECK_INTERVAL_PUSH);
    245             if (mContentResolver.update(Mailbox.CONTENT_URI, cv,
    246                     WHERE_ACCOUNT_AND_SYNC_INTERVAL_PING,
    247                     new String[] {Long.toString(mAccount.mId)}) > 0) {
    248                 ExchangeService.kick("change ping boxes to push");
    249             }
    250 
    251             // Determine our protocol version, if we haven't already and save it in the Account
    252             // Also re-check protocol version at least once a day (in case of upgrade)
    253             if (mAccount.mProtocolVersion == null || firstSync ||
    254                    ((System.currentTimeMillis() - mMailbox.mSyncTime) > DAYS)) {
    255                 userLog("Determine EAS protocol version");
    256                 EasResponse resp = sendHttpClientOptions();
    257                 try {
    258                     int code = resp.getStatus();
    259                     userLog("OPTIONS response: ", code);
    260                     if (code == HttpStatus.SC_OK) {
    261                         Header header = resp.getHeader("MS-ASProtocolCommands");
    262                         userLog(header.getValue());
    263                         header = resp.getHeader("ms-asprotocolversions");
    264                         try {
    265                             setupProtocolVersion(this, header);
    266                         } catch (MessagingException e) {
    267                             // Since we've already validated, this can't really happen
    268                             // But if it does, we'll rethrow this...
    269                             throw new IOException(e);
    270                         }
    271                         // Save the protocol version
    272                         cv.clear();
    273                         // Save the protocol version in the account; if we're using 12.0 or greater,
    274                         // set the flag for support of SmartForward
    275                         cv.put(Account.PROTOCOL_VERSION, mProtocolVersion);
    276                         if (mProtocolVersionDouble >= 12.0) {
    277                             cv.put(Account.FLAGS,
    278                                     mAccount.mFlags |
    279                                     Account.FLAGS_SUPPORTS_SMART_FORWARD |
    280                                     Account.FLAGS_SUPPORTS_SEARCH |
    281                                     Account.FLAGS_SUPPORTS_GLOBAL_SEARCH);
    282                         }
    283                         mAccount.update(mContext, cv);
    284                         cv.clear();
    285                         // Save the sync time of the account mailbox to current time
    286                         cv.put(Mailbox.SYNC_TIME, System.currentTimeMillis());
    287                         mMailbox.update(mContext, cv);
    288                      } else if (code == EAS_REDIRECT_CODE && canHandleAccountMailboxRedirect(resp)) {
    289                         // Cause this to re-run
    290                         throw new IOException("Will retry after a brief hold...");
    291                      } else {
    292                         errorLog("OPTIONS command failed; throwing IOException");
    293                         throw new IOException();
    294                     }
    295                 } finally {
    296                     resp.close();
    297                 }
    298             }
    299 
    300             // Change all pushable boxes to push when we start the account mailbox
    301             if (mAccount.mSyncInterval == Account.CHECK_INTERVAL_PUSH) {
    302                 cv.clear();
    303                 cv.put(Mailbox.SYNC_INTERVAL, Mailbox.CHECK_INTERVAL_PUSH);
    304                 if (mContentResolver.update(Mailbox.CONTENT_URI, cv,
    305                         ExchangeService.WHERE_IN_ACCOUNT_AND_PUSHABLE,
    306                         new String[] {Long.toString(mAccount.mId)}) > 0) {
    307                     userLog("Push account; set pushable boxes to push...");
    308                 }
    309             }
    310 
    311             while (!isStopped()) {
    312                 // If we're not allowed to sync (e.g. roaming policy), leave now
    313                 if (!ExchangeService.canAutoSync(mAccount)) return;
    314                 userLog("Sending Account syncKey: ", mAccount.mSyncKey);
    315                 Serializer s = new Serializer();
    316                 s.start(Tags.FOLDER_FOLDER_SYNC).start(Tags.FOLDER_SYNC_KEY)
    317                     .text(mAccount.mSyncKey).end().end().done();
    318                 EasResponse resp = sendHttpClientPost("FolderSync", s.toByteArray());
    319                 try {
    320                     if (isStopped()) break;
    321                     int code = resp.getStatus();
    322                     if (code == HttpStatus.SC_OK) {
    323                         if (!resp.isEmpty()) {
    324                             InputStream is = resp.getInputStream();
    325                             // Returns true if we need to sync again
    326                             if (new FolderSyncParser(is,
    327                                     new AccountSyncAdapter(this)).parse()) {
    328                                 continue;
    329                             }
    330                         }
    331                     } else if (EasResponse.isProvisionError(code)) {
    332                         throw new CommandStatusException(CommandStatus.NEEDS_PROVISIONING);
    333                     } else if (EasResponse.isAuthError(code)) {
    334                         mExitStatus = EasSyncService.EXIT_LOGIN_FAILURE;
    335                         return;
    336                     } else if (code == EAS_REDIRECT_CODE && canHandleAccountMailboxRedirect(resp)) {
    337                         // This will cause a retry of the FolderSync
    338                         continue;
    339                     } else {
    340                         userLog("FolderSync response error: ", code);
    341                     }
    342                 } finally {
    343                     resp.close();
    344                 }
    345 
    346                 // Change all push/hold boxes to push
    347                 cv.clear();
    348                 cv.put(Mailbox.SYNC_INTERVAL, Account.CHECK_INTERVAL_PUSH);
    349                 if (mContentResolver.update(Mailbox.CONTENT_URI, cv,
    350                         WHERE_PUSH_HOLD_NOT_ACCOUNT_MAILBOX,
    351                         new String[] {Long.toString(mAccount.mId)}) > 0) {
    352                     userLog("Set push/hold boxes to push...");
    353                 }
    354 
    355                 try {
    356                     ExchangeService.callback()
    357                         .syncMailboxListStatus(mAccount.mId,
    358                                 exitStatusToServiceStatus(mExitStatus),
    359                                 0);
    360                 } catch (RemoteException e1) {
    361                     // Don't care if this fails
    362                 }
    363 
    364                 // Before each run of the pingLoop, if this Account has a PolicySet, make sure it's
    365                 // active; otherwise, clear out the key/flag.  This should cause a provisioning
    366                 // error on the next POST, and start the security sequence over again
    367                 String key = mAccount.mSecuritySyncKey;
    368                 if (!TextUtils.isEmpty(key)) {
    369                     Policy policy = Policy.restorePolicyWithId(mContext, mAccount.mPolicyKey);
    370                     if ((policy != null) && !PolicyServiceProxy.isActive(mContext, policy)) {
    371                         resetSecurityPolicies();
    372                     }
    373                 }
    374 
    375                 // Wait for push notifications.
    376                 String threadName = Thread.currentThread().getName();
    377                 try {
    378                     runPingLoop();
    379                 } catch (StaleFolderListException e) {
    380                     // We break out if we get told about a stale folder list
    381                     userLog("Ping interrupted; folder list requires sync...");
    382                 } catch (IllegalHeartbeatException e) {
    383                     // If we're sending an illegal heartbeat, reset either the min or the max to
    384                     // that heartbeat
    385                     resetHeartbeats(e.mLegalHeartbeat);
    386                 } finally {
    387                     Thread.currentThread().setName(threadName);
    388                 }
    389             }
    390         } catch (CommandStatusException e) {
    391             // If the sync error is a provisioning failure (perhaps policies changed),
    392             // let's try the provisioning procedure
    393             // Provisioning must only be attempted for the account mailbox - trying to
    394             // provision any other mailbox may result in race conditions and the
    395             // creation of multiple policy keys.
    396             int status = e.mStatus;
    397             if (CommandStatus.isNeedsProvisioning(status)) {
    398                 if (!tryProvision(this)) {
    399                     // Set the appropriate failure status
    400                     mExitStatus = EasSyncService.EXIT_SECURITY_FAILURE;
    401                     return;
    402                 }
    403             } else if (CommandStatus.isDeniedAccess(status)) {
    404                 mExitStatus = EasSyncService.EXIT_ACCESS_DENIED;
    405                 try {
    406                     ExchangeService.callback().syncMailboxListStatus(mAccount.mId,
    407                             EmailServiceStatus.ACCESS_DENIED, 0);
    408                 } catch (RemoteException e1) {
    409                     // Don't care if this fails
    410                 }
    411                 return;
    412             } else {
    413                 userLog("Unexpected status: " + CommandStatus.toString(status));
    414                 mExitStatus = EasSyncService.EXIT_EXCEPTION;
    415             }
    416         } catch (IOException e) {
    417             // We catch this here to send the folder sync status callback
    418             // A folder sync failed callback will get sent from run()
    419             try {
    420                 if (!isStopped()) {
    421                     // NOTE: The correct status is CONNECTION_ERROR, but the UI displays this, and
    422                     // it's not really appropriate for EAS as this is not unexpected for a ping and
    423                     // connection errors are retried in any case
    424                     ExchangeService.callback()
    425                         .syncMailboxListStatus(mAccount.mId, EmailServiceStatus.SUCCESS, 0);
    426                 }
    427             } catch (RemoteException e1) {
    428                 // Don't care if this fails
    429             }
    430             throw e;
    431         }
    432     }
    433 
    434     /**
    435      * Reset either our minimum or maximum ping heartbeat to a heartbeat known to be legal
    436      * @param legalHeartbeat a known legal heartbeat (from the EAS server)
    437      */
    438     /*package*/ void resetHeartbeats(int legalHeartbeat) {
    439         userLog("Resetting min/max heartbeat, legal = " + legalHeartbeat);
    440         // We are here because the current heartbeat (mPingHeartbeat) is invalid.  Depending on
    441         // whether the argument is above or below the current heartbeat, we can infer the need to
    442         // change either the minimum or maximum heartbeat
    443         if (legalHeartbeat > mPingHeartbeat) {
    444             // The legal heartbeat is higher than the ping heartbeat; therefore, our minimum was
    445             // too low.  We respond by raising either or both of the minimum heartbeat or the
    446             // force heartbeat to the argument value
    447             if (mPingMinHeartbeat < legalHeartbeat) {
    448                 mPingMinHeartbeat = legalHeartbeat;
    449             }
    450             if (mPingForceHeartbeat < legalHeartbeat) {
    451                 mPingForceHeartbeat = legalHeartbeat;
    452             }
    453             // If our minimum is now greater than the max, bring them together
    454             if (mPingMinHeartbeat > mPingMaxHeartbeat) {
    455                 mPingMaxHeartbeat = legalHeartbeat;
    456             }
    457         } else if (legalHeartbeat < mPingHeartbeat) {
    458             // The legal heartbeat is lower than the ping heartbeat; therefore, our maximum was
    459             // too high.  We respond by lowering the maximum to the argument value
    460             mPingMaxHeartbeat = legalHeartbeat;
    461             // If our maximum is now less than the minimum, bring them together
    462             if (mPingMaxHeartbeat < mPingMinHeartbeat) {
    463                 mPingMinHeartbeat = legalHeartbeat;
    464             }
    465         }
    466         // Set current heartbeat to the legal heartbeat
    467         mPingHeartbeat = legalHeartbeat;
    468         // Allow the heartbeat logic to run
    469         mPingHeartbeatDropped = false;
    470     }
    471 
    472     private void pushFallback(long mailboxId) {
    473         Mailbox mailbox = Mailbox.restoreMailboxWithId(mContext, mailboxId);
    474         if (mailbox == null) {
    475             return;
    476         }
    477         ContentValues cv = new ContentValues();
    478         int mins = PING_FALLBACK_PIM;
    479         if (mailbox.mType == Mailbox.TYPE_INBOX) {
    480             mins = PING_FALLBACK_INBOX;
    481         }
    482         cv.put(Mailbox.SYNC_INTERVAL, mins);
    483         mContentResolver.update(ContentUris.withAppendedId(Mailbox.CONTENT_URI, mailboxId),
    484                 cv, null, null);
    485         errorLog("*** PING ERROR LOOP: Set " + mailbox.mDisplayName + " to " + mins
    486                 + " min sync");
    487         ExchangeService.kick("push fallback");
    488     }
    489 
    490     /**
    491      * Simplistic attempt to determine a NAT timeout, based on experience with various carriers
    492      * and networks.  The string "reset by peer" is very common in these situations, so we look for
    493      * that specifically.  We may add additional tests here as more is learned.
    494      * @param message
    495      * @return whether this message is likely associated with a NAT failure
    496      */
    497     private boolean isLikelyNatFailure(String message) {
    498         if (message == null) return false;
    499         if (message.contains("reset by peer")) {
    500             return true;
    501         }
    502         return false;
    503     }
    504 
    505     private void sleep(long ms, boolean runAsleep) {
    506         if (runAsleep) {
    507             ExchangeService.runAsleep(mMailboxId, ms+(5*SECONDS));
    508         }
    509         try {
    510             Thread.sleep(ms);
    511         } catch (InterruptedException e) {
    512             // Doesn't matter whether we stop early; it's the thought that counts
    513         } finally {
    514             if (runAsleep) {
    515                 ExchangeService.runAwake(mMailboxId);
    516             }
    517         }
    518     }
    519 
    520     @Override
    521     protected EasResponse sendPing(byte[] bytes, int heartbeat) throws IOException {
    522        Thread.currentThread().setName(mAccount.mDisplayName + ": Ping");
    523        if (Eas.USER_LOG) {
    524            userLog("Send ping, timeout: " + heartbeat + "s, high: " + mPingHighWaterMark + 's');
    525        }
    526        return sendHttpClientPost(EasSyncService.PING_COMMAND, new ByteArrayEntity(bytes),
    527                (heartbeat+5)*SECONDS);
    528     }
    529 
    530     private void runPingLoop() throws IOException, StaleFolderListException,
    531             IllegalHeartbeatException, CommandStatusException {
    532         int pingHeartbeat = mPingHeartbeat;
    533         userLog("runPingLoop");
    534         // Do push for all sync services here
    535         long endTime = System.currentTimeMillis() + (30*MINUTES);
    536         HashMap<String, Integer> pingErrorMap = new HashMap<String, Integer>();
    537         ArrayList<String> readyMailboxes = new ArrayList<String>();
    538         ArrayList<String> notReadyMailboxes = new ArrayList<String>();
    539         int pingWaitCount = 0;
    540         long inboxId = -1;
    541         android.accounts.Account amAccount = new android.accounts.Account(mAccount.mEmailAddress,
    542                 Eas.EXCHANGE_ACCOUNT_MANAGER_TYPE);
    543         while ((System.currentTimeMillis() < endTime) && !isStopped()) {
    544             // Count of pushable mailboxes
    545             int pushCount = 0;
    546             // Count of mailboxes that can be pushed right now
    547             int canPushCount = 0;
    548             // Count of uninitialized boxes
    549             int uninitCount = 0;
    550 
    551             Serializer s = new Serializer();
    552             Cursor c = mContentResolver.query(Mailbox.CONTENT_URI, Mailbox.CONTENT_PROJECTION,
    553                     MailboxColumns.ACCOUNT_KEY + '=' + mAccount.mId +
    554                     AND_FREQUENCY_PING_PUSH_AND_NOT_ACCOUNT_MAILBOX, null, null);
    555             if (c == null) throw new ProviderUnavailableException();
    556             notReadyMailboxes.clear();
    557             readyMailboxes.clear();
    558             // Look for an inbox, and remember its id
    559             if (inboxId == -1) {
    560                 inboxId = Mailbox.findMailboxOfType(mContext, mAccount.mId, Mailbox.TYPE_INBOX);
    561             }
    562             try {
    563                 // Loop through our pushed boxes seeing what is available to push
    564                 while (c.moveToNext()) {
    565                     pushCount++;
    566                     // Two requirements for push:
    567                     // 1) ExchangeService tells us the mailbox is syncable (not running/not stopped)
    568                     // 2) The syncKey isn't "0" (i.e. it's synced at least once)
    569                     long mailboxId = c.getLong(Mailbox.CONTENT_ID_COLUMN);
    570                     String mailboxName = c.getString(Mailbox.CONTENT_DISPLAY_NAME_COLUMN);
    571 
    572                     // See what type of box we've got and get authority
    573                     int mailboxType = c.getInt(Mailbox.CONTENT_TYPE_COLUMN);
    574                     String authority = EmailContent.AUTHORITY;
    575                     switch(mailboxType) {
    576                         case Mailbox.TYPE_CALENDAR:
    577                             authority = CalendarContract.AUTHORITY;
    578                             break;
    579                         case Mailbox.TYPE_CONTACTS:
    580                             authority = ContactsContract.AUTHORITY;
    581                             break;
    582                     }
    583 
    584                     // See whether we can ping for this mailbox
    585                     int pingStatus;
    586                     if (!ContentResolver.getSyncAutomatically(amAccount, authority)) {
    587                         pingStatus = ExchangeService.PING_STATUS_DISABLED;
    588                     } else {
    589                         pingStatus = ExchangeService.pingStatus(mailboxId);
    590 
    591                     }
    592 
    593                     if (pingStatus == ExchangeService.PING_STATUS_OK) {
    594                         String syncKey = c.getString(Mailbox.CONTENT_SYNC_KEY_COLUMN);
    595                         if ((syncKey == null) || syncKey.equals("0")) {
    596                             // We can't push until the initial sync is done
    597                             pushCount--;
    598                             uninitCount++;
    599                             continue;
    600                         }
    601 
    602                         if (canPushCount++ == 0) {
    603                             // Initialize the Ping command
    604                             s.start(Tags.PING_PING)
    605                                 .data(Tags.PING_HEARTBEAT_INTERVAL,
    606                                         Integer.toString(pingHeartbeat))
    607                                 .start(Tags.PING_FOLDERS);
    608                         }
    609 
    610                         String folderClass = getTargetCollectionClassFromCursor(c);
    611                         s.start(Tags.PING_FOLDER)
    612                             .data(Tags.PING_ID, c.getString(Mailbox.CONTENT_SERVER_ID_COLUMN))
    613                             .data(Tags.PING_CLASS, folderClass)
    614                             .end();
    615                         readyMailboxes.add(mailboxName);
    616                     } else if ((pingStatus == ExchangeService.PING_STATUS_RUNNING) ||
    617                             (pingStatus == ExchangeService.PING_STATUS_WAITING)) {
    618                         notReadyMailboxes.add(mailboxName);
    619                     } else if (pingStatus == ExchangeService.PING_STATUS_UNABLE) {
    620                         pushCount--;
    621                         userLog(mailboxName, " in error state; ignore");
    622                         continue;
    623                     } else if (pingStatus == ExchangeService.PING_STATUS_DISABLED) {
    624                         pushCount--;
    625                         userLog(mailboxName, " disabled by user; ignore");
    626                         continue;
    627                     }
    628                 }
    629             } finally {
    630                 c.close();
    631             }
    632 
    633             if (Eas.USER_LOG) {
    634                 if (!notReadyMailboxes.isEmpty()) {
    635                     userLog("Ping not ready for: " + notReadyMailboxes);
    636                 }
    637                 if (!readyMailboxes.isEmpty()) {
    638                     userLog("Ping ready for: " + readyMailboxes);
    639                 }
    640             }
    641 
    642             // If we've waited 10 seconds or more, just ping with whatever boxes are ready
    643             // But use a shorter than normal heartbeat
    644             boolean forcePing = !notReadyMailboxes.isEmpty() && (pingWaitCount > 5);
    645 
    646             if ((canPushCount > 0) && ((canPushCount == pushCount) || forcePing)) {
    647                 // If all pingable boxes are ready for push, send Ping to the server
    648                 s.end().end().done();
    649                 pingWaitCount = 0;
    650                 mPostAborted = false;
    651                 mPostReset = false;
    652 
    653                 // If we've been stopped, this is a good time to return
    654                 if (isStopped()) return;
    655 
    656                 long pingTime = SystemClock.elapsedRealtime();
    657                 try {
    658                     // Send the ping, wrapped by appropriate timeout/alarm
    659                     if (forcePing) {
    660                         userLog("Forcing ping after waiting for all boxes to be ready");
    661                     }
    662                     EasResponse resp =
    663                         sendPing(s.toByteArray(), forcePing ? mPingForceHeartbeat : pingHeartbeat);
    664 
    665                     try {
    666                         int code = resp.getStatus();
    667                         userLog("Ping response: ", code);
    668 
    669                         // If we're not allowed to sync (e.g. roaming policy), terminate gracefully
    670                         // now; otherwise we might start a sync based on the response
    671                         if (!ExchangeService.canAutoSync(mAccount)) {
    672                             stop();
    673                         }
    674 
    675                         // Return immediately if we've been asked to stop during the ping
    676                         if (isStopped()) {
    677                             userLog("Stopping pingLoop");
    678                             return;
    679                         }
    680 
    681                         if (code == HttpStatus.SC_OK) {
    682                             // Make sure to clear out any pending sync errors
    683                             ExchangeService.removeFromSyncErrorMap(mMailboxId);
    684                             if (!resp.isEmpty()) {
    685                                 InputStream is = resp.getInputStream();
    686                                 int pingResult = parsePingResult(is, mContentResolver,
    687                                         pingErrorMap);
    688                                 // If our ping completed (status = 1), and wasn't forced and we're
    689                                 // not at the maximum, try increasing timeout by two minutes
    690                                 if (pingResult == PROTOCOL_PING_STATUS_COMPLETED && !forcePing) {
    691                                     if (pingHeartbeat > mPingHighWaterMark) {
    692                                         mPingHighWaterMark = pingHeartbeat;
    693                                         userLog("Setting high water mark at: ", mPingHighWaterMark);
    694                                     }
    695                                     if ((pingHeartbeat < mPingMaxHeartbeat) &&
    696                                             !mPingHeartbeatDropped) {
    697                                         pingHeartbeat += PING_HEARTBEAT_INCREMENT;
    698                                         if (pingHeartbeat > mPingMaxHeartbeat) {
    699                                             pingHeartbeat = mPingMaxHeartbeat;
    700                                         }
    701                                         userLog("Increase ping heartbeat to ", pingHeartbeat, "s");
    702                                     }
    703                                 } else if (pingResult == PROTOCOL_PING_STATUS_BAD_PARAMETERS ||
    704                                         pingResult == PROTOCOL_PING_STATUS_RETRY) {
    705                                     // These errors appear to be server-related (I've seen a bad
    706                                     // parameters result with known good parameters...)
    707                                     userLog("Server error during Ping: " + pingResult);
    708                                     // Act as if we have an IOException (backoff, etc.)
    709                                     throw new IOException();
    710                                 }
    711                             } else {
    712                                 userLog("Ping returned empty result; throwing IOException");
    713                                 throw new IOException();
    714                             }
    715                         } else if (EasResponse.isAuthError(code)) {
    716                             mExitStatus = EasSyncService.EXIT_LOGIN_FAILURE;
    717                             userLog("Authorization error during Ping: ", code);
    718                             throw new IOException();
    719                         }
    720                     } finally {
    721                         resp.close();
    722                     }
    723                 } catch (IOException e) {
    724                     String message = e.getMessage();
    725                     // If we get the exception that is indicative of a NAT timeout and if we
    726                     // haven't yet "fixed" the timeout, back off by two minutes and "fix" it
    727                     boolean hasMessage = message != null;
    728                     userLog("IOException runPingLoop: " + (hasMessage ? message : "[no message]"));
    729                     if (mPostReset) {
    730                         // Nothing to do in this case; this is ExchangeService telling us to try
    731                         // another ping.
    732                     } else if (mPostAborted || isLikelyNatFailure(message)) {
    733                         long pingLength = SystemClock.elapsedRealtime() - pingTime;
    734                         if ((pingHeartbeat > mPingMinHeartbeat) &&
    735                                 (pingHeartbeat > mPingHighWaterMark)) {
    736                             pingHeartbeat -= PING_HEARTBEAT_INCREMENT;
    737                             mPingHeartbeatDropped = true;
    738                             if (pingHeartbeat < mPingMinHeartbeat) {
    739                                 pingHeartbeat = mPingMinHeartbeat;
    740                             }
    741                             userLog("Decreased ping heartbeat to ", pingHeartbeat, "s");
    742                         } else if (mPostAborted) {
    743                             // There's no point in throwing here; this can happen in two cases
    744                             // 1) An alarm, which indicates minutes without activity; no sense
    745                             //    backing off
    746                             // 2) ExchangeService abort, due to sync of mailbox.  Again, we want to
    747                             //    keep on trying to ping
    748                             userLog("Ping aborted; retry");
    749                         } else if (pingLength < 2000) {
    750                             userLog("Abort or NAT type return < 2 seconds; throwing IOException");
    751                             throw e;
    752                         } else {
    753                             userLog("NAT type IOException");
    754                         }
    755                     } else if (hasMessage && message.contains("roken pipe")) {
    756                         // The "broken pipe" error (uppercase or lowercase "b") seems to be an
    757                         // internal error, so let's not throw an exception (which leads to delays)
    758                         // but rather simply run through the loop again
    759                     } else {
    760                         throw e;
    761                     }
    762                 }
    763             } else if (forcePing) {
    764                 // In this case, there aren't any boxes that are pingable, but there are boxes
    765                 // waiting (for IOExceptions)
    766                 userLog("pingLoop waiting 60s for any pingable boxes");
    767                 sleep(60*SECONDS, true);
    768             } else if (pushCount > 0) {
    769                 // If we want to Ping, but can't just yet, wait a little bit
    770                 // TODO Change sleep to wait and use notify from ExchangeService when a sync ends
    771                 sleep(2*SECONDS, false);
    772                 pingWaitCount++;
    773                 //userLog("pingLoop waited 2s for: ", (pushCount - canPushCount), " box(es)");
    774             } else if (uninitCount > 0) {
    775                 // In this case, we're doing an initial sync of at least one mailbox.  Since this
    776                 // is typically a one-time case, I'm ok with trying again every 10 seconds until
    777                 // we're in one of the other possible states.
    778                 userLog("pingLoop waiting for initial sync of ", uninitCount, " box(es)");
    779                 sleep(10*SECONDS, true);
    780             } else if (inboxId == -1) {
    781                 // In this case, we're still syncing mailboxes, so sleep for only a short time
    782                 sleep(45*SECONDS, true);
    783             } else {
    784                 // We've got nothing to do, so we'll check again in 20 minutes at which time
    785                 // we'll update the folder list, check for policy changes and/or remote wipe, etc.
    786                 // Let the device sleep in the meantime...
    787                 userLog(ACCOUNT_MAILBOX_SLEEP_TEXT);
    788                 sleep(ACCOUNT_MAILBOX_SLEEP_TIME, true);
    789             }
    790         }
    791 
    792         // Save away the current heartbeat
    793         mPingHeartbeat = pingHeartbeat;
    794     }
    795 
    796     private int parsePingResult(InputStream is, ContentResolver cr,
    797             HashMap<String, Integer> errorMap)
    798             throws IOException, StaleFolderListException, IllegalHeartbeatException,
    799                 CommandStatusException {
    800         PingParser pp = new PingParser(is, this);
    801         if (pp.parse()) {
    802             // True indicates some mailboxes need syncing...
    803             // syncList has the serverId's of the mailboxes...
    804             mBindArguments[0] = Long.toString(mAccount.mId);
    805             mPingChangeList = pp.getSyncList();
    806             for (String serverId: mPingChangeList) {
    807                 mBindArguments[1] = serverId;
    808                 Cursor c = cr.query(Mailbox.CONTENT_URI, Mailbox.CONTENT_PROJECTION,
    809                         WHERE_ACCOUNT_KEY_AND_SERVER_ID, mBindArguments, null);
    810                 if (c == null) throw new ProviderUnavailableException();
    811                 try {
    812                     if (c.moveToFirst()) {
    813 
    814                         /**
    815                          * Check the boxes reporting changes to see if there really were any...
    816                          * We do this because bugs in various Exchange servers can put us into a
    817                          * looping behavior by continually reporting changes in a mailbox, even when
    818                          * there aren't any.
    819                          *
    820                          * This behavior is seemingly random, and therefore we must code defensively
    821                          * by backing off of push behavior when it is detected.
    822                          *
    823                          * One known cause, on certain Exchange 2003 servers, is acknowledged by
    824                          * Microsoft, and the server hotfix for this case can be found at
    825                          * http://support.microsoft.com/kb/923282
    826                          */
    827 
    828                         // Check the status of the last sync
    829                         String status = c.getString(Mailbox.CONTENT_SYNC_STATUS_COLUMN);
    830                         int type = ExchangeService.getStatusType(status);
    831                         // This check should always be true...
    832                         if (type == ExchangeService.SYNC_PING) {
    833                             int changeCount = ExchangeService.getStatusChangeCount(status);
    834                             if (changeCount > 0) {
    835                                 errorMap.remove(serverId);
    836                             } else if (changeCount == 0) {
    837                                 // This means that a ping reported changes in error; we keep a count
    838                                 // of consecutive errors of this kind
    839                                 String name = c.getString(Mailbox.CONTENT_DISPLAY_NAME_COLUMN);
    840                                 Integer failures = errorMap.get(serverId);
    841                                 if (failures == null) {
    842                                     userLog("Last ping reported changes in error for: ", name);
    843                                     errorMap.put(serverId, 1);
    844                                 } else if (failures > MAX_PING_FAILURES) {
    845                                     // We'll back off of push for this box
    846                                     pushFallback(c.getLong(Mailbox.CONTENT_ID_COLUMN));
    847                                     continue;
    848                                 } else {
    849                                     userLog("Last ping reported changes in error for: ", name);
    850                                     errorMap.put(serverId, failures + 1);
    851                                 }
    852                             }
    853                         }
    854 
    855                         // If there were no problems with previous sync, we'll start another one
    856                         ExchangeService.startManualSync(c.getLong(Mailbox.CONTENT_ID_COLUMN),
    857                                 ExchangeService.SYNC_PING, null);
    858                     }
    859                 } finally {
    860                     c.close();
    861                 }
    862             }
    863         }
    864         return pp.getSyncStatus();
    865     }
    866 
    867     /**
    868      * Translate exit status code to service status code (used in callbacks)
    869      * @param exitStatus the service's exit status
    870      * @return the corresponding service status
    871      */
    872     private int exitStatusToServiceStatus(int exitStatus) {
    873         switch(exitStatus) {
    874             case EasSyncService.EXIT_SECURITY_FAILURE:
    875                 return EmailServiceStatus.SECURITY_FAILURE;
    876             case EasSyncService.EXIT_LOGIN_FAILURE:
    877                 return EmailServiceStatus.LOGIN_FAILED;
    878             default:
    879                 return EmailServiceStatus.SUCCESS;
    880         }
    881     }
    882 }
    883