http://packetstormsecurity.org/UNIX/admin/xscreensaver-3.34.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, 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
452   struct hostent *hent;
453
454     /* Local Variables */
455
456     struct sockaddr_in *iaddr;
457
458     /* Set up the target address we first assume that the name is the
459        IP address as a string */
460
461     iaddr = (struct sockaddr_in *) &(target->address);
462     iaddr->sin_family = AF_INET;
463     if ((iaddr->sin_addr.s_addr = inet_addr(target->name)) >= 0) {
464       char ip[4];
465       ip[3] = iaddr->sin_addr.s_addr >> 24 & 255;
466       ip[2] = iaddr->sin_addr.s_addr >> 16 & 255;
467       ip[1] = iaddr->sin_addr.s_addr >>  8 & 255;
468       ip[0] = iaddr->sin_addr.s_addr       & 255;
469       hent = gethostbyaddr (ip, 4, AF_INET);
470       if (hent && hent->h_name && *hent->h_name) {
471         target->name = strdup (hent->h_name);
472         return 1;
473       }
474     }
475
476     /* Conversion of IP address failed, try to look the host up by name */
477
478     hent = gethostbyname(target->name);
479     if (hent == NULL) {
480       fprintf(stderr, "%s: could not resolve host %s\n",
481               progname, target->name);
482       return 0;
483     }
484     memcpy(&iaddr->sin_addr, hent->h_addr_list[0],
485            sizeof(iaddr->sin_addr));
486
487     /* Done */
488
489     return 1;
490 }
491
492 /*
493  * Create a target for a host.
494  *
495  * Args:
496  *    name - The name of the host.
497  *
498  * Returns:
499  *    A newly allocated target or null if the host could not be resolved.
500  */
501
502 static ping_target *
503 newHost(char *name) 
504 {
505
506     /* Local Variables */
507
508     ping_target *target = NULL;
509
510     /* Create the target */
511
512     if ((target = calloc(1, sizeof(ping_target))) == NULL) {
513         fprintf(stderr, "%s: Out of Memory\n", progname);
514         goto target_init_error;
515     }
516     if ((target->name = strdup(name)) == NULL) {
517         fprintf(stderr, "%s: Out of Memory\n", progname);
518         goto target_init_error;
519     }
520
521     /* Lookup the host */
522
523     if (! lookupHost(target))
524         goto target_init_error;
525
526     /* Done */
527
528     if (debug_p)
529       {
530         struct sockaddr_in *iaddr = (struct sockaddr_in *) &(target->address);
531         unsigned long ip = iaddr->sin_addr.s_addr;
532         fprintf (stderr, "%s:   added host %d.%d.%d.%d (%s)\n", progname,
533                  ip & 255, ip >> 8 & 255, ip >> 16 & 255, ip >> 24 & 255, 
534                  target->name);
535       }
536
537     return target;
538
539     /* Handle errors here */
540
541 target_init_error:
542     if (target != NULL)
543         free(target);
544     return NULL;
545 }
546
547 /*
548  * Generate a list of ping targets from the entries in a file.
549  *
550  * Args:
551  *    fname - The name of the file. This file is expected to be in the same
552  *            format as /etc/hosts.
553  *
554  * Returns:
555  *    A list of targets to ping or null if an error occured.
556  */
557
558 static ping_target *
559 readPingHostsFile(char *fname) 
560 {
561     /* Local Variables */
562
563     FILE *fp;
564     char buf[LINE_MAX];
565     char *p;
566     ping_target *list = NULL;
567     char *addr, *name;
568     ping_target *new;
569
570     /* Make sure we in fact have a file to process */
571
572     if ((fname == NULL) || (fname[0] == '\0')) {
573         fprintf(stderr, "%s: invalid ping host file name\n", progname);
574         return NULL;
575     }
576
577     /* Open the file */
578
579     if ((fp = fopen(fname, "r")) == NULL) {
580         char msg[1024];
581         sprintf(msg, "%s: unable to open host file %s", progname, fname);
582         perror(msg);
583         return NULL;
584     }
585
586     if (debug_p)
587       fprintf (stderr, "%s:  reading file %s\n", progname, fname);
588
589     /* Read the file line by line */
590
591     while ((p = fgets(buf, LINE_MAX, fp)) != NULL) {
592
593         /*
594          * Parse the line skipping those that start with '#'.
595          * The rest of the lines in the file should be in the same
596          * format as a /etc/hosts file. We are only concerned with
597          * the first two field, the IP address and the name
598          */
599
600         while ((*p == ' ') || (*p == '\t'))
601             p++;
602         if (*p == '#')
603             continue;
604
605         /* Get the name and address */
606
607         name = addr = NULL;
608         if ((addr = strtok(buf, " \t\n")) != NULL)
609             name = strtok(NULL, " \t\n");
610         else
611             continue;
612
613         /* Check to see if the addr looks like an addr.  If not, assume
614            the addr is a name and there is no addr.  This way, we can
615            handle files whose lines have "xx.xx.xx.xx hostname" as their
616            first two tokens, and also files that have a hostname as their
617            first token (like .ssh/known_hosts and .rhosts.)
618          */
619         {
620           int i; char c;
621           if (4 != sscanf(addr, "%d.%d.%d.%d%c", &i, &i, &i, &i, &c))
622             {
623               name = addr;
624               addr = NULL;
625             }
626         }
627         /*printf ("\"%s\" \"%s\"\n", name, addr);*/
628
629         /* Create a new target using first the name then the address */
630
631         new = NULL;
632         if (name != NULL)
633             new = newHost(name);
634         if (new == NULL && addr != NULL)
635             new = newHost(addr);
636
637         /* Add it to the list if we got one */
638
639         if (new != NULL) {
640             new->next = list;
641             list = new;
642         }
643     }
644
645     /* Close the file and return the list */
646
647     fclose(fp);
648     return list;
649 }
650
651
652 static ping_target *
653 delete_duplicate_hosts (ping_target *list)
654 {
655   ping_target *head = list;
656   ping_target *rest;
657
658   for (rest = head; rest; rest = rest->next)
659     {
660       struct sockaddr_in *i1 = (struct sockaddr_in *) &(rest->address);
661       unsigned long ip1 = i1->sin_addr.s_addr;
662
663       static ping_target *rest2;
664       for (rest2 = rest; rest2; rest2 = rest2->next)
665         {
666           if (rest2 && rest2->next)
667             {
668               struct sockaddr_in *i2 = (struct sockaddr_in *)
669                 &(rest2->next->address);
670               unsigned long ip2 = i2->sin_addr.s_addr;
671
672               if (ip1 == ip2)
673                 {
674                   if (debug_p)
675                     fprintf (stderr, "%s: deleted duplicate: %s\n",
676                              progname, rest2->next->name);
677                   rest2->next = rest2->next->next;
678                 }
679             }
680         }
681     }
682
683   return head;
684 }
685
686
687
688
689 /*
690  * Generate a list ping targets consisting of all of the entries on
691  * the same subnet.
692  *
693  * Returns:
694  *    A list of all of the hosts on this net.
695  */
696
697 static ping_target *
698 subnetHostsList(int base, int subnet_width) 
699 {
700     unsigned long mask;
701
702     /* Local Variables */
703
704     char hostname[BUFSIZ];
705     char address[BUFSIZ];
706     struct hostent *hent;
707     char *p;
708     int i;
709     ping_target *new;
710     ping_target *list = NULL;
711
712     if (subnet_width < 24)
713       {
714         fprintf (stderr,
715     "%s: pinging %u hosts is a bad idea; please use a subnet mask of 24 bits\n"
716                  "       or more (255 hosts max.)\n",
717                  progname, (1L << (32 - subnet_width)) - 1);
718         exit (1);
719       }
720     else if (subnet_width > 30)
721       {
722         fprintf (stderr, "%s: a subnet of %d bits doesn't make sense:"
723                  " try \"subnet/24\" or \"subnet/29\".\n",
724                  progname, subnet_width);
725         exit (1);
726       }
727
728
729     if (debug_p)
730       fprintf (stderr, "%s:   adding %d-bit subnet\n", progname, subnet_width);
731
732     /* Get our hostname */
733
734     if (gethostname(hostname, BUFSIZ)) {
735         fprintf(stderr, "%s: unable to get local hostname\n", progname);
736         return NULL;
737     }
738
739     /* Get our IP address and convert it to a string */
740
741     if ((hent = gethostbyname(hostname)) == NULL) {
742         fprintf(stderr, "%s: unable to lookup our IP address\n", progname);
743         return NULL;
744     }
745     strcpy(address, inet_ntoa(*((struct in_addr *)hent->h_addr_list[0])));
746
747     /* Construct targets for all addresses in this subnet */
748
749     mask = 0;
750     for (i = 0; i < subnet_width; i++)
751       mask |= (1L << (31-i));
752
753     /* If no base IP specified, assume localhost. */
754     if (base == 0)
755       base = ((((unsigned char) hent->h_addr_list[0][0]) << 24) |
756               (((unsigned char) hent->h_addr_list[0][1]) << 16) |
757               (((unsigned char) hent->h_addr_list[0][2]) <<  8) |
758               (((unsigned char) hent->h_addr_list[0][3])));
759
760     for (i = 255; i >= 0; i--) {
761         int ip = (base & 0xFFFFFF00) | i;
762       
763         if ((ip & mask) != (base & mask))   /* not in the mask range at all */
764           continue;
765         if ((ip & ~mask) == 0)              /* broadcast address */
766           continue;
767         if ((ip & ~mask) == ~mask)          /* broadcast address */
768           continue;
769
770         sprintf (address, "%d.%d.%d.%d", 
771                  (ip>>24)&255, (ip>>16)&255, (ip>>8)&255, (ip)&255);
772
773         if (debug_p > 1)
774           fprintf(stderr, "%s:  subnet: %s (%d.%d.%d.%d & %d.%d.%d.%d / %d)\n",
775                   progname,
776                   address,
777                   (base>>24)&255, (base>>16)&255, (base>>8)&255, base&mask&255,
778                   (mask>>24)&255, (mask>>16)&255, (mask>>8)&255, mask&255,
779                   subnet_width);
780
781         p = address + strlen(address) + 1;
782         sprintf(p, "%d", i);
783
784         new = newHost(address);
785         if (new != NULL) {
786             new->next = list;
787             list = new;
788         }
789     }
790
791     /* Done */
792
793     return list;
794 }
795
796 /*
797  * Initialize the ping sensor.
798  *
799  * Returns:
800  *    A newly allocated ping_info structure or null if an error occured.
801  */
802
803 static ping_target *parse_mode (Bool ping_works_p);
804
805 static ping_info *
806 init_ping(void) 
807 {
808
809   Bool socket_initted_p = False;
810
811     /* Local Variables */
812
813     ping_info *pi = NULL;               /* The new ping_info struct */
814     ping_target *pt;                    /* Used to count the targets */
815
816     /* Create the ping info structure */
817
818     if ((pi = (ping_info *) calloc(1, sizeof(ping_info))) == NULL) {
819         fprintf(stderr, "%s: Out of memory\n", progname);
820         goto ping_init_error;
821     }
822
823     /* Create the ICMP socket */
824
825     if ((pi->icmpsock = socket(AF_INET, SOCK_RAW, IPPROTO_ICMP)) >= 0) {
826       socket_initted_p = True;
827     }
828
829     /* Disavow privs */
830
831     setuid(getuid());
832
833
834     pi->pid = getpid() & 0xFFFF;
835     pi->seq = 0;
836     pi->timeout = get_integer_resource("pingTimeout", "PingTimeout");
837
838     /* Generate a list of targets */
839
840     pi->targets = parse_mode (socket_initted_p);
841     pi->targets = delete_duplicate_hosts (pi->targets);
842
843
844     /* Make sure there is something to ping */
845
846     if (pi->targets == NULL) {
847       goto ping_init_error;
848     }
849
850     /* Count the targets */
851
852     pt = pi->targets;
853     pi->numtargets = 0;
854     while (pt != NULL) {
855         pi->numtargets++;
856         pt = pt->next;
857     }
858
859     /* Done */
860
861     return pi;
862
863     /* Handle initialization errors here */
864
865 ping_init_error:
866     if (pi != NULL)
867         free(pi);
868     return NULL;
869 }
870
871
872 /*
873  * Ping a host.
874  *
875  * Args:
876  *    pi   - The ping information strcuture.
877  *    host - The name or IP address of the host to ping (in ascii).
878  */
879
880 static void
881 sendping(ping_info *pi, ping_target *pt) 
882 {
883
884     /* Local Variables */
885
886     u_char *packet;
887     struct ICMP *icmph;
888     int result;
889
890     /*
891      * Note, we will send the character name of the host that we are
892      * pinging in the packet so that we don't have to keep track of the
893      * name or do an address lookup when it comes back.
894      */
895
896     int pcktsiz = sizeof(struct ICMP) + sizeof(struct timeval) +
897         strlen(pt->name) + 1;
898
899     /* Create the ICMP packet */
900
901     if ((packet = (u_char *) malloc(pcktsiz)) == (void *) 0)
902         return;  /* Out of memory */
903     icmph = (struct ICMP *) packet;
904     ICMP_TYPE(icmph) = ICMP_ECHO;
905     ICMP_CODE(icmph) = 0;
906     ICMP_CHECKSUM(icmph) = 0;
907     ICMP_ID(icmph) = pi->pid;
908     ICMP_SEQ(icmph) = pi->seq++;
909     gettimeofday((struct timeval *) &packet[sizeof(struct ICMP)],
910                  (struct timezone *) 0);
911     strcpy((char *) &packet[sizeof(struct ICMP) + sizeof(struct timeval)],
912            pt->name);
913     ICMP_CHECKSUM(icmph) = checksum((u_short *)packet, pcktsiz);
914
915     /* Send it */
916
917     if ((result = sendto(pi->icmpsock, packet, pcktsiz, 0, 
918                          &pt->address, sizeof(pt->address))) !=  pcktsiz) {
919 #if 0
920         char errbuf[BUFSIZ];
921         sprintf(errbuf, "%s: error sending ping to %s", progname, pt->name);
922         perror(errbuf);
923 #endif
924     }
925 }
926
927 /*
928  * Catch a signal and do nothing.
929  *
930  * Args:
931  *    sig - The signal that was caught.
932  */
933
934 static void
935 sigcatcher(int sig)
936 {
937     timer_expired = 1;
938 }
939
940 /*
941  * Compute the checksum on a ping packet.
942  *
943  * Args:
944  *    packet - A pointer to the packet to compute the checksum for.
945  *    size   - The size of the packet.
946  *
947  * Returns:
948  *    The computed checksum
949  *    
950  */
951
952 static u_short
953 checksum(u_short *packet, int size) 
954 {
955
956     /* Local Variables */
957
958     register int nleft = size;
959     register u_short *w = packet;
960     register int sum = 0;
961     u_short answer = 0;
962
963     /*
964      * Our algorithm is simple, using a 32 bit accumulator (sum), we add
965      * sequential 16 bit words to it, and at the end, fold back all the
966      * carry bits from the top 16 bits into the lower 16 bits.
967      */
968
969     while (nleft > 1)  {
970         sum += *w++;
971         nleft -= 2;
972     }
973
974     /* mop up an odd byte, if necessary */
975
976     if (nleft == 1) {
977         *(u_char *)(&answer) = *(u_char *)w ;
978         *(1 + (u_char *)(&answer)) = 0;
979         sum += answer;
980     }
981
982     /* add back carry outs from top 16 bits to low 16 bits */
983
984     sum = (sum >> 16) + (sum & 0xffff);     /* add hi 16 to low 16 */
985     sum += (sum >> 16);                     /* add carry */
986     answer = ~sum;                          /* truncate to 16 bits */
987
988     /* Done */
989
990     return(answer);
991 }
992
993 /*
994  * Look for ping replies.
995  *
996  * Retrieve all outstanding ping replies.
997  *
998  * Args:
999  *    si - Information about the sonar.
1000  *    pi - Ping information.
1001  *    ttl - The time each bogie is to live on the screen
1002  *
1003  * Returns:
1004  *    A Bogie list of all the machines that replied.
1005  */
1006
1007 static Bogie *
1008 getping(sonar_info *si, ping_info *pi) 
1009 {
1010
1011     /* Local Variables */
1012
1013     struct sockaddr from;
1014     int fromlen;
1015     int result;
1016     u_char packet[1024];
1017     struct timeval now;
1018     struct timeval *then;
1019     struct ip *ip;
1020     int iphdrlen;
1021     struct ICMP *icmph;
1022     Bogie *bl = NULL;
1023     Bogie *new;
1024     char *name;
1025     struct sigaction sa;
1026     struct itimerval it;
1027     fd_set rfds;
1028     struct timeval tv;
1029
1030     /* Set up a signal to interupt our wait for a packet */
1031
1032     sigemptyset(&sa.sa_mask);
1033     sa.sa_flags = 0;
1034     sa.sa_handler = sigcatcher;
1035     if (sigaction(SIGALRM, &sa, 0) == -1) {
1036         char msg[1024];
1037         sprintf(msg, "%s: unable to trap SIGALRM", progname);
1038         perror(msg);
1039         exit(1);
1040     }
1041
1042     /* Set up a timer to interupt us if we don't get a packet */
1043
1044     it.it_interval.tv_sec = 0;
1045     it.it_interval.tv_usec = 0;
1046     it.it_value.tv_sec = 0;
1047     it.it_value.tv_usec = pi->timeout;
1048     timer_expired = 0;
1049     setitimer(ITIMER_REAL, &it, NULL);
1050
1051     /* Wait for a result packet */
1052
1053     fromlen = sizeof(from);
1054     while (! timer_expired) {
1055       tv.tv_usec=pi->timeout;
1056       tv.tv_sec=0;
1057       FD_ZERO(&rfds);
1058       FD_SET(pi->icmpsock,&rfds);
1059       /* only wait a little while, in case we raced with the timer expiration.
1060          From Valentijn Sessink <valentyn@openoffice.nl> */
1061       if (select(pi->icmpsock+1, &rfds, NULL, NULL, &tv) >0) {
1062         result = recvfrom(pi->icmpsock, packet, sizeof(packet),
1063                       0, &from, &fromlen);
1064
1065         /* Check the packet */
1066
1067         gettimeofday(&now, (struct timezone *) 0);
1068         ip = (struct ip *) packet;
1069         iphdrlen = IP_HDRLEN(ip) << 2;
1070         icmph = (struct ICMP *) &packet[iphdrlen];
1071
1072         /* Was the packet a reply?? */
1073
1074         if (ICMP_TYPE(icmph) != ICMP_ECHOREPLY) {
1075             /* Ignore anything but ICMP Replies */
1076             continue; /* Nope */
1077         }
1078
1079         /* Was it for us? */
1080
1081         if (ICMP_ID(icmph) != pi->pid) {
1082             /* Ignore packets not set from us */
1083             continue; /* Nope */
1084         }
1085
1086         /* Copy the name of the bogie */
1087
1088         if ((name =
1089              strdup((char *) &packet[iphdrlen + 
1090                                     + sizeof(struct ICMP)
1091                                     + sizeof(struct timeval)])) == NULL) {
1092             fprintf(stderr, "%s: Out of memory\n", progname);
1093             return bl;
1094         }
1095
1096         /* If the name is an IP addr, try to resolve it. */
1097         {
1098           int iip[4];
1099           char c;
1100           if (4 == sscanf(name, " %d.%d.%d.%d %c",
1101                           &iip[0], &iip[1], &iip[2], &iip[3], &c))
1102             {
1103               unsigned char ip[4];
1104               struct hostent *h;
1105               ip[0] = iip[0]; ip[1] = iip[1]; ip[2] = iip[2]; ip[3] = iip[3];
1106               h = gethostbyaddr ((char *) ip, 4, AF_INET);
1107               if (h && h->h_name && *h->h_name)
1108                 {
1109                   free (name);
1110                   name = strdup (h->h_name);
1111                 }
1112             }
1113         }
1114
1115         /* Create the new Bogie and add it to the list we are building */
1116
1117         if ((new = newBogie(name, 0, si->current, si->TTL)) == NULL)
1118             return bl;
1119         new->next = bl;
1120         bl = new;
1121
1122         /* Compute the round trip time */
1123
1124         then =  (struct timeval *) &packet[iphdrlen +
1125                                           sizeof(struct ICMP)];
1126         new->distance = delta(then, &now) / 100;
1127         if (new->distance == 0)
1128                 new->distance = 2; /* HACK */
1129       }
1130     }
1131
1132     /* Done */
1133
1134     return bl;
1135 }
1136
1137 /*
1138  * Ping hosts.
1139  *
1140  * Args:
1141  *    si - Sonar Information.
1142  *    pi - Ping Information.
1143  *
1144  * Returns:
1145  *    A list of hosts that replied to pings or null if there were none.
1146  */
1147
1148 static Bogie *
1149 ping(sonar_info *si, void *vpi) 
1150 {
1151
1152     /*
1153      * This tries to distribute the targets evely around the field of the
1154      * sonar.
1155      */
1156
1157     ping_info *pi = (ping_info *) vpi;
1158     static ping_target *ptr = NULL;
1159
1160     int tick = si->current * -1 + 1;
1161     if ((ptr == NULL) && (tick == 1))
1162         ptr = pi->targets;
1163
1164     if (pi->numtargets <= 90) {
1165         int xdrant = 90 / pi->numtargets;
1166         if ((tick % xdrant) == 0) {
1167             if (ptr != (ping_target *) 0) {
1168                 sendping(pi, ptr);
1169                 ptr = ptr->next;
1170             }
1171         }
1172
1173     } else if (pi->numtargets > 90) {
1174         if (ptr != (ping_target *) 0) {
1175             sendping(pi, ptr);
1176             ptr = ptr->next;
1177         }
1178     }
1179
1180     /* Get the results */
1181
1182     return getping(si, pi);
1183 }
1184
1185 #endif /* HAVE_PING */
1186
1187 /*
1188  * Calculate the difference between two timevals in microseconds.
1189  *
1190  * Args:
1191  *    then - The older timeval.
1192  *    now  - The newer timeval.
1193  *
1194  * Returns:
1195  *   The difference between the two in microseconds.
1196  */
1197
1198 static long
1199 delta(struct timeval *then, struct timeval *now) 
1200 {
1201     return (((now->tv_sec - then->tv_sec) * 1000000) + 
1202                (now->tv_usec - then->tv_usec));  
1203 }
1204
1205 /*
1206  * Initialize the simulation mode.
1207  */
1208
1209 static sim_info *
1210 init_sim(void) 
1211 {
1212
1213     /* Local Variables */
1214
1215     sim_info *si;
1216     int i;
1217
1218     /* Create the simulation info structure */
1219
1220     if ((si = (sim_info *) calloc(1, sizeof(sim_info))) == NULL) {
1221         fprintf(stderr, "%s: Out of memory\n", progname);
1222         return NULL;
1223     }
1224
1225     /* Team A */
1226
1227     si->numA = get_integer_resource("teamACount", "TeamACount");
1228     if ((si->teamA = (sim_target *)calloc(si->numA, sizeof(sim_target)))
1229         == NULL) {
1230         free(si);
1231         fprintf(stderr, "%s: Out of Memory\n", progname);
1232         return NULL;
1233     }
1234     si->teamAID = get_string_resource("teamAName", "TeamAName");
1235     for (i = 0; i < si->numA; i++) {
1236         if ((si->teamA[i].name = (char *) malloc(strlen(si->teamAID) + 4))
1237             == NULL) {
1238             free(si);
1239             fprintf(stderr, "%s: Out of Memory\n", progname);
1240             return NULL;
1241         }
1242         sprintf(si->teamA[i].name, "%s%03d", si->teamAID, i+1);
1243         si->teamA[i].nexttick = (int) (90.0 * random() / RAND_MAX);
1244         si->teamA[i].nextdist = (int) (100.0 * random() / RAND_MAX);
1245         si->teamA[i].movedonsweep = -1;
1246     }
1247
1248     /* Team B */
1249
1250     si->numB = get_integer_resource("teamBCount", "TeamBCount");
1251     if ((si->teamB = (sim_target *)calloc(si->numB, sizeof(sim_target)))
1252         == NULL) {
1253         free(si);
1254         fprintf(stderr, "%s: Out of Memory\n", progname);
1255         return NULL;
1256     }
1257     si->teamBID = get_string_resource("teamBName", "TeamBName");
1258     for (i = 0; i < si->numB; i++) {
1259         if ((si->teamB[i].name = (char *) malloc(strlen(si->teamBID) + 4))
1260             == NULL) {
1261             free(si);
1262             fprintf(stderr, "%s: Out of Memory\n", progname);
1263             return NULL;
1264         }
1265         sprintf(si->teamB[i].name, "%s%03d", si->teamBID, i+1);
1266         si->teamB[i].nexttick = (int) (90.0 * random() / RAND_MAX);
1267         si->teamB[i].nextdist = (int) (100.0 * random() / RAND_MAX);
1268         si->teamB[i].movedonsweep = -1;
1269     }
1270
1271     /* Done */
1272
1273     return si;
1274 }
1275
1276 /*
1277  * Initialize the Sonar.
1278  *
1279  * Args:
1280  *    dpy - The X display.
1281  *    win - The X window;
1282  *
1283  * Returns:
1284  *   A sonar_info strcuture or null if memory allocation problems occur.
1285  */
1286
1287 static sonar_info *
1288 init_sonar(Display *dpy, Window win) 
1289 {
1290
1291     /* Local Variables */
1292
1293     XGCValues gcv;
1294     XWindowAttributes xwa;
1295     sonar_info *si;
1296     XColor start, end;
1297     int h1, h2;
1298     double s1, s2, v1, v2;
1299
1300     /* Create the Sonar information structure */
1301
1302     if ((si = (sonar_info *) calloc(1, sizeof(sonar_info))) == NULL) {
1303         fprintf(stderr, "%s: Out of memory\n", progname);
1304         return NULL;
1305     }
1306
1307     /* Initialize the structure for the current environment */
1308
1309     si->dpy = dpy;
1310     si->win = win;
1311     si->visable = NULL;
1312     XGetWindowAttributes(dpy, win, &xwa);
1313     si->cmap = xwa.colormap;
1314     si->width = xwa.width;
1315     si->height = xwa.height;
1316     si->centrex = si->width / 2;
1317     si->centrey = si->height / 2;
1318     si->maxx = si->centrex + MY_MIN(si->centrex, si->centrey) - 10;
1319     si->minx = si->centrex - MY_MIN(si->centrex, si->centrey) + 10;
1320     si->maxy = si->centrey + MY_MIN(si->centrex, si->centrey) - 10;
1321     si->miny = si->centrey - MY_MIN(si->centrex, si->centrey) + 10;
1322     si->radius = si->maxx - si->centrex;
1323     si->current = 0;
1324     si->sweepnum = 0;
1325
1326     /* Get the font */
1327
1328     if (((si->font = XLoadQueryFont(dpy, get_string_resource ("font", "Font")))
1329          == NULL) &&
1330         ((si->font = XLoadQueryFont(dpy, "fixed")) == NULL)) {
1331         fprintf(stderr, "%s: can't load an appropriate font\n", progname);
1332         return NULL;
1333     }
1334
1335     /* Get the delay between animation frames */
1336
1337     si->delay = get_integer_resource ("delay", "Integer");
1338
1339     if (si->delay < 0) si->delay = 0;
1340     si->TTL = get_integer_resource("ttl", "TTL");
1341
1342     /* Create the Graphics Contexts that will be used to draw things */
1343
1344     gcv.foreground = 
1345         get_pixel_resource ("sweepColor", "SweepColor", dpy, si->cmap);
1346     si->hi = XCreateGC(dpy, win, GCForeground, &gcv);
1347     gcv.font = si->font->fid;
1348     si->text = XCreateGC(dpy, win, GCForeground|GCFont, &gcv);
1349     gcv.foreground = get_pixel_resource("scopeColor", "ScopeColor",
1350                                         dpy, si->cmap);
1351     si->erase = XCreateGC (dpy, win, GCForeground, &gcv);
1352     gcv.foreground = get_pixel_resource("gridColor", "GridColor",
1353                                         dpy, si->cmap);
1354     si->grid = XCreateGC (dpy, win, GCForeground, &gcv);
1355
1356     /* Compute pixel values for fading text on the display */
1357
1358     XParseColor(dpy, si->cmap, 
1359                 get_string_resource("textColor", "TextColor"), &start);
1360     XParseColor(dpy, si->cmap, 
1361                 get_string_resource("scopeColor", "ScopeColor"), &end);
1362
1363     rgb_to_hsv (start.red, start.green, start.blue, &h1, &s1, &v1);
1364     rgb_to_hsv (end.red, end.green, end.blue, &h2, &s2, &v2);
1365
1366     si->text_steps = get_integer_resource("textSteps", "TextSteps");
1367     if (si->text_steps < 0 || si->text_steps > 255)
1368       si->text_steps = 10;
1369
1370     si->text_colors = (XColor *) calloc(si->text_steps, sizeof(XColor));
1371     make_color_ramp (dpy, si->cmap,
1372                      h1, s1, v1,
1373                      h2, s2, v2,
1374                      si->text_colors, &si->text_steps,
1375                      False, True, False);
1376
1377     /* Compute the pixel values for the fading sweep */
1378
1379     XParseColor(dpy, si->cmap, 
1380                 get_string_resource("sweepColor", "SweepColor"), &start);
1381
1382     rgb_to_hsv (start.red, start.green, start.blue, &h1, &s1, &v1);
1383
1384     si->sweep_degrees = get_integer_resource("sweepDegrees", "Degrees");
1385     if (si->sweep_degrees <= 0) si->sweep_degrees = 20;
1386     if (si->sweep_degrees > 350) si->sweep_degrees = 350;
1387
1388     si->sweep_segs = get_integer_resource("sweepSegments", "SweepSegments");
1389     if (si->sweep_segs < 1 || si->sweep_segs > 255)
1390       si->sweep_segs = 255;
1391
1392     si->sweep_colors = (XColor *) calloc(si->sweep_segs, sizeof(XColor));
1393     make_color_ramp (dpy, si->cmap,
1394                      h1, s1, v1,
1395                      h2, s2, v2,
1396                      si->sweep_colors, &si->sweep_segs,
1397                      False, True, False);
1398
1399     /* Done */
1400
1401     return si;
1402 }
1403
1404 /*
1405  * Update the location of a simulated bogie.
1406  */
1407
1408 static void
1409 updateLocation(sim_target *t) 
1410 {
1411
1412     int xdist, xtick;
1413
1414     xtick = (int) (3.0 * random() / RAND_MAX) - 1;
1415     xdist = (int) (11.0 * random() / RAND_MAX) - 5;
1416     if (((t->nexttick + xtick) < 90) && ((t->nexttick + xtick) >= 0))
1417         t->nexttick += xtick;
1418     else
1419         t->nexttick -= xtick;
1420     if (((t->nextdist + xdist) < 100) && ((t->nextdist+xdist) >= 0))
1421         t->nextdist += xdist;
1422     else
1423         t->nextdist -= xdist;
1424 }
1425
1426 /*
1427  * The simulator. This uses information in the sim_info to simulate a bunch
1428  * of bogies flying around on the screen.
1429  */
1430
1431 /*
1432  * TODO: It would be cool to have the two teams chase each other around and
1433  *       shoot it out.
1434  */
1435
1436 static Bogie *
1437 simulator(sonar_info *si, void *vinfo) 
1438 {
1439
1440     /* Local Variables */
1441
1442     int i;
1443     Bogie *list = NULL;
1444     Bogie *new;
1445     sim_target *t;
1446     sim_info *info = (sim_info *) vinfo;
1447
1448     /* Check team A */
1449
1450     for (i = 0; i < info->numA; i++) {
1451         t = &info->teamA[i];
1452         if ((t->movedonsweep != si->sweepnum) &&
1453             (t->nexttick == (si->current * -1))) {
1454             new = newBogie(strdup(t->name), t->nextdist, si->current, si->TTL);
1455             if (list != NULL)
1456                 new->next = list;
1457             list = new;
1458             updateLocation(t);
1459             t->movedonsweep = si->sweepnum;
1460         }
1461     }
1462
1463     /* Team B */
1464
1465     for (i = 0; i < info->numB; i++) {
1466         t = &info->teamB[i];
1467         if ((t->movedonsweep != si->sweepnum) &&
1468             (t->nexttick == (si->current * -1))) {
1469             new = newBogie(strdup(t->name), t->nextdist, si->current, si->TTL);
1470             if (list != NULL)
1471                 new->next = list;
1472             list = new;
1473             updateLocation(t);
1474             t->movedonsweep = si->sweepnum;
1475         }
1476     }
1477
1478     /* Done */
1479
1480     return list;
1481 }
1482
1483 /*
1484  * Compute the X coordinate of the label.
1485  *
1486  * Args:
1487  *    si - The sonar info block.
1488  *    label - The label that will be drawn.
1489  *    x - The x coordinate of the bogie.
1490  *
1491  * Returns:
1492  *    The x coordinate of the start of the label.
1493  */
1494
1495 static int
1496 computeStringX(sonar_info *si, char *label, int x) 
1497 {
1498
1499     int width = XTextWidth(si->font, label, strlen(label));
1500     return x - (width / 2);
1501 }
1502
1503 /*
1504  * Compute the Y coordinate of the label.
1505  *
1506  * Args:
1507  *    si - The sonar information.
1508  *    y - The y coordinate of the bogie.
1509  *
1510  * Returns:
1511  *    The y coordinate of the start of the label.
1512  */
1513
1514 /* TODO: Add smarts to keep label in sonar screen */
1515
1516 static int
1517 computeStringY(sonar_info *si, int y) 
1518 {
1519
1520     int fheight = si->font->ascent + si->font->descent;
1521     return y + 5 + fheight;
1522 }
1523
1524 /*
1525  * Draw a Bogie on the radar screen.
1526  *
1527  * Args:
1528  *    si       - Sonar Information.
1529  *    draw     - A flag to indicate if the bogie should be drawn or erased.
1530  *    name     - The name of the bogie.
1531  *    degrees  - The number of degrees that it should apprear at.
1532  *    distance - The distance the object is from the centre.
1533  *    ttl      - The time this bogie has to live.
1534  *    age      - The time this bogie has been around.
1535  */
1536
1537 static void
1538 DrawBogie(sonar_info *si, int draw, char *name, int degrees, 
1539           int distance, int ttl, int age) 
1540 {
1541
1542     /* Local Variables */
1543
1544     int x, y;
1545     GC gc;
1546     int ox = si->centrex;
1547     int oy = si->centrey;
1548     int index, delta;
1549
1550     /* Compute the coordinates of the object */
1551
1552     if (distance != 0)
1553       distance = (log((double) distance) / 10.0) * si->radius;
1554     x = ox + ((double) distance * cos(4.0 * ((double) degrees)/57.29578));
1555     y = oy - ((double) distance * sin(4.0 * ((double) degrees)/57.29578));
1556
1557     /* Set up the graphics context */
1558
1559     if (draw) {
1560
1561         /* Here we attempt to compute the distance into the total life of
1562          * object that we currently are. This distance is used against
1563          * the total lifetime to compute a fraction which is the index of
1564          * the color to draw the bogie.
1565          */
1566
1567         if (si->current <= degrees)
1568             delta = (si->current - degrees) * -1;
1569         else
1570             delta = 90 + (degrees - si->current);
1571         delta += (age * 90);
1572         index = (si->text_steps - 1) * ((float) delta / (90.0 * (float) ttl));
1573         gc = si->text;
1574         XSetForeground(si->dpy, gc, si->text_colors[index].pixel);
1575
1576     } else
1577         gc = si->erase;
1578
1579   /* Draw (or erase) the Bogie */
1580
1581     XFillArc(si->dpy, si->win, gc, x, y, 5, 5, 0, 360 * 64);
1582     XDrawString(si->dpy, si->win, gc,
1583                 computeStringX(si, name, x),
1584                 computeStringY(si, y), name, strlen(name));
1585 }
1586
1587
1588 /*
1589  * Draw the sonar grid.
1590  *
1591  * Args:
1592  *    si - Sonar information block.
1593  */
1594
1595 static void
1596 drawGrid(sonar_info *si) 
1597 {
1598
1599     /* Local Variables */
1600
1601     int i;
1602     int width = si->maxx - si->minx;
1603     int height = si->maxy - si->miny;
1604   
1605     /* Draw the circles */
1606
1607     XDrawArc(si->dpy, si->win, si->grid, si->minx - 10, si->miny - 10, 
1608              width + 20, height + 20,  0, (360 * 64));
1609
1610     XDrawArc(si->dpy, si->win, si->grid, si->minx, si->miny, 
1611              width, height,  0, (360 * 64));
1612
1613     XDrawArc(si->dpy, si->win, si->grid, 
1614              (int) (si->minx + (.166 * width)), 
1615              (int) (si->miny + (.166 * height)), 
1616              (unsigned int) (.666 * width), (unsigned int)(.666 * height),
1617              0, (360 * 64));
1618
1619     XDrawArc(si->dpy, si->win, si->grid, 
1620              (int) (si->minx + (.333 * width)),
1621              (int) (si->miny + (.333 * height)), 
1622              (unsigned int) (.333 * width), (unsigned int) (.333 * height),
1623              0, (360 * 64));
1624
1625     /* Draw the radial lines */
1626
1627     for (i = 0; i < 360; i += 10)
1628         if (i % 30 == 0)
1629             XDrawLine(si->dpy, si->win, si->grid, si->centrex, si->centrey,
1630                       (int) (si->centrex +
1631                       (si->radius + 10) * (cos((double) i / 57.29578))),
1632                       (int) (si->centrey -
1633                       (si->radius + 10)*(sin((double) i / 57.29578))));
1634         else
1635             XDrawLine(si->dpy, si->win, si->grid, 
1636                       (int) (si->centrex + si->radius *
1637                              (cos((double) i / 57.29578))),
1638                       (int) (si->centrey - si->radius *
1639                              (sin((double) i / 57.29578))),
1640                       (int) (si->centrex +
1641                       (si->radius + 10) * (cos((double) i / 57.29578))),
1642                       (int) (si->centrey - 
1643                       (si->radius + 10) * (sin((double) i / 57.29578))));
1644 }
1645
1646 /*
1647  * Update the Sonar scope.
1648  *
1649  * Args:
1650  *    si - The Sonar information.
1651  *    bl - A list  of bogies to add to the scope.
1652  */
1653
1654 static void
1655 Sonar(sonar_info *si, Bogie *bl) 
1656 {
1657
1658     /* Local Variables */
1659
1660     Bogie *bp, *prev;
1661     int i;
1662
1663     /* Check for expired tagets and remove them from the visable list */
1664
1665     prev = NULL;
1666     for (bp = si->visable; bp != NULL; bp = (bp ? bp->next : 0)) {
1667
1668         /*
1669          * Remove it from the visable list if it's expired or we have
1670          * a new target with the same name.
1671          */
1672
1673         bp->age ++;
1674
1675         if (((bp->tick == si->current) && (++bp->age >= bp->ttl)) ||
1676             (findNode(bl, bp->name) != NULL)) {
1677             DrawBogie(si, 0, bp->name, bp->tick,
1678                       bp->distance, bp->ttl, bp->age);
1679             if (prev == NULL)
1680                 si->visable = bp->next;
1681             else
1682                 prev->next = bp->next;
1683             freeBogie(bp);
1684             bp = prev;
1685         } else
1686             prev = bp;
1687     }
1688
1689     /* Draw the sweep */
1690
1691     {
1692       int seg_deg = (si->sweep_degrees * 64) / si->sweep_segs;
1693       int start_deg = si->current * 4 * 64;
1694       if (seg_deg <= 0) seg_deg = 1;
1695       for (i = 0; i < si->sweep_segs; i++) {
1696         XSetForeground(si->dpy, si->hi, si->sweep_colors[i].pixel);
1697         XFillArc(si->dpy, si->win, si->hi, si->minx, si->miny, 
1698                  si->maxx - si->minx, si->maxy - si->miny,
1699                  start_deg + (i * seg_deg),
1700                  seg_deg);
1701       }
1702
1703       /* Remove the trailing wedge the sonar */
1704       XFillArc(si->dpy, si->win, si->erase, si->minx, si->miny, 
1705                si->maxx - si->minx, si->maxy - si->miny, 
1706                start_deg + (i * seg_deg),
1707                (4 * 64));
1708     }
1709
1710     /* Move the new targets to the visable list */
1711
1712     for (bp = bl; bp != (Bogie *) 0; bp = bl) {
1713         bl = bl->next;
1714         bp->next = si->visable;
1715         si->visable = bp;
1716     }
1717
1718     /* Draw the visable targets */
1719
1720     for (bp = si->visable; bp != NULL; bp = bp->next) {
1721         if (bp->age < bp->ttl)          /* grins */
1722            DrawBogie(si, 1, bp->name, bp->tick, bp->distance, bp->ttl,bp->age);
1723     }
1724
1725     /* Redraw the grid */
1726
1727     drawGrid(si);
1728 }
1729
1730
1731 static ping_target *
1732 parse_mode (Bool ping_works_p)
1733 {
1734   char *source = get_string_resource ("ping", "Ping");
1735   char *token, *end;
1736
1737   ping_target *hostlist = 0;
1738
1739   if (!source) source = strdup("");
1740
1741   if (!*source || !strcmp (source, "default"))
1742     {
1743 # ifdef HAVE_PING
1744       if (ping_works_p)         /* if root or setuid, ping will work. */
1745         source = strdup("subnet/29,/etc/hosts");
1746       else
1747 # endif
1748         source = strdup("simulation");
1749     }
1750
1751   token = source;
1752   end = source + strlen(source);
1753   while (token < end)
1754     {
1755       char *next;
1756 # ifdef HAVE_PING
1757       ping_target *new;
1758       struct stat st;
1759       unsigned int n0=0, n1=0, n2=0, n3=0, m=0;
1760       char d;
1761 # endif /* HAVE_PING */
1762
1763       for (next = token;
1764            *next != ',' && *next != ' ' && *next != '\t' && *next != '\n';
1765            next++)
1766         ;
1767       *next = 0;
1768
1769
1770       if (debug_p)
1771         fprintf (stderr, "%s: parsing %s\n", progname, token);
1772
1773       if (!strcmp (token, "simulation"))
1774         return 0;
1775
1776       if (!ping_works_p)
1777         {
1778           fprintf(stderr,
1779            "%s: this program must be setuid to root for `ping mode' to work.\n"
1780              "       Running in `simulation mode' instead.\n",
1781                   progname);
1782           return 0;
1783         }
1784
1785 #ifdef HAVE_PING
1786       if ((4 == sscanf (token, "%d.%d.%d/%d %c",    &n0,&n1,&n2,    &m,&d)) ||
1787           (5 == sscanf (token, "%d.%d.%d.%d/%d %c", &n0,&n1,&n2,&n3,&m,&d)))
1788         {
1789           /* subnet: A.B.C.D/M
1790              subnet: A.B.C/M
1791            */
1792           unsigned long ip = (n0 << 24) | (n1 << 16) | (n2 << 8) | n3;
1793           new = subnetHostsList(ip, m);
1794         }
1795       else if (4 == sscanf (token, "%d.%d.%d.%d %c", &n0, &n1, &n2, &n3, &d))
1796         {
1797           /* IP: A.B.C.D
1798            */
1799           new = newHost (token);
1800         }
1801       else if (!strcmp (token, "subnet"))
1802         {
1803           new = subnetHostsList(0, 24);
1804         }
1805       else if (1 == sscanf (token, "subnet/%d %c", &m))
1806         {
1807           new = subnetHostsList(0, m);
1808         }
1809       else if (*token == '.' || *token == '/' || !stat (token, &st))
1810         {
1811           /* file name
1812            */
1813           new = readPingHostsFile (token);
1814         }
1815       else
1816         {
1817           /* not an existant file - must be a host name
1818            */
1819           new = newHost (token);
1820         }
1821
1822       if (new)
1823         {
1824           ping_target *nn = new;
1825           while (nn && nn->next)
1826             nn = nn->next;
1827           nn->next = hostlist;
1828           hostlist = new;
1829
1830           sensor = ping;
1831         }
1832 #endif /* HAVE_PING */
1833
1834       token = next + 1;
1835       while (token < end &&
1836              (*token == ',' || *token == ' ' ||
1837               *token == '\t' || *token == '\n'))
1838         token++;
1839     }
1840
1841   return hostlist;
1842 }
1843
1844
1845
1846 /*
1847  * Main screen saver hack.
1848  *
1849  * Args:
1850  *    dpy - The X display.
1851  *    win - The X window.
1852  */
1853
1854 void 
1855 screenhack(Display *dpy, Window win) 
1856 {
1857
1858     /* Local Variables */
1859
1860     sonar_info *si;
1861     struct timeval start, finish;
1862     Bogie *bl;
1863     long sleeptime;
1864
1865     debug_p = get_boolean_resource ("debug", "Debug");
1866
1867     sensor = 0;
1868 # ifdef HAVE_PING
1869     sensor_info = (void *) init_ping();
1870 # else  /* !HAVE_PING */
1871     sensor_info = 0;
1872     parse_mode (0);  /* just to check argument syntax */
1873 # endif /* !HAVE_PING */
1874
1875     if (sensor == 0)
1876       {
1877         sensor = simulator;
1878         if ((sensor_info = (void *) init_sim()) == NULL)
1879           exit(1);
1880       }
1881
1882     if ((si = init_sonar(dpy, win)) == (sonar_info *) 0)
1883         exit(1);
1884
1885
1886     /* Sonar loop */
1887
1888     while (1) {
1889
1890         /* Call the sensor and display the results */
1891
1892         gettimeofday(&start, (struct timezone *) 0);
1893         bl = sensor(si, sensor_info);
1894         Sonar(si, bl);
1895
1896         /* Set up and sleep for the next one */
1897
1898         si->current = (si->current - 1) % 90;
1899         if (si->current == 0)
1900           si->sweepnum++;
1901         XSync (dpy, False);
1902         gettimeofday(&finish, (struct timezone *) 0);
1903         sleeptime = si->delay - delta(&start, &finish);
1904         screenhack_handle_events (dpy);
1905         if (sleeptime > 0L)
1906             usleep(sleeptime);
1907
1908     }
1909 }