summaryrefslogtreecommitdiff
path: root/app/src/main/java/net/taler/wallet/HostCardEmulatorService.kt
blob: 9134df44d0a2c4fd00a5fee2d5224e1bde8757a7 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
package net.taler.wallet

import android.content.*
import android.net.Uri
import android.nfc.cardemulation.HostApduService
import android.os.Bundle
import android.util.Log
import java.io.ByteArrayInputStream
import java.io.ByteArrayOutputStream
import java.net.URI
import java.util.concurrent.ConcurrentLinkedDeque

fun makeApduSuccessResponse(payload: ByteArray): ByteArray {
    val stream = ByteArrayOutputStream()
    stream.write(payload)
    stream.write(0x90)
    stream.write(0x00)
    return stream.toByteArray()
}


fun makeApduFailureResponse(): ByteArray {
    val stream = ByteArrayOutputStream()
    stream.write(0x6F)
    stream.write(0x00)
    return stream.toByteArray()
}


fun readApduBodySize(stream: ByteArrayInputStream): Int {
    val b0 = stream.read()
    if (b0 == -1) {
        return 0;
    }
    if (b0 != 0) {
        return b0
    }
    val b1 = stream.read()
    val b2 = stream.read()

    return (b1 shl 8) and b2
}


class HostCardEmulatorService: HostApduService() {

    val queuedRequests: ConcurrentLinkedDeque<String> = ConcurrentLinkedDeque()
    lateinit var receiver: BroadcastReceiver

    override fun onCreate() {
        super.onCreate()
        receiver = object : BroadcastReceiver() {
            override fun onReceive(p0: Context?, p1: Intent?) {
                queuedRequests.addLast(p1!!.getStringExtra("tunnelMessage"))
            }
        }
        IntentFilter(HTTP_TUNNEL_REQUEST).also { filter ->
            registerReceiver(receiver, filter)
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        unregisterReceiver(receiver)
    }

    override fun onDeactivated(reason: Int) {
        Log.d(TAG, "Deactivated: $reason")
        Intent().also { intent ->
            intent.action = MERCHANT_NFC_DISCONNECTED
            sendBroadcast(intent)
        }
    }

    override fun processCommandApdu(commandApdu: ByteArray?,
                                    extras: Bundle?): ByteArray {

        Log.d(TAG, "Processing command APDU")

        if (commandApdu == null) {
            Log.d(TAG, "APDU is null")
            return makeApduFailureResponse()
        }

        val stream = ByteArrayInputStream(commandApdu)

        val command = stream.read()

        if (command != 0) {
            Log.d(TAG, "APDU has invalid command")
            return makeApduFailureResponse()
        }

        val instruction = stream.read()

        // Read instruction parameters, currently ignored.
        stream.read()
        stream.read()

        if (instruction == SELECT_INS) {
            // FIXME: validate body!
            return makeApduSuccessResponse(ByteArray(0))
        }

        if (instruction == GET_INS) {
            val req = queuedRequests.poll()
            return if (req != null) {
                Log.v(TAG,"sending tunnel request")
                makeApduSuccessResponse(req.toByteArray(Charsets.UTF_8))
            } else {
                makeApduSuccessResponse(ByteArray(0))
            }
        }

        if (instruction == PUT_INS) {
            val bodySize = readApduBodySize(stream)
            val talerInstr = stream.read()
            val bodyBytes = stream.readBytes()
            if (1 + bodyBytes.size != bodySize) {
                Log.w(TAG, "mismatched body size ($bodySize vs ${bodyBytes.size}")
            }

            when (talerInstr) {
                1 -> {
                    val url = String(bodyBytes, Charsets.UTF_8)
                    Log.v(TAG, "got URL: '$url'")

                    Intent(this, MainActivity::class.java).also { intent ->
                        intent.data = Uri.parse(url)
                        intent.action = Intent.ACTION_VIEW
                        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                        startActivity(intent)
                    }
                }
                2 -> {
                    Log.v(TAG, "got http response: ${bodyBytes.toString(Charsets.UTF_8)}")

                    Intent().also { intent ->
                        intent.action = HTTP_TUNNEL_RESPONSE
                        intent.putExtra("response", bodyBytes.toString(Charsets.UTF_8))
                        sendBroadcast(intent)
                    }
                }
                else -> {
                    Log.v(TAG, "taler instruction $talerInstr unknown")
                }
            }

            return makeApduSuccessResponse(ByteArray(0))
        }

        return makeApduFailureResponse()
    }

    companion object {
        const val TAG = "taler-wallet-hce"
        const val SELECT_INS = 0xA4
        const val PUT_INS = 0xDA
        const val GET_INS = 0xCA

        const val TRIGGER_PAYMENT_ACTION = "net.taler.TRIGGER_PAYMENT_ACTION"

        const val MERCHANT_NFC_CONNECTED = "net.taler.MERCHANT_NFC_CONNECTED"
        const val MERCHANT_NFC_DISCONNECTED = "net.taler.MERCHANT_NFC_DISCONNECTED"

        const val HTTP_TUNNEL_RESPONSE = "net.taler.HTTP_TUNNEL_RESPONSE"
        const val HTTP_TUNNEL_REQUEST = "net.taler.HTTP_TUNNEL_REQUEST"
    }
}