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