1988821bd3612c32dc99aceef288711daeba2d32
[xscreensaver] / hacks / sonar.c
1 /* sonar.c --- Simulate a sonar screen.
2  *
3  * This is an implementation of a general purpose reporting tool in the
4  * format of a Sonar display. It is designed such that a sensor is read
5  * on every movement of a sweep arm and the results of that sensor are
6  * displayed on the screen. The location of the display points (targets) on the
7  * screen are determined by the current localtion of the sweep and a distance
8  * value associated with the target. 
9  *
10  * Currently the only two sensors that are implemented are the simulator
11  * (the default) and the ping sensor. The simulator randomly creates a set
12  * of bogies that move around on the scope while the ping sensor can be
13  * used to display hosts on your network.
14  *
15  * The ping code is only compiled in if you define HAVE_ICMP or HAVE_ICMPHDR,
16  * because, unfortunately, different systems have different ways of creating
17  * these sorts of packets.
18  *
19  * Also: creating an ICMP socket is a privileged operation, so the program
20  * needs to be installed SUID root if you want to use the ping mode.  If you
21  * check the code you will see that this privilige is given up immediately
22  * after the socket is created.
23  *
24  * It should be easy to extend this code to support other sorts of sensors.
25  * Some ideas:
26  *   - search the output of "netstat" for the list of hosts to ping;
27  *   - plot the contents of /proc/interrupts;
28  *   - plot the process table, by process size, cpu usage, or total time;
29  *   - plot the logged on users by idle time or cpu usage.
30  *
31  * Copyright (C) 1998, 2001
32  *  by Stephen Martin (smartin@vanderfleet-martin.net).
33  * Permission to use, copy, modify, distribute, and sell this software and its
34  * documentation for any purpose is hereby granted without fee, provided that
35  * the above copyright notice appear in all copies and that both that
36  * copyright notice and this permission notice appear in supporting
37  * documentation.  No representations are made about the suitability of this
38  * software for any purpose.  It is provided "as is" without express or 
39  * implied warranty.
40  *
41  * $Revision: 1.20 $
42  *
43  * Version 1.0 April 27, 1998.
44  * - Initial version
45  * - Submitted to RedHat Screensaver Contest
46  * 
47  * Version 1.1 November 3, 1998.
48  * - Added simulation mode.
49  * - Added enhancements by Thomas Bahls <thommy@cs.tu-berlin.de>
50  * - Fixed huge memory leak.
51  * - Submitted to xscreensavers
52  * 
53  * Version 1.2
54  * - All ping code is now ifdef-ed by the compile time symbol HAVE_PING;
55  *   use -DHAVE_PING to include it when you compile.
56  * - Sweep now uses gradients.
57  * - Fixed portability problems with icmphdr on some systems.
58  * - removed lowColor option/resource.
59  * - changed copyright notice so that it could be included in the xscreensavers
60  *   collection.
61  *
62  * Version 1.3 November 16, 1998.
63  * - All ping code is now ifdef-ed by the compile time symbol PING use -DPING
64  *   to include it when you compile.
65  * - Sweep now uses gradients.
66  * - Fixed portability problems with icmphdr on some systems.
67  * - removed lowcolour option/resource.
68  * - changed copyright notice so that it could be included in the xscreensavers
69  *   collection.
70  *
71  * Version 1.4 November 18, 1998.
72  * - More ping portability fixes.
73  *
74  * Version 1.5 November 19, 1998.
75  * - Synced up with jwz's changes.
76  * - Now need to define HAVE_PING to compile in the ping stuff.
77  */
78
79 /* These are computed by configure now:
80    #define HAVE_ICMP
81    #define HAVE_ICMPHDR
82  */
83
84
85 /* Include Files */
86
87 #include <stdlib.h>
88 #include <stdio.h>
89 #include <math.h>
90 #include <sys/stat.h>
91
92 #include "screenhack.h"
93 #include "colors.h"
94 #include "hsv.h"
95
96 #if defined(HAVE_ICMP) || defined(HAVE_ICMPHDR)
97 # include <unistd.h>
98 # include <limits.h>
99 # include <signal.h>
100 # include <fcntl.h>
101 # include <sys/types.h>
102 # include <sys/time.h>
103 # include <sys/ipc.h>
104 # include <sys/shm.h>
105 # include <sys/socket.h>
106 # include <netinet/in_systm.h>
107 # include <netinet/in.h>
108 # include <netinet/ip.h>
109 # include <netinet/ip_icmp.h>
110 # include <netinet/udp.h>
111 # include <arpa/inet.h>
112 # include <netdb.h>
113 #endif /* HAVE_ICMP || HAVE_ICMPHDR */
114
115
116 /* Defines */
117
118 #undef MY_MIN
119 #define MY_MIN(a,b) ((a)<(b)?(a - 50):(b - 10))
120
121 #ifndef LINE_MAX
122 # define LINE_MAX 2048
123 #endif
124
125 /* Frigging icmp */
126
127 #if defined(HAVE_ICMP)
128 # define HAVE_PING
129 # define ICMP             icmp
130 # define ICMP_TYPE(p)     (p)->icmp_type
131 # define ICMP_CODE(p)     (p)->icmp_code
132 # define ICMP_CHECKSUM(p) (p)->icmp_cksum
133 # define ICMP_ID(p)       (p)->icmp_id
134 # define ICMP_SEQ(p)      (p)->icmp_seq
135 #elif defined(HAVE_ICMPHDR)
136 # define HAVE_PING
137 # define ICMP             icmphdr
138 # define ICMP_TYPE(p)     (p)->type
139 # define ICMP_CODE(p)     (p)->code
140 # define ICMP_CHECKSUM(p) (p)->checksum
141 # define ICMP_ID(p)       (p)->un.echo.id
142 # define ICMP_SEQ(p)      (p)->un.echo.sequence
143 #else
144 # undef HAVE_PING
145 #endif
146
147
148 #ifdef HAVE_PING
149 # if defined(__DECC) || defined(_IP_VHL)
150    /* This is how you do it on DEC C, and possibly some BSD systems. */
151 #  define IP_HDRLEN(ip)   ((ip)->ip_vhl & 0x0F)
152 # else
153    /* This is how you do it on everything else. */
154 #  define IP_HDRLEN(ip)   ((ip)->ip_hl)
155 # endif
156 #endif /* HAVE_PING */
157
158
159 /* Forward References */
160
161 #ifdef HAVE_PING
162 static u_short checksum(u_short *, int);
163 #endif
164 static long delta(struct timeval *, struct timeval *);
165
166
167 /* Data Structures */
168
169 /*
170  * The Bogie.
171  *
172  * This represents an object that is visable on the scope.
173  */
174
175 typedef struct Bogie {
176     char *name;                 /* The name of the thing being displayed */
177     int distance;               /* The distance to this thing (0 - 100) */
178     int tick;                   /* The tick that it was found on */
179     int ttl;                    /* The time to live */
180     int age;                    /* How long it's been around */
181     struct Bogie *next;         /* The next one in the list */
182 } Bogie;
183
184 /*
185  * Sonar Information.
186  *
187  * This contains all of the runtime information about the sonar scope.
188  */
189
190 typedef struct {
191     Display *dpy;               /* The X display */
192     Window win;                 /* The window */
193     GC hi,                      /* The leading edge of the sweep */
194         lo,                     /* The trailing part of the sweep */
195         erase,                  /* Used to erase things */
196         grid,                   /* Used to draw the grid */
197         text;                   /* Used to draw text */
198     Colormap cmap;              /* The colormap */
199     XFontStruct *font;          /* The font to use for the labels */
200     int text_steps;             /* How many steps to fade text. */
201     XColor *text_colors;        /* Pixel values used to fade text */
202     int sweep_degrees;          /* How much of the circle the sweep uses */
203     int sweep_segs;             /* How many gradients in the sweep. */
204     XColor *sweep_colors;        /* The sweep pixel values */
205     int width, height;          /* Window dimensions */
206     int minx, miny, maxx, maxy, /* Bounds of the scope */
207         centrex, centrey, radius; /* Parts of the scope circle */
208     Bogie *visable;             /* List of visable objects */
209     int current;                /* Current position of sweep */
210     int sweepnum;               /* The current id of the sweep */
211     int delay;                  /* how long between each frame of the anim */
212
213     int TTL;                    /* The number of ticks that bogies are visible
214                                    on the screen before they fade away. */
215 } sonar_info;
216
217 static Bool debug_p = False;
218
219
220 /* 
221  * Variables to support the differnt Sonar modes.
222  */
223
224 Bogie *(*sensor)(sonar_info *, void *); /* The current sensor */
225 void *sensor_info;                      /* Information about the sensor */
226
227 /*
228  * A list of targets to ping.
229  */
230
231 typedef struct ping_target {
232     char *name;                 /* The name of the target */
233 #ifdef HAVE_PING
234     struct sockaddr address;    /* The address of the target */
235 #endif /* HAVE_PING */
236     struct ping_target *next;   /* The next one in the list */
237 } ping_target;
238
239
240 #ifdef HAVE_PING
241 /*
242  * Ping Information.
243  *
244  * This contains the information for the ping sensor.
245  */
246
247 typedef struct {
248     int icmpsock;               /* Socket for sending pings */
249     int pid;                    /* Our process ID */
250     int seq;                    /* Packet sequence number */
251     int timeout;                /* Timeout value for pings */
252     ping_target *targets;       /* List of targets to ping */
253     int numtargets;             /* The number of targets to ping */
254 } ping_info;
255
256 /* Flag to indicate that the timer has expired on us */
257
258 static int timer_expired;
259
260 #endif /* HAVE_PING */
261
262 /*
263  * A list of targets for the simulator
264  */
265
266 typedef struct sim_target {
267     char *name;                 /* The name of the target */
268     int nexttick;               /* The next tick that this will be seen */
269     int nextdist;               /* The distance on that tick */
270     int movedonsweep;           /* The number of the sweep this last moved */
271 } sim_target;
272
273 /*
274  * Simulator Information.
275  *
276  * This contains the information for the simulator mode.
277  */
278
279 typedef struct {
280     sim_target *teamA;          /* The bogies for the A team */
281     int numA;                   /* The number of bogies in team A */
282     char *teamAID;              /* The identifier for bogies in team A */
283     sim_target *teamB;          /* The bogies for the B team */
284     int numB;                   /* The number of bogies in team B */
285     char *teamBID;              /* The identifier for bogies in team B */
286 } sim_info;
287
288 /* Name of the Screensaver hack */
289
290 char *progclass="sonar";
291
292 /* Application Defaults */
293
294 char *defaults [] = {
295     ".background:      #000000",
296     ".sweepColor:      #00FF00",
297     "*delay:           100000",
298     "*scopeColor:      #003300",
299     "*gridColor:       #00AA00",
300     "*textColor:       #FFFF00",
301     "*ttl:             90",
302     "*mode:            default",
303     "*font:            fixed",
304     "*sweepDegrees:    30",
305
306     "*textSteps:       80",     /* npixels */
307     "*sweepSegments:   80",     /* npixels */
308
309     "*pingTimeout:     3000",
310
311     "*teamAName:       F18",
312     "*teamBName:       MIG",
313     "*teamACount:      4",
314     "*teamBCount:      4",
315
316     "*ping:            default",
317     ".debug:           false",
318     0
319 };
320
321 /* Options passed to this program */
322
323 XrmOptionDescRec options [] = {
324     {"-background",   ".background",   XrmoptionSepArg, 0 },
325     {"-sweep-color",  ".sweepColor",   XrmoptionSepArg, 0 },
326     {"-scope-color",  ".scopeColor",   XrmoptionSepArg, 0 },
327     {"-grid-color",   ".gridColor",    XrmoptionSepArg, 0 },
328     {"-text-color",   ".textColor",    XrmoptionSepArg, 0 },
329     {"-ttl",          ".ttl",          XrmoptionSepArg, 0 },
330     {"-font",         ".font",         XrmoptionSepArg, 0 },
331 #ifdef HAVE_PING
332     {"-ping-timeout", ".pingTimeout",  XrmoptionSepArg, 0 },
333 #endif /* HAVE_PING */
334     {"-team-a-name",   ".teamAName",   XrmoptionSepArg, 0 },
335     {"-team-b-name",   ".teamBName",   XrmoptionSepArg, 0 },
336     {"-team-a-count",  ".teamACount",  XrmoptionSepArg, 0 },
337     {"-team-b-count",  ".teamBCount",  XrmoptionSepArg, 0 },
338
339     {"-ping",          ".ping",        XrmoptionSepArg, 0 },
340     {"-debug",         ".debug",       XrmoptionNoArg, "True" },
341     { 0, 0, 0, 0 }
342 };
343
344 /*
345  * Create a new Bogie and set some initial values.
346  *
347  * Args:
348  *    name     - The name of the bogie.
349  *    distance - The distance value.
350  *    tick     - The tick value.
351  *    ttl      - The time to live value.
352  *
353  * Returns:
354  *    The newly allocated bogie or null if a memory problem occured.
355  */
356
357 static Bogie *
358 newBogie(char *name, int distance, int tick, int ttl) 
359 {
360
361     /* Local Variables */
362
363     Bogie *new;
364
365     /* Allocate a bogie and initialize it */
366
367     if ((new = (Bogie *) calloc(1, sizeof(Bogie))) == NULL) {
368         fprintf(stderr, "%s: Out of Memory\n", progname);
369         return NULL;
370     }
371     new->name = name;
372     new->distance = distance;
373     new->tick = tick;
374     new->ttl = ttl;
375     new->age = 0;
376     new->next = (Bogie *) 0;
377     return new;
378 }
379
380 /*
381  * Free a Bogie.
382  *
383  * Args:
384  *    b - The bogie to free.
385  */
386
387
388 static void
389 freeBogie(Bogie *b) 
390 {
391     if (b->name != (char *) 0)
392         free(b->name);
393     free(b);
394 }
395
396 /*
397  * Find a bogie by name in a list.
398  *
399  * This does a simple linear search of the list for a given name.
400  *
401  * Args:
402  *    bl   - The Bogie list to search.
403  *    name - The name to look for.
404  *
405  * Returns:
406  *    The requested Bogie or null if it wasn't found.
407  */
408
409 static Bogie *
410 findNode(Bogie *bl, char *name) 
411 {
412
413     /* Local Variables */
414
415     Bogie *p;
416
417     /* Abort if the list is empty or no name is given */
418
419     if ((name == NULL) || (bl == NULL))
420         return NULL;
421
422     /* Search the list for the desired name */
423
424     p = bl;
425     while (p != NULL) {
426         if (strcmp(p->name, name) == 0)
427             return p;
428         p = p->next;
429     }
430
431     /* Not found */
432
433     return NULL;
434 }
435
436 #ifdef HAVE_PING
437
438 /*
439  * Lookup the address for a ping target;
440  *
441  * Args:
442  *    target - The ping_target fill in the address for.
443  *
444  * Returns:
445  *    1 if the host was successfully resolved, 0 otherwise.
446  */
447
448 static int
449 lookupHost(ping_target *target) 
450 {
451   struct hostent *hent;
452   struct sockaddr_in *iaddr;
453
454   int iip[4];
455   char c;
456
457   iaddr = (struct sockaddr_in *) &(target->address);
458   iaddr->sin_family = AF_INET;
459
460   if (4 == sscanf(target->name, "%d.%d.%d.%d%c",
461                   &iip[0], &iip[1], &iip[2], &iip[3], &c))
462     {
463       /* It's an IP address.
464        */
465       unsigned char ip[4];
466
467       ip[0] = iip[0];
468       ip[1] = iip[1];
469       ip[2] = iip[2];
470       ip[3] = iip[3];
471
472       if (ip[3] == 0)
473         {
474           if (debug_p > 1)
475             fprintf (stderr, "%s:   ignoring bogus IP %s\n",
476                      progname, target->name);
477           return 0;
478         }
479
480       iaddr->sin_addr.s_addr = ((ip[3] << 24) |
481                                 (ip[2] << 16) |
482                                 (ip[1] <<  8) |
483                                 (ip[0]));
484       hent = gethostbyaddr (ip, 4, AF_INET);
485
486       if (debug_p > 1)
487         fprintf (stderr, "%s:   %s => %s\n",
488                  progname, target->name,
489                  ((hent && hent->h_name && *hent->h_name)
490                   ? hent->h_name : "<unknown>"));
491
492       if (hent && hent->h_name && *hent->h_name)
493         target->name = strdup (hent->h_name);
494     }
495   else
496     {
497       /* It's a host name.
498        */
499       hent = gethostbyname (target->name);
500       if (!hent)
501         {
502           fprintf (stderr, "%s: could not resolve host:  %s\n",
503                    progname, target->name);
504           return 0;
505         }
506
507       memcpy (&iaddr->sin_addr, hent->h_addr_list[0],
508               sizeof(iaddr->sin_addr));
509
510       if (debug_p > 1)
511         fprintf (stderr, "%s:   %s => %d.%d.%d.%d\n",
512                  progname, target->name,
513                  iaddr->sin_addr.s_addr       & 255,
514                  iaddr->sin_addr.s_addr >>  8 & 255,
515                  iaddr->sin_addr.s_addr >> 16 & 255,
516                  iaddr->sin_addr.s_addr >> 24 & 255);
517     }
518   return 1;
519 }
520
521
522 static void
523 print_host (FILE *out, unsigned long ip, const char *name)
524 {
525   char ips[50];
526   sprintf (ips, "%d.%d.%d.%d",
527            (ip)       & 255,
528            (ip >>  8) & 255,
529            (ip >> 16) & 255,
530            (ip >> 24) & 255);
531   if (!name || !*name) name = "<unknown>";
532   fprintf (out, "%-16s %s\n", ips, name);
533 }
534
535
536 /*
537  * Create a target for a host.
538  *
539  * Args:
540  *    name - The name of the host.
541  *
542  * Returns:
543  *    A newly allocated target or null if the host could not be resolved.
544  */
545
546 static ping_target *
547 newHost(char *name) 
548 {
549
550     /* Local Variables */
551
552     ping_target *target = NULL;
553
554     /* Create the target */
555
556     if ((target = calloc(1, sizeof(ping_target))) == NULL) {
557         fprintf(stderr, "%s: Out of Memory\n", progname);
558         goto target_init_error;
559     }
560     if ((target->name = strdup(name)) == NULL) {
561         fprintf(stderr, "%s: Out of Memory\n", progname);
562         goto target_init_error;
563     }
564
565     /* Lookup the host */
566
567     if (! lookupHost(target))
568         goto target_init_error;
569
570     /* Don't ever use loopback (127.0.0) hosts */
571     {
572       struct sockaddr_in *iaddr = (struct sockaddr_in *) &(target->address);
573       unsigned long ip = iaddr->sin_addr.s_addr;
574       if ((ip         & 255) == 127 &&
575           ((ip >>  8) & 255) == 0 &&
576           ((ip >> 16) & 255) == 0)
577         {
578           if (debug_p)
579             fprintf (stderr, "%s:   ignoring loopback host %s\n",
580                      progname, target->name);
581           goto target_init_error;
582         }
583     }
584
585     /* Done */
586
587     if (debug_p)
588       {
589         struct sockaddr_in *iaddr = (struct sockaddr_in *) &(target->address);
590         unsigned long ip = iaddr->sin_addr.s_addr;
591         fprintf (stderr, "%s:   added ", progname);
592         print_host (stderr, ip, target->name);
593       }
594
595     return target;
596
597     /* Handle errors here */
598
599 target_init_error:
600     if (target != NULL)
601         free(target);
602     return NULL;
603 }
604
605 /*
606  * Generate a list of ping targets from the entries in a file.
607  *
608  * Args:
609  *    fname - The name of the file. This file is expected to be in the same
610  *            format as /etc/hosts.
611  *
612  * Returns:
613  *    A list of targets to ping or null if an error occured.
614  */
615
616 static ping_target *
617 readPingHostsFile(char *fname) 
618 {
619     /* Local Variables */
620
621     FILE *fp;
622     char buf[LINE_MAX];
623     char *p;
624     ping_target *list = NULL;
625     char *addr, *name;
626     ping_target *new;
627
628     /* Make sure we in fact have a file to process */
629
630     if ((fname == NULL) || (fname[0] == '\0')) {
631         fprintf(stderr, "%s: invalid ping host file name\n", progname);
632         return NULL;
633     }
634
635     /* Open the file */
636
637     if ((fp = fopen(fname, "r")) == NULL) {
638         char msg[1024];
639         sprintf(msg, "%s: unable to open host file %s", progname, fname);
640         perror(msg);
641         return NULL;
642     }
643
644     if (debug_p)
645       fprintf (stderr, "%s:  reading file %s\n", progname, fname);
646
647     /* Read the file line by line */
648
649     while ((p = fgets(buf, LINE_MAX, fp)) != NULL) {
650
651         /*
652          * Parse the line skipping those that start with '#'.
653          * The rest of the lines in the file should be in the same
654          * format as a /etc/hosts file. We are only concerned with
655          * the first two field, the IP address and the name
656          */
657
658         while ((*p == ' ') || (*p == '\t'))
659             p++;
660         if (*p == '#')
661             continue;
662
663         /* Get the name and address */
664
665         name = addr = NULL;
666         if ((addr = strtok(buf, " ,;\t\n")) != NULL)
667             name = strtok(NULL, " ,;\t\n");
668         else
669             continue;
670
671         /* Check to see if the addr looks like an addr.  If not, assume
672            the addr is a name and there is no addr.  This way, we can
673            handle files whose lines have "xx.xx.xx.xx hostname" as their
674            first two tokens, and also files that have a hostname as their
675            first token (like .ssh/known_hosts and .rhosts.)
676          */
677         {
678           int i; char c;
679           if (4 != sscanf(addr, "%d.%d.%d.%d%c", &i, &i, &i, &i, &c))
680             {
681               name = addr;
682               addr = NULL;
683             }
684         }
685
686         /* If the name is all digits, it's not a name. */
687         if (name)
688           {
689             const char *s;
690             for (s = name; *s; s++)
691               if (*s < '0' || *s > '9')
692                 break;
693             if (! *s)
694               {
695                 if (debug_p > 1)
696                   fprintf (stderr, "%s:  skipping bogus name \"%s\" (%s)\n",
697                            progname, name, addr);
698                 name = NULL;
699               }
700           }
701
702         /* Create a new target using first the name then the address */
703
704         new = NULL;
705         if (name != NULL)
706             new = newHost(name);
707         if (new == NULL && addr != NULL)
708             new = newHost(addr);
709
710         /* Add it to the list if we got one */
711
712         if (new != NULL) {
713             new->next = list;
714             list = new;
715         }
716     }
717
718     /* Close the file and return the list */
719
720     fclose(fp);
721     return list;
722 }
723
724
725 static ping_target *
726 delete_duplicate_hosts (ping_target *list)
727 {
728   ping_target *head = list;
729   ping_target *rest;
730
731   for (rest = head; rest; rest = rest->next)
732     {
733       struct sockaddr_in *i1 = (struct sockaddr_in *) &(rest->address);
734       unsigned long ip1 = i1->sin_addr.s_addr;
735
736       static ping_target *rest2;
737       for (rest2 = rest; rest2; rest2 = rest2->next)
738         {
739           if (rest2 && rest2->next)
740             {
741               struct sockaddr_in *i2 = (struct sockaddr_in *)
742                 &(rest2->next->address);
743               unsigned long ip2 = i2->sin_addr.s_addr;
744
745               if (ip1 == ip2)
746                 {
747                   if (debug_p)
748                     {
749                       fprintf (stderr, "%s: deleted duplicate: ", progname);
750                       print_host (stderr, ip2, rest2->next->name);
751                     }
752                   rest2->next = rest2->next->next;
753                 }
754             }
755         }
756     }
757
758   return head;
759 }
760
761
762
763
764 /*
765  * Generate a list ping targets consisting of all of the entries on
766  * the same subnet.
767  *
768  * Returns:
769  *    A list of all of the hosts on this net.
770  */
771
772 static ping_target *
773 subnetHostsList(int base, int subnet_width) 
774 {
775     unsigned long mask;
776
777     /* Local Variables */
778
779     char hostname[BUFSIZ];
780     char address[BUFSIZ];
781     struct hostent *hent;
782     char *p;
783     int i;
784     ping_target *new;
785     ping_target *list = NULL;
786
787     if (subnet_width < 24)
788       {
789         fprintf (stderr,
790     "%s: pinging %u hosts is a bad idea; please use a subnet mask of 24 bits\n"
791                  "       or more (255 hosts max.)\n",
792                  progname, (1L << (32 - subnet_width)) - 1);
793         exit (1);
794       }
795     else if (subnet_width > 30)
796       {
797         fprintf (stderr, "%s: a subnet of %d bits doesn't make sense:"
798                  " try \"subnet/24\" or \"subnet/29\".\n",
799                  progname, subnet_width);
800         exit (1);
801       }
802
803
804     if (debug_p)
805       fprintf (stderr, "%s:   adding %d-bit subnet\n", progname, subnet_width);
806
807     /* Get our hostname */
808
809     if (gethostname(hostname, BUFSIZ)) {
810         fprintf(stderr, "%s: unable to get local hostname\n", progname);
811         return NULL;
812     }
813
814     /* Get our IP address and convert it to a string */
815
816     if ((hent = gethostbyname(hostname)) == NULL) {
817         fprintf(stderr, "%s: unable to lookup our IP address\n", progname);
818         return NULL;
819     }
820     strcpy(address, inet_ntoa(*((struct in_addr *)hent->h_addr_list[0])));
821
822     /* Construct targets for all addresses in this subnet */
823
824     mask = 0;
825     for (i = 0; i < subnet_width; i++)
826       mask |= (1L << (31-i));
827
828     /* If no base IP specified, assume localhost. */
829     if (base == 0)
830       base = ((((unsigned char) hent->h_addr_list[0][0]) << 24) |
831               (((unsigned char) hent->h_addr_list[0][1]) << 16) |
832               (((unsigned char) hent->h_addr_list[0][2]) <<  8) |
833               (((unsigned char) hent->h_addr_list[0][3])));
834
835     if (base == ((127 << 24) | 1))
836       {
837         fprintf (stderr,
838                  "%s: unable to determine local subnet address: \"%s\"\n"
839                  "       resolves to loopback address %d.%d.%d.%d.\n",
840                  progname, hostname,
841                  (base >> 24) & 255, (base >> 16) & 255,
842                  (base >>  8) & 255, (base      ) & 255);
843         return NULL;
844       }
845
846     for (i = 255; i >= 0; i--) {
847         int ip = (base & 0xFFFFFF00) | i;
848       
849         if ((ip & mask) != (base & mask))   /* not in the mask range at all */
850           continue;
851         if ((ip & ~mask) == 0)              /* broadcast address */
852           continue;
853         if ((ip & ~mask) == ~mask)          /* broadcast address */
854           continue;
855
856         sprintf (address, "%d.%d.%d.%d", 
857                  (ip>>24)&255, (ip>>16)&255, (ip>>8)&255, (ip)&255);
858
859         if (debug_p > 1)
860           fprintf(stderr, "%s:  subnet: %s (%d.%d.%d.%d & %d.%d.%d.%d / %d)\n",
861                   progname,
862                   address,
863                   (base>>24)&255, (base>>16)&255, (base>>8)&255, base&mask&255,
864                   (mask>>24)&255, (mask>>16)&255, (mask>>8)&255, mask&255,
865                   subnet_width);
866
867         p = address + strlen(address) + 1;
868         sprintf(p, "%d", i);
869
870         new = newHost(address);
871         if (new != NULL) {
872             new->next = list;
873             list = new;
874         }
875     }
876
877     /* Done */
878
879     return list;
880 }
881
882 /*
883  * Initialize the ping sensor.
884  *
885  * Returns:
886  *    A newly allocated ping_info structure or null if an error occured.
887  */
888
889 static ping_target *parse_mode (Bool ping_works_p);
890
891 static ping_info *
892 init_ping(void) 
893 {
894
895   Bool socket_initted_p = False;
896
897     /* Local Variables */
898
899     ping_info *pi = NULL;               /* The new ping_info struct */
900     ping_target *pt;                    /* Used to count the targets */
901
902     /* Create the ping info structure */
903
904     if ((pi = (ping_info *) calloc(1, sizeof(ping_info))) == NULL) {
905         fprintf(stderr, "%s: Out of memory\n", progname);
906         goto ping_init_error;
907     }
908
909     /* Create the ICMP socket */
910
911     if ((pi->icmpsock = socket(AF_INET, SOCK_RAW, IPPROTO_ICMP)) >= 0) {
912       socket_initted_p = True;
913     }
914
915     /* Disavow privs */
916
917     setuid(getuid());
918
919
920     pi->pid = getpid() & 0xFFFF;
921     pi->seq = 0;
922     pi->timeout = get_integer_resource("pingTimeout", "PingTimeout");
923
924     /* Generate a list of targets */
925
926     pi->targets = parse_mode (socket_initted_p);
927     pi->targets = delete_duplicate_hosts (pi->targets);
928
929
930     if (debug_p)
931       {
932         ping_target *t;
933         fprintf (stderr, "%s: Target list:\n", progname);
934         for (t = pi->targets; t; t = t->next)
935           {
936             struct sockaddr_in *iaddr = (struct sockaddr_in *) &(t->address);
937             unsigned long ip = iaddr->sin_addr.s_addr;
938             fprintf (stderr, "%s:   ", progname);
939             print_host (stderr, ip, t->name);
940           }
941       }
942
943     /* Make sure there is something to ping */
944
945     if (pi->targets == NULL) {
946       goto ping_init_error;
947     }
948
949     /* Count the targets */
950
951     pt = pi->targets;
952     pi->numtargets = 0;
953     while (pt != NULL) {
954         pi->numtargets++;
955         pt = pt->next;
956     }
957
958     /* Done */
959
960     return pi;
961
962     /* Handle initialization errors here */
963
964 ping_init_error:
965     if (pi != NULL)
966         free(pi);
967     return NULL;
968 }
969
970
971 /*
972  * Ping a host.
973  *
974  * Args:
975  *    pi   - The ping information strcuture.
976  *    host - The name or IP address of the host to ping (in ascii).
977  */
978
979 static void
980 sendping(ping_info *pi, ping_target *pt) 
981 {
982
983     /* Local Variables */
984
985     u_char *packet;
986     struct ICMP *icmph;
987     int result;
988
989     /*
990      * Note, we will send the character name of the host that we are
991      * pinging in the packet so that we don't have to keep track of the
992      * name or do an address lookup when it comes back.
993      */
994
995     int pcktsiz = sizeof(struct ICMP) + sizeof(struct timeval) +
996         strlen(pt->name) + 1;
997
998     /* Create the ICMP packet */
999
1000     if ((packet = (u_char *) malloc(pcktsiz)) == (void *) 0)
1001         return;  /* Out of memory */
1002     icmph = (struct ICMP *) packet;
1003     ICMP_TYPE(icmph) = ICMP_ECHO;
1004     ICMP_CODE(icmph) = 0;
1005     ICMP_CHECKSUM(icmph) = 0;
1006     ICMP_ID(icmph) = pi->pid;
1007     ICMP_SEQ(icmph) = pi->seq++;
1008     gettimeofday((struct timeval *) &packet[sizeof(struct ICMP)],
1009                  (struct timezone *) 0);
1010     strcpy((char *) &packet[sizeof(struct ICMP) + sizeof(struct timeval)],
1011            pt->name);
1012     ICMP_CHECKSUM(icmph) = checksum((u_short *)packet, pcktsiz);
1013
1014     /* Send it */
1015
1016     if ((result = sendto(pi->icmpsock, packet, pcktsiz, 0, 
1017                          &pt->address, sizeof(pt->address))) !=  pcktsiz) {
1018 #if 0
1019         char errbuf[BUFSIZ];
1020         sprintf(errbuf, "%s: error sending ping to %s", progname, pt->name);
1021         perror(errbuf);
1022 #endif
1023     }
1024 }
1025
1026 /*
1027  * Catch a signal and do nothing.
1028  *
1029  * Args:
1030  *    sig - The signal that was caught.
1031  */
1032
1033 static void
1034 sigcatcher(int sig)
1035 {
1036     timer_expired = 1;
1037 }
1038
1039 /*
1040  * Compute the checksum on a ping packet.
1041  *
1042  * Args:
1043  *    packet - A pointer to the packet to compute the checksum for.
1044  *    size   - The size of the packet.
1045  *
1046  * Returns:
1047  *    The computed checksum
1048  *    
1049  */
1050
1051 static u_short
1052 checksum(u_short *packet, int size) 
1053 {
1054
1055     /* Local Variables */
1056
1057     register int nleft = size;
1058     register u_short *w = packet;
1059     register int sum = 0;
1060     u_short answer = 0;
1061
1062     /*
1063      * Our algorithm is simple, using a 32 bit accumulator (sum), we add
1064      * sequential 16 bit words to it, and at the end, fold back all the
1065      * carry bits from the top 16 bits into the lower 16 bits.
1066      */
1067
1068     while (nleft > 1)  {
1069         sum += *w++;
1070         nleft -= 2;
1071     }
1072
1073     /* mop up an odd byte, if necessary */
1074
1075     if (nleft == 1) {
1076         *(u_char *)(&answer) = *(u_char *)w ;
1077         *(1 + (u_char *)(&answer)) = 0;
1078         sum += answer;
1079     }
1080
1081     /* add back carry outs from top 16 bits to low 16 bits */
1082
1083     sum = (sum >> 16) + (sum & 0xffff);     /* add hi 16 to low 16 */
1084     sum += (sum >> 16);                     /* add carry */
1085     answer = ~sum;                          /* truncate to 16 bits */
1086
1087     /* Done */
1088
1089     return(answer);
1090 }
1091
1092 /*
1093  * Look for ping replies.
1094  *
1095  * Retrieve all outstanding ping replies.
1096  *
1097  * Args:
1098  *    si - Information about the sonar.
1099  *    pi - Ping information.
1100  *    ttl - The time each bogie is to live on the screen
1101  *
1102  * Returns:
1103  *    A Bogie list of all the machines that replied.
1104  */
1105
1106 static Bogie *
1107 getping(sonar_info *si, ping_info *pi) 
1108 {
1109
1110     /* Local Variables */
1111
1112     struct sockaddr from;
1113     int fromlen;
1114     int result;
1115     u_char packet[1024];
1116     struct timeval now;
1117     struct timeval *then;
1118     struct ip *ip;
1119     int iphdrlen;
1120     struct ICMP *icmph;
1121     Bogie *bl = NULL;
1122     Bogie *new;
1123     char *name;
1124     struct sigaction sa;
1125     struct itimerval it;
1126     fd_set rfds;
1127     struct timeval tv;
1128
1129     /* Set up a signal to interupt our wait for a packet */
1130
1131     sigemptyset(&sa.sa_mask);
1132     sa.sa_flags = 0;
1133     sa.sa_handler = sigcatcher;
1134     if (sigaction(SIGALRM, &sa, 0) == -1) {
1135         char msg[1024];
1136         sprintf(msg, "%s: unable to trap SIGALRM", progname);
1137         perror(msg);
1138         exit(1);
1139     }
1140
1141     /* Set up a timer to interupt us if we don't get a packet */
1142
1143     it.it_interval.tv_sec = 0;
1144     it.it_interval.tv_usec = 0;
1145     it.it_value.tv_sec = 0;
1146     it.it_value.tv_usec = pi->timeout;
1147     timer_expired = 0;
1148     setitimer(ITIMER_REAL, &it, NULL);
1149
1150     /* Wait for a result packet */
1151
1152     fromlen = sizeof(from);
1153     while (! timer_expired) {
1154       tv.tv_usec=pi->timeout;
1155       tv.tv_sec=0;
1156       FD_ZERO(&rfds);
1157       FD_SET(pi->icmpsock,&rfds);
1158       /* only wait a little while, in case we raced with the timer expiration.
1159          From Valentijn Sessink <valentyn@openoffice.nl> */
1160       if (select(pi->icmpsock+1, &rfds, NULL, NULL, &tv) >0) {
1161         result = recvfrom(pi->icmpsock, packet, sizeof(packet),
1162                       0, &from, &fromlen);
1163
1164         /* Check the packet */
1165
1166         gettimeofday(&now, (struct timezone *) 0);
1167         ip = (struct ip *) packet;
1168         iphdrlen = IP_HDRLEN(ip) << 2;
1169         icmph = (struct ICMP *) &packet[iphdrlen];
1170
1171         /* Was the packet a reply?? */
1172
1173         if (ICMP_TYPE(icmph) != ICMP_ECHOREPLY) {
1174             /* Ignore anything but ICMP Replies */
1175             continue; /* Nope */
1176         }
1177
1178         /* Was it for us? */
1179
1180         if (ICMP_ID(icmph) != pi->pid) {
1181             /* Ignore packets not set from us */
1182             continue; /* Nope */
1183         }
1184
1185         /* Copy the name of the bogie */
1186
1187         if ((name =
1188              strdup((char *) &packet[iphdrlen + 
1189                                     + sizeof(struct ICMP)
1190                                     + sizeof(struct timeval)])) == NULL) {
1191             fprintf(stderr, "%s: Out of memory\n", progname);
1192             return bl;
1193         }
1194
1195         /* If the name is an IP addr, try to resolve it. */
1196         {
1197           int iip[4];
1198           char c;
1199           if (4 == sscanf(name, " %d.%d.%d.%d %c",
1200                           &iip[0], &iip[1], &iip[2], &iip[3], &c))
1201             {
1202               unsigned char ip[4];
1203               struct hostent *h;
1204               ip[0] = iip[0]; ip[1] = iip[1]; ip[2] = iip[2]; ip[3] = iip[3];
1205               h = gethostbyaddr ((char *) ip, 4, AF_INET);
1206               if (h && h->h_name && *h->h_name)
1207                 {
1208                   free (name);
1209                   name = strdup (h->h_name);
1210                 }
1211             }
1212         }
1213
1214         /* Create the new Bogie and add it to the list we are building */
1215
1216         if ((new = newBogie(name, 0, si->current, si->TTL)) == NULL)
1217             return bl;
1218         new->next = bl;
1219         bl = new;
1220
1221         /* Compute the round trip time */
1222
1223         then =  (struct timeval *) &packet[iphdrlen +
1224                                           sizeof(struct ICMP)];
1225         new->distance = delta(then, &now) / 100;
1226         if (new->distance == 0)
1227                 new->distance = 2; /* HACK */
1228       }
1229     }
1230
1231     /* Done */
1232
1233     return bl;
1234 }
1235
1236 /*
1237  * Ping hosts.
1238  *
1239  * Args:
1240  *    si - Sonar Information.
1241  *    pi - Ping Information.
1242  *
1243  * Returns:
1244  *    A list of hosts that replied to pings or null if there were none.
1245  */
1246
1247 static Bogie *
1248 ping(sonar_info *si, void *vpi) 
1249 {
1250
1251     /*
1252      * This tries to distribute the targets evely around the field of the
1253      * sonar.
1254      */
1255
1256     ping_info *pi = (ping_info *) vpi;
1257     static ping_target *ptr = NULL;
1258
1259     int tick = si->current * -1 + 1;
1260     if ((ptr == NULL) && (tick == 1))
1261         ptr = pi->targets;
1262
1263     if (pi->numtargets <= 90) {
1264         int xdrant = 90 / pi->numtargets;
1265         if ((tick % xdrant) == 0) {
1266             if (ptr != (ping_target *) 0) {
1267                 sendping(pi, ptr);
1268                 ptr = ptr->next;
1269             }
1270         }
1271
1272     } else if (pi->numtargets > 90) {
1273         if (ptr != (ping_target *) 0) {
1274             sendping(pi, ptr);
1275             ptr = ptr->next;
1276         }
1277     }
1278
1279     /* Get the results */
1280
1281     return getping(si, pi);
1282 }
1283
1284 #endif /* HAVE_PING */
1285
1286 /*
1287  * Calculate the difference between two timevals in microseconds.
1288  *
1289  * Args:
1290  *    then - The older timeval.
1291  *    now  - The newer timeval.
1292  *
1293  * Returns:
1294  *   The difference between the two in microseconds.
1295  */
1296
1297 static long
1298 delta(struct timeval *then, struct timeval *now) 
1299 {
1300     return (((now->tv_sec - then->tv_sec) * 1000000) + 
1301                (now->tv_usec - then->tv_usec));  
1302 }
1303
1304 /*
1305  * Initialize the simulation mode.
1306  */
1307
1308 static sim_info *
1309 init_sim(void) 
1310 {
1311
1312     /* Local Variables */
1313
1314     sim_info *si;
1315     int i;
1316
1317     /* Create the simulation info structure */
1318
1319     if ((si = (sim_info *) calloc(1, sizeof(sim_info))) == NULL) {
1320         fprintf(stderr, "%s: Out of memory\n", progname);
1321         return NULL;
1322     }
1323
1324     /* Team A */
1325
1326     si->numA = get_integer_resource("teamACount", "TeamACount");
1327     if ((si->teamA = (sim_target *)calloc(si->numA, sizeof(sim_target)))
1328         == NULL) {
1329         free(si);
1330         fprintf(stderr, "%s: Out of Memory\n", progname);
1331         return NULL;
1332     }
1333     si->teamAID = get_string_resource("teamAName", "TeamAName");
1334     for (i = 0; i < si->numA; i++) {
1335         if ((si->teamA[i].name = (char *) malloc(strlen(si->teamAID) + 4))
1336             == NULL) {
1337             free(si);
1338             fprintf(stderr, "%s: Out of Memory\n", progname);
1339             return NULL;
1340         }
1341         sprintf(si->teamA[i].name, "%s%03d", si->teamAID, i+1);
1342         si->teamA[i].nexttick = (int) (90.0 * random() / RAND_MAX);
1343         si->teamA[i].nextdist = (int) (100.0 * random() / RAND_MAX);
1344         si->teamA[i].movedonsweep = -1;
1345     }
1346
1347     /* Team B */
1348
1349     si->numB = get_integer_resource("teamBCount", "TeamBCount");
1350     if ((si->teamB = (sim_target *)calloc(si->numB, sizeof(sim_target)))
1351         == NULL) {
1352         free(si);
1353         fprintf(stderr, "%s: Out of Memory\n", progname);
1354         return NULL;
1355     }
1356     si->teamBID = get_string_resource("teamBName", "TeamBName");
1357     for (i = 0; i < si->numB; i++) {
1358         if ((si->teamB[i].name = (char *) malloc(strlen(si->teamBID) + 4))
1359             == NULL) {
1360             free(si);
1361             fprintf(stderr, "%s: Out of Memory\n", progname);
1362             return NULL;
1363         }
1364         sprintf(si->teamB[i].name, "%s%03d", si->teamBID, i+1);
1365         si->teamB[i].nexttick = (int) (90.0 * random() / RAND_MAX);
1366         si->teamB[i].nextdist = (int) (100.0 * random() / RAND_MAX);
1367         si->teamB[i].movedonsweep = -1;
1368     }
1369
1370     /* Done */
1371
1372     return si;
1373 }
1374
1375 /*
1376  * Initialize the Sonar.
1377  *
1378  * Args:
1379  *    dpy - The X display.
1380  *    win - The X window;
1381  *
1382  * Returns:
1383  *   A sonar_info strcuture or null if memory allocation problems occur.
1384  */
1385
1386 static sonar_info *
1387 init_sonar(Display *dpy, Window win) 
1388 {
1389
1390     /* Local Variables */
1391
1392     XGCValues gcv;
1393     XWindowAttributes xwa;
1394     sonar_info *si;
1395     XColor start, end;
1396     int h1, h2;
1397     double s1, s2, v1, v2;
1398
1399     /* Create the Sonar information structure */
1400
1401     if ((si = (sonar_info *) calloc(1, sizeof(sonar_info))) == NULL) {
1402         fprintf(stderr, "%s: Out of memory\n", progname);
1403         return NULL;
1404     }
1405
1406     /* Initialize the structure for the current environment */
1407
1408     si->dpy = dpy;
1409     si->win = win;
1410     si->visable = NULL;
1411     XGetWindowAttributes(dpy, win, &xwa);
1412     si->cmap = xwa.colormap;
1413     si->width = xwa.width;
1414     si->height = xwa.height;
1415     si->centrex = si->width / 2;
1416     si->centrey = si->height / 2;
1417     si->maxx = si->centrex + MY_MIN(si->centrex, si->centrey) - 10;
1418     si->minx = si->centrex - MY_MIN(si->centrex, si->centrey) + 10;
1419     si->maxy = si->centrey + MY_MIN(si->centrex, si->centrey) - 10;
1420     si->miny = si->centrey - MY_MIN(si->centrex, si->centrey) + 10;
1421     si->radius = si->maxx - si->centrex;
1422     si->current = 0;
1423     si->sweepnum = 0;
1424
1425     /* Get the font */
1426
1427     if (((si->font = XLoadQueryFont(dpy, get_string_resource ("font", "Font")))
1428          == NULL) &&
1429         ((si->font = XLoadQueryFont(dpy, "fixed")) == NULL)) {
1430         fprintf(stderr, "%s: can't load an appropriate font\n", progname);
1431         return NULL;
1432     }
1433
1434     /* Get the delay between animation frames */
1435
1436     si->delay = get_integer_resource ("delay", "Integer");
1437
1438     if (si->delay < 0) si->delay = 0;
1439     si->TTL = get_integer_resource("ttl", "TTL");
1440
1441     /* Create the Graphics Contexts that will be used to draw things */
1442
1443     gcv.foreground = 
1444         get_pixel_resource ("sweepColor", "SweepColor", dpy, si->cmap);
1445     si->hi = XCreateGC(dpy, win, GCForeground, &gcv);
1446     gcv.font = si->font->fid;
1447     si->text = XCreateGC(dpy, win, GCForeground|GCFont, &gcv);
1448     gcv.foreground = get_pixel_resource("scopeColor", "ScopeColor",
1449                                         dpy, si->cmap);
1450     si->erase = XCreateGC (dpy, win, GCForeground, &gcv);
1451     gcv.foreground = get_pixel_resource("gridColor", "GridColor",
1452                                         dpy, si->cmap);
1453     si->grid = XCreateGC (dpy, win, GCForeground, &gcv);
1454
1455     /* Compute pixel values for fading text on the display */
1456
1457     XParseColor(dpy, si->cmap, 
1458                 get_string_resource("textColor", "TextColor"), &start);
1459     XParseColor(dpy, si->cmap, 
1460                 get_string_resource("scopeColor", "ScopeColor"), &end);
1461
1462     rgb_to_hsv (start.red, start.green, start.blue, &h1, &s1, &v1);
1463     rgb_to_hsv (end.red, end.green, end.blue, &h2, &s2, &v2);
1464
1465     si->text_steps = get_integer_resource("textSteps", "TextSteps");
1466     if (si->text_steps < 0 || si->text_steps > 255)
1467       si->text_steps = 10;
1468
1469     si->text_colors = (XColor *) calloc(si->text_steps, sizeof(XColor));
1470     make_color_ramp (dpy, si->cmap,
1471                      h1, s1, v1,
1472                      h2, s2, v2,
1473                      si->text_colors, &si->text_steps,
1474                      False, True, False);
1475
1476     /* Compute the pixel values for the fading sweep */
1477
1478     XParseColor(dpy, si->cmap, 
1479                 get_string_resource("sweepColor", "SweepColor"), &start);
1480
1481     rgb_to_hsv (start.red, start.green, start.blue, &h1, &s1, &v1);
1482
1483     si->sweep_degrees = get_integer_resource("sweepDegrees", "Degrees");
1484     if (si->sweep_degrees <= 0) si->sweep_degrees = 20;
1485     if (si->sweep_degrees > 350) si->sweep_degrees = 350;
1486
1487     si->sweep_segs = get_integer_resource("sweepSegments", "SweepSegments");
1488     if (si->sweep_segs < 1 || si->sweep_segs > 255)
1489       si->sweep_segs = 255;
1490
1491     si->sweep_colors = (XColor *) calloc(si->sweep_segs, sizeof(XColor));
1492     make_color_ramp (dpy, si->cmap,
1493                      h1, s1, v1,
1494                      h2, s2, v2,
1495                      si->sweep_colors, &si->sweep_segs,
1496                      False, True, False);
1497
1498     if (si->sweep_segs <= 0)
1499       si->sweep_segs = 1;
1500
1501     /* Done */
1502
1503     return si;
1504 }
1505
1506 /*
1507  * Update the location of a simulated bogie.
1508  */
1509
1510 static void
1511 updateLocation(sim_target *t) 
1512 {
1513
1514     int xdist, xtick;
1515
1516     xtick = (int) (3.0 * random() / RAND_MAX) - 1;
1517     xdist = (int) (11.0 * random() / RAND_MAX) - 5;
1518     if (((t->nexttick + xtick) < 90) && ((t->nexttick + xtick) >= 0))
1519         t->nexttick += xtick;
1520     else
1521         t->nexttick -= xtick;
1522     if (((t->nextdist + xdist) < 100) && ((t->nextdist+xdist) >= 0))
1523         t->nextdist += xdist;
1524     else
1525         t->nextdist -= xdist;
1526 }
1527
1528 /*
1529  * The simulator. This uses information in the sim_info to simulate a bunch
1530  * of bogies flying around on the screen.
1531  */
1532
1533 /*
1534  * TODO: It would be cool to have the two teams chase each other around and
1535  *       shoot it out.
1536  */
1537
1538 static Bogie *
1539 simulator(sonar_info *si, void *vinfo) 
1540 {
1541
1542     /* Local Variables */
1543
1544     int i;
1545     Bogie *list = NULL;
1546     Bogie *new;
1547     sim_target *t;
1548     sim_info *info = (sim_info *) vinfo;
1549
1550     /* Check team A */
1551
1552     for (i = 0; i < info->numA; i++) {
1553         t = &info->teamA[i];
1554         if ((t->movedonsweep != si->sweepnum) &&
1555             (t->nexttick == (si->current * -1))) {
1556             new = newBogie(strdup(t->name), t->nextdist, si->current, si->TTL);
1557             if (list != NULL)
1558                 new->next = list;
1559             list = new;
1560             updateLocation(t);
1561             t->movedonsweep = si->sweepnum;
1562         }
1563     }
1564
1565     /* Team B */
1566
1567     for (i = 0; i < info->numB; i++) {
1568         t = &info->teamB[i];
1569         if ((t->movedonsweep != si->sweepnum) &&
1570             (t->nexttick == (si->current * -1))) {
1571             new = newBogie(strdup(t->name), t->nextdist, si->current, si->TTL);
1572             if (list != NULL)
1573                 new->next = list;
1574             list = new;
1575             updateLocation(t);
1576             t->movedonsweep = si->sweepnum;
1577         }
1578     }
1579
1580     /* Done */
1581
1582     return list;
1583 }
1584
1585 /*
1586  * Compute the X coordinate of the label.
1587  *
1588  * Args:
1589  *    si - The sonar info block.
1590  *    label - The label that will be drawn.
1591  *    x - The x coordinate of the bogie.
1592  *
1593  * Returns:
1594  *    The x coordinate of the start of the label.
1595  */
1596
1597 static int
1598 computeStringX(sonar_info *si, char *label, int x) 
1599 {
1600
1601     int width = XTextWidth(si->font, label, strlen(label));
1602     return x - (width / 2);
1603 }
1604
1605 /*
1606  * Compute the Y coordinate of the label.
1607  *
1608  * Args:
1609  *    si - The sonar information.
1610  *    y - The y coordinate of the bogie.
1611  *
1612  * Returns:
1613  *    The y coordinate of the start of the label.
1614  */
1615
1616 /* TODO: Add smarts to keep label in sonar screen */
1617
1618 static int
1619 computeStringY(sonar_info *si, int y) 
1620 {
1621
1622     int fheight = si->font->ascent + si->font->descent;
1623     return y + 5 + fheight;
1624 }
1625
1626 /*
1627  * Draw a Bogie on the radar screen.
1628  *
1629  * Args:
1630  *    si       - Sonar Information.
1631  *    draw     - A flag to indicate if the bogie should be drawn or erased.
1632  *    name     - The name of the bogie.
1633  *    degrees  - The number of degrees that it should apprear at.
1634  *    distance - The distance the object is from the centre.
1635  *    ttl      - The time this bogie has to live.
1636  *    age      - The time this bogie has been around.
1637  */
1638
1639 static void
1640 DrawBogie(sonar_info *si, int draw, char *name, int degrees, 
1641           int distance, int ttl, int age) 
1642 {
1643
1644     /* Local Variables */
1645
1646     int x, y;
1647     GC gc;
1648     int ox = si->centrex;
1649     int oy = si->centrey;
1650     int index, delta;
1651
1652     /* Compute the coordinates of the object */
1653
1654     if (distance != 0)
1655       distance = (log((double) distance) / 10.0) * si->radius;
1656     x = ox + ((double) distance * cos(4.0 * ((double) degrees)/57.29578));
1657     y = oy - ((double) distance * sin(4.0 * ((double) degrees)/57.29578));
1658
1659     /* Set up the graphics context */
1660
1661     if (draw) {
1662
1663         /* Here we attempt to compute the distance into the total life of
1664          * object that we currently are. This distance is used against
1665          * the total lifetime to compute a fraction which is the index of
1666          * the color to draw the bogie.
1667          */
1668
1669         if (si->current <= degrees)
1670             delta = (si->current - degrees) * -1;
1671         else
1672             delta = 90 + (degrees - si->current);
1673         delta += (age * 90);
1674         index = (si->text_steps - 1) * ((float) delta / (90.0 * (float) ttl));
1675         gc = si->text;
1676         XSetForeground(si->dpy, gc, si->text_colors[index].pixel);
1677
1678     } else
1679         gc = si->erase;
1680
1681   /* Draw (or erase) the Bogie */
1682
1683     XFillArc(si->dpy, si->win, gc, x, y, 5, 5, 0, 360 * 64);
1684     XDrawString(si->dpy, si->win, gc,
1685                 computeStringX(si, name, x),
1686                 computeStringY(si, y), name, strlen(name));
1687 }
1688
1689
1690 /*
1691  * Draw the sonar grid.
1692  *
1693  * Args:
1694  *    si - Sonar information block.
1695  */
1696
1697 static void
1698 drawGrid(sonar_info *si) 
1699 {
1700
1701     /* Local Variables */
1702
1703     int i;
1704     int width = si->maxx - si->minx;
1705     int height = si->maxy - si->miny;
1706   
1707     /* Draw the circles */
1708
1709     XDrawArc(si->dpy, si->win, si->grid, si->minx - 10, si->miny - 10, 
1710              width + 20, height + 20,  0, (360 * 64));
1711
1712     XDrawArc(si->dpy, si->win, si->grid, si->minx, si->miny, 
1713              width, height,  0, (360 * 64));
1714
1715     XDrawArc(si->dpy, si->win, si->grid, 
1716              (int) (si->minx + (.166 * width)), 
1717              (int) (si->miny + (.166 * height)), 
1718              (unsigned int) (.666 * width), (unsigned int)(.666 * height),
1719              0, (360 * 64));
1720
1721     XDrawArc(si->dpy, si->win, si->grid, 
1722              (int) (si->minx + (.333 * width)),
1723              (int) (si->miny + (.333 * height)), 
1724              (unsigned int) (.333 * width), (unsigned int) (.333 * height),
1725              0, (360 * 64));
1726
1727     /* Draw the radial lines */
1728
1729     for (i = 0; i < 360; i += 10)
1730         if (i % 30 == 0)
1731             XDrawLine(si->dpy, si->win, si->grid, si->centrex, si->centrey,
1732                       (int) (si->centrex +
1733                       (si->radius + 10) * (cos((double) i / 57.29578))),
1734                       (int) (si->centrey -
1735                       (si->radius + 10)*(sin((double) i / 57.29578))));
1736         else
1737             XDrawLine(si->dpy, si->win, si->grid, 
1738                       (int) (si->centrex + si->radius *
1739                              (cos((double) i / 57.29578))),
1740                       (int) (si->centrey - si->radius *
1741                              (sin((double) i / 57.29578))),
1742                       (int) (si->centrex +
1743                       (si->radius + 10) * (cos((double) i / 57.29578))),
1744                       (int) (si->centrey - 
1745                       (si->radius + 10) * (sin((double) i / 57.29578))));
1746 }
1747
1748 /*
1749  * Update the Sonar scope.
1750  *
1751  * Args:
1752  *    si - The Sonar information.
1753  *    bl - A list  of bogies to add to the scope.
1754  */
1755
1756 static void
1757 Sonar(sonar_info *si, Bogie *bl) 
1758 {
1759
1760     /* Local Variables */
1761
1762     Bogie *bp, *prev;
1763     int i;
1764
1765     /* Check for expired tagets and remove them from the visable list */
1766
1767     prev = NULL;
1768     for (bp = si->visable; bp != NULL; bp = (bp ? bp->next : 0)) {
1769
1770         /*
1771          * Remove it from the visable list if it's expired or we have
1772          * a new target with the same name.
1773          */
1774
1775         bp->age ++;
1776
1777         if (((bp->tick == si->current) && (++bp->age >= bp->ttl)) ||
1778             (findNode(bl, bp->name) != NULL)) {
1779             DrawBogie(si, 0, bp->name, bp->tick,
1780                       bp->distance, bp->ttl, bp->age);
1781             if (prev == NULL)
1782                 si->visable = bp->next;
1783             else
1784                 prev->next = bp->next;
1785             freeBogie(bp);
1786             bp = prev;
1787         } else
1788             prev = bp;
1789     }
1790
1791     /* Draw the sweep */
1792
1793     {
1794       int seg_deg = (si->sweep_degrees * 64) / si->sweep_segs;
1795       int start_deg = si->current * 4 * 64;
1796       if (seg_deg <= 0) seg_deg = 1;
1797       for (i = 0; i < si->sweep_segs; i++) {
1798         XSetForeground(si->dpy, si->hi, si->sweep_colors[i].pixel);
1799         XFillArc(si->dpy, si->win, si->hi, si->minx, si->miny, 
1800                  si->maxx - si->minx, si->maxy - si->miny,
1801                  start_deg + (i * seg_deg),
1802                  seg_deg);
1803       }
1804
1805       /* Remove the trailing wedge the sonar */
1806       XFillArc(si->dpy, si->win, si->erase, si->minx, si->miny, 
1807                si->maxx - si->minx, si->maxy - si->miny, 
1808                start_deg + (i * seg_deg),
1809                (4 * 64));
1810     }
1811
1812     /* Move the new targets to the visable list */
1813
1814     for (bp = bl; bp != (Bogie *) 0; bp = bl) {
1815         bl = bl->next;
1816         bp->next = si->visable;
1817         si->visable = bp;
1818     }
1819
1820     /* Draw the visable targets */
1821
1822     for (bp = si->visable; bp != NULL; bp = bp->next) {
1823         if (bp->age < bp->ttl)          /* grins */
1824            DrawBogie(si, 1, bp->name, bp->tick, bp->distance, bp->ttl,bp->age);
1825     }
1826
1827     /* Redraw the grid */
1828
1829     drawGrid(si);
1830 }
1831
1832
1833 static ping_target *
1834 parse_mode (Bool ping_works_p)
1835 {
1836   char *source = get_string_resource ("ping", "Ping");
1837   char *token, *end;
1838
1839   ping_target *hostlist = 0;
1840
1841   if (!source) source = strdup("");
1842
1843   if (!*source || !strcmp (source, "default"))
1844     {
1845 # ifdef HAVE_PING
1846       if (ping_works_p)         /* if root or setuid, ping will work. */
1847         source = strdup("subnet/29,/etc/hosts");
1848       else
1849 # endif
1850         source = strdup("simulation");
1851     }
1852
1853   token = source;
1854   end = source + strlen(source);
1855   while (token < end)
1856     {
1857       char *next;
1858 # ifdef HAVE_PING
1859       ping_target *new;
1860       struct stat st;
1861       unsigned int n0=0, n1=0, n2=0, n3=0, m=0;
1862       char d;
1863 # endif /* HAVE_PING */
1864
1865       for (next = token;
1866            *next != ',' && *next != ' ' && *next != '\t' && *next != '\n';
1867            next++)
1868         ;
1869       *next = 0;
1870
1871
1872       if (debug_p)
1873         fprintf (stderr, "%s: parsing %s\n", progname, token);
1874
1875       if (!strcmp (token, "simulation"))
1876         return 0;
1877
1878       if (!ping_works_p)
1879         {
1880           fprintf(stderr,
1881            "%s: this program must be setuid to root for `ping mode' to work.\n"
1882              "       Running in `simulation mode' instead.\n",
1883                   progname);
1884           return 0;
1885         }
1886
1887 #ifdef HAVE_PING
1888       if ((4 == sscanf (token, "%d.%d.%d/%d %c",    &n0,&n1,&n2,    &m,&d)) ||
1889           (5 == sscanf (token, "%d.%d.%d.%d/%d %c", &n0,&n1,&n2,&n3,&m,&d)))
1890         {
1891           /* subnet: A.B.C.D/M
1892              subnet: A.B.C/M
1893            */
1894           unsigned long ip = (n0 << 24) | (n1 << 16) | (n2 << 8) | n3;
1895           new = subnetHostsList(ip, m);
1896         }
1897       else if (4 == sscanf (token, "%d.%d.%d.%d %c", &n0, &n1, &n2, &n3, &d))
1898         {
1899           /* IP: A.B.C.D
1900            */
1901           new = newHost (token);
1902         }
1903       else if (!strcmp (token, "subnet"))
1904         {
1905           new = subnetHostsList(0, 24);
1906         }
1907       else if (1 == sscanf (token, "subnet/%d %c", &m))
1908         {
1909           new = subnetHostsList(0, m);
1910         }
1911       else if (*token == '.' || *token == '/' || !stat (token, &st))
1912         {
1913           /* file name
1914            */
1915           new = readPingHostsFile (token);
1916         }
1917       else
1918         {
1919           /* not an existant file - must be a host name
1920            */
1921           new = newHost (token);
1922         }
1923
1924       if (new)
1925         {
1926           ping_target *nn = new;
1927           while (nn && nn->next)
1928             nn = nn->next;
1929           nn->next = hostlist;
1930           hostlist = new;
1931
1932           sensor = ping;
1933         }
1934 #endif /* HAVE_PING */
1935
1936       token = next + 1;
1937       while (token < end &&
1938              (*token == ',' || *token == ' ' ||
1939               *token == '\t' || *token == '\n'))
1940         token++;
1941     }
1942
1943   return hostlist;
1944 }
1945
1946
1947
1948 /*
1949  * Main screen saver hack.
1950  *
1951  * Args:
1952  *    dpy - The X display.
1953  *    win - The X window.
1954  */
1955
1956 void 
1957 screenhack(Display *dpy, Window win) 
1958 {
1959
1960     /* Local Variables */
1961
1962     sonar_info *si;
1963     struct timeval start, finish;
1964     Bogie *bl;
1965     long sleeptime;
1966
1967     debug_p = get_boolean_resource ("debug", "Debug");
1968
1969     sensor = 0;
1970 # ifdef HAVE_PING
1971     sensor_info = (void *) init_ping();
1972 # else  /* !HAVE_PING */
1973     sensor_info = 0;
1974     parse_mode (0);  /* just to check argument syntax */
1975 # endif /* !HAVE_PING */
1976
1977     if (sensor == 0)
1978       {
1979         sensor = simulator;
1980         if ((sensor_info = (void *) init_sim()) == NULL)
1981           exit(1);
1982       }
1983
1984     if ((si = init_sonar(dpy, win)) == (sonar_info *) 0)
1985         exit(1);
1986
1987
1988     /* Sonar loop */
1989
1990     while (1) {
1991
1992         /* Call the sensor and display the results */
1993
1994         gettimeofday(&start, (struct timezone *) 0);
1995         bl = sensor(si, sensor_info);
1996         Sonar(si, bl);
1997
1998         /* Set up and sleep for the next one */
1999
2000         si->current = (si->current - 1) % 90;
2001         if (si->current == 0)
2002           si->sweepnum++;
2003         XSync (dpy, False);
2004         gettimeofday(&finish, (struct timezone *) 0);
2005         sleeptime = si->delay - delta(&start, &finish);
2006         screenhack_handle_events (dpy);
2007         if (sleeptime > 0L)
2008             usleep(sleeptime);
2009
2010     }
2011 }