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