summaryrefslogtreecommitdiff
path: root/switchctl.c
blob: 3a259fcc27db20f1888a0278055cc3459e6d7d0a (plain)
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
/*
 *  rhctl
 *
 *  Copyright (C) 2009 Christian Pointner <equinox@spreadspace.org>
 *
 *  This file is part of rhctl.
 *
 *  rhctl 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
 *  any later version.
 *
 *  rhctl 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 rhctl. If not, see <http://www.gnu.org/licenses/>.
 */

#include "datatypes.h"

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>

#include "log.h"
#include "sig_handler.h"
#include "options.h"

#include "command_queue.h"
#include "client_list.h"
#include "key_value_storage.h"

#include "daemon.h"
#include "utils.h"

int send_command(int switch_fd, cmd_t* cmd)
{
  if(!cmd)
    return -1;
  
  char* c = NULL;
  switch(cmd->cmd) {
  case SWITCH: c = cmd->param; break;
  case STATUS: c = "*0SL"; break;
  }
  
  if(c == NULL)
    return 0;

  int ret = send_string(switch_fd, c);
  if(ret > 0) {
    cmd_sent(cmd);
    return 0;
  }

  return ret;
}

int send_response(int fd, const char* response)
{
  if(!response)
    return -1;

  int ret = send_string(fd, response);
  do {
    ret = write(fd, "\n", 1);
  } while(!ret || (ret == -1 && errno == EINTR));

  if(ret > 0)
    return 0;

  return ret;
}

int process_cmd_request(const char* cmd, cmd_id_t cmd_id, const char* param, int fd, cmd_t **cmd_q, client_t* client_lst, options_t* opt)
{
  client_t* c = client_find(client_lst, fd);
  if(!c) {
    log_printf(WARNING, "ignoring request from unknown client");
    return 0;
  }

  if(c->type == HEARTBEAT) {
    log_printf(WARNING, "ignoring requests from heartbeat agent");
    return 0;
  }

  char* cmd_param = NULL;
  if(cmd_id == SWITCH) {
    if((opt->mode_ == MODE_MASTER && c->type == STANDBY )||
       (opt->mode_ == MODE_STANDBY && c->type == MASTER ))
    {
      log_printf(INFO, "ignoring request from inactive system (%s)", c->type == MASTER ? "master" : "standby");
      return 0;
    }
  
    if(!param) {
      log_printf(INFO, "ignoring switch command without parameter");
      return 0;
    }

    if(param[0] == '*') {
      cmd_param = strdup(param);
    }
    else {
      const char* ch_name = NULL;
      cmd_param = strdup("*0Fxnn");
      if(!strncmp(param, "up ", 3)) {
        cmd_param[3] = 'U';
        ch_name = &(param[3]);
      }
      else if(!strncmp(param, "down ", 5)) {
        cmd_param[3] = 'D';
        ch_name = &(param[5]);
      }
      else {
        log_printf(INFO, "ignoring invalid switch command: '%s'", param);
        return 0;
      }
      char* ch_nr = key_value_storage_find(&opt->alias_table_, ch_name);
      if(!ch_nr || ch_nr[0] == 0 || ch_nr[1] == 0 || ch_nr[2] != 0) {
        log_printf(ERROR, "invalid channel name or number: %s", ch_name);
        return 0;
      }
      
      cmd_param[4] = ch_nr[0];
      cmd_param[5] = ch_nr[1];
    }
    log_printf(DEBUG, "enqueing command to switch: '%s' (request was: '%s')", cmd_param, param);
  }

  int ret = cmd_push(cmd_q, fd, cmd_id, cmd_param);
  if(cmd_param) 
    free(cmd_param);
  if(ret)
    return ret;

  if(cmd_id == STATUS) {
    char buf[30];
    snprintf(buf, 30, "Current Mode: %s", opt->mode_ == MODE_MASTER ? "Master" : "Standby");
    send_response(fd, buf);
    client_t* client;
    int listener_cnt = 0;
    for(client = client_lst; client; client = client->next)
      if(client->status_listener && client->fd != fd) {
        send_response(client->fd, buf);
        listener_cnt++;
      }
    log_printf(DEBUG, "sent status to %d additional listeners", listener_cnt);
  }

  log_printf(NOTICE, "command: %s", cmd); 

  return 0;
}

void process_cmd_type(const char* param, int fd, client_t* client_lst)
{
  if(param) {
    client_t* client = client_find(client_lst, fd);
    if(client) {
      if(!strncmp(param, "master", 6))
        client->type = MASTER;
      else if(!strncmp(param, "standby", 7))
        client->type = STANDBY;      
      else if(!strncmp(param, "heartbeat", 9))
        client->type = HEARTBEAT;
      else {
        log_printf(DEBUG, "unkown client type '%s'", param);
        return;
      }
      log_printf(DEBUG, "client %d type set to %s", fd, param);
    }
    else
      log_printf(ERROR, "unable to set client type for %d: client not found", fd);
  }
  else
    log_printf(ERROR, "unable to set client type for %d: empty parameter", fd);
}


void process_cmd_mode(const char* param, options_t* opt)
{
  if(param) {
    if(!strncmp(param, "master", 6))
      opt->mode_ = MODE_MASTER;
    else if(!strncmp(param, "standby", 7))
      opt->mode_ = MODE_STANDBY;
    else {
      log_printf(DEBUG, "unkown mode '%s'", param);
      return;
    }
  }
  else
    log_printf(ERROR, "unable to set mode: empty parameter");

  log_printf(NOTICE, "new mode: %s", opt->mode_ == MODE_MASTER ? "master" : "standby");
}
 
void process_cmd_listen(const char* param, int fd, client_t* client_lst)
{
  client_t* listener = client_find(client_lst, fd);
  if(listener) {
    if(!param) {
      listener->status_listener = 1;
      listener->error_listener = 1;      
      listener->request_listener = 1;
    }
    else {
      if(!strncmp(param, "status", 6))
        listener->status_listener = 1;
      else if(!strncmp(param, "error", 5))
        listener->error_listener = 1;      
      else if(!strncmp(param, "request", 7))
        listener->request_listener = 1;
      else {
        log_printf(DEBUG, "unkown listener type '%s'", param);
        return;
      }
    }
    log_printf(DEBUG, "listener %d requests %s messages", fd, param ? param:"all");
  }
  else
    log_printf(ERROR, "unable to add listener %d", fd);
}

int process_cmd(const char* cmd, int fd, cmd_t **cmd_q, client_t* client_lst, options_t* opt)
{
  log_printf(DEBUG, "processing command from %d", fd);

  if(!cmd_q || !cmd)
    return -1;
  
  cmd_id_t cmd_id;
  if(!strncmp(cmd, "switch", 6))
    cmd_id = SWITCH;
  else if(!strncmp(cmd, "type", 4))
    cmd_id = TYPE;
  else if(!strncmp(cmd, "mode", 4))
    cmd_id = MODE;
  else if(!strncmp(cmd, "status", 6))
    cmd_id = STATUS;
  else if(!strncmp(cmd, "log", 3))
    cmd_id = LOG;
  else if(!strncmp(cmd, "listen", 6)) {
    cmd_id = LISTEN;
  }
  else {
    log_printf(WARNING, "unknown command '%s'", cmd);
    return 0;
  }
  char* param = strchr(cmd, ' ');
  if(param) 
    param++;

  if(cmd_id == SWITCH || cmd_id == MODE) {
    char* resp;
    asprintf(&resp, "Request: %s", cmd);
    if(resp) {
      char* linefeed = strchr(resp, '\n');
      if(linefeed) linefeed[0] = 0;
      client_t* client;
      int listener_cnt = 0;
      for(client = client_lst; client; client = client->next)
        if(client->request_listener && client->fd != fd) {
          send_response(client->fd, resp);
          listener_cnt++;
        }
      free(resp);
      log_printf(DEBUG, "sent request to %d additional listeners", listener_cnt);
    }
// else silently ignore memory alloc error
  }

  switch(cmd_id) {
  case SWITCH: 
  case STATUS: {
    int ret = process_cmd_request(cmd, cmd_id, param, fd, cmd_q, client_lst, opt);
    if(ret)
      return ret;
    break;
  }
  case TYPE: process_cmd_type(param, fd, client_lst); break;
  case MODE: process_cmd_mode(param, opt); break;
  case LOG: {
    if(param && param[0])
      log_printf(NOTICE, "ext msg: %s", param); 
    else
      log_printf(DEBUG, "ignoring empty ext log message");
    break;
  }
  case LISTEN: process_cmd_listen(param, fd, client_lst); break;
  }
  
  return 0;
}

int process_switch(int switch_fd)
{
  int ret = 0;
  struct timeval tv;
  fd_set fds;
  FD_ZERO(&fds);
  FD_SET(switch_fd, &fds);
  char buf[1];

  for(;;) {
    tv.tv_sec = 0;
    tv.tv_usec = 0;
    ret = select(switch_fd+1, &fds, NULL, NULL, &tv);
    if(!ret)
      return 0;
    else if(ret < 0)
      return ret;

    ret = read(switch_fd, buf, 1);
    if(!ret)
      return 2;
    if(ret == -1 && errno == EAGAIN)
      return 0;
    else if(ret < 0)
      break;
  }

  return ret;
}

int main_loop(int switch_fd, int cmd_listen_fd, options_t* opt)
{
  log_printf(NOTICE, "entering main loop");

  fd_set readfds, tmpfds;
  FD_ZERO(&readfds);
  FD_SET(switch_fd, &readfds);
  FD_SET(cmd_listen_fd, &readfds);
  int max_fd = switch_fd > cmd_listen_fd ? switch_fd : cmd_listen_fd;
  cmd_t* cmd_q = NULL;
  client_t* client_lst = NULL;

  int sig_fd = signal_init();
  if(sig_fd < 0)
    return -1;
  FD_SET(sig_fd, &readfds);
  max_fd = (max_fd < sig_fd) ? sig_fd : max_fd;

  struct timeval timeout;
  int return_value = 0;
  while(!return_value) {
    memcpy(&tmpfds, &readfds, sizeof(tmpfds));

    timeout.tv_sec = 0;
    timeout.tv_usec = 200000;
    int ret = select(max_fd+1, &tmpfds, NULL, NULL, &timeout);
    if(ret == -1 && errno != EINTR) {
      log_printf(ERROR, "select returned with error: %s", strerror(errno));
      return_value = -1;
      break;
    }
    if(ret == -1)
      continue;
    if(!ret) {
      if(cmd_q && cmd_has_expired(*cmd_q)) {
        log_printf(ERROR, "last command expired");
        cmd_pop(&cmd_q);
      }
      else
        continue;
    }

    if(FD_ISSET(sig_fd, &tmpfds)) {
      if(signal_handle()) {
        return_value = 1;
        break;
      }
    }
   
    if(FD_ISSET(switch_fd, &tmpfds)) {
      return_value = process_switch(switch_fd);
      if(return_value)
        break;
    }

    if(FD_ISSET(cmd_listen_fd, &tmpfds)) {
      int new_fd = accept(cmd_listen_fd, NULL, NULL);
      if(new_fd < 0) {
        log_printf(ERROR, "accept returned with error: %s", strerror(errno));
        return_value = -1;
        break;
      }  
      log_printf(DEBUG, "new command connection (fd=%d)", new_fd);
      FD_SET(new_fd, &readfds);
      max_fd = (max_fd < new_fd) ? new_fd : max_fd;
      fcntl(new_fd, F_SETFL, O_NONBLOCK);
      client_add(&client_lst, new_fd);
    }

    client_t* lst = client_lst;
    while(lst) {
      if(FD_ISSET(lst->fd, &tmpfds)) {
        return_value = nonblock_recvline(&(lst->buffer), lst->fd, &cmd_q, client_lst, opt);
        if(return_value == 2) {
          log_printf(DEBUG, "removing closed command connection (fd=%d)", lst->fd);
          client_t* deletee = lst;
          lst = lst->next;
          FD_CLR(deletee->fd, &readfds);
          client_remove(&client_lst, deletee->fd);
          return_value = 0;
          continue;
        }
        if(return_value)
          break;

      }
      lst = lst->next;
    }

    if(cmd_q && !cmd_q->sent)
      send_command(switch_fd, cmd_q);
  }

  cmd_clear(&cmd_q);
  client_clear(&client_lst);
  signal_stop();
  return return_value;
}

int main(int argc, char* argv[])
{
  log_init();

  options_t opt;
  int ret = options_parse(&opt, argc, argv);
  if(ret) {
    if(ret > 0) {
      fprintf(stderr, "syntax error near: %s\n\n", argv[ret]);
    }
    if(ret == -2) {
      fprintf(stderr, "memory error on options_parse, exiting\n");
    }

    if(ret != -2)
      options_print_usage();

    options_clear(&opt);
    log_close();
    exit(ret);
  }
  string_list_element_t* tmp = opt.log_targets_.first_;
  if(!tmp) {
    log_add_target("syslog:3,switchctl,daemon");
  }
  else {
    while(tmp) {
      ret = log_add_target(tmp->string_);
      if(ret) {
        switch(ret) {
        case -2: fprintf(stderr, "memory error on log_add_target, exitting\n"); break;
        case -3: fprintf(stderr, "unknown log target: '%s', exitting\n", tmp->string_); break;
        case -4: fprintf(stderr, "this log target is only allowed once: '%s', exitting\n", tmp->string_); break;
        default: fprintf(stderr, "syntax error near: '%s', exitting\n", tmp->string_); break;
        }
        
        options_clear(&opt);
        log_close();
        exit(ret);
      }
      tmp = tmp->next_;
    }
  }
  log_printf(NOTICE, "just started...");
  if(options_parse_post(&opt)) {
    options_clear(&opt);
    log_close();
    exit(-1);
  }

  priv_info_t priv;
  if(opt.username_)
    if(priv_init(&priv, opt.username_, opt.groupname_)) {
      options_clear(&opt);
      log_close();
      exit(-1);
    }

  FILE* pid_file = NULL;
  if(opt.pid_file_) {
    pid_file = fopen(opt.pid_file_, "w");
    if(!pid_file) {
      log_printf(WARNING, "unable to open pid file: %s", strerror(errno));
    }
  }

  if(opt.chroot_dir_)
    if(do_chroot(opt.chroot_dir_)) {
      options_clear(&opt);
      log_close();
      exit(-1);
    }
  if(opt.username_)
    if(priv_drop(&priv)) {
      options_clear(&opt);
      log_close();
      exit(-1);
    }

  if(opt.daemonize_) {
    pid_t oldpid = getpid();
    daemonize();
    log_printf(INFO, "running in background now (old pid: %d)", oldpid);
  }

  if(pid_file) {
    pid_t pid = getpid();
    fprintf(pid_file, "%d", pid);
    fclose(pid_file);
  }

  int cmd_listen_fd = init_command_socket(opt.command_sock_);
  if(cmd_listen_fd < 0) {
    options_clear(&opt);
    log_close();
    exit(-1);
  }
  
  int switch_fd = 0;
  for(;;) {
    switch_fd = open(opt.switch_dev_, O_RDWR | O_NOCTTY);
    if(switch_fd < 0)
      ret = 2;
    else {
      ret = setup_tty(switch_fd);
      if(ret)
        ret = 2;
      else
        ret = main_loop(switch_fd, cmd_listen_fd, &opt);
    }

    if(ret == 2) {
      log_printf(ERROR, "%s error, trying to reopen in 5 seconds..", opt.switch_dev_);
      if(switch_fd > 0)
        close(switch_fd);
      sleep(5);
    }
    else
      break;
  }

  close(cmd_listen_fd);
  if(switch_fd > 0)
    close(switch_fd);

  if(!ret)
    log_printf(NOTICE, "normal shutdown");
  else if(ret < 0)
    log_printf(NOTICE, "shutdown after error");
  else
    log_printf(NOTICE, "shutdown after signal");

  options_clear(&opt);
  log_close();

  return ret;
}