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