| 50 | } |
| 51 | |
| 52 | static int wrapCommandApdu(unsigned int channel, const unsigned char *command, size_t commandLength, |
| 53 | unsigned int packetSize, unsigned char *out, size_t outLength) { |
| 54 | size_t sequenceIdx = 0; |
| 55 | size_t offset = 0; |
| 56 | size_t offsetOut = 0; |
| 57 | if (packetSize < 3) { |
| 58 | return -1; |
| 59 | } |
| 60 | if (outLength < 7) { |
| 61 | return -1; |
| 62 | } |
| 63 | outLength -= 7; |
| 64 | out[offsetOut++] = ((channel >> 8) & 0xff); |
| 65 | out[offsetOut++] = (channel & 0xff); |
| 66 | out[offsetOut++] = TAG_APDU; |
| 67 | out[offsetOut++] = ((sequenceIdx >> 8) & 0xff); |
| 68 | out[offsetOut++] = (sequenceIdx & 0xff); |
| 69 | sequenceIdx++; |
| 70 | out[offsetOut++] = ((commandLength >> 8) & 0xff); |
| 71 | out[offsetOut++] = (commandLength & 0xff); |
| 72 | size_t blockSize = (commandLength > packetSize - 7 ? packetSize - 7 : commandLength); |
| 73 | if (outLength < blockSize) { |
| 74 | return -1; |
| 75 | } |
| 76 | outLength -= blockSize; |
| 77 | memcpy(out + offsetOut, command + offset, blockSize); |
| 78 | offsetOut += blockSize; |
| 79 | offset += blockSize; |
| 80 | while (offset != commandLength) { |
| 81 | if (outLength < 5) { |
| 82 | return -1; |
| 83 | } |
| 84 | outLength -= 5; |
| 85 | out[offsetOut++] = ((channel >> 8) & 0xff); |
| 86 | out[offsetOut++] = (channel & 0xff); |
| 87 | out[offsetOut++] = TAG_APDU; |
| 88 | out[offsetOut++] = ((sequenceIdx >> 8) & 0xff); |
| 89 | out[offsetOut++] = (sequenceIdx & 0xff); |
| 90 | sequenceIdx++; |
| 91 | blockSize = ((commandLength - offset) > packetSize - 5 ? packetSize - 5 : commandLength - offset); |
| 92 | if (outLength < blockSize) { |
| 93 | return -1; |
| 94 | } |
| 95 | outLength -= blockSize; |
| 96 | memcpy(out + offsetOut, command + offset, blockSize); |
| 97 | offsetOut += blockSize; |
| 98 | offset += blockSize; |
| 99 | } |
| 100 | while ((offsetOut % packetSize) != 0) { |
| 101 | if (outLength < 1) { |
| 102 | return -1; |
| 103 | } |
| 104 | outLength--; |
| 105 | out[offsetOut++] = 0; |
| 106 | } |
| 107 | return static_cast<int>(offsetOut); |
| 108 | } |
| 109 | |