NXEngine v1.0.0.6
[NXEngine.git] / niku.cpp
blob7f30a4574c8290167e773fa7421295762df13691
2 #include <stdio.h>
3 #include <stdint.h>
4 #include "niku.fdh"
6 /*
7 290.rec contains the tick value 4 times, followed by the 4 byte key
8 to decrypt each instance, for a total of 20 bytes.
9 */
11 // load the contents of 290.rec and store in value_out. Returns 0 on success.
12 // If there is no such file or an error occurs, writes 0 to value_out.
13 bool niku_load(uint32_t *value_out)
15 FILE *fp;
16 uint8_t buffer[20];
17 uint32_t *result = (uint32_t *)buffer;
18 int i, j;
20 const char *fname = getfname();
21 fp = fileopen(fname, "rb");
22 if (!fp)
24 stat("niku_load: couldn't open file '%s'", fname);
25 if (value_out) *value_out = 0;
26 return 1;
29 fread(buffer, 20, 1, fp);
30 fclose(fp);
32 for(i=0;i<4;i++)
34 uint8_t key = buffer[i+16];
36 j = i * 4;
37 buffer[j] -= key;
38 buffer[j+1] -= key;
39 buffer[j+2] -= key;
40 buffer[j+3] -= (key / 2);
43 if ((result[0] != result[1]) || \
44 (result[0] != result[2]) || \
45 (result[0] != result[3]))
47 stat("niku_load: value mismatch; '%s' corrupt", fname);
48 if (value_out) *value_out = 0;
50 else
52 stat("niku_load: loaded value 0x%x from %s", *result, fname);
53 if (value_out) *value_out = *result;
56 return 0;
59 // save the timestamp in value to 290.rec.
60 bool niku_save(uint32_t value)
62 uint8_t buf_byte[20];
63 uint32_t *buf_dword = (uint32_t *)buf_byte;
65 // place values
66 buf_dword[0] = value;
67 buf_dword[1] = value;
68 buf_dword[2] = value;
69 buf_dword[3] = value;
71 // generate keys
72 buf_byte[16] = random(0, 255);
73 buf_byte[17] = random(0, 255);
74 buf_byte[18] = random(0, 255);
75 buf_byte[19] = random(0, 255);
77 // encode each copy
78 for(int i=0;i<4;i++)
80 uint8_t *ptr = (uint8_t *)&buf_dword[i];
81 uint8_t key = buf_byte[i+16];
83 ptr[0] += key;
84 ptr[1] += key;
85 ptr[2] += key;
86 ptr[3] += key / 2;
89 const char *fname = getfname();
90 FILE *fp = fileopen(fname, "wb");
91 if (!fp)
93 staterr("niku_save: failed to open '%s'", fname);
94 return 1;
97 fwrite(buf_byte, 20, 1, fp);
98 fclose(fp);
100 stat("niku_save: wrote value 0x%08x", value);
101 return 0;
105 void c------------------------------() {}
108 static const char *getfname()
110 // might do stuff with sprintf here to place it in other subdirectories, etc.
111 // is just here for expansion.
112 return "290.rec";