-
Notifications
You must be signed in to change notification settings - Fork 32
/
amiitool.cpp
113 lines (87 loc) · 2.52 KB
/
amiitool.cpp
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
#include "amiitool.h"
#include "amiibo.h"
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#define COMMAND_SIZE 1000
Amiitool *Amiitool::_shared = NULL;
const char *Amiitool::_keyPath = NULL;
Amiitool *Amiitool::shared() {
if (!_shared) { _shared = new Amiitool(); }
return _shared;
}
void Amiitool::setKeyPath(const char *keyPath) {
Amiitool::_keyPath = keyPath;
}
Amiitool::Amiitool() {
if (pipe(writePipe) < 0) {
fprintf(stderr, "Could not open write pipe\n");
exit(1);
}
if (pipe(readPipe) < 0) {
fprintf(stderr, "Could not open read pipe\n");
exit(1);
}
savedStdin = dup(0);
savedStdout = dup(1);
}
int Amiitool::decryptBuffer(uint8_t *encryptedBuffer, uint8_t *decryptedBuffer) {
printf("\nDecrypting bin\n");
return pipeToAmiitool("-d", Amiitool::_keyPath, encryptedBuffer, decryptedBuffer);
}
int Amiitool::encryptBuffer(uint8_t *encryptedBuffer, uint8_t *decryptedBuffer) {
printf("Encrypting\n");
return pipeToAmiitool("-e", Amiitool::_keyPath, decryptedBuffer, encryptedBuffer);
}
int Amiitool::pipeToAmiitool(const char *args, const char* keyPath, uint8_t *inputBuffer, uint8_t *outputBuffer) {
printf("Sending bin to amiitool...");
redirectIO();
int pipeSize;
if (AMIIBO_SIZE != (pipeSize = write(writePipe[1], inputBuffer, AMIIBO_SIZE))) {
fprintf(stderr, "Wrote incorrect size to pipe: %d\n", pipeSize);
perror("write");
exit(1);
}
const char *staticCommand = "./amiitool/amiitool %s -k %s";
char command[COMMAND_SIZE + strlen(staticCommand)];
if (strlen(keyPath) >= COMMAND_SIZE) {
fprintf(stderr, "Key path too big\n");
exit(1);
}
sprintf(command, staticCommand, args, keyPath);
system(command);
if (AMIIBO_SIZE != (pipeSize = read(readPipe[0], outputBuffer, AMIIBO_SIZE))) {
fprintf(stderr, "Read incorrect size from pipe: %d\n", pipeSize);
exit(1);
}
resetIO();
printf("Done\n");
return 0;
}
void Amiitool::redirectIO() {
if (dup2(writePipe[0], 0) < 0) {
fprintf(stderr, "Could not redirect stdin\n");
exit(1);
}
if (dup2(readPipe[1], 1) < 0) {
fprintf(stderr, "Could not redirect stdout\n");
exit(1);
}
}
void Amiitool::resetIO() {
if (dup2(savedStdin, 0) < 0) {
fprintf(stderr, "Could not reset stdin\n");
exit(1);
}
if (dup2(savedStdout, 1) < 0) {
fprintf(stderr, "Could not reset stdout\n");
exit(1);
}
}
void Amiitool::printHex(const uint8_t *buffer, const size_t size) {
size_t i;
for (i = 0; i < size; i++) {
printf("%02x ", buffer[i]);
}
printf("\n");
}