hmland: handle commands spanning packet-boundaries
[hmcfgusb] / hmland.c
CommitLineData
4732a863 1/* HM-CFG-LAN emulation for HM-CFG-USB
9db2e455 2 *
b229c878 3 * Copyright (c) 2013-15 Michael Gernoth <michael@gernoth.net>
9db2e455
MG
4 *
5 * Permission is hereby granted, free of charge, to any person obtaining a copy
6 * of this software and associated documentation files (the "Software"), to
7 * deal in the Software without restriction, including without limitation the
8 * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
9 * sell copies of the Software, and to permit persons to whom the Software is
10 * furnished to do so, subject to the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be included in
13 * all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
20 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
21 * IN THE SOFTWARE.
22 */
23
24#include <stdio.h>
25#include <stdlib.h>
26#include <unistd.h>
27#include <stdint.h>
18e63b25 28#include <stdarg.h>
9db2e455
MG
29#include <string.h>
30#include <strings.h>
31#include <poll.h>
4371275b 32#include <signal.h>
9db2e455 33#include <errno.h>
e0a7146e
MG
34#include <sys/types.h>
35#include <sys/socket.h>
b0bf6ad2 36#include <sys/stat.h>
e6ab4631 37#include <fcntl.h>
fbbbfa37 38#include <time.h>
e0a7146e
MG
39#include <netinet/in.h>
40#include <arpa/inet.h>
9db2e455
MG
41#include <libusb-1.0/libusb.h>
42
c44f15b8 43#include "version.h"
9db2e455
MG
44#include "hexdump.h"
45#include "hmcfgusb.h"
46
b0bf6ad2
MG
47#define PID_FILE "/var/run/hmland.pid"
48
62f25bae 49#define DEFAULT_REBOOT_SECONDS 86400
b229c878
MG
50#define LAN_READ_CHUNK_SIZE 2048
51/* Don't allow remote clients to consume all of our memory */
52#define LAN_MAX_LINE_LENGTH 4096
53#define LAN_MAX_BUF_LENGTH 1048576
62f25bae 54
627e3f33
MG
55extern char *optarg;
56
e0a7146e 57static int impersonate_hmlanif = 0;
627e3f33
MG
58static int debug = 0;
59static int verbose = 0;
18e63b25 60static FILE *logfile = NULL;
62f25bae 61static int reboot_seconds = 0;
30a2aa7a
MG
62static int reboot_at_hour = -1;
63static int reboot_at_minute = -1;
c8cafbea 64static int reboot_set = 0;
b229c878
MG
65static uint8_t *lan_read_buf = NULL;
66static int lan_read_buflen = 0;
e0a7146e 67
d84111c4
MG
68struct queued_rx {
69 char *rx;
70 int len;
71 struct queued_rx *next;
72};
73
74static struct queued_rx *qrx = NULL;
75static int wait_for_h = 0;
76
e75295bb
MG
77#define FLAG_LENGTH_BYTE (1<<0)
78#define FLAG_FORMAT_HEX (1<<1)
79#define FLAG_COMMA_BEFORE (1<<2)
80#define FLAG_COMMA_AFTER (1<<3)
81#define FLAG_NL (1<<4)
82#define FLAG_IGNORE_COMMAS (1<<5)
83
84#define CHECK_SPACE(x) if ((*outpos + x) > outend) { fprintf(stderr, "Not enough space!\n"); return 0; }
85#define CHECK_AVAIL(x) if ((*inpos + x) > inend) { fprintf(stderr, "Not enough input available!\n"); return 0; }
86
fbbbfa37
MG
87static void print_timestamp(FILE *f)
88{
89 struct timeval tv;
90 struct tm *tmp;
91 char ts[32];
92
93 gettimeofday(&tv, NULL);
94 tmp = localtime(&tv.tv_sec);
95 memset(ts, 0, sizeof(ts));
96 strftime(ts, sizeof(ts)-1, "%Y-%m-%d %H:%M:%S", tmp);
97 fprintf(f, "%s.%06ld: ", ts, tv.tv_usec);
98}
99
18e63b25
MG
100static void write_log(char *buf, int len, char *fmt, ...)
101{
102 va_list ap;
103 int i;
104
105 if ((!logfile) && (!verbose))
106 return;
107
108 if (logfile)
109 print_timestamp(logfile);
110 if (verbose)
111 print_timestamp(stdout);
112
113 if (fmt) {
114 if (logfile) {
115 va_start(ap, fmt);
116 vfprintf(logfile, fmt, ap);
117 va_end(ap);
118 }
119 if (verbose) {
120 va_start(ap, fmt);
121 vprintf(fmt, ap);
122 va_end(ap);
123 }
124 }
125
126 if (buf && len) {
127 for (i = 0; i < len; i++) {
128 if (logfile)
129 fprintf(logfile, "%c", buf[i]);
130 if (verbose)
131 printf("%c", buf[i]);
132 }
133 if (logfile)
134 fprintf(logfile, "\n");
135 if (verbose)
136 printf("\n");
137 }
138 if (logfile)
139 fflush(logfile);
140}
141
e75295bb
MG
142static int format_part_out(uint8_t **inpos, int inlen, uint8_t **outpos, int outlen, int len, int flags)
143{
51d4ece6
MG
144 const uint8_t nibble[16] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
145 'A', 'B', 'C', 'D', 'E', 'F'};
e75295bb
MG
146 uint8_t *buf_out = *outpos;
147 uint8_t *outend = *outpos + outlen;
148 uint8_t *inend = *inpos + inlen;
149 int i;
150
151 if (flags & FLAG_COMMA_BEFORE) {
152 CHECK_SPACE(1);
153 **outpos=',';
154 *outpos += 1;
155 }
156
157 if (flags & FLAG_LENGTH_BYTE) {
158 CHECK_AVAIL(1);
159 len = **inpos;
160 *inpos += 1;
161 }
162
163 if (flags & FLAG_FORMAT_HEX) {
e75295bb
MG
164 CHECK_AVAIL(len);
165 CHECK_SPACE(len*2);
166 for (i = 0; i < len; i++) {
51d4ece6
MG
167 **outpos = nibble[((**inpos) & 0xf0) >> 4];
168 *outpos += 1;
169 **outpos = nibble[((**inpos) & 0xf)];
170 *inpos += 1; *outpos += 1;
e75295bb
MG
171 }
172 } else {
173 CHECK_AVAIL(len);
174 CHECK_SPACE(len);
175 memcpy(*outpos, *inpos, len);
176 *outpos += len;
177 *inpos += len;
178 }
179
180 if (flags & FLAG_COMMA_AFTER) {
181 CHECK_SPACE(1);
182 **outpos=',';
183 *outpos += 1;
184 }
185
186 if (flags & FLAG_NL) {
187 CHECK_SPACE(2);
188 **outpos='\r';
189 *outpos += 1;
190 **outpos='\n';
191 *outpos += 1;
192 }
193
194 return *outpos - buf_out;
195}
196
51d4ece6
MG
197static uint8_t ascii_to_nibble(uint8_t a)
198{
199 uint8_t c = 0x00;
200
201 if ((a >= '0') && (a <= '9')) {
202 c = a - '0';
203 } else if ((a >= 'A') && (a <= 'F')) {
204 c = (a - 'A') + 10;
205 } else if ((a >= 'a') && (a <= 'f')) {
206 c = (a - 'a') + 10;
207 }
208
209 return c;
210}
211
e75295bb
MG
212static int parse_part_in(uint8_t **inpos, int inlen, uint8_t **outpos, int outlen, int flags)
213{
214 uint8_t *buf_out = *outpos;
215 uint8_t *outend = *outpos + outlen;
216 uint8_t *inend = *inpos + inlen;
e75295bb
MG
217
218 if (flags & FLAG_LENGTH_BYTE) {
219 int len = 0;
220 uint8_t *ip;
221
222 ip = *inpos;
223 while(ip < inend) {
224 if (*ip == ',') {
225 ip++;
226 if (!(flags & FLAG_IGNORE_COMMAS))
227 break;
228
229 continue;
230 }
231 len++;
232 ip++;
233 }
234 CHECK_SPACE(1);
235 **outpos = (len / 2);
236 *outpos += 1;
237 }
238
239 while(*inpos < inend) {
240 if (**inpos == ',') {
241 *inpos += 1;
242 if (!(flags & FLAG_IGNORE_COMMAS))
243 break;
244
245 continue;
246 }
247
248 CHECK_SPACE(1);
249 CHECK_AVAIL(2);
e75295bb 250
51d4ece6
MG
251 **outpos = ascii_to_nibble(**inpos) << 4;
252 *inpos += 1;
253 **outpos |= ascii_to_nibble(**inpos);
254 *inpos += 1; *outpos += 1;
e75295bb
MG
255 }
256
257 return *outpos - buf_out;
258}
259
4371275b 260static int hmlan_format_out(uint8_t *buf, int buf_len, void *data)
9db2e455 261{
e75295bb
MG
262 uint8_t out[1024];
263 uint8_t *outpos;
264 uint8_t *inpos;
c8cafbea 265 uint16_t version;
e0a7146e 266 int fd = *((int*)data);
4371275b 267 int w;
9db2e455
MG
268
269 if (buf_len < 1)
4371275b 270 return 1;
9db2e455 271
e0a7146e 272 memset(out, 0, sizeof(out));
e75295bb
MG
273 outpos = out;
274 inpos = buf;
e0a7146e 275
e75295bb 276 format_part_out(&inpos, (buf_len-(inpos-buf)), &outpos, (sizeof(out)-(outpos-out)), 1, 0);
9db2e455
MG
277 switch(buf[0]) {
278 case 'H':
e0a7146e
MG
279 if (impersonate_hmlanif) {
280 buf[5] = 'L';
281 buf[6] = 'A';
282 buf[7] = 'N';
283 }
e75295bb 284 format_part_out(&inpos, (buf_len-(inpos-buf)), &outpos, (sizeof(out)-(outpos-out)), 0, FLAG_LENGTH_BYTE);
c8cafbea
MG
285 version = inpos[0] << 8;
286 version |= inpos[1];
e75295bb
MG
287 format_part_out(&inpos, (buf_len-(inpos-buf)), &outpos, (sizeof(out)-(outpos-out)), 2, FLAG_FORMAT_HEX | FLAG_COMMA_BEFORE);
288 format_part_out(&inpos, (buf_len-(inpos-buf)), &outpos, (sizeof(out)-(outpos-out)), 0, FLAG_COMMA_BEFORE | FLAG_LENGTH_BYTE);
289 format_part_out(&inpos, (buf_len-(inpos-buf)), &outpos, (sizeof(out)-(outpos-out)), 3, FLAG_FORMAT_HEX | FLAG_COMMA_BEFORE);
290 format_part_out(&inpos, (buf_len-(inpos-buf)), &outpos, (sizeof(out)-(outpos-out)), 3, FLAG_FORMAT_HEX | FLAG_COMMA_BEFORE);
291 format_part_out(&inpos, (buf_len-(inpos-buf)), &outpos, (sizeof(out)-(outpos-out)), 4, FLAG_FORMAT_HEX | FLAG_COMMA_BEFORE);
292 format_part_out(&inpos, (buf_len-(inpos-buf)), &outpos, (sizeof(out)-(outpos-out)), 2, FLAG_FORMAT_HEX | FLAG_COMMA_BEFORE | FLAG_NL);
9db2e455 293
c8cafbea
MG
294 if (!reboot_set) {
295 int new_reboot_seconds;
296
297 if (version < 0x03c7) {
298 new_reboot_seconds = DEFAULT_REBOOT_SECONDS;
299 } else {
300 new_reboot_seconds = 0;
301 }
302
303 if (verbose && new_reboot_seconds && (reboot_seconds != new_reboot_seconds))
304 printf("Rebooting in %u seconds due to old firmware (0.%d)\n",
305 new_reboot_seconds, version);
306
307 reboot_seconds = new_reboot_seconds;
308 }
309
9db2e455
MG
310 break;
311 case 'E':
e75295bb
MG
312 format_part_out(&inpos, (buf_len-(inpos-buf)), &outpos, (sizeof(out)-(outpos-out)), 3, FLAG_FORMAT_HEX);
313 format_part_out(&inpos, (buf_len-(inpos-buf)), &outpos, (sizeof(out)-(outpos-out)), 2, FLAG_FORMAT_HEX | FLAG_COMMA_BEFORE);
314 format_part_out(&inpos, (buf_len-(inpos-buf)), &outpos, (sizeof(out)-(outpos-out)), 4, FLAG_FORMAT_HEX | FLAG_COMMA_BEFORE);
315 format_part_out(&inpos, (buf_len-(inpos-buf)), &outpos, (sizeof(out)-(outpos-out)), 1, FLAG_FORMAT_HEX | FLAG_COMMA_BEFORE);
316 format_part_out(&inpos, (buf_len-(inpos-buf)), &outpos, (sizeof(out)-(outpos-out)), 2, FLAG_FORMAT_HEX | FLAG_COMMA_BEFORE);
317 format_part_out(&inpos, (buf_len-(inpos-buf)), &outpos, (sizeof(out)-(outpos-out)), 0, FLAG_FORMAT_HEX | FLAG_COMMA_BEFORE | FLAG_LENGTH_BYTE | FLAG_NL);
318
9db2e455
MG
319 break;
320 case 'R':
e75295bb
MG
321 format_part_out(&inpos, (buf_len-(inpos-buf)), &outpos, (sizeof(out)-(outpos-out)), 4, FLAG_FORMAT_HEX);
322 format_part_out(&inpos, (buf_len-(inpos-buf)), &outpos, (sizeof(out)-(outpos-out)), 2, FLAG_FORMAT_HEX | FLAG_COMMA_BEFORE);
323 format_part_out(&inpos, (buf_len-(inpos-buf)), &outpos, (sizeof(out)-(outpos-out)), 4, FLAG_FORMAT_HEX | FLAG_COMMA_BEFORE);
324 format_part_out(&inpos, (buf_len-(inpos-buf)), &outpos, (sizeof(out)-(outpos-out)), 1, FLAG_FORMAT_HEX | FLAG_COMMA_BEFORE);
325 format_part_out(&inpos, (buf_len-(inpos-buf)), &outpos, (sizeof(out)-(outpos-out)), 2, FLAG_FORMAT_HEX | FLAG_COMMA_BEFORE);
326 format_part_out(&inpos, (buf_len-(inpos-buf)), &outpos, (sizeof(out)-(outpos-out)), 0, FLAG_FORMAT_HEX | FLAG_COMMA_BEFORE | FLAG_LENGTH_BYTE | FLAG_NL);
327
9db2e455
MG
328 break;
329 case 'I':
e75295bb
MG
330 format_part_out(&inpos, (buf_len-(inpos-buf)), &outpos, (sizeof(out)-(outpos-out)), 1, FLAG_FORMAT_HEX);
331 format_part_out(&inpos, (buf_len-(inpos-buf)), &outpos, (sizeof(out)-(outpos-out)), 1, FLAG_FORMAT_HEX | FLAG_COMMA_BEFORE);
332 format_part_out(&inpos, (buf_len-(inpos-buf)), &outpos, (sizeof(out)-(outpos-out)), 1, FLAG_FORMAT_HEX | FLAG_COMMA_BEFORE);
333 format_part_out(&inpos, (buf_len-(inpos-buf)), &outpos, (sizeof(out)-(outpos-out)), 1, FLAG_FORMAT_HEX | FLAG_COMMA_BEFORE | FLAG_NL);
334
53d7bde2
MG
335 break;
336 case 'G':
337 format_part_out(&inpos, (buf_len-(inpos-buf)), &outpos, (sizeof(out)-(outpos-out)), 1, FLAG_FORMAT_HEX | FLAG_NL);
338
e75295bb 339 break;
9db2e455 340 default:
e75295bb 341 format_part_out(&inpos, (buf_len-(inpos-buf)), &outpos, (sizeof(out)-(outpos-out)), buf_len-1, FLAG_FORMAT_HEX | FLAG_NL);
9db2e455
MG
342 hexdump(buf, buf_len, "Unknown> ");
343 break;
344 }
d84111c4
MG
345
346 /* Queue packet until first respone to 'K' is received */
347 if (wait_for_h && buf[0] != 'H') {
348 struct queued_rx **rxp = &qrx;
349
350 while (*rxp)
351 rxp = &((*rxp)->next);
352
353 *rxp = malloc(sizeof(struct queued_rx));
354 if (!*rxp) {
355 perror("malloc");
356 return 0;
357 }
358
359 memset(*rxp, 0, sizeof(struct queued_rx));
360 (*rxp)->len = outpos-out;
361 (*rxp)->rx = malloc((*rxp)->len);
362 if (!(*rxp)->rx) {
363 perror("malloc");
364 return 0;
365 }
366 memset((*rxp)->rx, 0, (*rxp)->len);
367 memcpy((*rxp)->rx, out, (*rxp)->len);
368
369 return 1;
370 }
371
18e63b25 372 write_log((char*)out, outpos-out-2, "LAN < ");
4371275b
MG
373
374 w = write(fd, out, outpos-out);
375 if (w <= 0) {
376 perror("write");
377 return 0;
378 }
379
59360394 380 /* Send all queued packets */
d84111c4
MG
381 if (wait_for_h) {
382 struct queued_rx *curr_rx = qrx;
383 struct queued_rx *last_rx;
384
385 while (curr_rx) {
18e63b25 386 write_log(curr_rx->rx, curr_rx->len-2, "LAN < ");
d84111c4
MG
387
388 w = write(fd, curr_rx->rx, curr_rx->len);
389 if (w <= 0) {
390 perror("write");
d84111c4
MG
391 }
392 last_rx = curr_rx;
393 curr_rx = curr_rx->next;
394
395 free(last_rx->rx);
396 free(last_rx);
397 }
398
399 qrx = NULL;
400
401 wait_for_h = 0;
402 }
403
4371275b 404 return 1;
9db2e455
MG
405}
406
b229c878 407static int hmlan_parse_one(uint8_t *cmd, int last, void *data)
9db2e455
MG
408{
409 struct hmcfgusb_dev *dev = data;
e75295bb
MG
410 uint8_t out[0x40]; //FIXME!!!
411 uint8_t *outpos;
b229c878
MG
412 uint8_t *inpos = cmd;
413
414 outpos = out;
9db2e455 415
b229c878
MG
416 if (last == 0)
417 return 1;
627e3f33 418
b229c878 419 write_log((char*)cmd, last, "LAN > ");
627e3f33 420
b229c878
MG
421 memset(out, 0, sizeof(out));
422 *outpos++ = *inpos++;
423
424 switch(*cmd) {
425 case 'S':
426 parse_part_in(&inpos, (last-(inpos-cmd)), &outpos, (sizeof(out)-(outpos-out)), 0);
427 parse_part_in(&inpos, (last-(inpos-cmd)), &outpos, (sizeof(out)-(outpos-out)), 0);
428 parse_part_in(&inpos, (last-(inpos-cmd)), &outpos, (sizeof(out)-(outpos-out)), 0);
429 parse_part_in(&inpos, (last-(inpos-cmd)), &outpos, (sizeof(out)-(outpos-out)), 0);
430 parse_part_in(&inpos, (last-(inpos-cmd)), &outpos, (sizeof(out)-(outpos-out)), 0);
431 parse_part_in(&inpos, (last-(inpos-cmd)), &outpos, (sizeof(out)-(outpos-out)), FLAG_LENGTH_BYTE);
432 break;
433 case 'Y':
434 parse_part_in(&inpos, (last-(inpos-cmd)), &outpos, (sizeof(out)-(outpos-out)), 0);
435 parse_part_in(&inpos, (last-(inpos-cmd)), &outpos, (sizeof(out)-(outpos-out)), 0);
436 parse_part_in(&inpos, (last-(inpos-cmd)), &outpos, (sizeof(out)-(outpos-out)), FLAG_LENGTH_BYTE);
437 break;
438 default:
439 parse_part_in(&inpos, (last-(inpos-cmd)), &outpos, (sizeof(out)-(outpos-out)), FLAG_IGNORE_COMMAS);
440 break;
441 }
627e3f33 442
b229c878 443 hmcfgusb_send(dev, out, sizeof(out), 1);
627e3f33 444
b229c878
MG
445 return 1;
446}
9db2e455 447
b229c878
MG
448static int hmlan_parse_in(int fd, void *data)
449{
450 uint8_t *newbuf;
451 int r;
452 int i;
627e3f33 453
b229c878
MG
454 newbuf = realloc(lan_read_buf, lan_read_buflen + LAN_READ_CHUNK_SIZE);
455 if (!newbuf) {
456 perror("realloc");
457 return 0;
458 }
459 lan_read_buf = newbuf;
460 r = read(fd, lan_read_buf + lan_read_buflen, LAN_READ_CHUNK_SIZE);
461 if (r > 0) {
462 lan_read_buflen += r;
463 if (lan_read_buflen > LAN_MAX_BUF_LENGTH) {
464 if (verbose)
465 printf("Our buffer is bigger than %d bytes (%d bytes), closing connection!\n", LAN_MAX_BUF_LENGTH, lan_read_buflen);
466 return -1;
467 }
468 while(lan_read_buflen > 0) {
469 int found = 0;
470
471 for (i = 0; i < lan_read_buflen; i++) {
472 if ((lan_read_buf[i] == '\r') || (lan_read_buf[i] == '\n')) {
473 if (i > 0)
474 hmlan_parse_one(lan_read_buf, i, data);
475 memmove(lan_read_buf, lan_read_buf + i + 1, lan_read_buflen - (i + 1));
476 lan_read_buflen -= (i + 1);
477 found = 1;
627e3f33
MG
478 break;
479 }
b229c878
MG
480 if (i > LAN_MAX_LINE_LENGTH) {
481 if (verbose)
482 printf("Client sent more than %d bytes without newline, closing connection!\n", LAN_MAX_LINE_LENGTH);
483 return -1;
484 }
627e3f33 485 }
b229c878
MG
486 if (!found)
487 break;
488 newbuf = realloc(lan_read_buf, lan_read_buflen);
489 if (lan_read_buflen && !newbuf) {
490 perror("realloc");
491 return 0;
627e3f33 492 }
b229c878 493 lan_read_buf = newbuf;
627e3f33 494 }
9db2e455 495 } else if (r < 0) {
fbbbfa37
MG
496 if (errno != ECONNRESET)
497 perror("read");
e0a7146e
MG
498 return r;
499 } else {
500 return 0;
9db2e455 501 }
e0a7146e
MG
502
503 return 1;
9db2e455
MG
504}
505
23d96b59 506static int comm(int fd_in, int fd_out, int master_socket, int flags)
9db2e455
MG
507{
508 struct hmcfgusb_dev *dev;
23d96b59 509 uint8_t out[0x40]; //FIXME!!!
9db2e455
MG
510 int quit = 0;
511
627e3f33
MG
512 hmcfgusb_set_debug(debug);
513
e0a7146e 514 dev = hmcfgusb_init(hmlan_format_out, &fd_out);
9db2e455
MG
515 if (!dev) {
516 fprintf(stderr, "Can't initialize HM-CFG-USB!\n");
e0a7146e
MG
517 return 0;
518 }
519
62f25bae 520 if (dev->bootloader) {
0ddb3740 521 if (verbose)
30a2aa7a 522 printf("HM-CFG-USB in bootloader mode, restarting in normal mode...\n");
0ddb3740
MG
523
524 hmcfgusb_leave_bootloader(dev);
525
62f25bae
MG
526 hmcfgusb_close(dev);
527 sleep(1);
528 return 0;
529 }
530
30a2aa7a
MG
531 if ((reboot_at_hour != -1) && (reboot_at_minute != -1)) {
532 struct tm *tm_s;
533 time_t tm;
534
535 tm = time(NULL);
536 tm_s = localtime(&tm);
537 if (tm_s == NULL) {
538 perror("localtime");
539 return 0;
540 }
541
30a2aa7a
MG
542 tm_s->tm_hour = reboot_at_hour;
543 tm_s->tm_min = reboot_at_minute;
544 tm_s->tm_sec = 0;
545
ec00d63b 546 tm = mktime(tm_s);
30a2aa7a 547 reboot_seconds = tm - dev->opened_at;
ec00d63b
MG
548
549 while (reboot_seconds <= 0)
550 reboot_seconds += 86400;
30a2aa7a
MG
551 }
552
553 if (verbose && reboot_seconds)
554 printf("Rebooting in %u seconds\n", reboot_seconds);
555
556
e0a7146e
MG
557 if (!hmcfgusb_add_pfd(dev, fd_in, POLLIN)) {
558 fprintf(stderr, "Can't add client to pollfd!\n");
559 hmcfgusb_close(dev);
560 return 0;
9db2e455
MG
561 }
562
e0a7146e
MG
563 if (master_socket >= 0) {
564 if (!hmcfgusb_add_pfd(dev, master_socket, POLLIN)) {
565 fprintf(stderr, "Can't add master_socket to pollfd!\n");
566 hmcfgusb_close(dev);
567 return 0;
568 }
9db2e455
MG
569 }
570
23d96b59
MG
571 memset(out, 0, sizeof(out));
572 out[0] = 'K';
d84111c4 573 wait_for_h = 1;
6262005e 574 hmcfgusb_send_null_frame(dev, 1);
23d96b59 575 hmcfgusb_send(dev, out, sizeof(out), 1);
9db2e455
MG
576
577 while(!quit) {
578 int fd;
579
3b35a8c1 580 fd = hmcfgusb_poll(dev, 1000); /* Wakeup device/bus at least once a second */
9db2e455 581 if (fd >= 0) {
e0a7146e
MG
582 if (fd == master_socket) {
583 int client;
584
585 client = accept(master_socket, NULL, 0);
586 if (client >= 0) {
587 shutdown(client, SHUT_RDWR);
588 close(client);
589 }
590 } else {
591 if (hmlan_parse_in(fd, dev) <= 0) {
592 quit = 1;
593 }
594 }
9db2e455
MG
595 } else if (fd == -1) {
596 if (errno) {
1e79d00a
MG
597 if (errno != ETIMEDOUT) {
598 perror("hmcfgusb_poll");
599 quit = 1;
600 } else {
601 /* periodically wakeup the device */
602 hmcfgusb_send_null_frame(dev, 1);
603 if (wait_for_h) {
604 memset(out, 0, sizeof(out));
605 out[0] = 'K';
606 hmcfgusb_send(dev, out, sizeof(out), 1);
607 }
608 }
9db2e455
MG
609 }
610 }
62f25bae
MG
611
612 if (reboot_seconds && ((dev->opened_at + reboot_seconds) <= time(NULL))) {
613 if (verbose) {
30a2aa7a 614 printf("HM-CFG-USB running since %lu seconds, rebooting now...\n",
62f25bae
MG
615 time(NULL) - dev->opened_at);
616 }
617 hmcfgusb_enter_bootloader(dev);
618 }
9db2e455
MG
619 }
620
813afd12 621 hmcfgusb_close(dev);
e0a7146e
MG
622 return 1;
623}
624
b0bf6ad2
MG
625void sigterm_handler(int sig)
626{
627 if (unlink(PID_FILE) == -1)
628 perror("Can't remove PID file");
629
630 exit(EXIT_SUCCESS);
631}
632
633#define FLAG_DAEMON (1 << 0)
634#define FLAG_PID_FILE (1 << 1)
635
636static int socket_server(char *iface, int port, int flags)
e0a7146e 637{
4371275b 638 struct sigaction sact;
e0a7146e
MG
639 struct sockaddr_in sin;
640 int sock;
641 int n;
627e3f33
MG
642 pid_t pid;
643
b0bf6ad2
MG
644 if (flags & FLAG_DAEMON) {
645 FILE *pidfile = NULL;
646
647 if (flags & FLAG_PID_FILE) {
e6ab4631
MG
648 int fd;
649
650 fd = open(PID_FILE, O_CREAT | O_EXCL | O_WRONLY, 0644);
651 if (fd == -1) {
652 if (errno == EEXIST) {
653 pid_t old_pid;
654 pidfile = fopen(PID_FILE, "r");
655 if (!pidfile) {
656 perror("PID file " PID_FILE " already exists, already running?");
657 exit(EXIT_FAILURE);
658 }
659
660 if (fscanf(pidfile, "%u", &old_pid) != 1) {
661 fclose(pidfile);
662 fprintf(stderr, "Can't read old PID from " PID_FILE ", already running?\n");
663 exit(EXIT_FAILURE);
664 }
665
666 fclose(pidfile);
667
668 fprintf(stderr, "Already running with PID %u according to " PID_FILE "!\n", old_pid);
669 exit(EXIT_FAILURE);
670 }
671 perror("Can't create PID file " PID_FILE);
672 exit(EXIT_FAILURE);
673 }
b0bf6ad2 674
e6ab4631 675 pidfile = fdopen(fd, "w");
b0bf6ad2 676 if (!pidfile) {
e6ab4631 677 perror("Can't reopen PID file fd");
b0bf6ad2
MG
678 exit(EXIT_FAILURE);
679 }
680
681 memset(&sact, 0, sizeof(sact));
682 sact.sa_handler = sigterm_handler;
683
684 if (sigaction(SIGTERM, &sact, NULL) == -1) {
685 perror("sigaction(SIGTERM)");
686 exit(EXIT_FAILURE);
687 }
688 }
689
627e3f33
MG
690 pid = fork();
691 if (pid > 0) {
b0bf6ad2
MG
692 if (pidfile) {
693 fprintf(pidfile, "%u\n", pid);
694 fclose(pidfile);
695 }
696
627e3f33
MG
697 printf("Daemon with PID %u started!\n", pid);
698 exit(EXIT_SUCCESS);
699 } else if (pid < 0) {
700 perror("fork");
701 exit(EXIT_FAILURE);
702 }
b0bf6ad2
MG
703
704 if (pidfile)
705 fclose(pidfile);
627e3f33 706 }
e0a7146e 707
4371275b
MG
708 memset(&sact, 0, sizeof(sact));
709 sact.sa_handler = SIG_IGN;
710
711 if (sigaction(SIGPIPE, &sact, NULL) == -1) {
b0bf6ad2 712 perror("sigaction(SIGPIPE)");
27f4063e 713 exit(EXIT_FAILURE);
4371275b
MG
714 }
715
e0a7146e
MG
716 impersonate_hmlanif = 1;
717
718 sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
719 if (sock == -1) {
720 perror("Can't open socket");
721 return EXIT_FAILURE;
722 }
723
724 n = 1;
725 if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &n, sizeof(n)) == -1) {
726 perror("Can't set socket options");
727 return EXIT_FAILURE;
728 }
729
730 memset(&sin, 0, sizeof(sin));
731 sin.sin_family = AF_INET;
732 sin.sin_port = htons(port);
4a8a2269
MG
733 if (!iface) {
734 sin.sin_addr.s_addr = htonl(INADDR_ANY);
735 } else {
736 if (inet_pton(AF_INET, iface, &(sin.sin_addr.s_addr)) != 1) {
560c3078 737 fprintf(stderr, "Can't convert IP %s, aborting!\n", iface);
4a8a2269
MG
738 return EXIT_FAILURE;
739 }
740 }
e0a7146e
MG
741
742 if (bind(sock, (struct sockaddr*)&sin, sizeof(sin)) == -1) {
743 perror("Can't bind socket");
744 return EXIT_FAILURE;
745 }
746
747 if (listen(sock, 1) == -1) {
748 perror("Can't listen on socket");
749 return EXIT_FAILURE;
750 }
751
752 while(1) {
753 struct sockaddr_in csin;
754 socklen_t csinlen;
755 int client;
627e3f33 756 in_addr_t client_addr;
e0a7146e
MG
757
758 memset(&csin, 0, sizeof(csin));
759 csinlen = sizeof(csin);
760 client = accept(sock, (struct sockaddr*)&csin, &csinlen);
761 if (client == -1) {
762 perror("Couldn't accept client");
763 continue;
764 }
765
627e3f33
MG
766 /* FIXME: getnameinfo... */
767 client_addr = ntohl(csin.sin_addr.s_addr);
768
18e63b25
MG
769 write_log(NULL, 0, "Client %d.%d.%d.%d connected!\n",
770 (client_addr & 0xff000000) >> 24,
771 (client_addr & 0x00ff0000) >> 16,
772 (client_addr & 0x0000ff00) >> 8,
773 (client_addr & 0x000000ff));
e0a7146e 774
23d96b59 775 comm(client, client, sock, flags);
e0a7146e
MG
776
777 shutdown(client, SHUT_RDWR);
778 close(client);
779
b229c878
MG
780 if (lan_read_buf)
781 free(lan_read_buf);
782 lan_read_buf = NULL;
783 lan_read_buflen = 0;
784
18e63b25
MG
785 write_log(NULL, 0, "Connection to %d.%d.%d.%d closed!\n",
786 (client_addr & 0xff000000) >> 24,
787 (client_addr & 0x00ff0000) >> 16,
788 (client_addr & 0x0000ff00) >> 8,
789 (client_addr & 0x000000ff));
e09806b6 790 sleep(1);
e0a7146e
MG
791 }
792
793 return EXIT_SUCCESS;
794}
795
23d96b59 796static int interactive_server(int flags)
e0a7146e 797{
23d96b59 798 if (!comm(STDIN_FILENO, STDOUT_FILENO, -1, flags))
e0a7146e 799 return EXIT_FAILURE;
9db2e455
MG
800
801 return EXIT_SUCCESS;
802}
e0a7146e 803
627e3f33
MG
804void hmlan_syntax(char *prog)
805{
806 fprintf(stderr, "Syntax: %s options\n\n", prog);
807 fprintf(stderr, "Possible options:\n");
30a2aa7a
MG
808 fprintf(stderr, "\t-D\t\tdebug mode\n");
809 fprintf(stderr, "\t-d\t\tdaemon mode\n");
810 fprintf(stderr, "\t-h\t\tthis help\n");
811 fprintf(stderr, "\t-i\t\tinteractive mode (connect HM-CFG-USB to terminal)\n");
812 fprintf(stderr, "\t-l ip\t\tlisten on given IP address only (for example 127.0.0.1)\n");
18e63b25 813 fprintf(stderr, "\t-L logfile\tlog network-communication to logfile\n");
30a2aa7a
MG
814 fprintf(stderr, "\t-P\t\tcreate PID file " PID_FILE " in daemon mode\n");
815 fprintf(stderr, "\t-p n\t\tlisten on port n (default: 1000)\n");
c8cafbea 816 fprintf(stderr, "\t-r n\t\treboot HM-CFG-USB after n seconds (0: no reboot, default: %u if FW < 0.967, 0 otherwise)\n", DEFAULT_REBOOT_SECONDS);
30a2aa7a
MG
817 fprintf(stderr, "\t hh:mm\treboot HM-CFG-USB daily at hh:mm\n");
818 fprintf(stderr, "\t-v\t\tverbose mode\n");
c44f15b8 819 fprintf(stderr, "\t-V\t\tshow version (" VERSION ")\n");
627e3f33
MG
820
821}
822
e0a7146e
MG
823int main(int argc, char **argv)
824{
627e3f33 825 int port = 1000;
4a8a2269 826 char *iface = NULL;
627e3f33 827 int interactive = 0;
b0bf6ad2 828 int flags = 0;
627e3f33
MG
829 char *ep;
830 int opt;
62f25bae 831
18e63b25 832 while((opt = getopt(argc, argv, "DdhiPp:Rr:l:L:vV")) != -1) {
627e3f33
MG
833 switch (opt) {
834 case 'D':
835 debug = 1;
836 verbose = 1;
837 break;
838 case 'd':
b0bf6ad2 839 flags |= FLAG_DAEMON;
627e3f33
MG
840 break;
841 case 'i':
842 interactive = 1;
843 break;
b0bf6ad2
MG
844 case 'P':
845 flags |= FLAG_PID_FILE;
846 break;
627e3f33
MG
847 case 'p':
848 port = strtoul(optarg, &ep, 10);
849 if (*ep != '\0') {
850 fprintf(stderr, "Can't parse port!\n");
851 exit(EXIT_FAILURE);
852 }
853 break;
23d96b59 854 case 'R':
b55c340d 855 fprintf(stderr, "-R is no longer needed (1s wakeup is default)\n");
23d96b59 856 break;
62f25bae
MG
857 case 'r':
858 reboot_seconds = strtoul(optarg, &ep, 10);
859 if (*ep != '\0') {
30a2aa7a
MG
860 if (*ep == ':') {
861 reboot_at_hour = reboot_seconds;
862 ep++;
863 reboot_at_minute = strtoul(ep, &ep, 10);
864 if (*ep != '\0') {
865 fprintf(stderr, "Can't parse reboot-time!\n");
866 exit(EXIT_FAILURE);
867 }
868
869 reboot_seconds = 0;
870 } else {
871 fprintf(stderr, "Can't parse reboot-timeout!\n");
872 exit(EXIT_FAILURE);
873 }
62f25bae 874 }
c8cafbea 875 reboot_set = 1;
62f25bae 876 break;
4a8a2269
MG
877 case 'l':
878 iface = optarg;
879 break;
18e63b25
MG
880 case 'L':
881 logfile = fopen(optarg, "a");
882 if (!logfile) {
883 perror("fopen(logfile)");
884 exit(EXIT_FAILURE);
885 }
886 break;
627e3f33
MG
887 case 'v':
888 verbose = 1;
889 break;
c44f15b8
MG
890 case 'V':
891 printf("hmland " VERSION "\n");
892 printf("Copyright (c) 2013 Michael Gernoth\n\n");
893 exit(EXIT_SUCCESS);
627e3f33
MG
894 case 'h':
895 case ':':
896 case '?':
897 default:
898 hmlan_syntax(argv[0]);
899 exit(EXIT_FAILURE);
900 break;
901 }
902 }
903
904 if (interactive) {
23d96b59 905 return interactive_server(flags);
627e3f33 906 } else {
b0bf6ad2 907 return socket_server(iface, port, flags);
627e3f33 908 }
e0a7146e 909}
Impressum, Datenschutz