BluetoothPbapObexServer.java revision 0d1322483285ccc9ca7bedf515821c5c105a44e6
1/*
2 * Copyright (c) 2008-2009, Motorola, Inc.
3 *
4 * All rights reserved.
5 *
6 * Redistribution and use in source and binary forms, with or without
7 * modification, are permitted provided that the following conditions are met:
8 *
9 * - Redistributions of source code must retain the above copyright notice,
10 * this list of conditions and the following disclaimer.
11 *
12 * - Redistributions in binary form must reproduce the above copyright notice,
13 * this list of conditions and the following disclaimer in the documentation
14 * and/or other materials provided with the distribution.
15 *
16 * - Neither the name of the Motorola, Inc. nor the names of its contributors
17 * may be used to endorse or promote products derived from this software
18 * without specific prior written permission.
19 *
20 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
21 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
24 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
25 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
26 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
27 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
28 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
29 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
30 * POSSIBILITY OF SUCH DAMAGE.
31 */
32
33package com.android.bluetooth.pbap;
34
35import android.content.Context;
36import android.os.Message;
37import android.os.Handler;
38import android.text.TextUtils;
39import android.util.Log;
40import android.provider.CallLog.Calls;
41import android.provider.CallLog;
42
43import java.io.IOException;
44import java.io.OutputStream;
45import java.text.CharacterIterator;
46import java.text.StringCharacterIterator;
47import java.util.ArrayList;
48import java.util.Arrays;
49
50import javax.obex.ServerRequestHandler;
51import javax.obex.ResponseCodes;
52import javax.obex.ApplicationParameter;
53import javax.obex.ServerOperation;
54import javax.obex.Operation;
55import javax.obex.HeaderSet;
56
57public class BluetoothPbapObexServer extends ServerRequestHandler {
58
59    private static final String TAG = "BluetoothPbapObexServer";
60
61    private static final boolean D = BluetoothPbapService.DEBUG;
62
63    private static final boolean V = BluetoothPbapService.VERBOSE;
64
65    private static final int UUID_LENGTH = 16;
66
67    // The length of suffix of vcard name - ".vcf" is 5
68    private static final int VCARD_NAME_SUFFIX_LENGTH = 5;
69
70    // 128 bit UUID for PBAP
71    private static final byte[] PBAP_TARGET = new byte[] {
72            0x79, 0x61, 0x35, (byte)0xf0, (byte)0xf0, (byte)0xc5, 0x11, (byte)0xd8, 0x09, 0x66,
73            0x08, 0x00, 0x20, 0x0c, (byte)0x9a, 0x66
74    };
75
76    // Currently not support SIM card
77    private static final String[] LEGAL_PATH = {
78            "/telecom", "/telecom/pb", "/telecom/ich", "/telecom/och", "/telecom/mch",
79            "/telecom/cch"
80    };
81
82    @SuppressWarnings("unused")
83    private static final String[] LEGAL_PATH_WITH_SIM = {
84            "/telecom", "/telecom/pb", "/telecom/ich", "/telecom/och", "/telecom/mch",
85            "/telecom/cch", "/SIM1", "/SIM1/telecom", "/SIM1/telecom/ich", "/SIM1/telecom/och",
86            "/SIM1/telecom/mch", "/SIM1/telecom/cch", "/SIM1/telecom/pb"
87
88    };
89
90    // SIM card
91    private static final String SIM1 = "SIM1";
92
93    // missed call history
94    private static final String MCH = "mch";
95
96    // incoming call history
97    private static final String ICH = "ich";
98
99    // outgoing call history
100    private static final String OCH = "och";
101
102    // combined call history
103    private static final String CCH = "cch";
104
105    // phone book
106    private static final String PB = "pb";
107
108    private static final String ICH_PATH = "/telecom/ich";
109
110    private static final String OCH_PATH = "/telecom/och";
111
112    private static final String MCH_PATH = "/telecom/mch";
113
114    private static final String CCH_PATH = "/telecom/cch";
115
116    private static final String PB_PATH = "/telecom/pb";
117
118    // type for list vcard objects
119    private static final String TYPE_LISTING = "x-bt/vcard-listing";
120
121    // type for get single vcard object
122    private static final String TYPE_VCARD = "x-bt/vcard";
123
124    // to indicate if need send body besides headers
125    private static final int NEED_SEND_BODY = -1;
126
127    // type for download all vcard objects
128    private static final String TYPE_PB = "x-bt/phonebook";
129
130    // The number of indexes in the phone book.
131    private boolean mNeedPhonebookSize = false;
132
133    // The number of missed calls that have not been checked on the PSE at the
134    // point of the request. Only apply to "mch" case.
135    private boolean mNeedNewMissedCallsNum = false;
136
137    private int mMissedCallSize = 0;
138
139    // record current path the client are browsing
140    private String mCurrentPath = "";
141
142    private Handler mCallback = null;
143
144    private Context mContext;
145
146    private BluetoothPbapVcardManager mVcardManager;
147
148    private int mOrderBy  = ORDER_BY_INDEXED;
149
150    private static int CALLLOG_NUM_LIMIT = 50;
151
152    public static int ORDER_BY_INDEXED = 0;
153
154    public static int ORDER_BY_ALPHABETICAL = 1;
155
156    public static boolean sIsAborted = false;
157
158    public static class ContentType {
159        public static final int PHONEBOOK = 1;
160
161        public static final int INCOMING_CALL_HISTORY = 2;
162
163        public static final int OUTGOING_CALL_HISTORY = 3;
164
165        public static final int MISSED_CALL_HISTORY = 4;
166
167        public static final int COMBINED_CALL_HISTORY = 5;
168    }
169
170    public BluetoothPbapObexServer(Handler callback, Context context) {
171        super();
172        mCallback = callback;
173        mContext = context;
174        mVcardManager = new BluetoothPbapVcardManager(mContext);
175    }
176
177    @Override
178    public int onConnect(final HeaderSet request, HeaderSet reply) {
179        if (V) logHeader(request);
180        notifyUpdateWakeLock();
181        try {
182            byte[] uuid = (byte[])request.getHeader(HeaderSet.TARGET);
183            if (uuid == null) {
184                return ResponseCodes.OBEX_HTTP_NOT_ACCEPTABLE;
185            }
186            if (D) Log.d(TAG, "onConnect(): uuid=" + Arrays.toString(uuid));
187
188            if (uuid.length != UUID_LENGTH) {
189                Log.w(TAG, "Wrong UUID length");
190                return ResponseCodes.OBEX_HTTP_NOT_ACCEPTABLE;
191            }
192            for (int i = 0; i < UUID_LENGTH; i++) {
193                if (uuid[i] != PBAP_TARGET[i]) {
194                    Log.w(TAG, "Wrong UUID");
195                    return ResponseCodes.OBEX_HTTP_NOT_ACCEPTABLE;
196                }
197            }
198            reply.setHeader(HeaderSet.WHO, uuid);
199        } catch (IOException e) {
200            Log.e(TAG, e.toString());
201            return ResponseCodes.OBEX_HTTP_INTERNAL_ERROR;
202        }
203
204        try {
205            byte[] remote = (byte[])request.getHeader(HeaderSet.WHO);
206            if (remote != null) {
207                if (D) Log.d(TAG, "onConnect(): remote=" + Arrays.toString(remote));
208                reply.setHeader(HeaderSet.TARGET, remote);
209            }
210        } catch (IOException e) {
211            Log.e(TAG, e.toString());
212            return ResponseCodes.OBEX_HTTP_INTERNAL_ERROR;
213        }
214
215        if (V) Log.v(TAG, "onConnect(): uuid is ok, will send out " +
216                "MSG_SESSION_ESTABLISHED msg.");
217
218        Message msg = Message.obtain(mCallback);
219        msg.what = BluetoothPbapService.MSG_SESSION_ESTABLISHED;
220        msg.sendToTarget();
221
222        return ResponseCodes.OBEX_HTTP_OK;
223    }
224
225    @Override
226    public void onDisconnect(final HeaderSet req, final HeaderSet resp) {
227        if (D) Log.d(TAG, "onDisconnect(): enter");
228        if (V) logHeader(req);
229        notifyUpdateWakeLock();
230        resp.responseCode = ResponseCodes.OBEX_HTTP_OK;
231        if (mCallback != null) {
232            Message msg = Message.obtain(mCallback);
233            msg.what = BluetoothPbapService.MSG_SESSION_DISCONNECTED;
234            msg.sendToTarget();
235            if (V) Log.v(TAG, "onDisconnect(): msg MSG_SESSION_DISCONNECTED sent out.");
236        }
237    }
238
239    @Override
240    public int onAbort(HeaderSet request, HeaderSet reply) {
241        if (D) Log.d(TAG, "onAbort(): enter.");
242        notifyUpdateWakeLock();
243        sIsAborted = true;
244        return ResponseCodes.OBEX_HTTP_OK;
245    }
246
247    @Override
248    public int onPut(final Operation op) {
249        if (D) Log.d(TAG, "onPut(): not support PUT request.");
250        notifyUpdateWakeLock();
251        return ResponseCodes.OBEX_HTTP_BAD_REQUEST;
252    }
253
254    @Override
255    public int onSetPath(final HeaderSet request, final HeaderSet reply, final boolean backup,
256            final boolean create) {
257        if (V) logHeader(request);
258        if (D) Log.d(TAG, "before setPath, mCurrentPath ==  " + mCurrentPath);
259        notifyUpdateWakeLock();
260        String current_path_tmp = mCurrentPath;
261        String tmp_path = null;
262        try {
263            tmp_path = (String)request.getHeader(HeaderSet.NAME);
264        } catch (IOException e) {
265            Log.e(TAG, "Get name header fail");
266            return ResponseCodes.OBEX_HTTP_INTERNAL_ERROR;
267        }
268        if (D) Log.d(TAG, "backup=" + backup + " create=" + create + " name=" + tmp_path);
269
270        if (backup) {
271            if (current_path_tmp.length() != 0) {
272                current_path_tmp = current_path_tmp.substring(0,
273                        current_path_tmp.lastIndexOf("/"));
274            }
275        } else {
276            if (tmp_path == null) {
277                current_path_tmp = "";
278            } else {
279                current_path_tmp = current_path_tmp + "/" + tmp_path;
280            }
281        }
282
283        if ((current_path_tmp.length() != 0) && (!isLegalPath(current_path_tmp))) {
284            if (create) {
285                Log.w(TAG, "path create is forbidden!");
286                return ResponseCodes.OBEX_HTTP_FORBIDDEN;
287            } else {
288                Log.w(TAG, "path is not legal");
289                return ResponseCodes.OBEX_HTTP_NOT_FOUND;
290            }
291        }
292        mCurrentPath = current_path_tmp;
293        if (V) Log.v(TAG, "after setPath, mCurrentPath ==  " + mCurrentPath);
294
295        return ResponseCodes.OBEX_HTTP_OK;
296    }
297
298    @Override
299    public void onClose() {
300        if (mCallback != null) {
301            Message msg = Message.obtain(mCallback);
302            msg.what = BluetoothPbapService.MSG_SERVERSESSION_CLOSE;
303            msg.sendToTarget();
304            if (D) Log.d(TAG, "onClose(): msg MSG_SERVERSESSION_CLOSE sent out.");
305        }
306    }
307
308    @Override
309    public int onGet(Operation op) {
310        notifyUpdateWakeLock();
311        sIsAborted = false;
312        HeaderSet request = null;
313        HeaderSet reply = new HeaderSet();
314        String type = "";
315        String name = "";
316        byte[] appParam = null;
317        AppParamValue appParamValue = new AppParamValue();
318        try {
319            request = op.getReceivedHeader();
320            type = (String)request.getHeader(HeaderSet.TYPE);
321            name = (String)request.getHeader(HeaderSet.NAME);
322            appParam = (byte[])request.getHeader(HeaderSet.APPLICATION_PARAMETER);
323        } catch (IOException e) {
324            Log.e(TAG, "request headers error");
325            return ResponseCodes.OBEX_HTTP_INTERNAL_ERROR;
326        }
327
328        if (V) logHeader(request);
329        if (D) Log.d(TAG, "OnGet type is " + type + "; name is " + name);
330
331        if (type == null) {
332            return ResponseCodes.OBEX_HTTP_NOT_ACCEPTABLE;
333        }
334        // Accroding to specification,the name header could be omitted such as
335        // sony erriccsonHBH-DS980
336
337        // For "x-bt/phonebook" and "x-bt/vcard-listing":
338        // if name == null, guess what carkit actually want from current path
339        // For "x-bt/vcard":
340        // We decide which kind of content client would like per current path
341
342        boolean validName = true;
343        if (TextUtils.isEmpty(name)) {
344            validName = false;
345        }
346
347        if (!validName || (validName && type.equals(TYPE_VCARD))) {
348            if (D) Log.d(TAG, "Guess what carkit actually want from current path (" +
349                    mCurrentPath + ")");
350
351            if (mCurrentPath.equals(PB_PATH)) {
352                appParamValue.needTag = ContentType.PHONEBOOK;
353            } else if (mCurrentPath.equals(ICH_PATH)) {
354                appParamValue.needTag = ContentType.INCOMING_CALL_HISTORY;
355            } else if (mCurrentPath.equals(OCH_PATH)) {
356                appParamValue.needTag = ContentType.OUTGOING_CALL_HISTORY;
357            } else if (mCurrentPath.equals(MCH_PATH)) {
358                appParamValue.needTag = ContentType.MISSED_CALL_HISTORY;
359                mNeedNewMissedCallsNum = true;
360            } else if (mCurrentPath.equals(CCH_PATH)) {
361                appParamValue.needTag = ContentType.COMBINED_CALL_HISTORY;
362            } else {
363                Log.w(TAG, "mCurrentpath is not valid path!!!");
364                return ResponseCodes.OBEX_HTTP_NOT_ACCEPTABLE;
365            }
366            if (D) Log.v(TAG, "onGet(): appParamValue.needTag=" + appParamValue.needTag);
367        } else {
368            // Not support SIM card currently
369            if (name.contains(SIM1.subSequence(0, SIM1.length()))) {
370                Log.w(TAG, "Not support access SIM card info!");
371                return ResponseCodes.OBEX_HTTP_NOT_ACCEPTABLE;
372            }
373
374            // we have weak name checking here to provide better
375            // compatibility with other devices,although unique name such as
376            // "pb.vcf" is required by SIG spec.
377            if (name.contains(PB.subSequence(0, PB.length()))) {
378                appParamValue.needTag = ContentType.PHONEBOOK;
379                if (D) Log.v(TAG, "download phonebook request");
380            } else if (name.contains(ICH.subSequence(0, ICH.length()))) {
381                appParamValue.needTag = ContentType.INCOMING_CALL_HISTORY;
382                if (D) Log.v(TAG, "download incoming calls request");
383            } else if (name.contains(OCH.subSequence(0, OCH.length()))) {
384                appParamValue.needTag = ContentType.OUTGOING_CALL_HISTORY;
385                if (D) Log.v(TAG, "download outgoing calls request");
386            } else if (name.contains(MCH.subSequence(0, MCH.length()))) {
387                appParamValue.needTag = ContentType.MISSED_CALL_HISTORY;
388                mNeedNewMissedCallsNum = true;
389                if (D) Log.v(TAG, "download missed calls request");
390            } else if (name.contains(CCH.subSequence(0, CCH.length()))) {
391                appParamValue.needTag = ContentType.COMBINED_CALL_HISTORY;
392                if (D) Log.v(TAG, "download combined calls request");
393            } else {
394                Log.w(TAG, "Input name doesn't contain valid info!!!");
395                return ResponseCodes.OBEX_HTTP_NOT_ACCEPTABLE;
396            }
397        }
398
399        if ((appParam != null) && !parseApplicationParameter(appParam, appParamValue)) {
400            return ResponseCodes.OBEX_HTTP_BAD_REQUEST;
401        }
402
403        // listing request
404        if (type.equals(TYPE_LISTING)) {
405            return pullVcardListing(appParam, appParamValue, reply, op);
406        }
407        // pull vcard entry request
408        else if (type.equals(TYPE_VCARD)) {
409            return pullVcardEntry(appParam, appParamValue, op, name, mCurrentPath);
410        }
411        // down load phone book request
412        else if (type.equals(TYPE_PB)) {
413            return pullPhonebook(appParam, appParamValue, reply, op, name);
414        } else {
415            Log.w(TAG, "unknown type request!!!");
416            return ResponseCodes.OBEX_HTTP_NOT_ACCEPTABLE;
417        }
418    }
419
420    /** check whether path is legal */
421    private final boolean isLegalPath(final String str) {
422        if (str.length() == 0) {
423            return true;
424        }
425        for (int i = 0; i < LEGAL_PATH.length; i++) {
426            if (str.equals(LEGAL_PATH[i])) {
427                return true;
428            }
429        }
430        return false;
431    }
432
433    private class AppParamValue {
434        public int maxListCount;
435
436        public int listStartOffset;
437
438        public String searchValue;
439
440        // Indicate which vCard parameter the search operation shall be carried
441        // out on. Can be "Name | Number | Sound", default value is "Name".
442        public String searchAttr;
443
444        // Indicate which sorting order shall be used for the
445        // <x-bt/vcard-listing> listing object.
446        // Can be "Alphabetical | Indexed | Phonetical", default value is
447        // "Indexed".
448        public String order;
449
450        public int needTag;
451
452        public boolean vcard21;
453
454        public AppParamValue() {
455            maxListCount = 0xFFFF;
456            listStartOffset = 0;
457            searchValue = "";
458            searchAttr = "";
459            order = "";
460            needTag = 0x00;
461            vcard21 = true;
462        }
463
464        public void dump() {
465            Log.i(TAG, "maxListCount=" + maxListCount + " listStartOffset=" + listStartOffset
466                    + " searchValue=" + searchValue + " searchAttr=" + searchAttr + " needTag="
467                    + needTag + " vcard21=" + vcard21 + " order=" + order);
468        }
469    }
470
471    /** To parse obex application parameter */
472    private final boolean parseApplicationParameter(final byte[] appParam,
473            AppParamValue appParamValue) {
474        int i = 0;
475        boolean parseOk = true;
476        while (i < appParam.length) {
477            switch (appParam[i]) {
478                case ApplicationParameter.TRIPLET_TAGID.FILTER_TAGID:
479                    i += 2; // length and tag field in triplet
480                    i += ApplicationParameter.TRIPLET_LENGTH.FILTER_LENGTH;
481                    break;
482                case ApplicationParameter.TRIPLET_TAGID.ORDER_TAGID:
483                    i += 2; // length and tag field in triplet
484                    appParamValue.order = Byte.toString(appParam[i]);
485                    i += ApplicationParameter.TRIPLET_LENGTH.ORDER_LENGTH;
486                    break;
487                case ApplicationParameter.TRIPLET_TAGID.SEARCH_VALUE_TAGID:
488                    i += 1; // length field in triplet
489                    // length of search value is variable
490                    int length = appParam[i];
491                    if (length == 0) {
492                        parseOk = false;
493                        break;
494                    }
495                    if (appParam[i+length] == 0x0) {
496                        appParamValue.searchValue = new String(appParam, i + 1, length-1);
497                    } else {
498                        appParamValue.searchValue = new String(appParam, i + 1, length);
499                    }
500                    i += length;
501                    i += 1;
502                    break;
503                case ApplicationParameter.TRIPLET_TAGID.SEARCH_ATTRIBUTE_TAGID:
504                    i += 2;
505                    appParamValue.searchAttr = Byte.toString(appParam[i]);
506                    i += ApplicationParameter.TRIPLET_LENGTH.SEARCH_ATTRIBUTE_LENGTH;
507                    break;
508                case ApplicationParameter.TRIPLET_TAGID.MAXLISTCOUNT_TAGID:
509                    i += 2;
510                    if (appParam[i] == 0 && appParam[i + 1] == 0) {
511                        mNeedPhonebookSize = true;
512                    } else {
513                        int highValue = appParam[i] & 0xff;
514                        int lowValue = appParam[i + 1] & 0xff;
515                        appParamValue.maxListCount = highValue * 256 + lowValue;
516                    }
517                    i += ApplicationParameter.TRIPLET_LENGTH.MAXLISTCOUNT_LENGTH;
518                    break;
519                case ApplicationParameter.TRIPLET_TAGID.LISTSTARTOFFSET_TAGID:
520                    i += 2;
521                    int highValue = appParam[i] & 0xff;
522                    int lowValue = appParam[i + 1] & 0xff;
523                    appParamValue.listStartOffset = highValue * 256 + lowValue;
524                    i += ApplicationParameter.TRIPLET_LENGTH.LISTSTARTOFFSET_LENGTH;
525                    break;
526                case ApplicationParameter.TRIPLET_TAGID.FORMAT_TAGID:
527                    i += 2;// length field in triplet
528                    if (appParam[i] != 0) {
529                        appParamValue.vcard21 = false;
530                    }
531                    i += ApplicationParameter.TRIPLET_LENGTH.FORMAT_LENGTH;
532                    break;
533                default:
534                    parseOk = false;
535                    Log.e(TAG, "Parse Application Parameter error");
536                    break;
537            }
538        }
539
540        if (D) appParamValue.dump();
541
542        return parseOk;
543    }
544
545    /** Form and Send an XML format String to client for Phone book listing */
546    private final int sendVcardListingXml(final int type, Operation op,
547            final int maxListCount, final int listStartOffset, final String searchValue,
548            String searchAttr) {
549        StringBuilder result = new StringBuilder();
550        int itemsFound = 0;
551        result.append("<?xml version=\"1.0\"?>");
552        result.append("<!DOCTYPE vcard-listing SYSTEM \"vcard-listing.dtd\">");
553        result.append("<vCard-listing version=\"1.0\">");
554
555        // Phonebook listing request
556        if (type == ContentType.PHONEBOOK) {
557            if (searchAttr.equals("0")) { // search by name
558                itemsFound = createList(maxListCount, listStartOffset, searchValue, result,
559                        "name");
560            } else if (searchAttr.equals("1")) { // search by number
561                itemsFound = createList(maxListCount, listStartOffset, searchValue, result,
562                        "number");
563            }// end of search by number
564            else {
565                return ResponseCodes.OBEX_HTTP_PRECON_FAILED;
566            }
567        }
568        // Call history listing request
569        else {
570            ArrayList<String> nameList = mVcardManager.loadCallHistoryList(type);
571            int requestSize = nameList.size() >= maxListCount ? maxListCount : nameList.size();
572            int startPoint = listStartOffset;
573            int endPoint = startPoint + requestSize;
574            if (endPoint > nameList.size()) {
575                endPoint = nameList.size();
576            }
577            if (D) Log.d(TAG, "call log list, size=" + requestSize + " offset=" + listStartOffset);
578
579            for (int j = startPoint; j < endPoint; j++) {
580                writeVCardEntry(j+1, nameList.get(j),result);
581            }
582        }
583        result.append("</vCard-listing>");
584
585        if (V) Log.v(TAG, "itemsFound =" + itemsFound);
586
587        return pushBytes(op, result.toString());
588    }
589
590    private int createList(final int maxListCount, final int listStartOffset,
591            final String searchValue, StringBuilder result, String type) {
592        int itemsFound = 0;
593        ArrayList<String> nameList = mVcardManager.getPhonebookNameList(mOrderBy);
594        final int requestSize = nameList.size() >= maxListCount ? maxListCount : nameList.size();
595        final int listSize = nameList.size();
596        String compareValue = "", currentValue;
597
598        if (D) Log.d(TAG, "search by " + type + ", requestSize=" + requestSize + " offset="
599                    + listStartOffset + " searchValue=" + searchValue);
600
601        if (type.equals("number")) {
602            // query the number, to get the names
603            ArrayList<String> names = mVcardManager.getContactNamesByNumber(searchValue);
604            for (int i = 0; i < names.size(); i++) {
605                compareValue = names.get(i).trim();
606                if (D) Log.d(TAG, "compareValue=" + compareValue);
607                for (int pos = listStartOffset; pos < listSize &&
608                        itemsFound < requestSize; pos++) {
609                    currentValue = nameList.get(pos);
610                    if (D) Log.d(TAG, "currentValue=" + currentValue);
611                    if (currentValue.startsWith(compareValue)) {
612                        itemsFound++;
613                        if (currentValue.contains(","))
614                           currentValue = currentValue.substring(0, currentValue.lastIndexOf(','));
615                        writeVCardEntry(pos, currentValue,result);
616                    }
617                }
618                if (itemsFound >= requestSize) {
619                    break;
620                }
621            }
622        } else {
623            if (searchValue != null) {
624                compareValue = searchValue.trim();
625            }
626            for (int pos = listStartOffset; pos < listSize &&
627                    itemsFound < requestSize; pos++) {
628                currentValue = nameList.get(pos);
629                if (currentValue.contains(","))
630                    currentValue = currentValue.substring(0, currentValue.lastIndexOf(','));
631
632                if (searchValue.isEmpty() || ((currentValue.toLowerCase()).equals(compareValue.toLowerCase()))) {
633                    itemsFound++;
634                    writeVCardEntry(pos, currentValue,result);
635                }
636            }
637        }
638        return itemsFound;
639    }
640
641    /**
642     * Function to send obex header back to client such as get phonebook size
643     * request
644     */
645    private final int pushHeader(final Operation op, final HeaderSet reply) {
646        OutputStream outputStream = null;
647
648        if (D) Log.d(TAG, "Push Header");
649        if (D) Log.d(TAG, reply.toString());
650
651        int pushResult = ResponseCodes.OBEX_HTTP_OK;
652        try {
653            op.sendHeaders(reply);
654            outputStream = op.openOutputStream();
655            outputStream.flush();
656        } catch (IOException e) {
657            Log.e(TAG, e.toString());
658            pushResult = ResponseCodes.OBEX_HTTP_INTERNAL_ERROR;
659        } finally {
660            if (!closeStream(outputStream, op)) {
661                pushResult = ResponseCodes.OBEX_HTTP_INTERNAL_ERROR;
662            }
663        }
664        return pushResult;
665    }
666
667    /** Function to send vcard data to client */
668    private final int pushBytes(Operation op, final String vcardString) {
669        if (vcardString == null) {
670            Log.w(TAG, "vcardString is null!");
671            return ResponseCodes.OBEX_HTTP_OK;
672        }
673
674        OutputStream outputStream = null;
675        int pushResult = ResponseCodes.OBEX_HTTP_OK;
676        try {
677            outputStream = op.openOutputStream();
678            outputStream.write(vcardString.getBytes());
679            if (V) Log.v(TAG, "Send Data complete!");
680        } catch (IOException e) {
681            Log.e(TAG, "open/write outputstrem failed" + e.toString());
682            pushResult = ResponseCodes.OBEX_HTTP_INTERNAL_ERROR;
683        }
684
685        if (!closeStream(outputStream, op)) {
686            pushResult = ResponseCodes.OBEX_HTTP_INTERNAL_ERROR;
687        }
688
689        return pushResult;
690    }
691
692    private final int handleAppParaForResponse(AppParamValue appParamValue, int size,
693            HeaderSet reply, Operation op) {
694        byte[] misnum = new byte[1];
695        ApplicationParameter ap = new ApplicationParameter();
696
697        // In such case, PCE only want the number of index.
698        // So response not contain any Body header.
699        if (mNeedPhonebookSize) {
700            if (V) Log.v(TAG, "Need Phonebook size in response header.");
701            mNeedPhonebookSize = false;
702
703            byte[] pbsize = new byte[2];
704
705            pbsize[0] = (byte)((size / 256) & 0xff);// HIGH VALUE
706            pbsize[1] = (byte)((size % 256) & 0xff);// LOW VALUE
707            ap.addAPPHeader(ApplicationParameter.TRIPLET_TAGID.PHONEBOOKSIZE_TAGID,
708                    ApplicationParameter.TRIPLET_LENGTH.PHONEBOOKSIZE_LENGTH, pbsize);
709
710            if (mNeedNewMissedCallsNum) {
711                mNeedNewMissedCallsNum = false;
712                int nmnum = size - mMissedCallSize;
713                mMissedCallSize = size;
714
715                nmnum = nmnum > 0 ? nmnum : 0;
716                misnum[0] = (byte)nmnum;
717                ap.addAPPHeader(ApplicationParameter.TRIPLET_TAGID.NEWMISSEDCALLS_TAGID,
718                        ApplicationParameter.TRIPLET_LENGTH.NEWMISSEDCALLS_LENGTH, misnum);
719                if (D) Log.d(TAG, "handleAppParaForResponse(): mNeedNewMissedCallsNum=true,  num= "
720                            + nmnum);
721            }
722            reply.setHeader(HeaderSet.APPLICATION_PARAMETER, ap.getAPPparam());
723
724            if (D) Log.d(TAG, "Send back Phonebook size only, without body info! Size= " + size);
725
726            return pushHeader(op, reply);
727        }
728
729        // Only apply to "mch" download/listing.
730        // NewMissedCalls is used only in the response, together with Body
731        // header.
732        if (mNeedNewMissedCallsNum) {
733            if (V) Log.v(TAG, "Need new missed call num in response header.");
734            mNeedNewMissedCallsNum = false;
735
736            int nmnum = size - mMissedCallSize;
737            mMissedCallSize = size;
738
739            nmnum = nmnum > 0 ? nmnum : 0;
740            misnum[0] = (byte)nmnum;
741            ap.addAPPHeader(ApplicationParameter.TRIPLET_TAGID.NEWMISSEDCALLS_TAGID,
742                    ApplicationParameter.TRIPLET_LENGTH.NEWMISSEDCALLS_LENGTH, misnum);
743            reply.setHeader(HeaderSet.APPLICATION_PARAMETER, ap.getAPPparam());
744            if (D) Log.d(TAG, "handleAppParaForResponse(): mNeedNewMissedCallsNum=true,  num= "
745                        + nmnum);
746
747            // Only Specifies the headers, not write for now, will write to PCE
748            // together with Body
749            try {
750                op.sendHeaders(reply);
751            } catch (IOException e) {
752                Log.e(TAG, e.toString());
753                return ResponseCodes.OBEX_HTTP_INTERNAL_ERROR;
754            }
755        }
756        return NEED_SEND_BODY;
757    }
758
759    private final int pullVcardListing(byte[] appParam, AppParamValue appParamValue,
760            HeaderSet reply, Operation op) {
761        String searchAttr = appParamValue.searchAttr.trim();
762
763        if (searchAttr == null || searchAttr.length() == 0) {
764            // If searchAttr is not set by PCE, set default value per spec.
765            appParamValue.searchAttr = "0";
766            if (D) Log.d(TAG, "searchAttr is not set by PCE, assume search by name by default");
767        } else if (!searchAttr.equals("0") && !searchAttr.equals("1")) {
768            Log.w(TAG, "search attr not supported");
769            if (searchAttr.equals("2")) {
770                // search by sound is not supported currently
771                Log.w(TAG, "do not support search by sound");
772                return ResponseCodes.OBEX_HTTP_NOT_IMPLEMENTED;
773            }
774            return ResponseCodes.OBEX_HTTP_PRECON_FAILED;
775        } else {
776            Log.i(TAG, "searchAttr is valid: " + searchAttr);
777        }
778
779        int size = mVcardManager.getPhonebookSize(appParamValue.needTag);
780        int needSendBody = handleAppParaForResponse(appParamValue, size, reply, op);
781        if (needSendBody != NEED_SEND_BODY) {
782            return needSendBody;
783        }
784
785        if (size == 0) {
786            if (V) Log.v(TAG, "PhonebookSize is 0, return.");
787            return ResponseCodes.OBEX_HTTP_OK;
788        }
789
790        String orderPara = appParamValue.order.trim();
791        if (TextUtils.isEmpty(orderPara)) {
792            // If order parameter is not set by PCE, set default value per spec.
793            orderPara = "0";
794            if (D) Log.d(TAG, "Order parameter is not set by PCE. " +
795                       "Assume order by 'Indexed' by default");
796        } else if (!orderPara.equals("0") && !orderPara.equals("1")) {
797            if (V) Log.v(TAG, "Order parameter is not supported: " + appParamValue.order);
798            if (orderPara.equals("2")) {
799                // Order by sound is not supported currently
800                Log.w(TAG, "Do not support order by sound");
801                return ResponseCodes.OBEX_HTTP_NOT_IMPLEMENTED;
802            }
803            return ResponseCodes.OBEX_HTTP_PRECON_FAILED;
804        } else {
805            Log.i(TAG, "Order parameter is valid: " + orderPara);
806        }
807
808        if (orderPara.equals("0")) {
809            mOrderBy = ORDER_BY_INDEXED;
810        } else if (orderPara.equals("1")) {
811            mOrderBy = ORDER_BY_ALPHABETICAL;
812        }
813
814        int sendResult = sendVcardListingXml(appParamValue.needTag, op, appParamValue.maxListCount,
815                appParamValue.listStartOffset, appParamValue.searchValue,
816                appParamValue.searchAttr);
817        return sendResult;
818    }
819
820    private final int pullVcardEntry(byte[] appParam, AppParamValue appParamValue,
821            Operation op, final String name, final String current_path) {
822        if (name == null || name.length() < VCARD_NAME_SUFFIX_LENGTH) {
823            if (D) Log.d(TAG, "Name is Null, or the length of name < 5 !");
824            return ResponseCodes.OBEX_HTTP_NOT_ACCEPTABLE;
825        }
826        String strIndex = name.substring(0, name.length() - VCARD_NAME_SUFFIX_LENGTH + 1);
827        int intIndex = 0;
828        if (strIndex.trim().length() != 0) {
829            try {
830                intIndex = Integer.parseInt(strIndex);
831            } catch (NumberFormatException e) {
832                Log.e(TAG, "catch number format exception " + e.toString());
833                return ResponseCodes.OBEX_HTTP_NOT_ACCEPTABLE;
834            }
835        }
836
837        int size = mVcardManager.getPhonebookSize(appParamValue.needTag);
838        if (size == 0) {
839            if (V) Log.v(TAG, "PhonebookSize is 0, return.");
840            return ResponseCodes.OBEX_HTTP_NOT_FOUND;
841        }
842
843        boolean vcard21 = appParamValue.vcard21;
844        if (appParamValue.needTag == 0) {
845            Log.w(TAG, "wrong path!");
846            return ResponseCodes.OBEX_HTTP_NOT_ACCEPTABLE;
847        } else if (appParamValue.needTag == ContentType.PHONEBOOK) {
848            if (intIndex < 0 || intIndex >= size) {
849                Log.w(TAG, "The requested vcard is not acceptable! name= " + name);
850                return ResponseCodes.OBEX_HTTP_NOT_FOUND;
851            } else if (intIndex == 0) {
852                // For PB_PATH, 0.vcf is the phone number of this phone.
853                String ownerVcard = mVcardManager.getOwnerPhoneNumberVcard(vcard21,null);
854                return pushBytes(op, ownerVcard);
855            } else {
856                return mVcardManager.composeAndSendPhonebookOneVcard(op, intIndex, vcard21, null,
857                        mOrderBy );
858            }
859        } else {
860            if (intIndex <= 0 || intIndex > size) {
861                Log.w(TAG, "The requested vcard is not acceptable! name= " + name);
862                return ResponseCodes.OBEX_HTTP_NOT_FOUND;
863            }
864            // For others (ich/och/cch/mch), 0.vcf is meaningless, and must
865            // begin from 1.vcf
866            if (intIndex >= 1) {
867                return mVcardManager.composeAndSendCallLogVcards(appParamValue.needTag, op,
868                        intIndex, intIndex, vcard21);
869            }
870        }
871        return ResponseCodes.OBEX_HTTP_OK;
872    }
873
874    private final int pullPhonebook(byte[] appParam, AppParamValue appParamValue, HeaderSet reply,
875            Operation op, final String name) {
876        // code start for passing PTS3.2 TC_PSE_PBD_BI_01_C
877        if (name != null) {
878            int dotIndex = name.indexOf(".");
879            String vcf = "vcf";
880            if (dotIndex >= 0 && dotIndex <= name.length()) {
881                if (name.regionMatches(dotIndex + 1, vcf, 0, vcf.length()) == false) {
882                    Log.w(TAG, "name is not .vcf");
883                    return ResponseCodes.OBEX_HTTP_NOT_ACCEPTABLE;
884                }
885            }
886        } // code end for passing PTS3.2 TC_PSE_PBD_BI_01_C
887
888        int pbSize = mVcardManager.getPhonebookSize(appParamValue.needTag);
889        int needSendBody = handleAppParaForResponse(appParamValue, pbSize, reply, op);
890        if (needSendBody != NEED_SEND_BODY) {
891            return needSendBody;
892        }
893
894        if (pbSize == 0) {
895            if (V) Log.v(TAG, "PhonebookSize is 0, return.");
896            return ResponseCodes.OBEX_HTTP_OK;
897        }
898
899        int requestSize = pbSize >= appParamValue.maxListCount ? appParamValue.maxListCount
900                : pbSize;
901        int startPoint = appParamValue.listStartOffset;
902        if (startPoint < 0 || startPoint >= pbSize) {
903            Log.w(TAG, "listStartOffset is not correct! " + startPoint);
904            return ResponseCodes.OBEX_HTTP_OK;
905        }
906
907        // Limit the number of call log to CALLLOG_NUM_LIMIT
908        if (appParamValue.needTag != BluetoothPbapObexServer.ContentType.PHONEBOOK) {
909            if (requestSize > CALLLOG_NUM_LIMIT) {
910               requestSize = CALLLOG_NUM_LIMIT;
911            }
912        }
913
914        int endPoint = startPoint + requestSize - 1;
915        if (endPoint > pbSize - 1) {
916            endPoint = pbSize - 1;
917        }
918        if (D) Log.d(TAG, "pullPhonebook(): requestSize=" + requestSize + " startPoint=" +
919                startPoint + " endPoint=" + endPoint);
920
921        boolean vcard21 = appParamValue.vcard21;
922        if (appParamValue.needTag == BluetoothPbapObexServer.ContentType.PHONEBOOK) {
923            if (startPoint == 0) {
924                String ownerVcard = mVcardManager.getOwnerPhoneNumberVcard(vcard21,null);
925                if (endPoint == 0) {
926                    return pushBytes(op, ownerVcard);
927                } else {
928                    return mVcardManager.composeAndSendPhonebookVcards(op, 1, endPoint, vcard21,
929                            ownerVcard);
930                }
931            } else {
932                return mVcardManager.composeAndSendPhonebookVcards(op, startPoint, endPoint,
933                        vcard21, null);
934            }
935        } else {
936            return mVcardManager.composeAndSendCallLogVcards(appParamValue.needTag, op,
937                    startPoint + 1, endPoint + 1, vcard21);
938        }
939    }
940
941    public static boolean closeStream(final OutputStream out, final Operation op) {
942        boolean returnvalue = true;
943        try {
944            if (out != null) {
945                out.close();
946            }
947        } catch (IOException e) {
948            Log.e(TAG, "outputStream close failed" + e.toString());
949            returnvalue = false;
950        }
951        try {
952            if (op != null) {
953                op.close();
954            }
955        } catch (IOException e) {
956            Log.e(TAG, "operation close failed" + e.toString());
957            returnvalue = false;
958        }
959        return returnvalue;
960    }
961
962    // Reserved for future use. In case PSE challenge PCE and PCE input wrong
963    // session key.
964    public final void onAuthenticationFailure(final byte[] userName) {
965    }
966
967    public static final String createSelectionPara(final int type) {
968        String selection = null;
969        switch (type) {
970            case ContentType.INCOMING_CALL_HISTORY:
971                selection = Calls.TYPE + "=" + CallLog.Calls.INCOMING_TYPE;
972                break;
973            case ContentType.OUTGOING_CALL_HISTORY:
974                selection = Calls.TYPE + "=" + CallLog.Calls.OUTGOING_TYPE;
975                break;
976            case ContentType.MISSED_CALL_HISTORY:
977                selection = Calls.TYPE + "=" + CallLog.Calls.MISSED_TYPE;
978                break;
979            default:
980                break;
981        }
982        if (V) Log.v(TAG, "Call log selection: " + selection);
983        return selection;
984    }
985
986    /**
987     * XML encode special characters in the name field
988     */
989    private void xmlEncode(String name, StringBuilder result) {
990        if (name == null) {
991            return;
992        }
993
994        final StringCharacterIterator iterator = new StringCharacterIterator(name);
995        char character =  iterator.current();
996        while (character != CharacterIterator.DONE ){
997            if (character == '<') {
998                result.append("&lt;");
999            }
1000            else if (character == '>') {
1001                result.append("&gt;");
1002            }
1003            else if (character == '\"') {
1004                result.append("&quot;");
1005            }
1006            else if (character == '\'') {
1007                result.append("&#039;");
1008            }
1009            else if (character == '&') {
1010                result.append("&amp;");
1011            }
1012            else {
1013                // The char is not a special one, add it to the result as is
1014                result.append(character);
1015            }
1016            character = iterator.next();
1017        }
1018    }
1019
1020    private void writeVCardEntry(int vcfIndex, String name, StringBuilder result) {
1021        result.append("<card handle=\"");
1022        result.append(vcfIndex);
1023        result.append(".vcf\" name=\"");
1024        xmlEncode(name, result);
1025        result.append("\"/>");
1026    }
1027
1028    private void notifyUpdateWakeLock() {
1029        Message msg = Message.obtain(mCallback);
1030        msg.what = BluetoothPbapService.MSG_ACQUIRE_WAKE_LOCK;
1031        msg.sendToTarget();
1032    }
1033
1034    public static final void logHeader(HeaderSet hs) {
1035        Log.v(TAG, "Dumping HeaderSet " + hs.toString());
1036        try {
1037
1038            Log.v(TAG, "COUNT : " + hs.getHeader(HeaderSet.COUNT));
1039            Log.v(TAG, "NAME : " + hs.getHeader(HeaderSet.NAME));
1040            Log.v(TAG, "TYPE : " + hs.getHeader(HeaderSet.TYPE));
1041            Log.v(TAG, "LENGTH : " + hs.getHeader(HeaderSet.LENGTH));
1042            Log.v(TAG, "TIME_ISO_8601 : " + hs.getHeader(HeaderSet.TIME_ISO_8601));
1043            Log.v(TAG, "TIME_4_BYTE : " + hs.getHeader(HeaderSet.TIME_4_BYTE));
1044            Log.v(TAG, "DESCRIPTION : " + hs.getHeader(HeaderSet.DESCRIPTION));
1045            Log.v(TAG, "TARGET : " + hs.getHeader(HeaderSet.TARGET));
1046            Log.v(TAG, "HTTP : " + hs.getHeader(HeaderSet.HTTP));
1047            Log.v(TAG, "WHO : " + hs.getHeader(HeaderSet.WHO));
1048            Log.v(TAG, "OBJECT_CLASS : " + hs.getHeader(HeaderSet.OBJECT_CLASS));
1049            Log.v(TAG, "APPLICATION_PARAMETER : " + hs.getHeader(HeaderSet.APPLICATION_PARAMETER));
1050        } catch (IOException e) {
1051            Log.e(TAG, "dump HeaderSet error " + e);
1052        }
1053    }
1054}
1055