1 /* sonar.c --- Simulate a sonar screen.
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.
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.
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.
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.
24 * It should be easy to extend this code to support other sorts of sensors.
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.
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
42 * Version 1.0 April 27, 1998.
44 * - Submitted to RedHat Screensaver Contest
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
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
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
70 * Version 1.4 November 18, 1998.
71 * - More ping portability fixes.
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.
78 /* These are computed by configure now:
90 #include "screenhack.h"
94 #if defined(HAVE_ICMP) || defined(HAVE_ICMPHDR)
99 # include <sys/types.h>
100 # include <sys/time.h>
101 # include <sys/ipc.h>
102 # include <sys/shm.h>
103 # include <sys/socket.h>
104 # include <netinet/in_systm.h>
105 # include <netinet/in.h>
106 # include <netinet/ip.h>
107 # include <netinet/ip_icmp.h>
108 # include <netinet/udp.h>
109 # include <arpa/inet.h>
111 #endif /* HAVE_ICMP || HAVE_ICMPHDR */
117 #define MY_MIN(a,b) ((a)<(b)?(a - 50):(b - 10))
120 # define LINE_MAX 2048
125 #if defined(HAVE_ICMP)
128 # define ICMP_TYPE(p) (p)->icmp_type
129 # define ICMP_CODE(p) (p)->icmp_code
130 # define ICMP_CHECKSUM(p) (p)->icmp_cksum
131 # define ICMP_ID(p) (p)->icmp_id
132 # define ICMP_SEQ(p) (p)->icmp_seq
133 #elif defined(HAVE_ICMPHDR)
135 # define ICMP icmphdr
136 # define ICMP_TYPE(p) (p)->type
137 # define ICMP_CODE(p) (p)->code
138 # define ICMP_CHECKSUM(p) (p)->checksum
139 # define ICMP_ID(p) (p)->un.echo.id
140 # define ICMP_SEQ(p) (p)->un.echo.sequence
145 /* Forward References */
148 static u_short checksum(u_short *, int);
150 static long delta(struct timeval *, struct timeval *);
152 /* Data Structures */
157 * This represents an object that is visable on the scope.
160 typedef struct Bogie {
161 char *name; /* The name of the thing being displayed */
162 int distance; /* The distance to this thing (0 - 100) */
163 int tick; /* The tick that it was found on */
164 int ttl; /* The time to live */
165 int age; /* How long it's been around */
166 struct Bogie *next; /* The next one in the list */
172 * This contains all of the runtime information about the sonar scope.
176 Display *dpy; /* The X display */
177 Window win; /* The window */
178 GC hi, /* The leading edge of the sweep */
179 lo, /* The trailing part of the sweep */
180 erase, /* Used to erase things */
181 grid, /* Used to draw the grid */
182 text; /* Used to draw text */
183 Colormap cmap; /* The colormap */
184 XFontStruct *font; /* The font to use for the labels */
185 int text_steps; /* How many steps to fade text. */
186 XColor *text_colors; /* Pixel values used to fade text */
187 int sweep_degrees; /* How much of the circle the sweep uses */
188 int sweep_segs; /* How many gradients in the sweep. */
189 XColor *sweep_colors; /* The sweep pixel values */
190 int width, height; /* Window dimensions */
191 int minx, miny, maxx, maxy, /* Bounds of the scope */
192 centrex, centrey, radius; /* Parts of the scope circle */
193 Bogie *visable; /* List of visable objects */
194 int current; /* Current position of sweep */
196 int delay; /* how long between each frame of the anim */
201 * Variables to support the differnt Sonar modes.
204 Bogie *(*sensor)(sonar_info *, void *); /* The current sensor */
205 void *sensor_info; /* Information about the sensor */
208 * A list of targets to ping.
212 typedef struct ping_target {
213 char *name; /* The name of the target */
214 struct sockaddr address; /* The address of the target */
215 struct ping_target *next; /* The next one in the list */
221 * This contains the information for the ping sensor.
225 int icmpsock; /* Socket for sending pings */
226 int pid; /* Our process ID */
227 int seq; /* Packet sequence number */
228 int timeout; /* Timeout value for pings */
229 ping_target *targets; /* List of targets to ping */
230 int numtargets; /* The number of targets to ping */
233 /* Flag to indicate that the timer has expired on us */
235 static int timer_expired;
238 #endif /* HAVE_PING */
241 * A list of targets for the simulator
244 typedef struct sim_target {
245 char *name; /* The name of the target */
246 int nexttick; /* The next tick that this will be seen */
247 int nextdist; /* The distance on that tick */
248 int movedlasttick; /* Flag to indicate we just moved this one */
252 * Simulator Information.
254 * This contains the information for the simulator mode.
258 sim_target *teamA; /* The bogies for the A team */
259 int numA; /* The number of bogies in team A */
260 char *teamAID; /* The identifier for bogies in team A */
261 sim_target *teamB; /* The bogies for the B team */
262 int numB; /* The number of bogies in team B */
263 char *teamBID; /* The identifier for bogies in team B */
266 /* Name of the Screensaver hack */
268 char *progclass="sonar";
270 /* Application Defaults */
272 char *defaults [] = {
273 ".background: #000000",
274 ".sweepColor: #00FF00",
276 "*scopeColor: #003300",
277 "*gridColor: #00AA00",
278 "*textColor: #FFFF00",
284 "*textSteps: 80", /* npixels */
285 "*sweepSegments: 80", /* npixels */
288 "*pingTimeout: 3000",
290 "*pingFile: /etc/hosts",
291 "*pingList: localhost",
292 #endif /* HAVE_PING */
300 /* Options passed to this program */
302 XrmOptionDescRec options [] = {
303 {"-background", ".background", XrmoptionSepArg, 0 },
304 {"-sweep-color", ".sweepColor", XrmoptionSepArg, 0 },
305 {"-scope-color", ".scopeColor", XrmoptionSepArg, 0 },
306 {"-grid-color", ".gridColor", XrmoptionSepArg, 0 },
307 {"-text-color", ".textColor", XrmoptionSepArg, 0 },
308 {"-ttl", ".ttl", XrmoptionSepArg, 0 },
309 {"-mode", ".mode", XrmoptionSepArg, 0 },
310 {"-font", ".font", XrmoptionSepArg, 0 },
312 {"-ping-timeout", ".pingTimeout", XrmoptionSepArg, 0 },
313 {"-ping-source", ".pingSource", XrmoptionSepArg, 0 },
314 {"-ping-file", ".pingFile", XrmoptionSepArg, 0 },
315 {"-ping-list", ".pingList", XrmoptionSepArg, 0 },
316 #endif /* HAVE_PING */
317 {"-team-a-name", ".teamAName", XrmoptionSepArg, 0 },
318 {"-team-b-name", ".teamBName", XrmoptionSepArg, 0 },
319 {"-team-a-count", ".teamACount", XrmoptionSepArg, 0 },
320 {"-team-b-count", ".teamBCount", XrmoptionSepArg, 0 },
325 * The number of ticks that bogies are visable on the screen before they
332 * Create a new Bogie and set some initial values.
335 * name - The name of the bogie.
336 * distance - The distance value.
337 * tick - The tick value.
338 * ttl - The time to live value.
341 * The newly allocated bogie or null if a memory problem occured.
345 newBogie(char *name, int distance, int tick, int ttl)
348 /* Local Variables */
352 /* Allocate a bogie and initialize it */
354 if ((new = (Bogie *) calloc(1, sizeof(Bogie))) == NULL) {
355 fprintf(stderr, "%s: Out of Memory\n", progname);
359 new->distance = distance;
363 new->next = (Bogie *) 0;
371 * b - The bogie to free.
377 if (b->name != (char *) 0)
383 * Find a bogie by name in a list.
385 * This does a simple linear search of the list for a given name.
388 * bl - The Bogie list to search.
389 * name - The name to look for.
392 * The requested Bogie or null if it wasn't found.
396 findNode(Bogie *bl, char *name)
399 /* Local Variables */
403 /* Abort if the list is empty or no name is given */
405 if ((name == NULL) || (bl == NULL))
408 /* Search the list for the desired name */
412 if (strcmp(p->name, name) == 0)
425 * Lookup the address for a ping target;
428 * target - The ping_target fill in the address for.
431 * 1 if the host was successfully resolved, 0 otherwise.
435 lookupHost(ping_target *target)
438 /* Local Variables */
440 struct sockaddr_in *iaddr;
442 /* Set up the target address we first assume that the name is the
443 IP address as a string */
445 iaddr = (struct sockaddr_in *) &(target->address);
446 iaddr->sin_family = AF_INET;
447 if ((iaddr->sin_addr.s_addr = inet_addr(target->name)) == -1) {
449 /* Conversion of IP address failed, try to look the host up by name */
451 struct hostent *hent = gethostbyname(target->name);
453 fprintf(stderr, "%s: could not resolve host %s\n",
454 progname, target->name);
457 memcpy(&iaddr->sin_addr, hent->h_addr_list[0],
458 sizeof(iaddr->sin_addr));
467 * Create a target for a host.
470 * name - The name of the host.
473 * A newly allocated target or null if the host could not be resolved.
480 /* Local Variables */
482 ping_target *target = NULL;
484 /* Create the target */
486 if ((target = calloc(1, sizeof(ping_target))) == NULL) {
487 fprintf(stderr, "%s: Out of Memory\n", progname);
488 goto target_init_error;
490 if ((target->name = strdup(name)) == NULL) {
491 fprintf(stderr, "%s: Out of Memory\n", progname);
492 goto target_init_error;
495 /* Lookup the host */
497 if (! lookupHost(target))
498 goto target_init_error;
504 /* Handle errors here */
513 * Generate a list of ping targets from the entries in a file.
516 * fname - The name of the file. This file is expected to be in the same
517 * format as /etc/hosts.
520 * A list of targets to ping or null if an error occured.
524 readPingHostsFile(char *fname)
527 /* Local Variables */
532 ping_target *list = NULL;
536 /* Make sure we in fact have a file to process */
538 if ((fname == NULL) || (fname[0] == '\0')) {
539 fprintf(stderr, "%s: invalid ping host file name\n", progname);
545 if ((fp = fopen(fname, "r")) == NULL) {
547 sprintf(msg, "%s: unable to open host file %s", progname, fname);
552 /* Read the file line by line */
554 while ((p = fgets(buf, LINE_MAX, fp)) != NULL) {
557 * Parse the line skipping those that start with '#'.
558 * The rest of the lines in the file should be in the same
559 * format as a /etc/hosts file. We are only concerned with
560 * the first two field, the IP address and the name
563 while ((*p == ' ') || (*p == '\t'))
568 /* Get the name and address */
571 if ((addr = strtok(buf, " \t\n")) != NULL)
572 name = strtok(NULL, " \t\n");
576 /* Check to see if the addr looks like an addr. If not, assume
577 the addr is a name and there is no addr. This way, we can
578 handle files whose lines have "xx.xx.xx.xx hostname" as their
579 first two tokens, and also files that have a hostname as their
580 first token (like .ssh/known_hosts and .rhosts.)
584 if (4 != sscanf(addr, "%d.%d.%d.%d%c", &i, &i, &i, &i, &c))
590 printf ("\"%s\" \"%s\"\n", name, addr);
592 /* Create a new target using first the name then the address */
597 if (new == NULL && addr != NULL)
600 /* Add it to the list if we got one */
608 /* Close the file and return the list */
615 * Generate a list of ping targets from the entries in a string.
618 * list - A list of comma separated host names.
621 * A list of targets to ping or null if an error occured.
625 readPingHostsList(char *list)
628 /* Local Variables */
631 ping_target *hostlist = NULL;
634 /* Check that there is a list */
636 if ((list == NULL) || (list[0] == '\0'))
639 /* Loop through the hosts and add them to the list to return */
641 host = strtok(list, ",");
642 while (host != NULL) {
645 new->next = hostlist;
648 host = strtok(NULL, ",");
657 * Generate a list ping targets consisting of all of the entries on
661 * A list of all of the hosts on this net.
665 subnetHostsList(void)
668 /* Local Variables */
670 char hostname[BUFSIZ];
671 char address[BUFSIZ];
672 struct hostent *hent;
676 ping_target *list = NULL;
678 /* Get our hostname */
680 if (gethostname(hostname, BUFSIZ)) {
681 fprintf(stderr, "%s: unable to get local hostname\n", progname);
685 /* Get our IP address and convert it to a string */
687 if ((hent = gethostbyname(hostname)) == NULL) {
688 fprintf(stderr, "%s: unable to lookup our IP address\n", progname);
691 strcpy(address, inet_ntoa(*((struct in_addr *)hent->h_addr_list[0])));
693 /* Get a pointer to the last "." in the string */
695 if ((p = strrchr(address, '.')) == NULL) {
696 fprintf(stderr, "%s: can't parse IP address %s\n", progname, address);
701 /* Construct targets for all addresses in this subnet */
703 /* #### jwz: actually, this is wrong, since it assumes a
704 netmask of 255.255.255.0. But I'm not sure how to find
707 for (i = 254; i > 0; i--) {
709 new = newHost(address);
722 * Initialize the ping sensor.
725 * A newly allocated ping_info structure or null if an error occured.
732 /* Local Variables */
734 ping_info *pi = NULL; /* The new ping_info struct */
735 char *src; /* The source of the ping hosts */
736 ping_target *pt; /* Used to count the targets */
738 /* Create the ping info structure */
740 if ((pi = (ping_info *) calloc(1, sizeof(ping_info))) == NULL) {
741 fprintf(stderr, "%s: Out of memory\n", progname);
742 goto ping_init_error;
745 /* Create the ICMP socket and turn off SUID */
747 if ((pi->icmpsock = socket(AF_INET, SOCK_RAW, IPPROTO_ICMP)) < 0) {
749 sprintf(msg, "%s: can't create ICMP socket", progname);
752 "%s: this program must be setuid to root for `ping mode' to work.\n",
754 goto ping_init_error;
757 pi->pid = getpid() & 0xFFFF;
759 pi->timeout = get_integer_resource("pingTimeout", "PingTimeout");
761 /* Generate a list of targets */
763 src = get_string_resource("pingSource", "PingSource");
764 if (strcmp(src, "file") == 0) {
767 * The list of ping targets is to come from a file in
771 pi->targets = readPingHostsFile(get_string_resource("pingFile",
774 } else if (strcmp(src, "list") == 0) {
776 /* The list of hosts is to come from the pinghostlist resource */
778 pi->targets = readPingHostsList(get_string_resource("pingList",
781 } else if (strcmp(src, "subnet") == 0) {
783 pi->targets = subnetHostsList();
790 "%s: pingSource must be `file', `list', or `subnet', not: %s\n",
795 /* Make sure there is something to ping */
797 if (pi->targets == NULL) {
798 fprintf(stderr, "%s: nothing to ping", progname);
799 goto ping_init_error;
802 /* Count the targets */
815 /* Handle initialization errors here */
827 * pi - The ping information strcuture.
828 * host - The name or IP address of the host to ping (in ascii).
832 sendping(ping_info *pi, ping_target *pt)
835 /* Local Variables */
842 * Note, we will send the character name of the host that we are
843 * pinging in the packet so that we don't have to keep track of the
844 * name or do an address lookup when it comes back.
847 int pcktsiz = sizeof(struct ICMP) + sizeof(struct timeval) +
848 strlen(pt->name) + 1;
850 /* Create the ICMP packet */
852 if ((packet = (u_char *) malloc(pcktsiz)) == (void *) 0)
853 return; /* Out of memory */
854 icmph = (struct ICMP *) packet;
855 ICMP_TYPE(icmph) = ICMP_ECHO;
856 ICMP_CODE(icmph) = 0;
857 ICMP_CHECKSUM(icmph) = 0;
858 ICMP_ID(icmph) = pi->pid;
859 ICMP_SEQ(icmph) = pi->seq++;
860 gettimeofday((struct timeval *) &packet[sizeof(struct ICMP)],
861 (struct timezone *) 0);
862 strcpy((char *) &packet[sizeof(struct ICMP) + sizeof(struct timeval)],
864 ICMP_CHECKSUM(icmph) = checksum((u_short *)packet, pcktsiz);
868 if ((result = sendto(pi->icmpsock, packet, pcktsiz, 0,
869 &pt->address, sizeof(pt->address))) != pcktsiz) {
872 sprintf(errbuf, "%s: error sending ping to %s", progname, pt->name);
879 * Catch a signal and do nothing.
882 * sig - The signal that was caught.
892 * Compute the checksum on a ping packet.
895 * packet - A pointer to the packet to compute the checksum for.
896 * size - The size of the packet.
899 * The computed checksum
904 checksum(u_short *packet, int size)
907 /* Local Variables */
909 register int nleft = size;
910 register u_short *w = packet;
911 register int sum = 0;
915 * Our algorithm is simple, using a 32 bit accumulator (sum), we add
916 * sequential 16 bit words to it, and at the end, fold back all the
917 * carry bits from the top 16 bits into the lower 16 bits.
925 /* mop up an odd byte, if necessary */
928 *(u_char *)(&answer) = *(u_char *)w ;
929 *(1 + (u_char *)(&answer)) = 0;
933 /* add back carry outs from top 16 bits to low 16 bits */
935 sum = (sum >> 16) + (sum & 0xffff); /* add hi 16 to low 16 */
936 sum += (sum >> 16); /* add carry */
937 answer = ~sum; /* truncate to 16 bits */
945 * Look for ping replies.
947 * Retrieve all outstanding ping replies.
950 * si - Information about the sonar.
951 * pi - Ping information.
952 * ttl - The time each bogie is to live on the screen
955 * A Bogie list of all the machines that replied.
959 getping(sonar_info *si, ping_info *pi, int ttl)
962 /* Local Variables */
964 struct sockaddr from;
969 struct timeval *then;
979 /* Set up a signal to interupt our wait for a packet */
981 sigemptyset(&sa.sa_mask);
983 sa.sa_handler = sigcatcher;
984 if (sigaction(SIGALRM, &sa, 0) == -1) {
986 sprintf(msg, "%s: unable to trap SIGALRM", progname);
991 /* Set up a timer to interupt us if we don't get a packet */
993 it.it_interval.tv_sec = 0;
994 it.it_interval.tv_usec = 0;
995 it.it_value.tv_sec = 0;
996 it.it_value.tv_usec = pi->timeout;
998 setitimer(ITIMER_REAL, &it, NULL);
1000 /* Wait for a result packet */
1002 fromlen = sizeof(from);
1003 while (! timer_expired &&
1004 (result = recvfrom(pi->icmpsock, packet, sizeof(packet),
1005 0, &from, &fromlen)) > 0) {
1007 /* Check the packet */
1009 gettimeofday(&now, (struct timezone *) 0);
1010 ip = (struct ip *) packet;
1012 iphdrlen = ip->ip_hl << 2;
1013 /* On DEC OSF1 4.0, the preceeding line needs to be
1014 iphdrlen = (ip->ip_vhl & 0x0F) << 2;
1015 but I don't know how to do this portably. -- jwz.
1018 icmph = (struct ICMP *) &packet[iphdrlen];
1020 /* Was the packet a reply?? */
1022 if (ICMP_TYPE(icmph) != ICMP_ECHOREPLY) {
1023 /* Ignore anything but ICMP Replies */
1024 continue; /* Nope */
1027 /* Was it for us? */
1029 if (ICMP_ID(icmph) != pi->pid) {
1030 /* Ignore packets not set from us */
1031 continue; /* Nope */
1034 /* Copy the name of the bogie */
1037 strdup((char *) &packet[iphdrlen +
1038 + sizeof(struct ICMP)
1039 + sizeof(struct timeval)])) == NULL) {
1040 fprintf(stderr, "%s: Out of memory\n", progname);
1044 /* If the name is an IP addr, try to resolve it. */
1048 if (4 == sscanf(name, " %d.%d.%d.%d %c",
1049 &iip[0], &iip[1], &iip[2], &iip[3], &c))
1051 unsigned char ip[4];
1053 ip[0] = iip[0]; ip[1] = iip[1]; ip[2] = iip[2]; ip[3] = iip[3];
1054 h = gethostbyaddr ((char *) ip, 4, AF_INET);
1055 if (h && h->h_name && *h->h_name)
1058 name = strdup (h->h_name);
1063 /* Create the new Bogie and add it to the list we are building */
1065 if ((new = newBogie(name, 0, si->current, ttl)) == NULL)
1070 /* Compute the round trip time */
1072 then = (struct timeval *) &packet[iphdrlen +
1073 sizeof(struct ICMP)];
1074 new->distance = delta(then, &now) / 100;
1075 if (new->distance == 0)
1076 new->distance = 2; /* HACK */
1088 * si - Sonar Information.
1089 * pi - Ping Information.
1092 * A list of hosts that replied to pings or null if there were none.
1096 ping(sonar_info *si, void *vpi)
1099 ping_info *pi = (ping_info *) vpi;
1100 static ping_target *ptr = NULL;
1102 int tick = si->current * -1 + 1;
1103 if ((ptr == NULL) && (tick == 1))
1106 if (pi->numtargets <= 90) {
1107 int xdrant = 90 / pi->numtargets;
1108 if ((tick % xdrant) == 0) {
1109 if (ptr != (ping_target *) 0) {
1115 } else if (pi->numtargets > 90) {
1116 if (ptr != (ping_target *) 0) {
1122 /* Get the results */
1124 return getping(si, pi, TTL);
1127 #endif /* HAVE_PING */
1130 * Calculate the difference between two timevals in microseconds.
1133 * then - The older timeval.
1134 * now - The newer timeval.
1137 * The difference between the two in microseconds.
1141 delta(struct timeval *then, struct timeval *now)
1143 return (((now->tv_sec - then->tv_sec) * 1000000) +
1144 (now->tv_usec - then->tv_usec));
1148 * Initialize the simulation mode.
1155 /* Local Variables */
1160 /* Create the simulation info structure */
1162 if ((si = (sim_info *) calloc(1, sizeof(sim_info))) == NULL) {
1163 fprintf(stderr, "%s: Out of memory\n", progname);
1169 si->numA = get_integer_resource("teamACount", "TeamACount");
1170 if ((si->teamA = (sim_target *)calloc(si->numA, sizeof(sim_target)))
1173 fprintf(stderr, "%s: Out of Memory\n", progname);
1176 si->teamAID = get_string_resource("teamAName", "TeamAName");
1177 for (i = 0; i < si->numA; i++) {
1178 if ((si->teamA[i].name = (char *) malloc(strlen(si->teamAID) + 4))
1181 fprintf(stderr, "%s: Out of Memory\n", progname);
1184 sprintf(si->teamA[i].name, "%s%03d", si->teamAID, i+1);
1185 si->teamA[i].nexttick = (int) (90.0 * random() / RAND_MAX);
1186 si->teamA[i].nextdist = (int) (100.0 * random() / RAND_MAX);
1191 si->numB = get_integer_resource("teamBCount", "TeamBCount");
1192 if ((si->teamB = (sim_target *)calloc(si->numB, sizeof(sim_target)))
1195 fprintf(stderr, "%s: Out of Memory\n", progname);
1198 si->teamBID = get_string_resource("teamBName", "TeamBName");
1199 for (i = 0; i < si->numB; i++) {
1200 if ((si->teamB[i].name = (char *) malloc(strlen(si->teamBID) + 4))
1203 fprintf(stderr, "%s: Out of Memory\n", progname);
1206 sprintf(si->teamB[i].name, "%s%03d", si->teamBID, i+1);
1207 si->teamB[i].nexttick = (int) (90.0 * random() / RAND_MAX);
1208 si->teamB[i].nextdist = (int) (100.0 * random() / RAND_MAX);
1217 * Initialize the Sonar.
1220 * dpy - The X display.
1221 * win - The X window;
1224 * A sonar_info strcuture or null if memory allocation problems occur.
1228 init_sonar(Display *dpy, Window win)
1231 /* Local Variables */
1234 XWindowAttributes xwa;
1238 double s1, s2, v1, v2;
1240 /* Create the Sonar information structure */
1242 if ((si = (sonar_info *) calloc(1, sizeof(sonar_info))) == NULL) {
1243 fprintf(stderr, "%s: Out of memory\n", progname);
1247 /* Initialize the structure for the current environment */
1252 XGetWindowAttributes(dpy, win, &xwa);
1253 si->cmap = xwa.colormap;
1254 si->width = xwa.width;
1255 si->height = xwa.height;
1256 si->centrex = si->width / 2;
1257 si->centrey = si->height / 2;
1258 si->maxx = si->centrex + MY_MIN(si->centrex, si->centrey) - 10;
1259 si->minx = si->centrex - MY_MIN(si->centrex, si->centrey) + 10;
1260 si->maxy = si->centrey + MY_MIN(si->centrex, si->centrey) - 10;
1261 si->miny = si->centrey - MY_MIN(si->centrex, si->centrey) + 10;
1262 si->radius = si->maxx - si->centrex;
1267 if (((si->font = XLoadQueryFont(dpy, get_string_resource ("font", "Font")))
1269 ((si->font = XLoadQueryFont(dpy, "fixed")) == NULL)) {
1270 fprintf(stderr, "%s: can't load an appropriate font\n", progname);
1274 /* Get the delay between animation frames */
1276 si->delay = get_integer_resource ("delay", "Integer");
1277 if (si->delay < 0) si->delay = 0;
1279 /* Create the Graphics Contexts that will be used to draw things */
1282 get_pixel_resource ("sweepColor", "SweepColor", dpy, si->cmap);
1283 si->hi = XCreateGC(dpy, win, GCForeground, &gcv);
1284 gcv.font = si->font->fid;
1285 si->text = XCreateGC(dpy, win, GCForeground|GCFont, &gcv);
1286 gcv.foreground = get_pixel_resource("scopeColor", "ScopeColor",
1288 si->erase = XCreateGC (dpy, win, GCForeground, &gcv);
1289 gcv.foreground = get_pixel_resource("gridColor", "GridColor",
1291 si->grid = XCreateGC (dpy, win, GCForeground, &gcv);
1293 /* Compute pixel values for fading text on the display */
1295 XParseColor(dpy, si->cmap,
1296 get_string_resource("textColor", "TextColor"), &start);
1297 XParseColor(dpy, si->cmap,
1298 get_string_resource("scopeColor", "ScopeColor"), &end);
1300 rgb_to_hsv (start.red, start.green, start.blue, &h1, &s1, &v1);
1301 rgb_to_hsv (end.red, end.green, end.blue, &h2, &s2, &v2);
1303 si->text_steps = get_integer_resource("textSteps", "TextSteps");
1304 if (si->text_steps < 0 || si->text_steps > 255)
1305 si->text_steps = 10;
1307 si->text_colors = (XColor *) calloc(si->text_steps, sizeof(XColor));
1308 make_color_ramp (dpy, si->cmap,
1311 si->text_colors, &si->text_steps,
1312 False, True, False);
1314 /* Compute the pixel values for the fading sweep */
1316 XParseColor(dpy, si->cmap,
1317 get_string_resource("sweepColor", "SweepColor"), &start);
1319 rgb_to_hsv (start.red, start.green, start.blue, &h1, &s1, &v1);
1321 si->sweep_degrees = get_integer_resource("sweepDegrees", "Degrees");
1322 if (si->sweep_degrees <= 0) si->sweep_degrees = 20;
1323 if (si->sweep_degrees > 350) si->sweep_degrees = 350;
1325 si->sweep_segs = get_integer_resource("sweepSegments", "SweepSegments");
1326 if (si->sweep_segs < 1 || si->sweep_segs > 255)
1327 si->sweep_segs = 255;
1329 si->sweep_colors = (XColor *) calloc(si->sweep_segs, sizeof(XColor));
1330 make_color_ramp (dpy, si->cmap,
1333 si->sweep_colors, &si->sweep_segs,
1334 False, True, False);
1342 * Update the location of a simulated bogie.
1346 updateLocation(sim_target *t)
1351 t->movedlasttick = 1;
1352 xtick = (int) (3.0 * random() / RAND_MAX) - 1;
1353 xdist = (int) (11.0 * random() / RAND_MAX) - 5;
1354 if (((t->nexttick + xtick) < 90) && ((t->nexttick + xtick) >= 0))
1355 t->nexttick += xtick;
1357 t->nexttick -= xtick;
1358 if (((t->nextdist + xdist) < 100) && ((t->nextdist+xdist) >= 0))
1359 t->nextdist += xdist;
1361 t->nextdist -= xdist;
1365 * The simulator. This uses information in the sim_info to simulate a bunch
1366 * of bogies flying around on the screen.
1370 * TODO: It would be cool to have the two teams chase each other around and
1375 simulator(sonar_info *si, void *vinfo)
1378 /* Local Variables */
1384 sim_info *info = (sim_info *) vinfo;
1388 for (i = 0; i < info->numA; i++) {
1389 t = &info->teamA[i];
1390 if (!t->movedlasttick && (t->nexttick == (si->current * -1))) {
1391 new = newBogie(strdup(t->name), t->nextdist, si->current, TTL);
1397 t->movedlasttick = 0;
1402 for (i = 0; i < info->numB; i++) {
1403 t = &info->teamB[i];
1404 if (!t->movedlasttick && (t->nexttick == (si->current * -1))) {
1405 new = newBogie(strdup(t->name), t->nextdist, si->current, TTL);
1409 t->movedlasttick = 1;
1412 t->movedlasttick = 0;
1421 * Compute the X coordinate of the label.
1424 * si - The sonar info block.
1425 * label - The label that will be drawn.
1426 * x - The x coordinate of the bogie.
1429 * The x coordinate of the start of the label.
1433 computeStringX(sonar_info *si, char *label, int x)
1436 int width = XTextWidth(si->font, label, strlen(label));
1437 return x - (width / 2);
1441 * Compute the Y coordinate of the label.
1444 * si - The sonar information.
1445 * y - The y coordinate of the bogie.
1448 * The y coordinate of the start of the label.
1451 /* TODO: Add smarts to keep label in sonar screen */
1454 computeStringY(sonar_info *si, int y)
1457 int fheight = si->font->ascent + si->font->descent;
1458 return y + 5 + fheight;
1462 * Draw a Bogie on the radar screen.
1465 * si - Sonar Information.
1466 * draw - A flag to indicate if the bogie should be drawn or erased.
1467 * name - The name of the bogie.
1468 * degrees - The number of degrees that it should apprear at.
1469 * distance - The distance the object is from the centre.
1470 * ttl - The time this bogie has to live.
1471 * age - The time this bogie has been around.
1475 DrawBogie(sonar_info *si, int draw, char *name, int degrees,
1476 int distance, int ttl, int age)
1479 /* Local Variables */
1483 int ox = si->centrex;
1484 int oy = si->centrey;
1487 /* Compute the coordinates of the object */
1489 distance = (log((double) distance) / 10.0) * si->radius;
1490 x = ox + ((double) distance * cos(4.0 * ((double) degrees)/57.29578));
1491 y = oy - ((double) distance * sin(4.0 * ((double) degrees)/57.29578));
1493 /* Set up the graphics context */
1497 /* Here we attempt to compute the distance into the total life of
1498 * object that we currently are. This distance is used against
1499 * the total lifetime to compute a fraction which is the index of
1500 * the color to draw the bogie.
1503 if (si->current <= degrees)
1504 delta = (si->current - degrees) * -1;
1506 delta = 90 + (degrees - si->current);
1507 delta += (age * 90);
1508 index = (si->text_steps - 1) * ((float) delta / (90.0 * (float) ttl));
1510 XSetForeground(si->dpy, gc, si->text_colors[index].pixel);
1515 /* Draw (or erase) the Bogie */
1517 XFillArc(si->dpy, si->win, gc, x, y, 5, 5, 0, 360 * 64);
1518 XDrawString(si->dpy, si->win, gc,
1519 computeStringX(si, name, x),
1520 computeStringY(si, y), name, strlen(name));
1525 * Draw the sonar grid.
1528 * si - Sonar information block.
1532 drawGrid(sonar_info *si)
1535 /* Local Variables */
1538 int width = si->maxx - si->minx;
1539 int height = si->maxy - si->miny;
1541 /* Draw the circles */
1543 XDrawArc(si->dpy, si->win, si->grid, si->minx - 10, si->miny - 10,
1544 width + 20, height + 20, 0, (360 * 64));
1546 XDrawArc(si->dpy, si->win, si->grid, si->minx, si->miny,
1547 width, height, 0, (360 * 64));
1549 XDrawArc(si->dpy, si->win, si->grid,
1550 (int) (si->minx + (.166 * width)),
1551 (int) (si->miny + (.166 * height)),
1552 (unsigned int) (.666 * width), (unsigned int)(.666 * height),
1555 XDrawArc(si->dpy, si->win, si->grid,
1556 (int) (si->minx + (.333 * width)),
1557 (int) (si->miny + (.333 * height)),
1558 (unsigned int) (.333 * width), (unsigned int) (.333 * height),
1561 /* Draw the radial lines */
1563 for (i = 0; i < 360; i += 10)
1565 XDrawLine(si->dpy, si->win, si->grid, si->centrex, si->centrey,
1566 (int) (si->centrex +
1567 (si->radius + 10) * (cos((double) i / 57.29578))),
1568 (int) (si->centrey -
1569 (si->radius + 10)*(sin((double) i / 57.29578))));
1571 XDrawLine(si->dpy, si->win, si->grid,
1572 (int) (si->centrex + si->radius *
1573 (cos((double) i / 57.29578))),
1574 (int) (si->centrey - si->radius *
1575 (sin((double) i / 57.29578))),
1576 (int) (si->centrex +
1577 (si->radius + 10) * (cos((double) i / 57.29578))),
1578 (int) (si->centrey -
1579 (si->radius + 10) * (sin((double) i / 57.29578))));
1583 * Update the Sonar scope.
1586 * si - The Sonar information.
1587 * bl - A list of bogies to add to the scope.
1591 Sonar(sonar_info *si, Bogie *bl)
1594 /* Local Variables */
1599 /* Check for expired tagets and remove them from the visable list */
1602 for (bp = si->visable; bp != NULL; bp = bp->next) {
1605 * Remove it from the visable list if it's expired or we have
1606 * a new target with the same name.
1611 if (((bp->tick == si->current) && (++bp->age >= bp->ttl)) ||
1612 (findNode(bl, bp->name) != NULL)) {
1613 DrawBogie(si, 0, bp->name, bp->tick,
1614 bp->distance, bp->ttl, bp->age);
1616 si->visable = bp->next;
1618 prev->next = bp->next;
1624 /* Draw the sweep */
1627 int seg_deg = (si->sweep_degrees * 64) / si->sweep_segs;
1628 int start_deg = si->current * 4 * 64;
1629 if (seg_deg <= 0) seg_deg = 1;
1630 for (i = 0; i < si->sweep_segs; i++) {
1631 XSetForeground(si->dpy, si->hi, si->sweep_colors[i].pixel);
1632 XFillArc(si->dpy, si->win, si->hi, si->minx, si->miny,
1633 si->maxx - si->minx, si->maxy - si->miny,
1634 start_deg + (i * seg_deg),
1638 /* Remove the trailing wedge the sonar */
1639 XFillArc(si->dpy, si->win, si->erase, si->minx, si->miny,
1640 si->maxx - si->minx, si->maxy - si->miny,
1641 start_deg + (i * seg_deg),
1645 /* Move the new targets to the visable list */
1647 for (bp = bl; bp != (Bogie *) 0; bp = bl) {
1649 bp->next = si->visable;
1653 /* Draw the visable targets */
1655 for (bp = si->visable; bp != NULL; bp = bp->next) {
1656 if (bp->age < bp->ttl) /* grins */
1657 DrawBogie(si, 1, bp->name, bp->tick, bp->distance, bp->ttl,bp->age);
1660 /* Redraw the grid */
1666 * Main screen saver hack.
1669 * dpy - The X display.
1670 * win - The X window.
1674 screenhack(Display *dpy, Window win)
1677 /* Local Variables */
1680 struct timeval start, finish;
1687 * Adding new sensors would involve supporting more modes other than
1688 * ping and initiailizing the sensor in the same way.
1691 mode = get_string_resource("mode", "Mode");
1693 if (!mode || !*mode || !strcmp(mode, "default")) /* Pick a good default. */
1696 if (geteuid() == 0) /* we're root or setuid -- ping will work. */
1700 mode = "simulation";
1704 if (strcmp(mode, "ping") == 0) {
1706 if ((sensor_info = (void *) init_ping()) == (void *) 0)
1708 fprintf (stderr, "%s: running in `simulation mode' instead.\n",
1713 #endif /* HAVE_PING */
1714 if (strcmp(mode, "simulation") == 0) {
1719 if ((sensor_info = (void *) init_sim()) == NULL)
1722 fprintf(stderr, "%s: unsupported Sonar mode: %s\n", progname, mode);
1724 "\tCurrently supported modes are `ping' and `simulation'\n");
1727 if ((si = init_sonar(dpy, win)) == (sonar_info *) 0)
1732 TTL = get_integer_resource("ttl", "TTL");
1736 /* Call the sensor and display the results */
1738 gettimeofday(&start, (struct timezone *) 0);
1739 bl = sensor(si, sensor_info);
1742 /* Set up and sleep for the next one */
1744 si->current = (si->current - 1) % 90;
1746 gettimeofday(&finish, (struct timezone *) 0);
1747 sleeptime = si->delay - delta(&start, &finish);
1748 screenhack_handle_events (dpy);