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