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