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