BluetoothOppObexServerSession.java revision 09e9cba205af60b3f42e7a4d891a7d1392e1f2a5
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.opp;
34
35import java.io.BufferedOutputStream;
36import java.io.File;
37import java.io.FileNotFoundException;
38import java.io.FileOutputStream;
39import java.io.IOException;
40import java.io.InputStream;
41
42import android.content.ContentValues;
43import android.content.Context;
44import android.content.Intent;
45import android.net.Uri;
46import android.os.Handler;
47import android.os.Message;
48import android.util.Log;
49import android.webkit.MimeTypeMap;
50
51import javax.obex.HeaderSet;
52import javax.obex.ObexTransport;
53import javax.obex.Operation;
54import javax.obex.ResponseCodes;
55import javax.obex.ServerRequestHandler;
56import javax.obex.ServerSession;
57
58/**
59 * This class runs as an OBEX server
60 */
61public class BluetoothOppObexServerSession extends ServerRequestHandler implements
62        BluetoothOppObexSession {
63
64    private static final String TAG = "BtOpp Server";
65
66    private ObexTransport mTransport;
67
68    private Context mContext;
69
70    private Handler mCallback = null;
71
72    /* status when server is blocking for user/auto confirmation */
73    private boolean mServerBlocking = true;
74
75    /* the current transfer info */
76    private BluetoothOppShareInfo mInfo;
77
78    /* info id when we insert the record */
79    private int mLocalShareInfoId;
80
81    private int mAccepted = BluetoothShare.USER_CONFIRMATION_PENDING;
82
83    private boolean mInterrupted = false;
84
85    private ServerSession mSession;
86
87    private long mTimestamp;
88
89    private BluetoothOppReceiveFileInfo mFileInfo;
90
91    public BluetoothOppObexServerSession(Context context, ObexTransport transport) {
92        mContext = context;
93        mTransport = transport;
94    }
95
96    public void unblock() {
97        mServerBlocking = false;
98    }
99
100    /**
101     * Called when connection is accepted from remote, to retrieve the first
102     * Header then wait for user confirmation
103     */
104    public void preStart() {
105        try {
106            if (Constants.LOGV) {
107                Log.v(TAG, "Create ServerSession with transport " + mTransport.toString());
108            }
109            mSession = new ServerSession(mTransport, this, null);
110        } catch (IOException e) {
111            Log.e(TAG, "Create server session error" + e);
112        }
113    }
114
115    /**
116     * Called from BluetoothOppTransfer to start the "Transfer"
117     */
118    public void start(Handler handler) {
119        if (Constants.LOGV) {
120            Log.v(TAG, "Start!");
121        }
122        mCallback = handler;
123
124    }
125
126    /**
127     * Called from BluetoothOppTransfer to cancel the "Transfer"
128     * Otherwise, server should end by itself.
129     */
130    public void stop() {
131        /*
132         * TODO now we implement in a tough way, just close the socket.
133         * maybe need nice way
134         */
135        if (Constants.LOGV) {
136            Log.v(TAG, "Stop!");
137        }
138        mInterrupted = true;
139        if (mSession != null) {
140            try {
141                mSession.close();
142                mTransport.close();
143            } catch (IOException e) {
144                Log.e(TAG, "close mTransport error" + e);
145            }
146        }
147    }
148
149    public void addShare(BluetoothOppShareInfo info) {
150        if (Constants.LOGV) {
151            Log.v(TAG, "addShare for id " + info.mId);
152        }
153        mInfo = info;
154        mFileInfo = processShareInfo();
155    }
156
157    @Override
158    public int onPut(Operation op) {
159        if (Constants.LOGV) {
160            Log.v(TAG, "onPut " + op.toString());
161        }
162        HeaderSet request;
163        String name, mimeType;
164        Long length;
165
166        int obexResponse = ResponseCodes.OBEX_HTTP_OK;
167
168        /**
169         * For multiple objects, reject further objects after user deny the
170         * first one
171         */
172        if (mAccepted == BluetoothShare.USER_CONFIRMATION_DENIED) {
173            return ResponseCodes.OBEX_HTTP_FORBIDDEN;
174        }
175
176        try {
177            boolean pre_reject = false;
178            request = op.getReceivedHeaders();
179            if (Constants.LOGVV) {
180                logHeader(request);
181            }
182            name = (String)request.getHeader(HeaderSet.NAME);
183            length = (Long)request.getHeader(HeaderSet.LENGTH);
184            mimeType = (String)request.getHeader(HeaderSet.TYPE);
185
186            if (length == 0) {
187                if (Constants.LOGV) {
188                    Log.w(TAG, "length is 0, reject the transfer");
189                }
190                pre_reject = true;
191                obexResponse = ResponseCodes.OBEX_HTTP_LENGTH_REQUIRED;
192            }
193
194            if (name == null || name.equals("")) {
195                if (Constants.LOGV) {
196                    Log.w(TAG, "name is null or empty, reject the transfer");
197                }
198                pre_reject = true;
199                obexResponse = ResponseCodes.OBEX_HTTP_BAD_REQUEST;
200            }
201
202            if (!pre_reject) {
203                /* first we look for Mimetype in Android map */
204                String extension, type;
205                int dotIndex = name.indexOf('.');
206                if (dotIndex < 0) {
207                    if (Constants.LOGV) {
208                        Log.w(TAG, "There is no file extension, reject the transfer");
209                    }
210                    pre_reject = true;
211                    obexResponse = ResponseCodes.OBEX_HTTP_BAD_REQUEST;
212                } else {
213                    extension = name.substring(dotIndex + 1);
214                    MimeTypeMap map = MimeTypeMap.getSingleton();
215                    type = map.getMimeTypeFromExtension(extension);
216                    if (Constants.LOGVV) {
217                        Log.v(TAG, "Mimetype guessed from extension " + extension + " is "
218                                + mimeType);
219                    }
220                    if (type != null) {
221                        mimeType = type;
222
223                    } else {
224                        if (mimeType == null) {
225                            if (Constants.LOGV) {
226                                Log.w(TAG, "Can't get mimetype, reject the transfer");
227                            }
228                            pre_reject = true;
229                            obexResponse = ResponseCodes.OBEX_HTTP_BAD_REQUEST;
230                        }
231                    }
232                    if (mimeType != null) {
233                        mimeType = mimeType.toLowerCase();
234                    }
235                }
236            }
237
238            if (!pre_reject
239                    && (mimeType == null || Constants.mimeTypeMatches(mimeType,
240                            Constants.UNACCEPTABLE_SHARE_INBOUND_TYPES))) {
241                if (Constants.LOGV) {
242                    Log.w(TAG, "mimeType is null or in unacceptable list, reject the transfer");
243                }
244                pre_reject = true;
245                obexResponse = ResponseCodes.OBEX_HTTP_UNSUPPORTED_TYPE;
246            }
247
248            if (pre_reject && obexResponse != ResponseCodes.OBEX_HTTP_OK) {
249                return obexResponse;
250            }
251
252        } catch (IOException e) {
253            Log.e(TAG, "get getReceivedHeaders error " + e);
254            return ResponseCodes.OBEX_HTTP_BAD_REQUEST;
255        }
256
257        ContentValues values = new ContentValues();
258
259        values.put(BluetoothShare.FILENAME_HINT, name);
260        values.put(BluetoothShare.TOTAL_BYTES, length.intValue());
261        values.put(BluetoothShare.MIMETYPE, mimeType);
262
263        if (mTransport instanceof BluetoothOppRfcommTransport) {
264            String a = ((BluetoothOppRfcommTransport)mTransport).getRemoteAddress();
265            values.put(BluetoothShare.DESTINATION, a);
266        } else {
267            values.put(BluetoothShare.DESTINATION, "FF:FF:FF:00:00:00");
268        }
269
270        values.put(BluetoothShare.DIRECTION, BluetoothShare.DIRECTION_INBOUND);
271        values.put(BluetoothShare.TIMESTAMP, mTimestamp);
272
273        boolean needConfirm = true;
274        /** It's not first put if !serverBlocking, so we auto accept it */
275        if (!mServerBlocking) {
276            values.put(BluetoothShare.USER_CONFIRMATION,
277                    BluetoothShare.USER_CONFIRMATION_AUTO_CONFIRMED);
278            needConfirm = false;
279        }
280
281        Uri contentUri = mContext.getContentResolver().insert(BluetoothShare.CONTENT_URI, values);
282        mLocalShareInfoId = Integer.parseInt(contentUri.getPathSegments().get(1));
283
284        if (needConfirm) {
285            Intent in = new Intent(BluetoothShare.INCOMING_FILE_CONFIRMATION_REQUEST_ACTION);
286            in.setClassName(Constants.THIS_PACKAGE_NAME, BluetoothOppReceiver.class.getName());
287            mContext.sendBroadcast(in);
288        }
289
290        if (Constants.LOGVV) {
291            Log.v(TAG, "insert contentUri: " + contentUri);
292            Log.v(TAG, "mLocalShareInfoId = " + mLocalShareInfoId);
293        }
294
295        // TODO add server wait timeout
296        mServerBlocking = true;
297
298        synchronized (this) {
299            try {
300                boolean msgSent = false;
301                while (mServerBlocking) {
302                    wait(1000);
303                    if (mCallback != null && !msgSent) {
304                        mCallback.sendMessageDelayed(mCallback
305                                .obtainMessage(BluetoothOppObexSession.MSG_CONNECT_TIMEOUT),
306                                BluetoothOppObexSession.SESSION_TIMEOUT);
307                        msgSent = true;
308                        if (Constants.LOGVV) {
309                            Log.v(TAG, "MSG_CONNECT_TIMEOUT sent");
310                        }
311                    }
312                }
313            } catch (InterruptedException e) {
314                if (Constants.LOGVV) {
315                    Log.v(TAG, "Interrupted in onPut blocking");
316                }
317            }
318        }
319        if (Constants.LOGV) {
320            Log.v(TAG, "Server unblocked ");
321        }
322        mCallback.removeMessages(BluetoothOppObexSession.MSG_CONNECT_TIMEOUT);
323
324        /* we should have mInfo now */
325
326        /*
327         * TODO check if this mInfo match the one that we insert before server
328         * blocking? just to make sure no error happens
329         */
330        if (mInfo.mId != mLocalShareInfoId) {
331            Log.e(TAG, "Unexpected error!");
332        }
333        mAccepted = mInfo.mConfirm;
334
335        if (Constants.LOGVV) {
336            Log.v(TAG, "after confirm: userAccepted=" + mAccepted);
337        }
338        int status = BluetoothShare.STATUS_SUCCESS;
339
340        if (mAccepted == BluetoothShare.USER_CONFIRMATION_CONFIRMED
341                || mAccepted == BluetoothShare.USER_CONFIRMATION_CONFIRMED) {
342            /* Confirm or auto-confirm */
343
344            if (mFileInfo.mFileName == null) {
345                status = mFileInfo.mStatus;
346                /* TODO need to check if this line is correct */
347                mInfo.mStatus = mFileInfo.mStatus;
348                Constants.updateShareStatus(mContext, mInfo.mId, status);
349                obexResponse = ResponseCodes.OBEX_HTTP_INTERNAL_ERROR;
350
351            }
352
353            if (mFileInfo.mFileName != null) {
354
355                ContentValues updateValues = new ContentValues();
356                contentUri = Uri.parse(BluetoothShare.CONTENT_URI + "/" + mInfo.mId);
357                updateValues.put(BluetoothShare._DATA, mFileInfo.mFileName);
358                updateValues.put(BluetoothShare.STATUS, BluetoothShare.STATUS_RUNNING);
359                mContext.getContentResolver().update(contentUri, updateValues, null, null);
360
361                status = receiveFile(mFileInfo, op);
362                /*
363                 * TODO map status to obex response code
364                 */
365                if (status != BluetoothShare.STATUS_SUCCESS) {
366                    obexResponse = ResponseCodes.OBEX_HTTP_INTERNAL_ERROR;
367                }
368                Constants.updateShareStatus(mContext, mInfo.mId, status);
369            }
370
371            if (status == BluetoothShare.STATUS_SUCCESS) {
372                Message msg = Message.obtain(mCallback, BluetoothOppObexSession.MSG_SHARE_COMPLETE);
373                msg.obj = mInfo;
374                msg.sendToTarget();
375            } else {
376                Message msg = Message.obtain(mCallback, BluetoothOppObexSession.MSG_SESSION_ERROR);
377                msg.obj = mInfo;
378                msg.sendToTarget();
379            }
380        } else if (mAccepted == BluetoothShare.USER_CONFIRMATION_DENIED
381                || mAccepted == BluetoothShare.USER_CONFIRMATION_TIMEOUT) {
382            /* user actively deny the inbound transfer */
383            /*
384             * Note There is a question: what's next if user deny the first obj?
385             * Option 1 :continue prompt for next objects
386             * Option 2 :reject next objects and finish the session
387             * Now we take option 2:
388             */
389            if (Constants.LOGVV) {
390                Log.v(TAG, "request forbidden, indicate interrupted");
391            }
392            status = BluetoothShare.STATUS_FORBIDDEN;
393            Constants.updateShareStatus(mContext, mInfo.mId, status);
394            obexResponse = ResponseCodes.OBEX_HTTP_FORBIDDEN;
395            Message msg = Message.obtain(mCallback);
396            /* TODO check which message should be sent */
397            msg.what = BluetoothOppObexSession.MSG_SHARE_INTERRUPTED;
398            msg.obj = mInfo;
399            msg.sendToTarget();
400        }
401        return obexResponse;
402    }
403
404    private int receiveFile(BluetoothOppReceiveFileInfo fileInfo, Operation op) {
405        /*
406         * implement receive file
407         */
408        int status = -1;
409        BufferedOutputStream bos = null;
410
411        InputStream is = null;
412        boolean error = false;
413        try {
414            is = op.openInputStream();
415        } catch (IOException e1) {
416            Log.e(TAG, "Error when openInputStream");
417            status = BluetoothShare.STATUS_OBEX_DATA_ERROR;
418            error = true;
419        }
420
421        Uri contentUri = Uri.parse(BluetoothShare.CONTENT_URI + "/" + mInfo.mId);
422
423        if (!error) {
424            ContentValues updateValues = new ContentValues();
425            updateValues.put(BluetoothShare._DATA, fileInfo.mFileName);
426            mContext.getContentResolver().update(contentUri, updateValues, null, null);
427        }
428
429        int position = 0;
430        if (!error) {
431            File f = new File(fileInfo.mFileName);
432            try {
433                bos = new BufferedOutputStream(new FileOutputStream(f), 0x10000);
434            } catch (FileNotFoundException e1) {
435                Log.e(TAG, "Error when open file " + f.toString());
436                status = BluetoothShare.STATUS_FILE_ERROR;
437                error = true;
438            }
439        }
440
441        if (!error) {
442            int outputBufferSize = op.getMaxPacketSize();
443            byte[] b = new byte[outputBufferSize];
444            int readLength = 0;
445            long timestamp;
446            try {
447                while ((!mInterrupted) && (position != fileInfo.mLength)) {
448
449                    if (Constants.LOGVV) {
450                        timestamp = System.currentTimeMillis();
451                    }
452
453                    readLength = is.read(b);
454
455                    if (readLength == -1) {
456                        if (Constants.LOGV) {
457                            Log.v(TAG, "Receive file reached stream end at position" + position);
458                        }
459                        break;
460                    }
461
462                    bos.write(b, 0, readLength);
463                    position += readLength;
464
465                    if (Constants.USE_EMULATOR_DEBUG) {
466                        synchronized (this) {
467                            try {
468                                wait(300);
469                            } catch (InterruptedException e) {
470                                status = BluetoothShare.STATUS_CANCELED;
471                                mInterrupted = true;
472                                if (Constants.LOGVV) {
473                                    Log.v(TAG, "ReceiveFile interrupted when receive file "
474                                            + fileInfo.mFileName + " at " + position + " of "
475                                            + position);
476                                }
477                                Constants.updateShareStatus(mContext, mInfo.mId, status);
478                            }
479                        }
480                    }
481
482                    if (Constants.LOGVV) {
483                        Log.v(TAG, "Receive file position = " + position + " readLength "
484                                + readLength + " bytes took "
485                                + (System.currentTimeMillis() - timestamp) + " ms");
486                    }
487
488                    ContentValues updateValues = new ContentValues();
489                    updateValues.put(BluetoothShare.CURRENT_BYTES, position);
490                    mContext.getContentResolver().update(contentUri, updateValues, null, null);
491                }
492            } catch (IOException e1) {
493                Log.e(TAG, "Error when receiving file");
494                status = BluetoothShare.STATUS_OBEX_DATA_ERROR;
495                error = true;
496            }
497        }
498
499        if (mInterrupted) {
500            if (Constants.LOGV) {
501                Log.v(TAG, "receiving file interrupted by user.");
502            }
503            status = BluetoothShare.STATUS_CANCELED;
504        } else {
505            if (position == fileInfo.mLength) {
506                if (Constants.LOGV) {
507                    Log.v(TAG, "Receiving file completed for " + fileInfo.mFileName);
508                }
509                status = BluetoothShare.STATUS_SUCCESS;
510            } else {
511                if (Constants.LOGV) {
512                    Log.v(TAG, "Reading file failed at " + position + " of " + fileInfo.mLength);
513                }
514                if (status == -1) {
515                    status = BluetoothShare.STATUS_UNKNOWN_ERROR;
516                }
517            }
518        }
519
520        Constants.updateShareStatus(mContext, mInfo.mId, status);
521        if (bos != null) {
522            try {
523                bos.close();
524            } catch (IOException e) {
525                Log.e(TAG, "Error when closing stream after send");
526            }
527        }
528        return status;
529    }
530
531    private BluetoothOppReceiveFileInfo processShareInfo() {
532        if (Constants.LOGV) {
533            Log.v(TAG, "processShareInfo() " + mInfo.mId);
534        }
535        BluetoothOppReceiveFileInfo fileInfo = BluetoothOppReceiveFileInfo.generateFileInfo(
536                mContext, mInfo.mId);
537        if (Constants.LOGVV) {
538            Log.v(TAG, "Generate BluetoothOppReceiveFileInfo:");
539            Log.v(TAG, "filename  :" + fileInfo.mFileName);
540            Log.v(TAG, "length    :" + fileInfo.mLength);
541            Log.v(TAG, "status    :" + fileInfo.mStatus);
542        }
543        return fileInfo;
544    }
545
546    @Override
547    public int onConnect(HeaderSet request, HeaderSet reply) {
548
549        if (Constants.LOGV) {
550            Log.v(TAG, "onConnect");
551        }
552        if (Constants.LOGVV) {
553            logHeader(request);
554        }
555
556        mTimestamp = System.currentTimeMillis();
557        return ResponseCodes.OBEX_HTTP_OK;
558    }
559
560    @Override
561    public void onDisconnect(HeaderSet req, HeaderSet resp) {
562
563        if (Constants.LOGV) {
564            Log.v(TAG, "onDisconnect");
565        }
566        resp.responseCode = ResponseCodes.OBEX_HTTP_OK;
567        /* onDisconnect could happen even before start() where mCallback is set */
568        if (mCallback != null) {
569            Message msg = Message.obtain(mCallback);
570            msg.what = BluetoothOppObexSession.MSG_SESSION_COMPLETE;
571            msg.obj = mInfo;
572            msg.sendToTarget();
573        }
574
575    }
576
577    @Override
578    public void onClose() {
579    }
580
581    private void logHeader(HeaderSet hs) {
582        Log.v(TAG, "Dumping HeaderSet " + hs.toString());
583        try {
584
585            Log.v(TAG, "COUNT : " + hs.getHeader(HeaderSet.COUNT));
586            Log.v(TAG, "NAME : " + hs.getHeader(HeaderSet.NAME));
587            Log.v(TAG, "TYPE : " + hs.getHeader(HeaderSet.TYPE));
588            Log.v(TAG, "LENGTH : " + hs.getHeader(HeaderSet.LENGTH));
589            Log.v(TAG, "TIME_ISO_8601 : " + hs.getHeader(HeaderSet.TIME_ISO_8601));
590            Log.v(TAG, "TIME_4_BYTE : " + hs.getHeader(HeaderSet.TIME_4_BYTE));
591            Log.v(TAG, "DESCRIPTION : " + hs.getHeader(HeaderSet.DESCRIPTION));
592            Log.v(TAG, "TARGET : " + hs.getHeader(HeaderSet.TARGET));
593            Log.v(TAG, "HTTP : " + hs.getHeader(HeaderSet.HTTP));
594            Log.v(TAG, "WHO : " + hs.getHeader(HeaderSet.WHO));
595            Log.v(TAG, "OBJECT_CLASS : " + hs.getHeader(HeaderSet.OBJECT_CLASS));
596            Log.v(TAG, "APPLICATION_PARAMETER : " + hs.getHeader(HeaderSet.APPLICATION_PARAMETER));
597        } catch (IOException e) {
598            Log.e(TAG, "dump HeaderSet error " + e);
599        }
600
601    }
602}
603