aboutsummaryrefslogtreecommitdiffstats
path: root/apps/sympathy.c
blob: f5ed2e0e80ff63e3201e5392eae7ddd3243af8fa (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
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
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
/*
 * sympathy.c:
 *
 * Copyright (c) 2008 James McKenzie <james@fishsoup.dhs.org>,
 * All rights reserved.
 *
 */

static char rcsid[] =
  "$Id$";

/*
 * $Log$
 * Revision 1.32  2008/03/03 06:04:42  james
 * *** empty log message ***
 *
 * Revision 1.31  2008/03/03 06:04:18  james
 * *** empty log message ***
 *
 * Revision 1.30  2008/03/02 10:38:18  james
 * *** empty log message ***
 *
 * Revision 1.29  2008/03/02 10:37:56  james
 * *** empty log message ***
 *
 * Revision 1.28  2008/03/02 10:27:24  james
 * *** empty log message ***
 *
 * Revision 1.27  2008/03/02 09:55:37  james
 * *** empty log message ***
 *
 * Revision 1.26  2008/02/29 14:55:09  james
 * *** empty log message ***
 *
 * Revision 1.25  2008/02/28 22:43:25  james
 * *** empty log message ***
 *
 * Revision 1.24  2008/02/28 22:00:42  james
 * *** empty log message ***
 *
 * Revision 1.23  2008/02/28 16:57:51  james
 * *** empty log message ***
 *
 * Revision 1.22  2008/02/28 01:47:44  james
 * *** empty log message ***
 *
 * Revision 1.21  2008/02/27 16:01:24  james
 * *** empty log message ***
 *
 * Revision 1.20  2008/02/27 10:00:34  james
 * *** empty log message ***
 *
 * Revision 1.19  2008/02/27 09:47:05  james
 * *** empty log message ***
 *
 * Revision 1.18  2008/02/27 09:42:53  james
 * *** empty log message ***
 *
 * Revision 1.17  2008/02/27 09:42:21  james
 * *** empty log message ***
 *
 * Revision 1.16  2008/02/27 01:31:38  james
 * *** empty log message ***
 *
 * Revision 1.15  2008/02/27 01:31:14  james
 * *** empty log message ***
 *
 * Revision 1.14  2008/02/24 00:43:55  james
 * *** empty log message ***
 *
 * Revision 1.13  2008/02/24 00:42:53  james
 * *** empty log message ***
 *
 * Revision 1.12  2008/02/23 11:48:52  james
 * *** empty log message ***
 *
 * Revision 1.11  2008/02/20 20:16:07  james
 * *** empty log message ***
 *
 * Revision 1.10  2008/02/20 19:44:37  james
 * @@
 *
 * Revision 1.9  2008/02/20 18:49:11  staffcvs
 * *** empty log message ***
 *
 * Revision 1.8  2008/02/20 18:33:37  james
 * *** empty log message ***
 *
 * Revision 1.7  2008/02/20 18:31:44  james
 * *** empty log message ***
 *
 * Revision 1.6  2008/02/20 17:18:33  james
 * *** empty log message ***
 *
 * Revision 1.5  2008/02/20 15:50:14  james
 * *** empty log message ***
 *
 * Revision 1.4  2008/02/20 02:11:35  james
 * *** empty log message ***
 *
 * Revision 1.3  2008/02/14 02:46:44  james
 * *** empty log message ***
 *
 * Revision 1.2  2008/02/14 00:57:58  james
 * *** empty log message ***
 *
 * Revision 1.1  2008/02/05 14:25:49  james
 * *** empty log message ***
 *
 */

#include <sys/types.h>
#include <stdarg.h>
#include <sympathy.h>
#include <stdlib.h>
#include <sys/utsname.h>
#include <sys/stat.h>
#include <dirent.h>
#include <string.h>
#include <strings.h>
#include <malloc.h>
#include <fcntl.h>
#include <sys/resource.h>
#include <sys/wait.h>


#include "mainloop.h"

extern void usage (void);
static char hostname[1024];

char *socket_dirs[] =
  { "~/.sympathy", "~/sympathy", "/etc/sympathy", "/var/sympathy", NULL };

int
safe_atoi (char *a)
{
  char *end;
  int ret;

  if (!a)
    return -1;

  ret = (int) strtol (a, &end, 0);

  if (end == a)
    return -1;

  return ret;
}

char *
fatal_moan (char *fmt, ...)
{
  va_list ap;


  va_start (ap, fmt);
  vfprintf (stderr, fmt, ap);
  va_end (ap);

  putc ('\n', stderr);
  exit (1);
}

static void
sigchld (int dummy)
{
  int status;
  wait3 (&status, WNOHANG, NULL);
}

/*Dispell zombies, from for example log compression*/
void
garlic (void)
{
  struct sigaction sa;

  sa.sa_handler = sigchld;
  sa.sa_flags = SA_RESTART;
  sigaction (SIGCHLD, &sa, NULL);
}

char *
teedious_snprintf (char *fmt, va_list ap)
{
  va_list aq;
  int size = 1024;
  char *buf = malloc (size);
  int n;

  if (!buf)
    fatal_moan ("malloc failed");

  while (1)
    {

      va_copy (aq, ap);
      n = vsnprintf (buf, size, fmt, aq);
      va_end (aq);

      if (n > -1 && n < (size))
        return buf;

      if (n > -1)               /* glibc 2.1 */
        size = n + 1;
      else                      /* glibc 2.0 */
        size *= 2;              /* twice the old size */

      buf = realloc (buf, size);

      if (!buf)
        fatal_moan ("malloc failed");
    }

}

char *
gloo_paths (char *dir, char *leaf)
{
  int i;
  char *ret, *ptr;
  if (!dir)
    dir = "";
  if (!leaf)
    leaf = "";
  ret = ptr = malloc (strlen (dir) + strlen (leaf) + 2);

  while (*dir)
    *(ptr++) = *(dir++);
  *(ptr++) = '/';
  while (*leaf)
    *(ptr++) = *(leaf++);
  *ptr = 0;

  return ret;
}


/*make the path in fmt from home (hence the name) */
char *
mome (char *fmt, ...)
{
  char *ret, *home, *leaf;
  va_list ap;


  home = getenv ("HOME");
  if (!home)
    return NULL;

  if (fmt)
    {
      va_start (ap, fmt);
      leaf = teedious_snprintf (fmt, ap);
      va_end (ap);
    }
  else
    {
      leaf = NULL;
    }

  ret = gloo_paths (home, leaf);
  if (leaf)
    free (leaf);

  return ret;
}


Socket *
find_socket (char *fmt, ...)
{
  Socket *ret;
  char *path, *leaf, *h, **ptr;
  va_list ap;


  if (fmt)
    {
      va_start (ap, fmt);
      leaf = teedious_snprintf (fmt, ap);
      va_end (ap);
    }
  else
    {
      leaf = NULL;
    }


  for (ptr = socket_dirs; *ptr; ptr++)
    {
      if (**ptr == '~')
        {
          h = mome (*ptr + 1);
        }
      else
        {
          h = *ptr;
        }

      if (!h)
        continue;


      path = gloo_paths (h, leaf);
      if (**ptr == '~')
        free (h);

      ret = socket_connect (path);

      free (path);

      if (ret)
        {
          free (leaf);
          return ret;
        }

    }

  free (leaf);
  return NULL;

}



int
list_sockets_in_dir (char *sockdir)
{
  struct dirent *ent;
  struct stat buf;
  char *sn = NULL;
  Socket *s;
  DIR *dir = opendir (sockdir);



  int hostname_len = strlen (hostname);

  if (!dir)
    return;

  rewinddir (dir);


  while ((ent = readdir (dir)))
    {
      sn = gloo_paths (sockdir, ent->d_name);
      if (stat (sn, &buf) || (!S_ISSOCK (buf.st_mode)))
        {
          free (sn);
          continue;
        }

      s = socket_connect (sn);

      if (s)
        {
          printf ("\t%s 	(Active)\n", sn);
          socket_free (s);
        }
      else
        {
          if (strncmp (ent->d_name, hostname, hostname_len))
            {
              printf ("\t%s	(Unknown - not this host)\n", sn);
            }
          else
            {
              printf ("\t%s	(Dead, wiped)\n", sn);
              unlink (sn);
            }
        }

      free (sn);
    }

  closedir (dir);

  return 0;
}

int
list_sockets (void)
{
  char **ptr, *h;


  for (ptr = socket_dirs; *ptr; ptr++)
    {
      if (**ptr == '~')
        {
          h = mome (*ptr + 1);
        }
      else
        {
          h = *ptr;
        }

      if (!h)
        continue;

      list_sockets_in_dir (h);

      if (**ptr == '~')
        free (h);

    }

  return 0;
}


void
get_hostname (void)
{
  struct utsname name;

  if (uname (&name))
    {
      strcpy (hostname, "unknown.");
      return;
    }


  strcpy (hostname, name.nodename);
  strcat (hostname, ".");
}


int
main (int argc, char *argv[])
{
  int c;
  extern char *optarg;
  extern int optind, opterr, optopt;
  CRT_Pos size = { VT102_COLS_80, VT102_ROWS_24 };

  int csnok_pipe[2] = { 0 };
  int csnok = 0;

  int oflags[128];
  char *oargs[128];

  Socket *server_socket = NULL, *client_socket = NULL;
  ANSI *ansi = NULL;
  TTY *tty = NULL;
  Log *log = NULL;

  int history = 200;
  int pid;

  char *pid_file = NULL;

  get_hostname ();

  memset (oflags, 0, sizeof (oflags));
  memset (oargs, 0, sizeof (oargs));
  while ((c = getopt (argc, argv, "RP:vw:utscr:lKHd:pb:fL:Fk:n:")) != EOF)
    {
      switch (c)
        {
        case ':':
        case 'h':
        case '?':
          usage ();
        default:
          if ((c > 64) && (c < 91))
            {
              oflags[c]++;
              oargs[c] = optarg;
            }
          else if ((c > 96) && (c < 123))
            {
              oflags[c]++;
              oargs[c] = optarg;
            }
          else
            {
              fprintf (stderr, "unknown option %c\n", c);
              usage ();
            }
        }

    }

  /*Compatability for screen's ls */
  if (oflags['l'])
    oflags['s'] = 0;


  {
    int sum = 0;
    sum += oflags['t'];
    sum += (oflags['s'] || oflags['c']) ? 1 : 0;
    sum += oflags['r'];
    sum += oflags['l'];
    sum += oflags['v'];

    if (!sum)
      {
        /*If no mode is specified behave like screen */
        oflags['s']++;
        oflags['c']++;
        sum++;
      }

    if (sum != 1)
      fatal_moan
        ("specifiy exactly one of ( -c and or -s ), -t, -r, -l and -v");
  }

  if (oflags['v'])
    {
      fprintf (stderr, "Version: %s\n", libsympathy_version ());
      fprintf (stderr, "Version: %s\n", rcsid);
      return 0;
    }

  if (oflags['l'])
    return list_sockets ();


  if (oflags['r'] && oflags['k'])
    fatal_moan ("-k is incompatible with -r");


  if (oflags['n'])
    {
      history = safe_atoi (oargs['n']);
      if (history < 0)
        fatal_moan ("cannot parse -n %s as an integer", oargs['n']);

      if (!history)
        fatal_moan ("agrument to -n must be greater than zero");
    }

  /*Fold -r implies -c */
  if (oflags['r'])
    oflags['c']++;

  if (oflags['p'] && oflags['d'])
    fatal_moan ("-p incompatible with -d");


  if (oflags['c'] && oflags['s'] && oflags['F'])
    fatal_moan ("-F is incompatible with -c -s");

  /*implement server and client: this process forks. The parent */
  /*becomes the client and the child forks again to become the */
  /*server. If there's no -k argument the client (parent) needs */
  /*to find out the pid of the server, we use a pipe */

  if (oflags['s'] && oflags['c'])
    {
      if (!oflags['k'])
        {
          csnok++;
          pipe (csnok_pipe);
        }

      switch (pid = fork ())
        {
        case 0:                /*child becomes the server */
          oflags['c'] = 0;
          oflags['H'] = 0;

          if (csnok)
            close (csnok_pipe[0]);
          break;
        case -1:
          fatal_moan ("fork failed");
        default:               /*parent becomes client */
          oflags['s'] = 0;
          oflags['K'] = 0;
          oflags['d'] = 0;
          oflags['p'] = 0;
          oflags['b'] = 0;
          oflags['f'] = 0;
          oflags['L'] = 0;
          oflags['R'] = 0;
          oflags['P'] = 0;
          oflags['n'] = 0;
          oflags['w'] = 0;

          /*Collect the child */
          waitpid (pid, NULL, 0);

          /*if there was no k argument we need to find the */
          /*pid of the server process so that we can work out */
          /*what the socket is called. The server tells us on */
          /*a pipe */

          if (csnok)
            {
              close (csnok_pipe[1]);

              if (read (csnok_pipe[0], &pid, sizeof (pid)) != sizeof (pid))
                fatal_moan ("Failed to receive pid of server process");

              close (csnok_pipe[0]);

              oargs['k'] = mome ("/.sympathy/%s%d", hostname, pid);
              oflags['k']++;
            }
        }
    }


  if (oflags['c'] && !oflags['k'] && !oflags['r'])
    fatal_moan ("-c requires a socket to be specified with -s or -k or -r");

  if ((oflags['p'] || oflags['d'] || oflags['K'] || oflags['b'] || oflags['f']
       || oflags['L'] || oflags['R'] || oflags['P']) && oflags['c'])
    fatal_moan
      ("-c or -r are incompatible with -p, -d, -K, -b, -f, -R, -P or -L");

  if (oflags['t'] || oflags['s'])
    {
      if (!oflags['p'] && !oflags['d'])
        oflags['p']++;
    }

  if (oflags['w'])
    {
      char buf[128], *ptr;
      strcpy (buf, oargs['w']);
      ptr = index (buf, 'x');
      if (ptr)
        {
          *ptr = 0;
          ptr++;
          size.y = safe_atoi (ptr);
        }
      size.x = safe_atoi (buf);

      if ((size.x > VT102_MAX_COLS) || (size.x < 1))
        fatal_moan ("-w requires a width between 1 and %d\n", VT102_MAX_COLS);

      if ((size.y > VT102_MAX_ROWS) || (size.y < 1))
        fatal_moan ("-w requires a height between 1 and %d\n",
                    VT102_MAX_ROWS);

    }

  if (oflags['s'] && !oflags['F'])
    {
      /*nochdir incase socket is relative path, unlink then will fail */
      daemon (1, 0);

    }


  if (oflags['s'])
    {
      char *path;
      path = mome ("/.sympathy");
      mkdir (path, 0700);
      free (path);


      if (!oflags['k'])
        {
          pid = getpid ();

          oargs['k'] = mome ("/.sympathy/%s%d", hostname, pid);
          oflags['k']++;
        }

      server_socket = socket_listen (oargs['k']);

      /*Tell our parent's parent what our pid is */
      if (csnok)
        {
          pid = getpid ();

          write (csnok_pipe[1], &pid, sizeof (pid));
          close (csnok_pipe[1]);
        }

      if (!server_socket)
        fatal_moan ("failed to create socket %s for listening", oargs['k']);

    }

  if (oflags['s'] || oflags['t'])
    {
      if (oflags['P'])
        {
          FILE *fp;
          pid_file = oargs['P'];
          fp = fopen (pid_file, "w");
          if (fp)
            {
              fprintf (fp, "%d", getpid ());
              fclose (fp);
            }
        }

      if (oflags['L'])
        {
          log = file_log_new (oargs['L'], oflags['R']);
          if (!log)
            fatal_moan ("unable to access log file %s", oargs['L']);
        }

      if (oflags['p'])
        {
          tty = ptty_open (NULL, NULL, &size);
          if (!tty)
            fatal_moan ("unable to open a ptty");
        }
      else
        {
          /*HACK-- check that console=device does not occur in */
          /*/proc/cmdline */
          if (!oargs['d'])
            fatal_moan ("no argument to -d");

          {
            char kernel_cmdline[4096] = { 0 };
            char search_string[1024] = "console=";
            char *ptr = oargs['d'];
            int fd;

            if (!strncmp ("/dev/", ptr, 5))
              ptr += 5;

            strcat (search_string, ptr);

            fd = open ("/proc/cmdline", O_RDONLY);
            read (fd, kernel_cmdline, sizeof (kernel_cmdline));
            close (fd);

            kernel_cmdline[sizeof (kernel_cmdline) - 1] = 0;

            if (strstr (kernel_cmdline, search_string))
              fatal_moan ("/proc/cmdline contains %s", search_string);
          }

          tty =
            serial_open (oargs['d'],
                         oflags['K'] ? SERIAL_LOCK_ACTIVE :
                         SERIAL_LOCK_PASSIVE);
          if (!tty)
            fatal_moan ("unable to open serial port %s", oargs['d']);
        }

      if (oflags['b'])
        {
          int baud = safe_atoi (oargs['b']);

          if (baud < 0)
            fatal_moan ("Unable to parse baudrate %s", oargs['b']);

          tty_set_baud (tty, baud);

        }

      tty_set_flow (tty, oflags['f'] ? 1 : 0);
    }


  if (oflags['r'])
    {
      char *id = oargs['r'];

      if (!id)
        fatal_moan ("-r requires an argument");

      if (safe_atoi (id) > 0)
        {
          client_socket = find_socket ("%s%d", hostname, safe_atoi (id));
        }
      else
        {
          client_socket = find_socket ("%s", id);
        }

      if (!client_socket)
        fatal_moan ("failed to find socket %s", oargs['r']);

    }
  else if (oflags['c'])
    {
      client_socket = socket_connect (oargs['k']);

      if (!client_socket)
        fatal_moan ("failed to connect to socket %s", oargs['k']);

    }


  if (oflags['c'] || oflags['t'])
    {

      if (oflags['H'])
        {
          ansi = ansi_new_html (stdout);
        }
      else
        {
          terminal_register_handlers ();
          ansi =
            ansi_new_from_terminal (terminal_open (0, 1),
                                    oflags['u'] ? 0 : 1);
          ansi->reset (ansi, NULL);
        }
    }

  mainloop (tty, server_socket, client_socket, ansi, log, history, &size);

  if (ansi)
    {
      ansi->close (ansi);
      terminal_atexit ();
    }

  if (tty)
    tty->close (tty);

  if (log)
    log->close (log);
  if (server_socket)
    socket_free (server_socket);
  if (client_socket)
    socket_free (client_socket);

  if (pid_file)
    unlink (pid_file);

  if (!oflags['H'])
    printf ("you have now exited sympathy\n");
  return 0;
}