1/*
2 * Copyright (C) 2015 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package android.nfc.cardemulation;
18
19import android.annotation.SdkConstant;
20import android.annotation.SdkConstant.SdkConstantType;
21import android.app.Service;
22import android.content.ComponentName;
23import android.content.Intent;
24import android.os.Bundle;
25import android.os.Handler;
26import android.os.IBinder;
27import android.os.Message;
28import android.os.Messenger;
29import android.os.RemoteException;
30import android.util.Log;
31
32/**
33 * <p>HostNfcFService is a convenience {@link Service} class that can be
34 * extended to emulate an NFC-F card inside an Android service component.
35 *
36 * <h3>NFC Protocols</h3>
37 * <p>Cards emulated by this class are based on the NFC-Forum NFC-F
38 * protocol (based on the JIS-X 6319-4 specification.)</p>
39 *
40 * <h3>System Code and NFCID2 registration</h3>
41 * <p>A {@link HostNfcFService HostNfcFService service} can register
42 * exactly one System Code and one NFCID2. For details about the use of
43 * System Code and NFCID2, see the NFC Forum Digital specification.</p>
44 * <p>To statically register a System Code and NFCID2 with the service, a {@link #SERVICE_META_DATA}
45 * entry must be included in the declaration of the service.
46 *
47 * <p>All {@link HostNfcFService HostNfcFService} declarations in the manifest must require the
48 * {@link android.Manifest.permission#BIND_NFC_SERVICE} permission
49 * in their &lt;service&gt; tag, to ensure that only the platform can bind to your service.</p>
50 *
51 * <p>An example of a HostNfcFService manifest declaration is shown below:
52 *
53 * <pre> &lt;service android:name=".MyHostNfcFService" android:exported="true" android:permission="android.permission.BIND_NFC_SERVICE"&gt;
54 *     &lt;intent-filter&gt;
55 *         &lt;action android:name="android.nfc.cardemulation.action.HOST_NFCF_SERVICE"/&gt;
56 *     &lt;/intent-filter&gt;
57 *     &lt;meta-data android:name="android.nfc.cardemulation.host_nfcf_service" android:resource="@xml/nfcfservice"/&gt;
58 * &lt;/service&gt;</pre>
59 *
60 * This meta-data tag points to an nfcfservice.xml file.
61 * An example of this file with a System Code and NFCID2 declaration is shown below:
62 * <pre>
63 * &lt;host-nfcf-service xmlns:android="http://schemas.android.com/apk/res/android"
64 *           android:description="@string/servicedesc"&gt;
65 *       &lt;system-code-filter android:name="4000"/&gt;
66 *       &lt;nfcid2-filter android:name="02FE000000000000"/&gt;
67 * &lt;/host-nfcf-service&gt;
68 * </pre>
69 *
70 * <p>The {@link android.R.styleable#HostNfcFService &lt;host-nfcf-service&gt;} is required
71 * to contain a
72 * {@link android.R.styleable#HostApduService_description &lt;android:description&gt;}
73 * attribute that contains a user-friendly description of the service that may be shown in UI.
74 * <p>The {@link android.R.styleable#HostNfcFService &lt;host-nfcf-service&gt;} must
75 * contain:
76 * <ul>
77 * <li>Exactly one {@link android.R.styleable#SystemCodeFilter &lt;system-code-filter&gt;} tag.</li>
78 * <li>Exactly one {@link android.R.styleable#Nfcid2Filter &lt;nfcid2-filter&gt;} tag.</li>
79 * </ul>
80 * </p>
81 *
82 * <p>Alternatively, the System Code and NFCID2 can be dynamically registererd for a service
83 * by using the {@link NfcFCardEmulation#registerSystemCodeForService(ComponentName, String)} and
84 * {@link NfcFCardEmulation#setNfcid2ForService(ComponentName, String)} methods.
85 * </p>
86 *
87 * <h3>Service selection</h3>
88 * <p>When a remote NFC devices wants to communicate with your service, it
89 * sends a SENSF_REQ command to the NFC controller, requesting a System Code.
90 * If a {@link NfcFCardEmulation NfcFCardEmulation service} has registered
91 * this system code and has been enabled by the foreground application, the
92 * NFC controller will respond with the NFCID2 that is registered for this service.
93 * The reader can then continue data exchange with this service by using the NFCID2.</p>
94 *
95 * <h3>Data exchange</h3>
96 * <p>After service selection, all frames addressed to the NFCID2 of this service will
97 * be sent through {@link #processNfcFPacket(byte[], Bundle)}, until the NFC link is
98 * broken.<p>
99 *
100 * <p>When the NFC link is broken, {@link #onDeactivated(int)} will be called.</p>
101 */
102public abstract class HostNfcFService extends Service {
103    /**
104     * The {@link Intent} action that must be declared as handled by the service.
105     */
106    @SdkConstant(SdkConstantType.SERVICE_ACTION)
107    public static final String SERVICE_INTERFACE =
108            "android.nfc.cardemulation.action.HOST_NFCF_SERVICE";
109
110    /**
111     * The name of the meta-data element that contains
112     * more information about this service.
113     */
114    public static final String SERVICE_META_DATA =
115            "android.nfc.cardemulation.host_nfcf_service";
116
117    /**
118     * Reason for {@link #onDeactivated(int)}.
119     * Indicates deactivation was due to the NFC link
120     * being lost.
121     */
122    public static final int DEACTIVATION_LINK_LOSS = 0;
123
124    static final String TAG = "NfcFService";
125
126    /**
127     * MSG_COMMAND_PACKET is sent by NfcService when
128     * a NFC-F command packet has been received.
129     *
130     * @hide
131     */
132    public static final int MSG_COMMAND_PACKET = 0;
133
134    /**
135     * MSG_RESPONSE_PACKET is sent to NfcService to send
136     * a response packet back to the remote device.
137     *
138     * @hide
139     */
140    public static final int MSG_RESPONSE_PACKET = 1;
141
142    /**
143     * MSG_DEACTIVATED is sent by NfcService when
144     * the current session is finished; because
145     * the NFC link was deactivated.
146     *
147     * @hide
148     */
149    public static final int MSG_DEACTIVATED = 2;
150
151   /**
152     * @hide
153     */
154    public static final String KEY_DATA = "data";
155
156    /**
157     * @hide
158     */
159    public static final String KEY_MESSENGER = "messenger";
160
161    /**
162     * Messenger interface to NfcService for sending responses.
163     * Only accessed on main thread by the message handler.
164     *
165     * @hide
166     */
167    Messenger mNfcService = null;
168
169    final Messenger mMessenger = new Messenger(new MsgHandler());
170
171    final class MsgHandler extends Handler {
172        @Override
173        public void handleMessage(Message msg) {
174            switch (msg.what) {
175            case MSG_COMMAND_PACKET:
176                Bundle dataBundle = msg.getData();
177                if (dataBundle == null) {
178                    return;
179                }
180                if (mNfcService == null) mNfcService = msg.replyTo;
181
182                byte[] packet = dataBundle.getByteArray(KEY_DATA);
183                if (packet != null) {
184                    byte[] responsePacket = processNfcFPacket(packet, null);
185                    if (responsePacket != null) {
186                        if (mNfcService == null) {
187                            Log.e(TAG, "Response not sent; service was deactivated.");
188                            return;
189                        }
190                        Message responseMsg = Message.obtain(null, MSG_RESPONSE_PACKET);
191                        Bundle responseBundle = new Bundle();
192                        responseBundle.putByteArray(KEY_DATA, responsePacket);
193                        responseMsg.setData(responseBundle);
194                        responseMsg.replyTo = mMessenger;
195                        try {
196                            mNfcService.send(responseMsg);
197                        } catch (RemoteException e) {
198                            Log.e("TAG", "Response not sent; RemoteException calling into " +
199                                    "NfcService.");
200                        }
201                    }
202                } else {
203                    Log.e(TAG, "Received MSG_COMMAND_PACKET without data.");
204                }
205                break;
206            case MSG_RESPONSE_PACKET:
207                if (mNfcService == null) {
208                    Log.e(TAG, "Response not sent; service was deactivated.");
209                    return;
210                }
211                try {
212                    msg.replyTo = mMessenger;
213                    mNfcService.send(msg);
214                } catch (RemoteException e) {
215                    Log.e(TAG, "RemoteException calling into NfcService.");
216                }
217                break;
218            case MSG_DEACTIVATED:
219                // Make sure we won't call into NfcService again
220                mNfcService = null;
221                onDeactivated(msg.arg1);
222                break;
223            default:
224                super.handleMessage(msg);
225            }
226        }
227    }
228
229    @Override
230    public final IBinder onBind(Intent intent) {
231        return mMessenger.getBinder();
232    }
233
234    /**
235     * Sends a response packet back to the remote device.
236     *
237     * <p>Note: this method may be called from any thread and will not block.
238     * @param responsePacket A byte-array containing the response packet.
239     */
240    public final void sendResponsePacket(byte[] responsePacket) {
241        Message responseMsg = Message.obtain(null, MSG_RESPONSE_PACKET);
242        Bundle dataBundle = new Bundle();
243        dataBundle.putByteArray(KEY_DATA, responsePacket);
244        responseMsg.setData(dataBundle);
245        try {
246            mMessenger.send(responseMsg);
247        } catch (RemoteException e) {
248            Log.e("TAG", "Local messenger has died.");
249        }
250    }
251
252    /**
253     * <p>This method will be called when a NFC-F packet has been received
254     * from a remote device. A response packet can be provided directly
255     * by returning a byte-array in this method. Note that in general
256     * response packets must be sent as quickly as possible, given the fact
257     * that the user is likely holding his device over an NFC reader
258     * when this method is called.
259     *
260     * <p class="note">This method is running on the main thread of your application.
261     * If you cannot return a response packet immediately, return null
262     * and use the {@link #sendResponsePacket(byte[])} method later.
263     *
264     * @param commandPacket The NFC-F packet that was received from the remote device
265     * @param extras A bundle containing extra data. May be null.
266     * @return a byte-array containing the response packet, or null if no
267     *         response packet can be sent at this point.
268     */
269    public abstract byte[] processNfcFPacket(byte[] commandPacket, Bundle extras);
270
271    /**
272     * This method will be called in following possible scenarios:
273     * <li>The NFC link has been lost
274     * @param reason {@link #DEACTIVATION_LINK_LOSS}
275     */
276    public abstract void onDeactivated(int reason);
277}
278