File: egctl.c

package info (click to toggle)
egctl 1:0.1-1
  • links: PTS
  • area: main
  • in suites: buster, stretch
  • size: 92 kB
  • ctags: 88
  • sloc: ansic: 465; makefile: 44
file content (617 lines) | stat: -rw-r--r-- 13,843 bytes parent folder | download
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
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
/*
 * egctl - EnerGenie EM-PMS-LAN control utility
 *
 * Copyright (c) 2014 Vitaly Sinilin <vs@kp4.ru>
 *
 * Published under the terms of the MIT License,
 * see the included COPYING file.
 */

#include <arpa/inet.h>
#include <errno.h>
#include <netinet/in.h>
#include <pwd.h>
#include <stdarg.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/select.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <unistd.h>

#define TASK_LEN            4
#define STATCRYP_LEN        4
#define CTRLCRYP_LEN        4
#define KEY_LEN             8

#define STATE_ON            0x11
#define STATE_ON_NO_VOLTAGE 0x12
#define STATE_OFF           0x22
#define STATE_OFF_VOLTAGE   0x21

#define STATE_INVALID       0xFF /* for internal use */

#define V21_STATE_ON        0x41
#define V21_STATE_OFF       0x82

#define SWITCH_ON           0x01
#define SWITCH_OFF          0x02
#define DONT_SWITCH         0x04

#define SOCKET_COUNT 4      /* AC power sockets, not network ones ;) */

#define ARRAY_SIZE(arr) (sizeof(arr) / sizeof((arr)[0]))

typedef enum
{
    EG_PROTO_V20,
    EG_PROTO_V21
} Protocol;

typedef enum
{
    ACTION_ON,
    ACTION_OFF,
    ACTION_TOGGLE,
    ACTION_LEFT,
    ACTION_INVALID
} Action;

typedef struct
{
    Action socket[SOCKET_COUNT];
} Actions;

typedef struct
{
    uint8_t octets[KEY_LEN];
} Key;

typedef struct
{
    /* since the protocol is little-endian, low word comes first */
    uint16_t loword;
    uint16_t hiword;
} __attribute__((__packed__)) Res;

typedef struct
{
    struct sockaddr_in addr;
    Protocol           proto;
    Key                key;
} Config;

typedef struct
{
    uint8_t socket[SOCKET_COUNT];
} Status, Controls;

typedef struct
{
    uint8_t task[TASK_LEN];
    Key     key;
} Session;

const char *g_egtabs[] =
{
    NULL,           /* placeholder for ~/.egtab */
    "/etc/egtab"
};

void vfatal(const char *fmt, va_list ap)
{
    vfprintf(stderr, fmt, ap);
    fprintf(stderr, "\n");
    exit(EXIT_FAILURE);
}

void fatal(const char *fmt, ...)
{
    va_list ap;
    va_start(ap, fmt);
    vfatal(fmt, ap);
    va_end(ap);
}

void warn(const char *fmt, ...)
{
    va_list ap;
    va_start(ap, fmt);
    vfprintf(stderr, fmt, ap);
    fprintf(stderr, "\n");
    va_end(ap);
}

#ifdef DEBUG
void dbg4(const char *name, const uint8_t *buf)
{
    fprintf(stderr, "%8s: 0x%02X 0x%02X 0x%02X 0x%02X\n",
            name, buf[0], buf[1], buf[2], buf[3]);
}
#else
#define dbg4(n,b)
#endif

void xread(int fd, void *buf, size_t count)
{
    ssize_t ret = read(fd, buf, count);

    if (ret == (ssize_t)count) {
        return;
    } else if (ret == -1) {
        if (errno != EINTR)
            fatal("Unable to read from socket: %s", strerror(errno));
        else
            ret = 0;
    }

    xread(fd, (char *)buf + ret, count - ret);
}

void xwrite(int fd, const void *buf, size_t count)
{
    ssize_t ret = write(fd, buf, count);

    if (ret == (ssize_t)count) {
        return;
    } else if (ret == -1) {
        if (errno != EINTR)
            fatal("Unable to write to socket: %s", strerror(errno));
        else
            ret = 0;
    }

    xwrite(fd, (char *)buf + ret, count - ret);
}

char *get_personal_egtab_name(void)
{
    static char egtab[1024] = "/dev/null";
    struct passwd *pwd = getpwuid(getuid());

    if (pwd) {
        snprintf(egtab, sizeof(egtab), "%s/.egtab", pwd->pw_dir);
    } else {
        warn("Unable to determine user home directory");
    }

    return egtab;
}

char *consume_until_whitespace(char **str)
{
    char *tok = *str;

    if (tok) {
        /* strip leading whitespaces */
        tok += strspn(tok, " \t");

        if (*tok == '\0') { /* no tokens */
            *str = NULL;
            tok = NULL;
        } else {
            char *eot = tok + strcspn(tok, " \t");
            if (*eot == '\0') { /* last token */
                *str = NULL;
            } else {
                *eot = '\0';
                *str = eot + 1;
            }
        }
    }

    return tok;
}

Protocol consume_protocol(char **str)
{
    Protocol proto;
    char *tok = consume_until_whitespace(str);

    if (!tok)
        fatal("Protocol isn't specified");

    if (!strcmp(tok, "pms20"))
        proto = EG_PROTO_V20;
    else if (!strcmp(tok, "pms21"))
        proto = EG_PROTO_V21;
    else
        fatal("Unknown protocol %s", tok);

    return proto;
}

in_addr_t consume_ip_address(char **str)
{
    in_addr_t addr;
    char *tok = consume_until_whitespace(str);

    if (!tok)
        fatal("IP address isn't specified");

    addr = inet_addr(tok);

    if (addr == INADDR_NONE) {
        /* It is ok that INADDR_NONE screens 255.255.255.255, since
         * this address isn't appropriate here anyway. */
        fatal("Invalid IP address specified");
    }

    return addr;
}

in_port_t consume_tcp_port(char **str)
{
    char *tok = consume_until_whitespace(str);

    if (!tok)
        fatal("TCP port isn't specified");

    return htons(atoi(tok));
}

Key consume_key(char **str)
{
    Key key;
    size_t keylen;
    char *tok = consume_until_whitespace(str);

    if (!tok)
        fatal("Password isn't specified");

    keylen = strlen(tok);

    if (keylen > KEY_LEN) {
        warn("Password too long, only first %u chars "
             "will be considered", KEY_LEN);
        keylen = KEY_LEN;
    }

    /* Key should be padded with trailing spaces */
    memset(key.octets, 0x20, KEY_LEN);
    memcpy(key.octets, tok, keylen);

    return key;
}

int get_device_entry(const char *name, FILE *fp, Config *conf)
{
    char buf[1024];
    char *line;

    while ((line = fgets(buf, sizeof(buf), fp)) != NULL) {
        char *tabname;

        if (line[0] == '#')
            continue;

        line[strcspn(line, "\n")] = '\0';

        tabname = consume_until_whitespace(&line);

        if (tabname && !strcmp(tabname, name)) {
            conf->proto = consume_protocol(&line);
            conf->addr.sin_addr.s_addr = consume_ip_address(&line);
            conf->addr.sin_port = consume_tcp_port(&line);
            conf->key = consume_key(&line);
            conf->addr.sin_family = AF_INET;
            return 1;
        }
    }

    return 0;
}

Config get_device_conf(const char *name)
{
    Config conf;
    int opened_tabs = 0;
    int ent_found = 0;
    size_t i;

    for (i = 0; !ent_found && i < ARRAY_SIZE(g_egtabs); i++) {
        FILE *fp = fopen(g_egtabs[i], "r");

        if (fp != NULL) {
            opened_tabs++;
            ent_found = get_device_entry(name, fp, &conf);
            fclose(fp);
        }
    }

    if (opened_tabs == 0)
        fatal("Unable to open any config file");

    if (!ent_found)
        fatal("%s: unknown device", name);

    return conf;
}

int create_socket(const struct sockaddr_in *addr)
{
    int ret;
    int sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);

    if (sock == -1)
        fatal("Unable to create socket: %s", strerror(errno));

    ret = connect(sock, (const struct sockaddr *)addr, sizeof(*addr));

    if (ret != 0)
        fatal("Unable to connect: %s", strerror(errno));

    return sock;
}

void establish_connection(int sock)
{
    int i, ret;
    fd_set fds;

    /* When the device is still on timeout from a previous session
     * it doesn't respond to the first Start condition packet. So
     * we will take several attempts. */

    for (i = 0; i < 4; i++) {
        struct timeval tv = { 0, 125000 };

        xwrite(sock, "\x11", 1);
        FD_ZERO(&fds);
        FD_SET(sock, &fds);
        ret = select(sock + 1, &fds, NULL, NULL, &tv);

        if (ret == 1)
            return;
    }

    fatal("Unable to establish connection with device");
}

Session authorize(int sock, Key key)
{
    Session s;
    Res res;
    fd_set fds;
    struct timeval tv = { 4, 0 };
    int ret;

    xread(sock, &s.task, sizeof(s.task));
    dbg4("task", s.task);

    res.loword = ((s.task[0] ^ key.octets[2]) * key.octets[0])
                 ^ (key.octets[6] | (key.octets[4] << 8))
                 ^ s.task[2];

    res.loword = htole16(res.loword);

    res.hiword = ((s.task[1] ^ key.octets[3]) * key.octets[1])
                 ^ (key.octets[7] | (key.octets[5] << 8))
                 ^ s.task[3];

    res.hiword = htole16(res.hiword);

    dbg4("res", (uint8_t *)&res);

    xwrite(sock, &res, sizeof(res));

    /* The protocol doesn't specify any explicit response on failed
     * authorization. So timeout is the only way to find out that
     * authorization hasn't been successful. */

    FD_ZERO(&fds);
    FD_SET(sock, &fds);
    ret = select(sock + 1, &fds, NULL, NULL, &tv);

    if (ret != 1)
        fatal("Authorization failed");

    s.key = key;

    return s;
}

Status decrypt_status(const uint8_t statcryp[], Session s)
{
    Status st;
    size_t i;

    for (i = 0; i < SOCKET_COUNT; i++)
        st.socket[i] =
            (((statcryp[3-i] - s.key.octets[1]) ^ s.key.octets[0]) - s.task[3])
            ^ s.task[2];

    return st;
}

uint8_t convert_v21_state(uint8_t state)
{
    switch (state) {
        case V21_STATE_ON:
            return STATE_ON;
        case V21_STATE_OFF:
            return STATE_OFF;
    }
    return STATE_INVALID;
}

Status convert_v21_status(Status st)
{
    size_t i;

    for (i = 0; i < SOCKET_COUNT; i++)
        st.socket[i] = convert_v21_state(st.socket[i]);

    return st;
}

Status recv_status(int sock, Session s, Protocol proto)
{
    Status st;
    uint8_t statcryp[STATCRYP_LEN];
    xread(sock, &statcryp, sizeof(statcryp));
    dbg4("statcryp", statcryp);
    st = decrypt_status(statcryp, s);

    /* Since the only difference between versions 2.0 and 2.1 of the
     * subset of the protocol that we use is the state constants, all
     * we need to do to support version 2.1 is just to map 2.1
     * constants to the equivalent 2.0 ones. */

    if (proto == EG_PROTO_V21)
        st = convert_v21_status(st);

    return st;
}

Action str_to_action(const char *action)
{
    if (!strcmp(action, "on"))
        return ACTION_ON;
    else if (!strcmp(action, "off"))
        return ACTION_OFF;
    else if (!strcmp(action, "toggle"))
        return ACTION_TOGGLE;
    else if (!strcmp(action, "left"))
        return ACTION_LEFT;

    return ACTION_INVALID;
}

Actions argv_to_actions(char *argv[])
{
    Actions actions;
    size_t i;

    for (i = 0; i < SOCKET_COUNT; i++) {
        Action action = str_to_action(argv[i]);

        if (action == ACTION_INVALID)
            fatal("Invalid action for socket %zu: %s", i+1, argv[i]);

        actions.socket[i] = action;
    }

    return actions;
}

Controls construct_controls(Status status, Actions actions)
{
    Controls ctrl;
    size_t i;

    for (i = 0; i < SOCKET_COUNT; i++) {
        switch (actions.socket[i]) {
            case ACTION_ON:
                ctrl.socket[i] = SWITCH_ON;
                break;
            case ACTION_OFF:
                ctrl.socket[i] = SWITCH_OFF;
                break;
            case ACTION_TOGGLE:
                switch (status.socket[i]) {
                    case STATE_ON:
                    case STATE_ON_NO_VOLTAGE:
                        ctrl.socket[i] = SWITCH_OFF;
                        break;
                    case STATE_OFF:
                    case STATE_OFF_VOLTAGE:
                        ctrl.socket[i] = SWITCH_ON;
                        break;
                    default:
                        warn("Cannot toggle socket %zu", i+1);
                        ctrl.socket[i] = DONT_SWITCH;
                        break;
                }
                break;
            default:
            case ACTION_LEFT:
                ctrl.socket[i] = DONT_SWITCH;
        }
    }

    return ctrl;
}

void send_controls(int sock, Session s, Controls ctrl)
{
    size_t i;
    uint8_t ctrlcryp[CTRLCRYP_LEN];

    /* Encrypt controls */
    for (i = 0; i < SOCKET_COUNT; i++)
        ctrlcryp[i] =
            (((ctrl.socket[3-i] ^ s.task[2]) + s.task[3]) ^ s.key.octets[0])
            + s.key.octets[1];

    xwrite(sock, &ctrlcryp, sizeof(ctrlcryp));
}

void close_session(int sock)
{
    /* Empirically found way to close session w/o 4 second timeout on
     * the device side is to send some invalid sequence. This helps
     * to avoid a hiccup on subsequent run of the utility. */
    xwrite(sock, "\x11", 1);
}

const char *get_state_str(uint8_t state)
{
    switch (state) {
        case STATE_ON:
            return "on";
        case STATE_ON_NO_VOLTAGE:
            return "on (no voltage!)";
        case STATE_OFF:
            return "off";
        case STATE_OFF_VOLTAGE:
            return "off (VOLTAGE IS PRESENT!)";
    }
    return "unknown";
}

void dump_status(Status st)
{
    size_t i;

    for (i = 0; i < SOCKET_COUNT; i++)
        printf("socket %zu - %s\n", i+1, get_state_str(st.socket[i]));
}

int main(int argc, char *argv[])
{
    int sock;
    Config conf;
    Session sess;

    if (argc != 2 && argc != 6) {
        fatal("egctl 0.1: EnerGenie EG-PMS-LAN control utility\n\n"
              "Usage: egctl NAME [S1 S2 S3 S4]\n"
              "  NAME is the name of the device in the egtab file\n"
              "  Sn is an action to perform on n-th socket: "
              "on, off, toggle or left");
    }

    g_egtabs[0] = get_personal_egtab_name();

    conf = get_device_conf(argv[1]);
    sock = create_socket(&conf.addr);
    establish_connection(sock);
    sess = authorize(sock, conf.key);

    if (argc == 6) {
        Actions act = argv_to_actions(argv+2);
        Status status = recv_status(sock, sess, conf.proto);
        Controls ctrl = construct_controls(status, act);
        send_controls(sock, sess, ctrl);
    }

    dump_status(recv_status(sock, sess, conf.proto));

    close_session(sock);
    close(sock);

    return EXIT_SUCCESS;
}