EasSyncService.java revision 0b3a1547b4adf380dab1cc9a1af6c227c9a4e00f
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
360    @Override
361    public void addRequest(Request request) {
362        // Don't allow duplicates of requests; just refuse them
363        if (mRequestQueue.contains(request)) return;
364        // Add the request
365        super.addRequest(request);
366    }
367
368    /**
369     * Determine whether an HTTP code represents an authentication error
370     * @param code the HTTP code returned by the server
371     * @return whether or not the code represents an authentication error
372     */
373    protected boolean isAuthError(int code) {
374        return (code == HttpStatus.SC_UNAUTHORIZED) || (code == HttpStatus.SC_FORBIDDEN);
375    }
376
377    /**
378     * Determine whether an HTTP code represents a provisioning error
379     * @param code the HTTP code returned by the server
380     * @return whether or not the code represents an provisioning error
381     */
382    protected boolean isProvisionError(int code) {
383        return (code == HTTP_NEED_PROVISIONING) || (code == HttpStatus.SC_FORBIDDEN);
384    }
385
386    private void setupProtocolVersion(EasSyncService service, Header versionHeader)
387            throws MessagingException {
388        // The string is a comma separated list of EAS versions in ascending order
389        // e.g. 1.0,2.0,2.5,12.0,12.1,14.0,14.1
390        String supportedVersions = versionHeader.getValue();
391        userLog("Server supports versions: ", supportedVersions);
392        String[] supportedVersionsArray = supportedVersions.split(",");
393        String ourVersion = null;
394        // Find the most recent version we support
395        for (String version: supportedVersionsArray) {
396            if (version.equals(Eas.SUPPORTED_PROTOCOL_EX2003) ||
397                    version.equals(Eas.SUPPORTED_PROTOCOL_EX2007) ||
398                    version.equals(Eas.SUPPORTED_PROTOCOL_EX2007_SP1) ||
399                    version.equals(Eas.SUPPORTED_PROTOCOL_EX2010) ||
400                    version.equals(Eas.SUPPORTED_PROTOCOL_EX2010_SP1)) {
401                ourVersion = version;
402            }
403        }
404        // If we don't support any of the servers supported versions, throw an exception here
405        // This will cause validation to fail
406        if (ourVersion == null) {
407            Log.w(TAG, "No supported EAS versions: " + supportedVersions);
408            throw new MessagingException(MessagingException.PROTOCOL_VERSION_UNSUPPORTED);
409        } else {
410            service.mProtocolVersion = ourVersion;
411            service.mProtocolVersionDouble = Eas.getProtocolVersionDouble(ourVersion);
412            if (service.mAccount != null) {
413                service.mAccount.mProtocolVersion = ourVersion;
414            }
415        }
416    }
417
418    /**
419     * Create an EasSyncService for the specified account
420     *
421     * @param context the caller's context
422     * @param account the account
423     * @return the service, or null if the account is on hold or hasn't been initialized
424     */
425    private static EasSyncService setupServiceForAccount(Context context, Account account) {
426        // Just return null if we're on security hold
427        if ((account.mFlags & Account.FLAGS_SECURITY_HOLD) != 0) {
428            return null;
429        }
430        // If there's no protocol version, we're not initialized
431        String protocolVersion = account.mProtocolVersion;
432        if (protocolVersion == null) {
433            return null;
434        }
435        EasSyncService svc = new EasSyncService("OutOfBand");
436        HostAuth ha = HostAuth.restoreHostAuthWithId(context, account.mHostAuthKeyRecv);
437        svc.mProtocolVersion = protocolVersion;
438        svc.mProtocolVersionDouble = Eas.getProtocolVersionDouble(protocolVersion);
439        svc.mContext = context;
440        svc.mHostAddress = ha.mAddress;
441        svc.mUserName = ha.mLogin;
442        svc.mPassword = ha.mPassword;
443        svc.setConnectionParameters(
444                (ha.mFlags & HostAuth.FLAG_SSL) != 0,
445                (ha.mFlags & HostAuth.FLAG_TRUST_ALL) != 0,
446                ha.mClientCertAlias);
447        try {
448            svc.mDeviceId = ExchangeService.getDeviceId(context);
449        } catch (IOException e) {
450            return null;
451        }
452        svc.mAccount = account;
453        return svc;
454    }
455
456    public static int searchMessages(Context context, long accountId, SearchParams searchParams,
457            long destMailboxId) {
458        // Sanity check for arguments
459        int offset = searchParams.mOffset;
460        int limit = searchParams.mLimit;
461        String filter = searchParams.mFilter;
462        if (limit < 0 || limit > MAX_SEARCH_RESULTS || offset < 0) return 0;
463        // TODO Should this be checked in UI?  Are there guidelines for minimums?
464        if (filter == null || filter.length() < MIN_QUERY_LENGTH) return 0;
465
466        int res = 0;
467        Account account = Account.restoreAccountWithId(context, accountId);
468        if (account == null) return res;
469        EasSyncService svc = setupServiceForAccount(context, account);
470        if (svc == null) return res;
471        try {
472            Mailbox searchMailbox = Mailbox.restoreMailboxWithId(context, destMailboxId);
473            // Sanity check; account might have been deleted?
474            if (searchMailbox == null) return res;
475            svc.mMailbox = searchMailbox;
476            svc.mAccount = account;
477            Serializer s = new Serializer();
478            s.start(Tags.SEARCH_SEARCH).start(Tags.SEARCH_STORE);
479            s.data(Tags.SEARCH_NAME, "Mailbox");
480            s.start(Tags.SEARCH_QUERY).start(Tags.SEARCH_AND);
481            s.data(Tags.SYNC_CLASS, "Email");
482            s.data(Tags.SEARCH_FREE_TEXT, filter);
483            s.end().end();              // SEARCH_AND, SEARCH_QUERY
484            s.start(Tags.SEARCH_OPTIONS);
485            if (offset == 0) {
486                s.tag(Tags.SEARCH_REBUILD_RESULTS);
487            }
488            if (searchParams.mIncludeChildren) {
489                s.tag(Tags.SEARCH_DEEP_TRAVERSAL);
490            }
491            // Range is sent in the form first-last (e.g. 0-9)
492            s.data(Tags.SEARCH_RANGE, offset + "-" + (offset + limit - 1));
493            s.start(Tags.BASE_BODY_PREFERENCE);
494            s.data(Tags.BASE_TYPE, Eas.BODY_PREFERENCE_HTML);
495            s.data(Tags.BASE_TRUNCATION_SIZE, "20000");
496            s.end();                    // BASE_BODY_PREFERENCE
497            s.end().end().end().done(); // SEARCH_OPTIONS, SEARCH_STORE, SEARCH_SEARCH
498            EasResponse resp = svc.sendHttpClientPost("Search", s.toByteArray());
499            try {
500                int code = resp.getStatus();
501                if (code == HttpStatus.SC_OK) {
502                    InputStream is = resp.getInputStream();
503                    try {
504                        new SearchParser(is, svc, filter).parse();
505                    } finally {
506                        is.close();
507                    }
508                } else {
509                    svc.userLog("Search returned " + code);
510                }
511            } finally {
512                resp.close();
513            }
514        } catch (IOException e) {
515            svc.userLog("Search exception " + e);
516        }
517        // TODO Capture and return the correct value
518        return res;
519    }
520
521    @Override
522    public Bundle validateAccount(HostAuth hostAuth,  Context context) {
523        Bundle bundle = new Bundle();
524        int resultCode = MessagingException.NO_ERROR;
525        try {
526            userLog("Testing EAS: ", hostAuth.mAddress, ", ", hostAuth.mLogin,
527                    ", ssl = ", hostAuth.shouldUseSsl() ? "1" : "0");
528            EasSyncService svc = new EasSyncService("%TestAccount%");
529            svc.mContext = context;
530            svc.mHostAddress = hostAuth.mAddress;
531            svc.mUserName = hostAuth.mLogin;
532            svc.mPassword = hostAuth.mPassword;
533
534            svc.setConnectionParameters(
535                    hostAuth.shouldUseSsl(),
536                    hostAuth.shouldTrustAllServerCerts(),
537                    hostAuth.mClientCertAlias);
538            // We mustn't use the "real" device id or we'll screw up current accounts
539            // Any string will do, but we'll go for "validate"
540            svc.mDeviceId = "validate";
541            svc.mAccount = new Account();
542            svc.mAccount.mEmailAddress = hostAuth.mLogin;
543            EasResponse resp = svc.sendHttpClientOptions();
544            try {
545                int code = resp.getStatus();
546                userLog("Validation (OPTIONS) response: " + code);
547                if (code == HttpStatus.SC_OK) {
548                    // No exception means successful validation
549                    Header commands = resp.getHeader("MS-ASProtocolCommands");
550                    Header versions = resp.getHeader("ms-asprotocolversions");
551                    // Make sure we've got the right protocol version set up
552                    try {
553                        if (commands == null || versions == null) {
554                            userLog("OPTIONS response without commands or versions");
555                            // We'll treat this as a protocol exception
556                            throw new MessagingException(0);
557                        }
558                        setupProtocolVersion(svc, versions);
559                    } catch (MessagingException e) {
560                        bundle.putInt(EmailServiceProxy.VALIDATE_BUNDLE_RESULT_CODE,
561                                MessagingException.PROTOCOL_VERSION_UNSUPPORTED);
562                        return bundle;
563                    }
564
565                    // Run second test here for provisioning failures using FolderSync
566                    userLog("Try folder sync");
567                    // Send "0" as the sync key for new accounts; otherwise, use the current key
568                    String syncKey = "0";
569                    Account existingAccount = Utility.findExistingAccount(
570                            context, -1L, hostAuth.mAddress, hostAuth.mLogin);
571                    if (existingAccount != null && existingAccount.mSyncKey != null) {
572                        syncKey = existingAccount.mSyncKey;
573                    }
574                    Serializer s = new Serializer();
575                    s.start(Tags.FOLDER_FOLDER_SYNC).start(Tags.FOLDER_SYNC_KEY).text(syncKey)
576                        .end().end().done();
577                    resp = svc.sendHttpClientPost("FolderSync", s.toByteArray());
578                    code = resp.getStatus();
579                    // We'll get one of the following responses if policies are required
580                    if (code == HttpStatus.SC_FORBIDDEN || code == HTTP_NEED_PROVISIONING) {
581                        throw new CommandStatusException(CommandStatus.NEEDS_PROVISIONING);
582                    } else if (code == HttpStatus.SC_NOT_FOUND) {
583                        // We get a 404 from OWA addresses (which are NOT EAS addresses)
584                        resultCode = MessagingException.PROTOCOL_VERSION_UNSUPPORTED;
585                    } else if (code == HttpStatus.SC_UNAUTHORIZED) {
586                        resultCode = resp.isMissingCertificate()
587                                ? MessagingException.CLIENT_CERTIFICATE_ERROR
588                                : MessagingException.AUTHENTICATION_FAILED;
589                    } else if (code != HttpStatus.SC_OK) {
590                        // Fail generically with anything other than success
591                        userLog("Unexpected response for FolderSync: ", code);
592                        resultCode = MessagingException.UNSPECIFIED_EXCEPTION;
593                    } else {
594                        // We need to parse the result to see if we've got a provisioning issue
595                        // (EAS 14.0 only)
596                        if (!resp.isEmpty()) {
597                            InputStream is = resp.getInputStream();
598                            // Create the parser with statusOnly set to true; we only care about
599                            // seeing if a CommandStatusException is thrown (indicating a
600                            // provisioning failure)
601                            new FolderSyncParser(is, new AccountSyncAdapter(svc), true).parse();
602                        }
603                        userLog("Validation successful");
604                    }
605                } else if (isAuthError(code)) {
606                    userLog("Authentication failed");
607                    resultCode = resp.isMissingCertificate()
608                            ? MessagingException.CLIENT_CERTIFICATE_ERROR
609                            : 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        mSsl = useSsl;
1279        mTrustSsl = trustAllServerCerts;
1280        mClientCertAlias = clientCertAlias;
1281
1282        // Register the new alias, if needed.
1283        if (mClientCertAlias != null) {
1284            // Ensure that the connection manager knows to use the proper client certificate
1285            // when establishing connections for this service.
1286            connManager.registerClientCert(mContext, mClientCertAlias, mTrustSsl);
1287        }
1288    }
1289
1290    private EmailClientConnectionManager getClientConnectionManager() {
1291        return ExchangeService.getClientConnectionManager();
1292    }
1293
1294    private HttpClient getHttpClient(int timeout) {
1295        HttpParams params = new BasicHttpParams();
1296        HttpConnectionParams.setConnectionTimeout(params, CONNECTION_TIMEOUT);
1297        HttpConnectionParams.setSoTimeout(params, timeout);
1298        HttpConnectionParams.setSocketBufferSize(params, 8192);
1299        HttpClient client = new DefaultHttpClient(getClientConnectionManager(), params);
1300        return client;
1301    }
1302
1303    public EasResponse sendHttpClientPost(String cmd, byte[] bytes) throws IOException {
1304        return sendHttpClientPost(cmd, new ByteArrayEntity(bytes), COMMAND_TIMEOUT);
1305    }
1306
1307    protected EasResponse sendHttpClientPost(String cmd, HttpEntity entity) throws IOException {
1308        return sendHttpClientPost(cmd, entity, COMMAND_TIMEOUT);
1309    }
1310
1311    protected EasResponse sendPing(byte[] bytes, int heartbeat) throws IOException {
1312       Thread.currentThread().setName(mAccount.mDisplayName + ": Ping");
1313       if (Eas.USER_LOG) {
1314           userLog("Send ping, timeout: " + heartbeat + "s, high: " + mPingHighWaterMark + 's');
1315       }
1316       return sendHttpClientPost(PING_COMMAND, new ByteArrayEntity(bytes), (heartbeat+5)*SECONDS);
1317    }
1318
1319    /**
1320     * Convenience method for executePostWithTimeout for use other than with the Ping command
1321     */
1322    protected EasResponse executePostWithTimeout(HttpClient client, HttpPost method, int timeout)
1323            throws IOException {
1324        return executePostWithTimeout(client, method, timeout, false);
1325    }
1326
1327    /**
1328     * Handle executing an HTTP POST command with proper timeout, watchdog, and ping behavior
1329     * @param client the HttpClient
1330     * @param method the HttpPost
1331     * @param timeout the timeout before failure, in ms
1332     * @param isPingCommand whether the POST is for the Ping command (requires wakelock logic)
1333     * @return the HttpResponse
1334     * @throws IOException
1335     */
1336    protected EasResponse executePostWithTimeout(HttpClient client, HttpPost method, int timeout,
1337            boolean isPingCommand) throws IOException {
1338        synchronized(getSynchronizer()) {
1339            mPendingPost = method;
1340            long alarmTime = timeout + WATCHDOG_TIMEOUT_ALLOWANCE;
1341            if (isPingCommand) {
1342                ExchangeService.runAsleep(mMailboxId, alarmTime);
1343            } else {
1344                ExchangeService.setWatchdogAlarm(mMailboxId, alarmTime);
1345            }
1346        }
1347        try {
1348            return EasResponse.fromHttpRequest(client, method);
1349        } finally {
1350            synchronized(getSynchronizer()) {
1351                if (isPingCommand) {
1352                    ExchangeService.runAwake(mMailboxId);
1353                } else {
1354                    ExchangeService.clearWatchdogAlarm(mMailboxId);
1355                }
1356                mPendingPost = null;
1357            }
1358        }
1359    }
1360
1361    public EasResponse sendHttpClientPost(String cmd, HttpEntity entity, int timeout)
1362            throws IOException {
1363        HttpClient client = getHttpClient(timeout);
1364        boolean isPingCommand = cmd.equals(PING_COMMAND);
1365
1366        // Split the mail sending commands
1367        String extra = null;
1368        boolean msg = false;
1369        if (cmd.startsWith("SmartForward&") || cmd.startsWith("SmartReply&")) {
1370            int cmdLength = cmd.indexOf('&');
1371            extra = cmd.substring(cmdLength);
1372            cmd = cmd.substring(0, cmdLength);
1373            msg = true;
1374        } else if (cmd.startsWith("SendMail&")) {
1375            msg = true;
1376        }
1377
1378        String us = makeUriString(cmd, extra);
1379        HttpPost method = new HttpPost(URI.create(us));
1380        // Send the proper Content-Type header; it's always wbxml except for messages when
1381        // the EAS protocol version is < 14.0
1382        // If entity is null (e.g. for attachments), don't set this header
1383        if (msg && (mProtocolVersionDouble < Eas.SUPPORTED_PROTOCOL_EX2010_DOUBLE)) {
1384            method.setHeader("Content-Type", "message/rfc822");
1385        } else if (entity != null) {
1386            method.setHeader("Content-Type", "application/vnd.ms-sync.wbxml");
1387        }
1388        setHeaders(method, !cmd.equals(PING_COMMAND));
1389        method.setEntity(entity);
1390        return executePostWithTimeout(client, method, timeout, isPingCommand);
1391    }
1392
1393    protected EasResponse sendHttpClientOptions() throws IOException {
1394        HttpClient client = getHttpClient(COMMAND_TIMEOUT);
1395        String us = makeUriString("OPTIONS", null);
1396        HttpOptions method = new HttpOptions(URI.create(us));
1397        setHeaders(method, false);
1398        return EasResponse.fromHttpRequest(client, method);
1399    }
1400
1401    private String getTargetCollectionClassFromCursor(Cursor c) {
1402        int type = c.getInt(Mailbox.CONTENT_TYPE_COLUMN);
1403        if (type == Mailbox.TYPE_CONTACTS) {
1404            return "Contacts";
1405        } else if (type == Mailbox.TYPE_CALENDAR) {
1406            return "Calendar";
1407        } else {
1408            return "Email";
1409        }
1410    }
1411
1412    /**
1413     * Negotiate provisioning with the server.  First, get policies form the server and see if
1414     * the policies are supported by the device.  Then, write the policies to the account and
1415     * tell SecurityPolicy that we have policies in effect.  Finally, see if those policies are
1416     * active; if so, acknowledge the policies to the server and get a final policy key that we
1417     * use in future EAS commands and write this key to the account.
1418     * @return whether or not provisioning has been successful
1419     * @throws IOException
1420     */
1421    private boolean tryProvision() throws IOException {
1422        // First, see if provisioning is even possible, i.e. do we support the policies required
1423        // by the server
1424        ProvisionParser pp = canProvision();
1425        if (pp != null) {
1426            // Get the policies from ProvisionParser
1427            Policy policy = pp.getPolicy();
1428            Policy oldPolicy = null;
1429            // Grab the old policy (if any)
1430            if (mAccount.mPolicyKey > 0) {
1431                oldPolicy = Policy.restorePolicyWithId(mContext, mAccount.mPolicyKey);
1432            }
1433            // Update the account with a null policyKey (the key we've gotten is
1434            // temporary and cannot be used for syncing)
1435            Policy.setAccountPolicy(mContext, mAccount, policy, null);
1436            // Make sure that SecurityPolicy is up-to-date
1437            SecurityPolicyDelegate.policiesUpdated(mContext, mAccount.mId);
1438            if (pp.getRemoteWipe()) {
1439                // We've gotten a remote wipe command
1440                ExchangeService.alwaysLog("!!! Remote wipe request received");
1441                // Start by setting the account to security hold
1442                SecurityPolicyDelegate.setAccountHoldFlag(mContext, mAccount, true);
1443                // Force a stop to any running syncs for this account (except this one)
1444                ExchangeService.stopNonAccountMailboxSyncsForAccount(mAccount.mId);
1445
1446                // If we're not the admin, we can't do the wipe, so just return
1447                if (!SecurityPolicyDelegate.isActiveAdmin(mContext)) {
1448                    ExchangeService.alwaysLog("!!! Not device admin; can't wipe");
1449                    return false;
1450                }
1451
1452                // First, we've got to acknowledge it, but wrap the wipe in try/catch so that
1453                // we wipe the device regardless of any errors in acknowledgment
1454                try {
1455                    ExchangeService.alwaysLog("!!! Acknowledging remote wipe to server");
1456                    acknowledgeRemoteWipe(pp.getSecuritySyncKey());
1457                } catch (Exception e) {
1458                    // Because remote wipe is such a high priority task, we don't want to
1459                    // circumvent it if there's an exception in acknowledgment
1460                }
1461                // Then, tell SecurityPolicy to wipe the device
1462                ExchangeService.alwaysLog("!!! Executing remote wipe");
1463                SecurityPolicyDelegate.remoteWipe(mContext);
1464                return false;
1465            } else if (SecurityPolicyDelegate.isActive(mContext, policy)) {
1466                // See if the required policies are in force; if they are, acknowledge the policies
1467                // to the server and get the final policy key
1468                String securitySyncKey = acknowledgeProvision(pp.getSecuritySyncKey(),
1469                        PROVISION_STATUS_OK);
1470                if (securitySyncKey != null) {
1471                    // If attachment policies have changed, fix up any affected attachment records
1472                    if (oldPolicy != null) {
1473                        if ((oldPolicy.mDontAllowAttachments != policy.mDontAllowAttachments) ||
1474                                (oldPolicy.mMaxAttachmentSize != policy.mMaxAttachmentSize)) {
1475                            Policy.setAttachmentFlagsForNewPolicy(mContext, mAccount, policy);
1476                        }
1477                    }
1478                    // Write the final policy key to the Account and say we've been successful
1479                    Policy.setAccountPolicy(mContext, mAccount, policy, securitySyncKey);
1480                    // Release any mailboxes that might be in a security hold
1481                    ExchangeService.releaseSecurityHold(mAccount);
1482                    return true;
1483                }
1484            } else {
1485                // Notify that we are blocked because of policies
1486                SecurityPolicyDelegate.policiesRequired(mContext, mAccount.mId);
1487            }
1488        }
1489        return false;
1490    }
1491
1492    private String getPolicyType() {
1493        return (mProtocolVersionDouble >=
1494            Eas.SUPPORTED_PROTOCOL_EX2007_DOUBLE) ? EAS_12_POLICY_TYPE : EAS_2_POLICY_TYPE;
1495    }
1496
1497    /**
1498     * Obtain a set of policies from the server and determine whether those policies are supported
1499     * by the device.
1500     * @return the ProvisionParser (holds policies and key) if we receive policies; null otherwise
1501     * @throws IOException
1502     */
1503    private ProvisionParser canProvision() throws IOException {
1504        Serializer s = new Serializer();
1505        s.start(Tags.PROVISION_PROVISION);
1506        if (mProtocolVersionDouble >= Eas.SUPPORTED_PROTOCOL_EX2010_DOUBLE) {
1507            // Send settings information in 14.0 and greater
1508            s.start(Tags.SETTINGS_DEVICE_INFORMATION).start(Tags.SETTINGS_SET);
1509            s.data(Tags.SETTINGS_MODEL, Build.MODEL);
1510            //s.data(Tags.SETTINGS_IMEI, "");
1511            //s.data(Tags.SETTINGS_FRIENDLY_NAME, "Friendly Name");
1512            s.data(Tags.SETTINGS_OS, "Android " + Build.VERSION.RELEASE);
1513            //s.data(Tags.SETTINGS_OS_LANGUAGE, "");
1514            //s.data(Tags.SETTINGS_PHONE_NUMBER, "");
1515            //s.data(Tags.SETTINGS_MOBILE_OPERATOR, "");
1516            s.data(Tags.SETTINGS_USER_AGENT, USER_AGENT);
1517            s.end().end();  // SETTINGS_SET, SETTINGS_DEVICE_INFORMATION
1518        }
1519        s.start(Tags.PROVISION_POLICIES);
1520        s.start(Tags.PROVISION_POLICY).data(Tags.PROVISION_POLICY_TYPE, getPolicyType()).end();
1521        s.end();  // PROVISION_POLICIES
1522        s.end().done(); // PROVISION_PROVISION
1523        EasResponse resp = sendHttpClientPost("Provision", s.toByteArray());
1524        try {
1525            int code = resp.getStatus();
1526            if (code == HttpStatus.SC_OK) {
1527                InputStream is = resp.getInputStream();
1528                ProvisionParser pp = new ProvisionParser(is, this);
1529                if (pp.parse()) {
1530                    // The PolicySet in the ProvisionParser will have the requirements for all KNOWN
1531                    // policies.  If others are required, hasSupportablePolicySet will be false
1532                    if (!pp.hasSupportablePolicySet())  {
1533                        // Try to acknowledge using the "partial" status (i.e. we can partially
1534                        // accommodate the required policies).  The server will agree to this if the
1535                        // "allow non-provisionable devices" setting is enabled on the server
1536                        String policyKey = acknowledgeProvision(pp.getSecuritySyncKey(),
1537                                PROVISION_STATUS_PARTIAL);
1538                        // Return either the parser (success) or null (failure)
1539                        if (policyKey != null) {
1540                            pp.clearUnsupportedPolicies();
1541                        }
1542                    }
1543                    return pp;
1544                }
1545            }
1546        } finally {
1547            resp.close();
1548        }
1549        // On failures, simply return null
1550        return null;
1551    }
1552
1553    /**
1554     * Acknowledge that we support the policies provided by the server, and that these policies
1555     * are in force.
1556     * @param tempKey the initial (temporary) policy key sent by the server
1557     * @return the final policy key, which can be used for syncing
1558     * @throws IOException
1559     */
1560    private void acknowledgeRemoteWipe(String tempKey) throws IOException {
1561        acknowledgeProvisionImpl(tempKey, PROVISION_STATUS_OK, true);
1562    }
1563
1564    private String acknowledgeProvision(String tempKey, String result) throws IOException {
1565        return acknowledgeProvisionImpl(tempKey, result, false);
1566    }
1567
1568    private String acknowledgeProvisionImpl(String tempKey, String status,
1569            boolean remoteWipe) throws IOException {
1570        Serializer s = new Serializer();
1571        s.start(Tags.PROVISION_PROVISION).start(Tags.PROVISION_POLICIES);
1572        s.start(Tags.PROVISION_POLICY);
1573
1574        // Use the proper policy type, depending on EAS version
1575        s.data(Tags.PROVISION_POLICY_TYPE, getPolicyType());
1576
1577        s.data(Tags.PROVISION_POLICY_KEY, tempKey);
1578        s.data(Tags.PROVISION_STATUS, status);
1579        s.end().end(); // PROVISION_POLICY, PROVISION_POLICIES
1580        if (remoteWipe) {
1581            s.start(Tags.PROVISION_REMOTE_WIPE);
1582            s.data(Tags.PROVISION_STATUS, PROVISION_STATUS_OK);
1583            s.end();
1584        }
1585        s.end().done(); // PROVISION_PROVISION
1586        EasResponse resp = sendHttpClientPost("Provision", s.toByteArray());
1587        try {
1588            int code = resp.getStatus();
1589            if (code == HttpStatus.SC_OK) {
1590                InputStream is = resp.getInputStream();
1591                ProvisionParser pp = new ProvisionParser(is, this);
1592                if (pp.parse()) {
1593                    // Return the final policy key from the ProvisionParser
1594                    return pp.getSecuritySyncKey();
1595                }
1596            }
1597        } finally {
1598            resp.close();
1599        }
1600        // On failures, return null
1601        return null;
1602    }
1603
1604    /**
1605     * Translate exit status code to service status code (used in callbacks)
1606     * @param exitStatus the service's exit status
1607     * @return the corresponding service status
1608     */
1609    private int exitStatusToServiceStatus(int exitStatus) {
1610        switch(exitStatus) {
1611            case EXIT_SECURITY_FAILURE:
1612                return EmailServiceStatus.SECURITY_FAILURE;
1613            case EXIT_LOGIN_FAILURE:
1614                return EmailServiceStatus.LOGIN_FAILED;
1615            default:
1616                return EmailServiceStatus.SUCCESS;
1617        }
1618    }
1619
1620    /**
1621     * Performs FolderSync
1622     *
1623     * @throws IOException
1624     * @throws EasParserException
1625     */
1626    public void runAccountMailbox() throws IOException, EasParserException {
1627        // Check that the account's mailboxes are consistent
1628        MailboxUtilities.checkMailboxConsistency(mContext, mAccount.mId);
1629        // Initialize exit status to success
1630        mExitStatus = EXIT_DONE;
1631        try {
1632            try {
1633                ExchangeService.callback()
1634                    .syncMailboxListStatus(mAccount.mId, EmailServiceStatus.IN_PROGRESS, 0);
1635            } catch (RemoteException e1) {
1636                // Don't care if this fails
1637            }
1638
1639            if (mAccount.mSyncKey == null) {
1640                mAccount.mSyncKey = "0";
1641                userLog("Account syncKey INIT to 0");
1642                ContentValues cv = new ContentValues();
1643                cv.put(AccountColumns.SYNC_KEY, mAccount.mSyncKey);
1644                mAccount.update(mContext, cv);
1645            }
1646
1647            boolean firstSync = mAccount.mSyncKey.equals("0");
1648            if (firstSync) {
1649                userLog("Initial FolderSync");
1650            }
1651
1652            // When we first start up, change all mailboxes to push.
1653            ContentValues cv = new ContentValues();
1654            cv.put(Mailbox.SYNC_INTERVAL, Mailbox.CHECK_INTERVAL_PUSH);
1655            if (mContentResolver.update(Mailbox.CONTENT_URI, cv,
1656                    WHERE_ACCOUNT_AND_SYNC_INTERVAL_PING,
1657                    new String[] {Long.toString(mAccount.mId)}) > 0) {
1658                ExchangeService.kick("change ping boxes to push");
1659            }
1660
1661            // Determine our protocol version, if we haven't already and save it in the Account
1662            // Also re-check protocol version at least once a day (in case of upgrade)
1663            if (mAccount.mProtocolVersion == null ||
1664                    ((System.currentTimeMillis() - mMailbox.mSyncTime) > DAYS)) {
1665                userLog("Determine EAS protocol version");
1666                EasResponse resp = sendHttpClientOptions();
1667                try {
1668                    int code = resp.getStatus();
1669                    userLog("OPTIONS response: ", code);
1670                    if (code == HttpStatus.SC_OK) {
1671                        Header header = resp.getHeader("MS-ASProtocolCommands");
1672                        userLog(header.getValue());
1673                        header = resp.getHeader("ms-asprotocolversions");
1674                        try {
1675                            setupProtocolVersion(this, header);
1676                        } catch (MessagingException e) {
1677                            // Since we've already validated, this can't really happen
1678                            // But if it does, we'll rethrow this...
1679                            throw new IOException();
1680                        }
1681                        // Save the protocol version
1682                        cv.clear();
1683                        // Save the protocol version in the account; if we're using 12.0 or greater,
1684                        // set the flag for support of SmartForward
1685                        cv.put(Account.PROTOCOL_VERSION, mProtocolVersion);
1686                        if (mProtocolVersionDouble >= 12.0) {
1687                            cv.put(Account.FLAGS,
1688                                    mAccount.mFlags | Account.FLAGS_SUPPORTS_SMART_FORWARD);
1689                        }
1690                        mAccount.update(mContext, cv);
1691                        cv.clear();
1692                        // Save the sync time of the account mailbox to current time
1693                        cv.put(Mailbox.SYNC_TIME, System.currentTimeMillis());
1694                        mMailbox.update(mContext, cv);
1695                     } else {
1696                        errorLog("OPTIONS command failed; throwing IOException");
1697                        throw new IOException();
1698                    }
1699                } finally {
1700                    resp.close();
1701                }
1702            }
1703
1704            // Change all pushable boxes to push when we start the account mailbox
1705            if (mAccount.mSyncInterval == Account.CHECK_INTERVAL_PUSH) {
1706                cv.clear();
1707                cv.put(Mailbox.SYNC_INTERVAL, Mailbox.CHECK_INTERVAL_PUSH);
1708                if (mContentResolver.update(Mailbox.CONTENT_URI, cv,
1709                        ExchangeService.WHERE_IN_ACCOUNT_AND_PUSHABLE,
1710                        new String[] {Long.toString(mAccount.mId)}) > 0) {
1711                    userLog("Push account; set pushable boxes to push...");
1712                }
1713            }
1714
1715            while (!mStop) {
1716                // If we're not allowed to sync (e.g. roaming policy), leave now
1717                if (!ExchangeService.canAutoSync(mAccount)) return;
1718                userLog("Sending Account syncKey: ", mAccount.mSyncKey);
1719                Serializer s = new Serializer();
1720                s.start(Tags.FOLDER_FOLDER_SYNC).start(Tags.FOLDER_SYNC_KEY)
1721                    .text(mAccount.mSyncKey).end().end().done();
1722                EasResponse resp = sendHttpClientPost("FolderSync", s.toByteArray());
1723                try {
1724                    if (mStop) break;
1725                    int code = resp.getStatus();
1726                    if (code == HttpStatus.SC_OK) {
1727                        if (!resp.isEmpty()) {
1728                            InputStream is = resp.getInputStream();
1729                            // Returns true if we need to sync again
1730                            if (new FolderSyncParser(is, new AccountSyncAdapter(this)).parse()) {
1731                                continue;
1732                            }
1733                        }
1734                    } else if (isProvisionError(code)) {
1735                        throw new CommandStatusException(CommandStatus.NEEDS_PROVISIONING);
1736                    } else if (isAuthError(code)) {
1737                        mExitStatus = EXIT_LOGIN_FAILURE;
1738                        return;
1739                    } else {
1740                        userLog("FolderSync response error: ", code);
1741                    }
1742                } finally {
1743                    resp.close();
1744                }
1745
1746                // Change all push/hold boxes to push
1747                cv.clear();
1748                cv.put(Mailbox.SYNC_INTERVAL, Account.CHECK_INTERVAL_PUSH);
1749                if (mContentResolver.update(Mailbox.CONTENT_URI, cv,
1750                        WHERE_PUSH_HOLD_NOT_ACCOUNT_MAILBOX,
1751                        new String[] {Long.toString(mAccount.mId)}) > 0) {
1752                    userLog("Set push/hold boxes to push...");
1753                }
1754
1755                try {
1756                    ExchangeService.callback()
1757                        .syncMailboxListStatus(mAccount.mId, exitStatusToServiceStatus(mExitStatus),
1758                                0);
1759                } catch (RemoteException e1) {
1760                    // Don't care if this fails
1761                }
1762
1763                // Before each run of the pingLoop, if this Account has a PolicySet, make sure it's
1764                // active; otherwise, clear out the key/flag.  This should cause a provisioning
1765                // error on the next POST, and start the security sequence over again
1766                String key = mAccount.mSecuritySyncKey;
1767                if (!TextUtils.isEmpty(key)) {
1768                    Policy policy = Policy.restorePolicyWithId(mContext, mAccount.mPolicyKey);
1769                    if (!SecurityPolicyDelegate.isActive(mContext, policy)) {
1770                        cv.clear();
1771                        cv.put(AccountColumns.SECURITY_FLAGS, 0);
1772                        cv.putNull(AccountColumns.SECURITY_SYNC_KEY);
1773                        long accountId = mAccount.mId;
1774                        mContentResolver.update(ContentUris.withAppendedId(
1775                                Account.CONTENT_URI, accountId), cv, null, null);
1776                        SecurityPolicyDelegate.policiesRequired(mContext, accountId);
1777                    }
1778                }
1779
1780                // Wait for push notifications.
1781                String threadName = Thread.currentThread().getName();
1782                try {
1783                    runPingLoop();
1784                } catch (StaleFolderListException e) {
1785                    // We break out if we get told about a stale folder list
1786                    userLog("Ping interrupted; folder list requires sync...");
1787                } catch (IllegalHeartbeatException e) {
1788                    // If we're sending an illegal heartbeat, reset either the min or the max to
1789                    // that heartbeat
1790                    resetHeartbeats(e.mLegalHeartbeat);
1791                } finally {
1792                    Thread.currentThread().setName(threadName);
1793                }
1794            }
1795        } catch (CommandStatusException e) {
1796            // If the sync error is a provisioning failure (perhaps policies changed),
1797            // let's try the provisioning procedure
1798            // Provisioning must only be attempted for the account mailbox - trying to
1799            // provision any other mailbox may result in race conditions and the
1800            // creation of multiple policy keys.
1801            int status = e.mStatus;
1802            if (CommandStatus.isNeedsProvisioning(status)) {
1803                if (!tryProvision()) {
1804                    // Set the appropriate failure status
1805                    mExitStatus = EXIT_SECURITY_FAILURE;
1806                    return;
1807                }
1808            } else if (CommandStatus.isDeniedAccess(status)) {
1809                mExitStatus = EXIT_ACCESS_DENIED;
1810                return;
1811            } else {
1812                userLog("Unexpected status: " + CommandStatus.toString(status));
1813                mExitStatus = EXIT_EXCEPTION;
1814            }
1815        } catch (IOException e) {
1816            // We catch this here to send the folder sync status callback
1817            // A folder sync failed callback will get sent from run()
1818            try {
1819                if (!mStop) {
1820                    // NOTE: The correct status is CONNECTION_ERROR, but the UI displays this, and
1821                    // it's not really appropriate for EAS as this is not unexpected for a ping and
1822                    // connection errors are retried in any case
1823                    ExchangeService.callback()
1824                        .syncMailboxListStatus(mAccount.mId,
1825                                EmailServiceStatus.SUCCESS, 0);
1826                }
1827            } catch (RemoteException e1) {
1828                // Don't care if this fails
1829            }
1830            throw e;
1831        }
1832    }
1833
1834    /**
1835     * Reset either our minimum or maximum ping heartbeat to a heartbeat known to be legal
1836     * @param legalHeartbeat a known legal heartbeat (from the EAS server)
1837     */
1838    /*package*/ void resetHeartbeats(int legalHeartbeat) {
1839        userLog("Resetting min/max heartbeat, legal = " + legalHeartbeat);
1840        // We are here because the current heartbeat (mPingHeartbeat) is invalid.  Depending on
1841        // whether the argument is above or below the current heartbeat, we can infer the need to
1842        // change either the minimum or maximum heartbeat
1843        if (legalHeartbeat > mPingHeartbeat) {
1844            // The legal heartbeat is higher than the ping heartbeat; therefore, our minimum was
1845            // too low.  We respond by raising either or both of the minimum heartbeat or the
1846            // force heartbeat to the argument value
1847            if (mPingMinHeartbeat < legalHeartbeat) {
1848                mPingMinHeartbeat = legalHeartbeat;
1849            }
1850            if (mPingForceHeartbeat < legalHeartbeat) {
1851                mPingForceHeartbeat = legalHeartbeat;
1852            }
1853            // If our minimum is now greater than the max, bring them together
1854            if (mPingMinHeartbeat > mPingMaxHeartbeat) {
1855                mPingMaxHeartbeat = legalHeartbeat;
1856            }
1857        } else if (legalHeartbeat < mPingHeartbeat) {
1858            // The legal heartbeat is lower than the ping heartbeat; therefore, our maximum was
1859            // too high.  We respond by lowering the maximum to the argument value
1860            mPingMaxHeartbeat = legalHeartbeat;
1861            // If our maximum is now less than the minimum, bring them together
1862            if (mPingMaxHeartbeat < mPingMinHeartbeat) {
1863                mPingMinHeartbeat = legalHeartbeat;
1864            }
1865        }
1866        // Set current heartbeat to the legal heartbeat
1867        mPingHeartbeat = legalHeartbeat;
1868        // Allow the heartbeat logic to run
1869        mPingHeartbeatDropped = false;
1870    }
1871
1872    private void pushFallback(long mailboxId) {
1873        Mailbox mailbox = Mailbox.restoreMailboxWithId(mContext, mailboxId);
1874        if (mailbox == null) {
1875            return;
1876        }
1877        ContentValues cv = new ContentValues();
1878        int mins = PING_FALLBACK_PIM;
1879        if (mailbox.mType == Mailbox.TYPE_INBOX) {
1880            mins = PING_FALLBACK_INBOX;
1881        }
1882        cv.put(Mailbox.SYNC_INTERVAL, mins);
1883        mContentResolver.update(ContentUris.withAppendedId(Mailbox.CONTENT_URI, mailboxId),
1884                cv, null, null);
1885        errorLog("*** PING ERROR LOOP: Set " + mailbox.mDisplayName + " to " + mins + " min sync");
1886        ExchangeService.kick("push fallback");
1887    }
1888
1889    /**
1890     * Simplistic attempt to determine a NAT timeout, based on experience with various carriers
1891     * and networks.  The string "reset by peer" is very common in these situations, so we look for
1892     * that specifically.  We may add additional tests here as more is learned.
1893     * @param message
1894     * @return whether this message is likely associated with a NAT failure
1895     */
1896    private boolean isLikelyNatFailure(String message) {
1897        if (message == null) return false;
1898        if (message.contains("reset by peer")) {
1899            return true;
1900        }
1901        return false;
1902    }
1903
1904    private void runPingLoop() throws IOException, StaleFolderListException,
1905            IllegalHeartbeatException, CommandStatusException {
1906        int pingHeartbeat = mPingHeartbeat;
1907        userLog("runPingLoop");
1908        // Do push for all sync services here
1909        long endTime = System.currentTimeMillis() + (30*MINUTES);
1910        HashMap<String, Integer> pingErrorMap = new HashMap<String, Integer>();
1911        ArrayList<String> readyMailboxes = new ArrayList<String>();
1912        ArrayList<String> notReadyMailboxes = new ArrayList<String>();
1913        int pingWaitCount = 0;
1914        long inboxId = -1;
1915
1916        while ((System.currentTimeMillis() < endTime) && !mStop) {
1917            // Count of pushable mailboxes
1918            int pushCount = 0;
1919            // Count of mailboxes that can be pushed right now
1920            int canPushCount = 0;
1921            // Count of uninitialized boxes
1922            int uninitCount = 0;
1923
1924            Serializer s = new Serializer();
1925            Cursor c = mContentResolver.query(Mailbox.CONTENT_URI, Mailbox.CONTENT_PROJECTION,
1926                    MailboxColumns.ACCOUNT_KEY + '=' + mAccount.mId +
1927                    AND_FREQUENCY_PING_PUSH_AND_NOT_ACCOUNT_MAILBOX, null, null);
1928            notReadyMailboxes.clear();
1929            readyMailboxes.clear();
1930            // Look for an inbox, and remember its id
1931            if (inboxId == -1) {
1932                inboxId = Mailbox.findMailboxOfType(mContext, mAccount.mId, Mailbox.TYPE_INBOX);
1933            }
1934            try {
1935                // Loop through our pushed boxes seeing what is available to push
1936                while (c.moveToNext()) {
1937                    pushCount++;
1938                    // Two requirements for push:
1939                    // 1) ExchangeService tells us the mailbox is syncable (not running/not stopped)
1940                    // 2) The syncKey isn't "0" (i.e. it's synced at least once)
1941                    long mailboxId = c.getLong(Mailbox.CONTENT_ID_COLUMN);
1942                    int pingStatus = ExchangeService.pingStatus(mailboxId);
1943                    String mailboxName = c.getString(Mailbox.CONTENT_DISPLAY_NAME_COLUMN);
1944                    if (pingStatus == ExchangeService.PING_STATUS_OK) {
1945                        String syncKey = c.getString(Mailbox.CONTENT_SYNC_KEY_COLUMN);
1946                        if ((syncKey == null) || syncKey.equals("0")) {
1947                            // We can't push until the initial sync is done
1948                            pushCount--;
1949                            uninitCount++;
1950                            continue;
1951                        }
1952
1953                        if (canPushCount++ == 0) {
1954                            // Initialize the Ping command
1955                            s.start(Tags.PING_PING)
1956                                .data(Tags.PING_HEARTBEAT_INTERVAL,
1957                                        Integer.toString(pingHeartbeat))
1958                                .start(Tags.PING_FOLDERS);
1959                        }
1960
1961                        String folderClass = getTargetCollectionClassFromCursor(c);
1962                        s.start(Tags.PING_FOLDER)
1963                            .data(Tags.PING_ID, c.getString(Mailbox.CONTENT_SERVER_ID_COLUMN))
1964                            .data(Tags.PING_CLASS, folderClass)
1965                            .end();
1966                        readyMailboxes.add(mailboxName);
1967                    } else if ((pingStatus == ExchangeService.PING_STATUS_RUNNING) ||
1968                            (pingStatus == ExchangeService.PING_STATUS_WAITING)) {
1969                        notReadyMailboxes.add(mailboxName);
1970                    } else if (pingStatus == ExchangeService.PING_STATUS_UNABLE) {
1971                        pushCount--;
1972                        userLog(mailboxName, " in error state; ignore");
1973                        continue;
1974                    }
1975                }
1976            } finally {
1977                c.close();
1978            }
1979
1980            if (Eas.USER_LOG) {
1981                if (!notReadyMailboxes.isEmpty()) {
1982                    userLog("Ping not ready for: " + notReadyMailboxes);
1983                }
1984                if (!readyMailboxes.isEmpty()) {
1985                    userLog("Ping ready for: " + readyMailboxes);
1986                }
1987            }
1988
1989            // If we've waited 10 seconds or more, just ping with whatever boxes are ready
1990            // But use a shorter than normal heartbeat
1991            boolean forcePing = !notReadyMailboxes.isEmpty() && (pingWaitCount > 5);
1992
1993            if ((canPushCount > 0) && ((canPushCount == pushCount) || forcePing)) {
1994                // If all pingable boxes are ready for push, send Ping to the server
1995                s.end().end().done();
1996                pingWaitCount = 0;
1997                mPostReset = false;
1998                mPostAborted = false;
1999
2000                // If we've been stopped, this is a good time to return
2001                if (mStop) return;
2002
2003                long pingTime = SystemClock.elapsedRealtime();
2004                try {
2005                    // Send the ping, wrapped by appropriate timeout/alarm
2006                    if (forcePing) {
2007                        userLog("Forcing ping after waiting for all boxes to be ready");
2008                    }
2009                    EasResponse resp =
2010                        sendPing(s.toByteArray(), forcePing ? mPingForceHeartbeat : pingHeartbeat);
2011
2012                    try {
2013                        int code = resp.getStatus();
2014                        userLog("Ping response: ", code);
2015
2016                        // If we're not allowed to sync (e.g. roaming policy), terminate gracefully
2017                        // now; otherwise we might start a sync based on the response
2018                        if (!ExchangeService.canAutoSync(mAccount)) {
2019                            mStop = true;
2020                        }
2021
2022                        // Return immediately if we've been asked to stop during the ping
2023                        if (mStop) {
2024                            userLog("Stopping pingLoop");
2025                            return;
2026                        }
2027
2028                        if (code == HttpStatus.SC_OK) {
2029                            // Make sure to clear out any pending sync errors
2030                            ExchangeService.removeFromSyncErrorMap(mMailboxId);
2031                            if (!resp.isEmpty()) {
2032                                InputStream is = resp.getInputStream();
2033                                int pingResult = parsePingResult(is, mContentResolver,
2034                                        pingErrorMap);
2035                                // If our ping completed (status = 1), and wasn't forced and we're
2036                                // not at the maximum, try increasing timeout by two minutes
2037                                if (pingResult == PROTOCOL_PING_STATUS_COMPLETED && !forcePing) {
2038                                    if (pingHeartbeat > mPingHighWaterMark) {
2039                                        mPingHighWaterMark = pingHeartbeat;
2040                                        userLog("Setting high water mark at: ", mPingHighWaterMark);
2041                                    }
2042                                    if ((pingHeartbeat < mPingMaxHeartbeat) &&
2043                                            !mPingHeartbeatDropped) {
2044                                        pingHeartbeat += PING_HEARTBEAT_INCREMENT;
2045                                        if (pingHeartbeat > mPingMaxHeartbeat) {
2046                                            pingHeartbeat = mPingMaxHeartbeat;
2047                                        }
2048                                        userLog("Increase ping heartbeat to ", pingHeartbeat, "s");
2049                                    }
2050                                }
2051                            } else {
2052                                userLog("Ping returned empty result; throwing IOException");
2053                                throw new IOException();
2054                            }
2055                        } else if (isAuthError(code)) {
2056                            mExitStatus = EXIT_LOGIN_FAILURE;
2057                            userLog("Authorization error during Ping: ", code);
2058                            throw new IOException();
2059                        }
2060                    } finally {
2061                        resp.close();
2062                    }
2063                } catch (IOException e) {
2064                    String message = e.getMessage();
2065                    // If we get the exception that is indicative of a NAT timeout and if we
2066                    // haven't yet "fixed" the timeout, back off by two minutes and "fix" it
2067                    boolean hasMessage = message != null;
2068                    userLog("IOException runPingLoop: " + (hasMessage ? message : "[no message]"));
2069                    if (mPostReset) {
2070                        // Nothing to do in this case; this is ExchangeService telling us to try
2071                        // another ping.
2072                    } else if (mPostAborted || isLikelyNatFailure(message)) {
2073                        long pingLength = SystemClock.elapsedRealtime() - pingTime;
2074                        if ((pingHeartbeat > mPingMinHeartbeat) &&
2075                                (pingHeartbeat > mPingHighWaterMark)) {
2076                            pingHeartbeat -= PING_HEARTBEAT_INCREMENT;
2077                            mPingHeartbeatDropped = true;
2078                            if (pingHeartbeat < mPingMinHeartbeat) {
2079                                pingHeartbeat = mPingMinHeartbeat;
2080                            }
2081                            userLog("Decreased ping heartbeat to ", pingHeartbeat, "s");
2082                        } else if (mPostAborted) {
2083                            // There's no point in throwing here; this can happen in two cases
2084                            // 1) An alarm, which indicates minutes without activity; no sense
2085                            //    backing off
2086                            // 2) ExchangeService abort, due to sync of mailbox.  Again, we want to
2087                            //    keep on trying to ping
2088                            userLog("Ping aborted; retry");
2089                        } else if (pingLength < 2000) {
2090                            userLog("Abort or NAT type return < 2 seconds; throwing IOException");
2091                            throw e;
2092                        } else {
2093                            userLog("NAT type IOException");
2094                        }
2095                    } else if (hasMessage && message.contains("roken pipe")) {
2096                        // The "broken pipe" error (uppercase or lowercase "b") seems to be an
2097                        // internal error, so let's not throw an exception (which leads to delays)
2098                        // but rather simply run through the loop again
2099                    } else {
2100                        throw e;
2101                    }
2102                }
2103            } else if (forcePing) {
2104                // In this case, there aren't any boxes that are pingable, but there are boxes
2105                // waiting (for IOExceptions)
2106                userLog("pingLoop waiting 60s for any pingable boxes");
2107                sleep(60*SECONDS, true);
2108            } else if (pushCount > 0) {
2109                // If we want to Ping, but can't just yet, wait a little bit
2110                // TODO Change sleep to wait and use notify from ExchangeService when a sync ends
2111                sleep(2*SECONDS, false);
2112                pingWaitCount++;
2113                //userLog("pingLoop waited 2s for: ", (pushCount - canPushCount), " box(es)");
2114            } else if (uninitCount > 0) {
2115                // In this case, we're doing an initial sync of at least one mailbox.  Since this
2116                // is typically a one-time case, I'm ok with trying again every 10 seconds until
2117                // we're in one of the other possible states.
2118                userLog("pingLoop waiting for initial sync of ", uninitCount, " box(es)");
2119                sleep(10*SECONDS, true);
2120            } else if (inboxId == -1) {
2121                // In this case, we're still syncing mailboxes, so sleep for only a short time
2122                sleep(45*SECONDS, true);
2123            } else {
2124                // We've got nothing to do, so we'll check again in 20 minutes at which time
2125                // we'll update the folder list, check for policy changes and/or remote wipe, etc.
2126                // Let the device sleep in the meantime...
2127                userLog(ACCOUNT_MAILBOX_SLEEP_TEXT);
2128                sleep(ACCOUNT_MAILBOX_SLEEP_TIME, true);
2129            }
2130        }
2131
2132        // Save away the current heartbeat
2133        mPingHeartbeat = pingHeartbeat;
2134    }
2135
2136    private void sleep(long ms, boolean runAsleep) {
2137        if (runAsleep) {
2138            ExchangeService.runAsleep(mMailboxId, ms+(5*SECONDS));
2139        }
2140        try {
2141            Thread.sleep(ms);
2142        } catch (InterruptedException e) {
2143            // Doesn't matter whether we stop early; it's the thought that counts
2144        } finally {
2145            if (runAsleep) {
2146                ExchangeService.runAwake(mMailboxId);
2147            }
2148        }
2149    }
2150
2151    private int parsePingResult(InputStream is, ContentResolver cr,
2152            HashMap<String, Integer> errorMap)
2153            throws IOException, StaleFolderListException, IllegalHeartbeatException,
2154                CommandStatusException {
2155        PingParser pp = new PingParser(is, this);
2156        if (pp.parse()) {
2157            // True indicates some mailboxes need syncing...
2158            // syncList has the serverId's of the mailboxes...
2159            mBindArguments[0] = Long.toString(mAccount.mId);
2160            mPingChangeList = pp.getSyncList();
2161            for (String serverId: mPingChangeList) {
2162                mBindArguments[1] = serverId;
2163                Cursor c = cr.query(Mailbox.CONTENT_URI, Mailbox.CONTENT_PROJECTION,
2164                        WHERE_ACCOUNT_KEY_AND_SERVER_ID, mBindArguments, null);
2165                try {
2166                    if (c.moveToFirst()) {
2167
2168                        /**
2169                         * Check the boxes reporting changes to see if there really were any...
2170                         * We do this because bugs in various Exchange servers can put us into a
2171                         * looping behavior by continually reporting changes in a mailbox, even when
2172                         * there aren't any.
2173                         *
2174                         * This behavior is seemingly random, and therefore we must code defensively
2175                         * by backing off of push behavior when it is detected.
2176                         *
2177                         * One known cause, on certain Exchange 2003 servers, is acknowledged by
2178                         * Microsoft, and the server hotfix for this case can be found at
2179                         * http://support.microsoft.com/kb/923282
2180                         */
2181
2182                        // Check the status of the last sync
2183                        String status = c.getString(Mailbox.CONTENT_SYNC_STATUS_COLUMN);
2184                        int type = ExchangeService.getStatusType(status);
2185                        // This check should always be true...
2186                        if (type == ExchangeService.SYNC_PING) {
2187                            int changeCount = ExchangeService.getStatusChangeCount(status);
2188                            if (changeCount > 0) {
2189                                errorMap.remove(serverId);
2190                            } else if (changeCount == 0) {
2191                                // This means that a ping reported changes in error; we keep a count
2192                                // of consecutive errors of this kind
2193                                String name = c.getString(Mailbox.CONTENT_DISPLAY_NAME_COLUMN);
2194                                Integer failures = errorMap.get(serverId);
2195                                if (failures == null) {
2196                                    userLog("Last ping reported changes in error for: ", name);
2197                                    errorMap.put(serverId, 1);
2198                                } else if (failures > MAX_PING_FAILURES) {
2199                                    // We'll back off of push for this box
2200                                    pushFallback(c.getLong(Mailbox.CONTENT_ID_COLUMN));
2201                                    continue;
2202                                } else {
2203                                    userLog("Last ping reported changes in error for: ", name);
2204                                    errorMap.put(serverId, failures + 1);
2205                                }
2206                            }
2207                        }
2208
2209                        // If there were no problems with previous sync, we'll start another one
2210                        ExchangeService.startManualSync(c.getLong(Mailbox.CONTENT_ID_COLUMN),
2211                                ExchangeService.SYNC_PING, null);
2212                    }
2213                } finally {
2214                    c.close();
2215                }
2216            }
2217        }
2218        return pp.getSyncStatus();
2219    }
2220
2221    /**
2222     * Common code to sync E+PIM data
2223     *
2224     * @param target an EasMailbox, EasContacts, or EasCalendar object
2225     */
2226    public void sync(AbstractSyncAdapter target) throws IOException {
2227        Mailbox mailbox = target.mMailbox;
2228
2229        boolean moreAvailable = true;
2230        int loopingCount = 0;
2231        while (!mStop && (moreAvailable || hasPendingRequests())) {
2232            // If we have no connectivity, just exit cleanly. ExchangeService will start us up again
2233            // when connectivity has returned
2234            if (!hasConnectivity()) {
2235                userLog("No connectivity in sync; finishing sync");
2236                mExitStatus = EXIT_DONE;
2237                return;
2238            }
2239
2240            // Every time through the loop we check to see if we're still syncable
2241            if (!target.isSyncable()) {
2242                mExitStatus = EXIT_DONE;
2243                return;
2244            }
2245
2246            // Now, handle various requests
2247            while (true) {
2248                Request req = null;
2249
2250                if (mRequestQueue.isEmpty()) {
2251                    break;
2252                } else {
2253                    req = mRequestQueue.peek();
2254                }
2255
2256                // Our two request types are PartRequest (loading attachment) and
2257                // MeetingResponseRequest (respond to a meeting request)
2258                if (req instanceof PartRequest) {
2259                    new AttachmentLoader(this, (PartRequest)req).loadAttachment();
2260                } else if (req instanceof MeetingResponseRequest) {
2261                    sendMeetingResponse((MeetingResponseRequest)req);
2262                } else if (req instanceof MessageMoveRequest) {
2263                    messageMoveRequest((MessageMoveRequest)req);
2264                }
2265
2266                // If there's an exception handling the request, we'll throw it
2267                // Otherwise, we remove the request
2268                mRequestQueue.remove();
2269            }
2270
2271            // Don't sync if we've got nothing to do
2272            if (!moreAvailable) {
2273                continue;
2274            }
2275
2276            Serializer s = new Serializer();
2277
2278            String className = target.getCollectionName();
2279            String syncKey = target.getSyncKey();
2280            userLog("sync, sending ", className, " syncKey: ", syncKey);
2281            s.start(Tags.SYNC_SYNC)
2282                .start(Tags.SYNC_COLLECTIONS)
2283                .start(Tags.SYNC_COLLECTION);
2284            // The "Class" element is removed in EAS 12.1 and later versions
2285            if (mProtocolVersionDouble < Eas.SUPPORTED_PROTOCOL_EX2007_SP1_DOUBLE) {
2286                s.data(Tags.SYNC_CLASS, className);
2287            }
2288            s.data(Tags.SYNC_SYNC_KEY, syncKey)
2289                .data(Tags.SYNC_COLLECTION_ID, mailbox.mServerId);
2290
2291            // Start with the default timeout
2292            int timeout = COMMAND_TIMEOUT;
2293            if (!syncKey.equals("0")) {
2294                // EAS doesn't allow GetChanges in an initial sync; sending other options
2295                // appears to cause the server to delay its response in some cases, and this delay
2296                // can be long enough to result in an IOException and total failure to sync.
2297                // Therefore, we don't send any options with the initial sync.
2298                // Set the truncation amount, body preference, lookback, etc.
2299                target.sendSyncOptions(mProtocolVersionDouble, s);
2300            } else {
2301                // Use enormous timeout for initial sync, which empirically can take a while longer
2302                timeout = 120*SECONDS;
2303            }
2304            // Send our changes up to the server
2305            target.sendLocalChanges(s);
2306
2307            s.end().end().end().done();
2308            EasResponse resp = sendHttpClientPost("Sync", new ByteArrayEntity(s.toByteArray()),
2309                    timeout);
2310            try {
2311                int code = resp.getStatus();
2312                if (code == HttpStatus.SC_OK) {
2313                    // In EAS 12.1, we can get "empty" sync responses, which indicate that there are
2314                    // no changes in the mailbox; handle that case here
2315                    // There are two cases here; if we get back a compressed stream (GZIP), we won't
2316                    // know until we try to parse it (and generate an EmptyStreamException). If we
2317                    // get uncompressed data, the response will be empty (i.e. have zero length)
2318                    boolean emptyStream = false;
2319                    if (!resp.isEmpty()) {
2320                        InputStream is = resp.getInputStream();
2321                        try {
2322                            moreAvailable = target.parse(is);
2323                            if (target.isLooping()) {
2324                                loopingCount++;
2325                                userLog("** Looping: " + loopingCount);
2326                                // After the maximum number of loops, we'll set moreAvailable to
2327                                // false and allow the sync loop to terminate
2328                                if (moreAvailable && (loopingCount > MAX_LOOPING_COUNT)) {
2329                                    userLog("** Looping force stopped");
2330                                    moreAvailable = false;
2331                                }
2332                            } else {
2333                                loopingCount = 0;
2334                            }
2335                            target.cleanup();
2336                        } catch (EmptyStreamException e) {
2337                            userLog("Empty stream detected in GZIP response");
2338                            emptyStream = true;
2339                        } catch (CommandStatusException e) {
2340                            // TODO 14.1
2341                            int status = e.mStatus;
2342                            if (CommandStatus.isNeedsProvisioning(status)) {
2343                                mExitStatus = EXIT_SECURITY_FAILURE;
2344                            } else if (CommandStatus.isDeniedAccess(status)) {
2345                                mExitStatus = EXIT_ACCESS_DENIED;
2346                            } else if (CommandStatus.isTransientError(status)) {
2347                                mExitStatus = EXIT_IO_ERROR;
2348                            } else {
2349                                mExitStatus = EXIT_EXCEPTION;
2350                            }
2351                            return;
2352                        }
2353                    } else {
2354                        emptyStream = true;
2355                    }
2356
2357                    if (emptyStream) {
2358                        // If this happens, exit cleanly, and change the interval from push to ping
2359                        // if necessary
2360                        userLog("Empty sync response; finishing");
2361                        if (mMailbox.mSyncInterval == Mailbox.CHECK_INTERVAL_PUSH) {
2362                            userLog("Changing mailbox from push to ping");
2363                            ContentValues cv = new ContentValues();
2364                            cv.put(Mailbox.SYNC_INTERVAL, Mailbox.CHECK_INTERVAL_PING);
2365                            mContentResolver.update(
2366                                    ContentUris.withAppendedId(Mailbox.CONTENT_URI, mMailbox.mId),
2367                                    cv, null, null);
2368                        }
2369                        if (mRequestQueue.isEmpty()) {
2370                            mExitStatus = EXIT_DONE;
2371                            return;
2372                        } else {
2373                            continue;
2374                        }
2375                    }
2376                } else {
2377                    userLog("Sync response error: ", code);
2378                    if (isProvisionError(code)) {
2379                        mExitStatus = EXIT_SECURITY_FAILURE;
2380                    } else if (isAuthError(code)) {
2381                        mExitStatus = EXIT_LOGIN_FAILURE;
2382                    } else {
2383                        mExitStatus = EXIT_IO_ERROR;
2384                    }
2385                    return;
2386                }
2387            } finally {
2388                resp.close();
2389            }
2390        }
2391        mExitStatus = EXIT_DONE;
2392    }
2393
2394    protected boolean setupService() {
2395        synchronized(getSynchronizer()) {
2396            mThread = Thread.currentThread();
2397            android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_BACKGROUND);
2398            TAG = mThread.getName();
2399        }
2400        // Make sure account and mailbox are always the latest from the database
2401        mAccount = Account.restoreAccountWithId(mContext, mAccount.mId);
2402        if (mAccount == null) return false;
2403        mMailbox = Mailbox.restoreMailboxWithId(mContext, mMailbox.mId);
2404        if (mMailbox == null) return false;
2405        HostAuth ha = HostAuth.restoreHostAuthWithId(mContext, mAccount.mHostAuthKeyRecv);
2406        if (ha == null) return false;
2407        mHostAddress = ha.mAddress;
2408        mUserName = ha.mLogin;
2409        mPassword = ha.mPassword;
2410        setConnectionParameters(
2411                (ha.mFlags & HostAuth.FLAG_SSL) != 0,
2412                (ha.mFlags & HostAuth.FLAG_TRUST_ALL) != 0,
2413                ha.mClientCertAlias);
2414
2415        // Set up our protocol version from the Account
2416        mProtocolVersion = mAccount.mProtocolVersion;
2417        // If it hasn't been set up, start with default version
2418        if (mProtocolVersion == null) {
2419            mProtocolVersion = Eas.DEFAULT_PROTOCOL_VERSION;
2420        }
2421        mProtocolVersionDouble = Eas.getProtocolVersionDouble(mProtocolVersion);
2422        return true;
2423    }
2424
2425    @Override
2426    public void run() {
2427        // Make sure account and mailbox are still valid
2428        if (!setupService()) return;
2429        // If we've been stopped, we're done
2430        if (mStop) return;
2431        if (mSyncReason >= ExchangeService.SYNC_CALLBACK_START) {
2432            try {
2433                ExchangeService.callback().syncMailboxStatus(mMailboxId,
2434                        EmailServiceStatus.IN_PROGRESS, 0);
2435            } catch (RemoteException e1) {
2436                // Don't care if this fails
2437            }
2438        }
2439
2440        // Whether or not we're the account mailbox
2441        try {
2442            mDeviceId = ExchangeService.getDeviceId(mContext);
2443            if ((mMailbox == null) || (mAccount == null)) {
2444                return;
2445            } else if (mMailbox.mType == Mailbox.TYPE_EAS_ACCOUNT_MAILBOX) {
2446                runAccountMailbox();
2447            } else {
2448                AbstractSyncAdapter target;
2449                if (mMailbox.mType == Mailbox.TYPE_CONTACTS) {
2450                    target = new ContactsSyncAdapter( this);
2451                } else if (mMailbox.mType == Mailbox.TYPE_CALENDAR) {
2452                    target = new CalendarSyncAdapter(this);
2453                } else {
2454                    target = new EmailSyncAdapter(this);
2455                }
2456                // We loop here because someone might have put a request in while we were syncing
2457                // and we've missed that opportunity...
2458                do {
2459                    if (mRequestTime != 0) {
2460                        userLog("Looping for user request...");
2461                        mRequestTime = 0;
2462                    }
2463                    sync(target);
2464                } while (mRequestTime != 0);
2465            }
2466        } catch (EasAuthenticationException e) {
2467            userLog("Caught authentication error");
2468            mExitStatus = EXIT_LOGIN_FAILURE;
2469        } catch (IOException e) {
2470            String message = e.getMessage();
2471            userLog("Caught IOException: ", (message == null) ? "No message" : message);
2472            mExitStatus = EXIT_IO_ERROR;
2473        } catch (Exception e) {
2474            userLog("Uncaught exception in EasSyncService", e);
2475        } finally {
2476            int status;
2477
2478            if (!mStop) {
2479                userLog("Sync finished");
2480                ExchangeService.done(this);
2481                switch (mExitStatus) {
2482                    case EXIT_IO_ERROR:
2483                        status = EmailServiceStatus.CONNECTION_ERROR;
2484                        break;
2485                    case EXIT_DONE:
2486                        status = EmailServiceStatus.SUCCESS;
2487                        ContentValues cv = new ContentValues();
2488                        cv.put(Mailbox.SYNC_TIME, System.currentTimeMillis());
2489                        String s = "S" + mSyncReason + ':' + status + ':' + mChangeCount;
2490                        cv.put(Mailbox.SYNC_STATUS, s);
2491                        mContentResolver.update(ContentUris.withAppendedId(Mailbox.CONTENT_URI,
2492                                mMailboxId), cv, null, null);
2493                        break;
2494                    case EXIT_LOGIN_FAILURE:
2495                        status = EmailServiceStatus.LOGIN_FAILED;
2496                        break;
2497                    case EXIT_SECURITY_FAILURE:
2498                        status = EmailServiceStatus.SECURITY_FAILURE;
2499                        // Ask for a new folder list.  This should wake up the account mailbox; a
2500                        // security error in account mailbox should start the provisioning process
2501                        ExchangeService.reloadFolderList(mContext, mAccount.mId, true);
2502                        break;
2503                    case EXIT_ACCESS_DENIED:
2504                        status = EmailServiceStatus.ACCESS_DENIED;
2505                        break;
2506                    default:
2507                        status = EmailServiceStatus.REMOTE_EXCEPTION;
2508                        errorLog("Sync ended due to an exception.");
2509                        break;
2510                }
2511            } else {
2512                userLog("Stopped sync finished.");
2513                status = EmailServiceStatus.SUCCESS;
2514            }
2515
2516            // Send a callback if this run was initiated by a service call
2517            if (mSyncReason >= ExchangeService.SYNC_CALLBACK_START) {
2518                try {
2519                    // Unless the user specifically asked for a sync, we really don't want to report
2520                    // connection issues, as they are likely to be transient.  In this case, we
2521                    // simply report success, so that the progress indicator terminates without
2522                    // putting up an error banner
2523                    if (mSyncReason != ExchangeService.SYNC_UI_REQUEST &&
2524                            status == EmailServiceStatus.CONNECTION_ERROR) {
2525                        status = EmailServiceStatus.SUCCESS;
2526                    }
2527                    ExchangeService.callback().syncMailboxStatus(mMailboxId, status, 0);
2528                } catch (RemoteException e1) {
2529                    // Don't care if this fails
2530                }
2531            }
2532
2533            // Make sure ExchangeService knows about this
2534            ExchangeService.kick("sync finished");
2535        }
2536    }
2537}
2538