-
Notifications
You must be signed in to change notification settings - Fork 126
Expand file tree
/
Copy pathmain.c
More file actions
528 lines (481 loc) · 12.5 KB
/
main.c
File metadata and controls
528 lines (481 loc) · 12.5 KB
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
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
/**
* nmrpflash - Netgear Unbrick Utility
* Copyright (C) 2016 Joseph Lehner <joseph.c.lehner@gmail.com>
*
* nmrpflash is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* nmrpflash is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with nmrpflash. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include <unistd.h>
#include <getopt.h>
#include <locale.h>
#include <stdlib.h>
#include <signal.h>
#include <locale.h>
#include <stdio.h>
#include <pcap.h>
#ifdef WITH_CTRL_THREAD
#include <pthread.h>
#endif
#include "nmrpd.h"
#ifndef NMRPFLASH_WINDOWS
#include <sys/utsname.h>
#endif
int usage(FILE *fp)
{
fprintf(fp,
"Usage: nmrpflash [OPTIONS...]\n"
"\n"
"Options (-i, and -f or -c are mandatory):\n"
" -a <ipaddr> IP address to assign to target device [%s]\n"
" -A <ipaddr> IP address to assign to selected interface [%s]\n"
" -B [<timeout>] Blind mode. Initial timeout (seconds) [%d s]\n"
" -c <command> Command to run before (or instead of) TFTP upload\n"
" -f <firmware> Firmware file\n"
" -F <filename> Remote filename to use during TFTP upload\n"
" -i <interface> Network interface directly connected to device\n"
" -m <mac> MAC address of target device (xx:xx:xx:xx:xx:xx)\n"
" -M <netmask> Subnet mask to assign to target device [%s]\n"
" -t <timeout> Timeout (in milliseconds) for NMRP packets [%d ms]\n"
" -T <timeout> Time (seconds) to wait after successful TFTP upload [%d s]\n"
" -p <port> Port to use for TFTP upload [%d]\n"
#ifdef NMRPFLASH_SET_REGION
" -R <region> Set device region (NA, WW, GR, PR, RU, BZ, IN, KO, JP, AU)\n"
#endif
" -S <n> Skip <n> bytes of the firmware file\n"
" -v Be verbose\n"
" -V Print version and exit\n"
" -L List network interfaces\n"
" -h Show this screen\n"
"\n"
"Example: (run as "
#ifndef NMRPFLASH_WINDOWS
"root"
#else
"administrator"
#endif
")\n\n"
#ifndef NMRPFLASH_WINDOWS
"# nmrpflash"
#else
"C:\\> nmrpflash.exe"
#endif
" -i eth0 -f firmware.bin\n"
"\n"
"The command specified by -c will have environment variables IP, NETMASK, PORT,\n"
"and MAC set to the router's IP address, subnet mask, TFTP port, and MAC address,\n"
"respectively.\n"
"\n"
"nmrpflash %s, Copyright (C) 2016-2025 Joseph C. Lehner\n"
"nmrpflash is free software, licensed under the GNU GPLv3.\n"
"Source code at https://github.com/jclehner/nmrpflash\n"
"\n"
"%s\n",
NMRP_DEFAULT_IP_REMOTE,
NMRP_DEFAULT_IP_LOCAL,
NMRP_DEFAULT_BLIND_TIMEOUT_S,
NMRP_DEFAULT_SUBNET,
NMRP_DEFAULT_RX_TIMEOUT_MS,
NMRP_DEFAULT_UL_TIMEOUT_S,
NMRP_DEFAULT_TFTP_PORT,
NMRPFLASH_VERSION,
pcap_lib_version()
);
return fp == stderr ? 1 : 0;
}
#ifdef NMRPFLASH_WINDOWS
void require_admin()
{
SID_IDENTIFIER_AUTHORITY auth = { SECURITY_NT_AUTHORITY };
PSID group = NULL;
BOOL admin, success = AllocateAndInitializeSid(
&auth, 2, SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_ADMINS,
0, 0, 0, 0, 0, 0, &group
);
if (success) {
success = CheckTokenMembership(NULL, group, &admin);
FreeSid(group);
if (success) {
if (!admin) {
fprintf(stderr, "Error: must be run as administrator\n");
exit(1);
} else {
return;
}
}
}
fprintf(stderr, "Warning: failed to check administrator privileges\n");
}
void show_exit_prompt()
{
DWORD pid;
HWND win = GetConsoleWindow();
if (!win || !GetWindowThreadProcessId(win, &pid)) {
return;
}
if (GetCurrentProcessId() == pid) {
printf("Press any key to exit\n");
getch();
}
}
// this is needed because atexit() expects cdecl, while WSACleanup() uses stdcall
void wsa_cleanup()
{
WSACleanup();
}
#else
void require_admin()
{
if (getuid() != 0) {
fprintf(stderr, "Error: must be run as root\n");
exit(1);
}
}
#endif
void print_version()
{
printf("nmrpflash %s", NMRPFLASH_VERSION);
if (!verbosity) {
printf("\n");
return;
}
#ifndef NMRPFLASH_WINDOWS
struct utsname uts;
if (uname(&uts) >= 0) {
#ifdef NMRPFLASH_MACOS
int maj, min;
if (sscanf(uts.release, "%d.%d", &maj, &min) == 2) {
if (maj >= 20) {
if (maj >= 25) { // macOS 26+
maj += 1;
} else { // macOS 11 - 15
maj -= 9;
}
printf(" on macOS %d", maj);
} else {
if (maj >= 16) { // macOS 10.12 - 10.15
printf("on macOS");
} else if (maj >= 12) { // OS X 10.8 - 10.11
printf("on OS X");
} else { // Mac OS X <= 10.7
printf("on Mac OS X");
}
printf(" 10.%d", maj - 4);
}
printf(" (%s)\n", uts.machine);
return;
}
#endif
printf(" on %s %s (%s)\n", uts.sysname, uts.release, uts.machine);
} else {
printf(" on unknown Unix-like OS\n");
}
#else
printf(" on Windows ");
OSVERSIONINFO os;
os.dwOSVersionInfoSize = sizeof(os);
if (GetVersionEx(&os)) {
if (os.dwMajorVersion == 6) {
if (os.dwMinorVersion == 0) {
printf("Vista");
} else if (os.dwMinorVersion == 1) {
printf("7");
} else if (os.dwMinorVersion == 2) {
printf("8");
} else if (os.dwMinorVersion == 3) {
printf("8.1");
}
} else if (os.dwMajorVersion == 10) {
if (os.dwBuildNumber < 22000) {
printf("10");
} else {
printf("11");
}
} else {
printf("%lu", os.dwMajorVersion);
}
} else {
printf("?");
}
printf(" (%s)\n", getenv("PROCESSOR_ARCHITECTURE"));
#endif
}
static bool list_callback(const struct ethsock_list_item* item, void* arg)
{
printf("%-15s ", item->device_name);
printf("%-15s ", item->ip4addr);
printf("%s ", mac_to_str(item->hwaddr));
if (item->pretty_name) {
printf("(%s)", item->pretty_name);
}
printf("\n");
*((int*)arg) += 1;
return true;
}
#ifdef WITH_CTRL_THREAD
// just temporary, for testing upcoming GUI code
static pthread_t ctrl_thread;
static bool ctrl_thread_started = false;
static void* ctrl_thread_func(void* arg)
{
while (true) {
switch (getchar()) {
case 'i':
kill(0, SIGINT);
break;
case 't':
kill(0, SIGTERM);
break;
}
}
return NULL;
}
#endif
void force_line_buffering_if_no_tty(FILE* stream)
{
int fd;
if (stream == stdout) {
fd = STDOUT_FILENO;
} else if (stream == stderr) {
fd = STDERR_FILENO;
} else {
return;
}
if (!isatty(fd)) {
setvbuf(stream, NULL, _IOLBF, BUFSIZ);
}
}
int main(int argc, char **argv)
{
int c, val, max, count;
bool list = false, have_dest_mac = false;
struct nmrpd_args args = {
.rx_timeout = NMRP_DEFAULT_RX_TIMEOUT_MS,
.ul_timeout = NMRP_DEFAULT_UL_TIMEOUT_S * 1000,
.tftpcmd = NULL,
.file_local = NULL,
.file_remote = NULL,
.ipaddr_intf = NULL,
.ipaddr = NULL,
.ipmask = NMRP_DEFAULT_SUBNET,
.intf = NULL,
.mac = "ff:ff:ff:ff:ff:ff",
.op = NMRP_UPLOAD_FW,
.port = NMRP_DEFAULT_TFTP_PORT,
.region = NULL,
.blind_timeout = 0,
.offset = 0,
};
#ifndef NMRPFLASH_WINDOWS
signal(SIGPIPE, SIG_IGN);
#endif
force_line_buffering_if_no_tty(stdout);
force_line_buffering_if_no_tty(stderr);
setlocale(LC_ALL, "en_US.UTF-8");
#ifdef NMRPFLASH_WINDOWS
WSADATA wsa;
SetConsoleOutputCP(CP_UTF8);
SetThreadUILanguage(MAKELANGID(LANG_ENGLISH, SUBLANG_DEFAULT));
atexit(&show_exit_prompt);
if (strstr(pcap_lib_version(), "WinPcap")) {
fprintf(stderr, "Warning: WinPcap is no longer supported! Install Npcap instead.\n");
}
val = WSAStartup(MAKEWORD(2, 2), &wsa);
if (val != 0) {
win_perror2("WSAStartup", val);
return 1;
}
atexit(&wsa_cleanup);
#ifndef _WIN64
// This dirty hack works around the WOW64 file system redirector[1], which would prevent
// us from calling programs residing in %windir%\System32 when running on a 64bit system
// (since nmrpflash is currently shipped as 32bit only).
//
// [1] https://msdn.microsoft.com/en-us/library/windows/desktop/aa384187(v=vs.85).aspx
char *oldpath = getenv("PATH");
char *windir = getenv("WINDIR");
if (oldpath && windir) {
char *newpath = malloc(strlen(oldpath) + strlen(windir) + 32);
sprintf(newpath, "%s;%s\\Sysnative", oldpath, windir);
SetEnvironmentVariable("PATH", newpath);
free(newpath);
}
#endif
#endif
opterr = 0;
while ((c = getopt(argc, argv, ":a:A:Bc:f:F:i:m:M:p:R:S:t:T:hLVvU")) != -1) {
switch (c) {
case 'a':
args.ipaddr = optarg;
break;
case 'A':
args.ipaddr_intf = optarg;
break;
case 'c':
args.tftpcmd = optarg;
break;
case 'f':
args.file_local = optarg;
break;
case 'F':
args.file_remote = optarg;
break;
case 'i':
args.intf = optarg;
break;
case 'm':
args.mac = optarg;
have_dest_mac = true;
break;
case 'M':
args.ipmask = optarg;
break;
#ifdef NMRPFLASH_SET_REGION
case 'R':
args.region = optarg;
break;
#endif
case 'B':
case 'p':
case 'S':
case 'T':
case 't':
if (c == 'p') {
max = 0xffff;
} else {
max = 0x7fffffff;
}
if (optarg) {
val = atoi(optarg);
if (val <= 0 || val > max) {
fprintf(stderr, "Invalid numeric value for -%c.\n", c);
return 1;
}
} else if (c == 'B') {
args.blind_timeout = NMRP_DEFAULT_BLIND_TIMEOUT_S;
break;
} else {
fprintf(stderr, "Missing argument for -%c.\n", c);
return 1;
}
if (c == 'B') {
args.blind_timeout = val;
} else if (c == 'p') {
args.port = val;
} else if (c == 't') {
args.rx_timeout = val;
} else if (c == 'T') {
args.ul_timeout = val * 1000;
} else if (c == 'S') {
args.offset = val;
}
break;
case 'V':
print_version();
return 0;
case 'v':
++verbosity;
break;
case 'L':
list = true;
break;
case 'h':
return usage(stdout);
case ':':
if (optopt == 'B') {
args.blind_timeout = NMRP_DEFAULT_BLIND_TIMEOUT_S;
break;
}
// fallthrough
default:
return usage(stderr);
}
}
if (verbosity) {
print_version();
}
if (args.ipaddr_intf && !args.ipaddr) {
fprintf(stderr, "Error: cannot use -A <ipaddr> without using -a <ipaddr>.\n");
return 1;
}
if (args.blind_timeout && !have_dest_mac) {
fprintf(stderr, "Error: use of -B requires -m <mac>.\n");
return 1;
}
#ifndef NMRPFLASH_FUZZ
if (!list && ((!args.file_local && !args.tftpcmd) || !args.intf)) {
return usage(stderr);
}
if (!list) {
require_admin();
}
#endif
if (list) {
count = 0;
val = ethsock_list_all(list_callback, &count);
if (!val && !count) {
fprintf(stderr, "Error: no suitable network interfaces found.\n");
val = -1;
}
} else {
#ifdef WITH_CTRL_THREAD
if (!isatty(STDIN_FILENO)) {
if (pthread_create(&ctrl_thread, NULL, ctrl_thread_func, NULL) != 0) {
perror("pthread_create");
return 1;
}
ctrl_thread_started = true;
if (verbosity > 1) {
printf("Control thread listening on stdin.\n");
}
} else if (verbosity > 1) {
printf("Not creating control thread.\n");
}
#endif
val = nmrp_do(&args);
#ifdef WITH_CTRL_THREAD
if (ctrl_thread_started) {
pthread_cancel(ctrl_thread);
}
#endif
if (val != 0 && !g_interrupted && args.hints) {
fprintf(stderr, "\n");
if (args.hints & NMRP_MAYBE_FIRMWARE_INVALID) {
fprintf(stderr,
"Firmware file rejected by router. Possible causes:\n"
"- Wrong firmware file (model number correct?)\n"
"- Wrong file format (e.g. .chk vs .trx file)\n"
"- Downgrading to a lower version number\n");
} else if (args.hints & NMRP_NO_ETHERNET_CONNECTION) {
fprintf(stderr,
"No Ethernet connection detected. Possible causes:\n"
"- Wrong Ethernet port - try others there's more than one\n"
"- Bad Ethernet cable\n"
"- Hardware issue\n");
} else if ((args.hints & NMRP_NO_NMRP_RESPONSE) && !args.blind_timeout) {
fprintf(stderr,
"No response from router. Possible causes/fixes:\n"
"- Unsupported router\n"
"- Wrong Ethernet port - try others if there's more than one\n"
"- Hold reset button for a few seconds while powering on router\n"
"- Try blind mode (`-B` option)");
} else if (args.hints & NMRP_TFTP_XMIT_BLK0_FAILURE) {
fprintf(stderr,
"Failed to send/receive initial TFTP packet. Possible fixes:\n"
"- Disable firewall, or add an exception for nmrpflash\n"
"- Manually specify IP addresses using `-a` and/or `-A`\n");
}
}
}
return val == 0 ? EXIT_SUCCESS : EXIT_FAILURE;
}