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@vanderfleet-martin.net).
32 * Permission to use, copy, modify, distribute, and sell this software and its
33 * documentation for any purpose is hereby granted without fee, provided that
34 * the above copyright notice appear in all copies and that both that
35 * copyright notice and this permission notice appear in supporting
36 * documentation. No representations are made about the suitability of this
37 * software for any purpose. It is provided "as is" without express or
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:
91 #include "screenhack.h"
95 #if defined(HAVE_ICMP) || defined(HAVE_ICMPHDR)
100 # include <sys/types.h>
101 # include <sys/time.h>
102 # include <sys/ipc.h>
103 # include <sys/shm.h>
104 # include <sys/socket.h>
105 # include <netinet/in_systm.h>
106 # include <netinet/in.h>
107 # include <netinet/ip.h>
108 # include <netinet/ip_icmp.h>
109 # include <netinet/udp.h>
110 # include <arpa/inet.h>
112 #endif /* HAVE_ICMP || HAVE_ICMPHDR */
118 #define MY_MIN(a,b) ((a)<(b)?(a - 50):(b - 10))
121 # define LINE_MAX 2048
126 #if defined(HAVE_ICMP)
129 # define ICMP_TYPE(p) (p)->icmp_type
130 # define ICMP_CODE(p) (p)->icmp_code
131 # define ICMP_CHECKSUM(p) (p)->icmp_cksum
132 # define ICMP_ID(p) (p)->icmp_id
133 # define ICMP_SEQ(p) (p)->icmp_seq
134 #elif defined(HAVE_ICMPHDR)
136 # define ICMP icmphdr
137 # define ICMP_TYPE(p) (p)->type
138 # define ICMP_CODE(p) (p)->code
139 # define ICMP_CHECKSUM(p) (p)->checksum
140 # define ICMP_ID(p) (p)->un.echo.id
141 # define ICMP_SEQ(p) (p)->un.echo.sequence
146 /* Forward References */
149 static u_short checksum(u_short *, int);
151 static long delta(struct timeval *, struct timeval *);
154 /* Data Structures */
159 * This represents an object that is visable on the scope.
162 typedef struct Bogie {
163 char *name; /* The name of the thing being displayed */
164 int distance; /* The distance to this thing (0 - 100) */
165 int tick; /* The tick that it was found on */
166 int ttl; /* The time to live */
167 int age; /* How long it's been around */
168 struct Bogie *next; /* The next one in the list */
174 * This contains all of the runtime information about the sonar scope.
178 Display *dpy; /* The X display */
179 Window win; /* The window */
180 GC hi, /* The leading edge of the sweep */
181 lo, /* The trailing part of the sweep */
182 erase, /* Used to erase things */
183 grid, /* Used to draw the grid */
184 text; /* Used to draw text */
185 Colormap cmap; /* The colormap */
186 XFontStruct *font; /* The font to use for the labels */
187 int text_steps; /* How many steps to fade text. */
188 XColor *text_colors; /* Pixel values used to fade text */
189 int sweep_degrees; /* How much of the circle the sweep uses */
190 int sweep_segs; /* How many gradients in the sweep. */
191 XColor *sweep_colors; /* The sweep pixel values */
192 int width, height; /* Window dimensions */
193 int minx, miny, maxx, maxy, /* Bounds of the scope */
194 centrex, centrey, radius; /* Parts of the scope circle */
195 Bogie *visable; /* List of visable objects */
196 int current; /* Current position of sweep */
197 int sweepnum; /* The current id of the sweep */
198 int delay; /* how long between each frame of the anim */
200 int TTL; /* The number of ticks that bogies are visible
201 on the screen before they fade away. */
204 static Bool debug_p = False;
208 * Variables to support the differnt Sonar modes.
211 Bogie *(*sensor)(sonar_info *, void *); /* The current sensor */
212 void *sensor_info; /* Information about the sensor */
215 * A list of targets to ping.
219 typedef struct ping_target {
220 char *name; /* The name of the target */
221 struct sockaddr address; /* The address of the target */
222 struct ping_target *next; /* The next one in the list */
228 * This contains the information for the ping sensor.
232 int icmpsock; /* Socket for sending pings */
233 int pid; /* Our process ID */
234 int seq; /* Packet sequence number */
235 int timeout; /* Timeout value for pings */
236 ping_target *targets; /* List of targets to ping */
237 int numtargets; /* The number of targets to ping */
240 /* Flag to indicate that the timer has expired on us */
242 static int timer_expired;
244 #endif /* HAVE_PING */
247 * A list of targets for the simulator
250 typedef struct sim_target {
251 char *name; /* The name of the target */
252 int nexttick; /* The next tick that this will be seen */
253 int nextdist; /* The distance on that tick */
254 int movedonsweep; /* The number of the sweep this last moved */
258 * Simulator Information.
260 * This contains the information for the simulator mode.
264 sim_target *teamA; /* The bogies for the A team */
265 int numA; /* The number of bogies in team A */
266 char *teamAID; /* The identifier for bogies in team A */
267 sim_target *teamB; /* The bogies for the B team */
268 int numB; /* The number of bogies in team B */
269 char *teamBID; /* The identifier for bogies in team B */
272 /* Name of the Screensaver hack */
274 char *progclass="sonar";
276 /* Application Defaults */
278 char *defaults [] = {
279 ".background: #000000",
280 ".sweepColor: #00FF00",
282 "*scopeColor: #003300",
283 "*gridColor: #00AA00",
284 "*textColor: #FFFF00",
290 "*textSteps: 80", /* npixels */
291 "*sweepSegments: 80", /* npixels */
293 "*pingTimeout: 3000",
305 /* Options passed to this program */
307 XrmOptionDescRec options [] = {
308 {"-background", ".background", XrmoptionSepArg, 0 },
309 {"-sweep-color", ".sweepColor", XrmoptionSepArg, 0 },
310 {"-scope-color", ".scopeColor", XrmoptionSepArg, 0 },
311 {"-grid-color", ".gridColor", XrmoptionSepArg, 0 },
312 {"-text-color", ".textColor", XrmoptionSepArg, 0 },
313 {"-ttl", ".ttl", XrmoptionSepArg, 0 },
314 {"-font", ".font", XrmoptionSepArg, 0 },
316 {"-ping-timeout", ".pingTimeout", XrmoptionSepArg, 0 },
317 #endif /* HAVE_PING */
318 {"-team-a-name", ".teamAName", XrmoptionSepArg, 0 },
319 {"-team-b-name", ".teamBName", XrmoptionSepArg, 0 },
320 {"-team-a-count", ".teamACount", XrmoptionSepArg, 0 },
321 {"-team-b-count", ".teamBCount", XrmoptionSepArg, 0 },
323 {"-ping", ".ping", XrmoptionSepArg, 0 },
324 {"-debug", ".debug", XrmoptionNoArg, "True" },
329 * Create a new Bogie and set some initial values.
332 * name - The name of the bogie.
333 * distance - The distance value.
334 * tick - The tick value.
335 * ttl - The time to live value.
338 * The newly allocated bogie or null if a memory problem occured.
342 newBogie(char *name, int distance, int tick, int ttl)
345 /* Local Variables */
349 /* Allocate a bogie and initialize it */
351 if ((new = (Bogie *) calloc(1, sizeof(Bogie))) == NULL) {
352 fprintf(stderr, "%s: Out of Memory\n", progname);
356 new->distance = distance;
360 new->next = (Bogie *) 0;
368 * b - The bogie to free.
375 if (b->name != (char *) 0)
381 * Find a bogie by name in a list.
383 * This does a simple linear search of the list for a given name.
386 * bl - The Bogie list to search.
387 * name - The name to look for.
390 * The requested Bogie or null if it wasn't found.
394 findNode(Bogie *bl, char *name)
397 /* Local Variables */
401 /* Abort if the list is empty or no name is given */
403 if ((name == NULL) || (bl == NULL))
406 /* Search the list for the desired name */
410 if (strcmp(p->name, name) == 0)
423 * Lookup the address for a ping target;
426 * target - The ping_target fill in the address for.
429 * 1 if the host was successfully resolved, 0 otherwise.
433 lookupHost(ping_target *target)
436 struct hostent *hent;
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)) >= 0) {
449 ip[3] = iaddr->sin_addr.s_addr >> 24 & 255;
450 ip[2] = iaddr->sin_addr.s_addr >> 16 & 255;
451 ip[1] = iaddr->sin_addr.s_addr >> 8 & 255;
452 ip[0] = iaddr->sin_addr.s_addr & 255;
453 hent = gethostbyaddr (ip, 4, AF_INET);
454 if (hent && hent->h_name && *hent->h_name) {
455 target->name = strdup (hent->h_name);
460 /* Conversion of IP address failed, try to look the host up by name */
462 hent = gethostbyname(target->name);
464 fprintf(stderr, "%s: could not resolve host %s\n",
465 progname, target->name);
468 memcpy(&iaddr->sin_addr, hent->h_addr_list[0],
469 sizeof(iaddr->sin_addr));
477 * Create a target for a host.
480 * name - The name of the host.
483 * A newly allocated target or null if the host could not be resolved.
490 /* Local Variables */
492 ping_target *target = NULL;
494 /* Create the target */
496 if ((target = calloc(1, sizeof(ping_target))) == NULL) {
497 fprintf(stderr, "%s: Out of Memory\n", progname);
498 goto target_init_error;
500 if ((target->name = strdup(name)) == NULL) {
501 fprintf(stderr, "%s: Out of Memory\n", progname);
502 goto target_init_error;
505 /* Lookup the host */
507 if (! lookupHost(target))
508 goto target_init_error;
514 struct sockaddr_in *iaddr = (struct sockaddr_in *) &(target->address);
515 unsigned long ip = iaddr->sin_addr.s_addr;
516 fprintf (stderr, "%s: added host %d.%d.%d.%d (%s)\n", progname,
517 ip & 255, ip >> 8 & 255, ip >> 16 & 255, ip >> 24 & 255,
523 /* Handle errors here */
532 * Generate a list of ping targets from the entries in a file.
535 * fname - The name of the file. This file is expected to be in the same
536 * format as /etc/hosts.
539 * A list of targets to ping or null if an error occured.
543 readPingHostsFile(char *fname)
545 /* Local Variables */
550 ping_target *list = NULL;
554 /* Make sure we in fact have a file to process */
556 if ((fname == NULL) || (fname[0] == '\0')) {
557 fprintf(stderr, "%s: invalid ping host file name\n", progname);
563 if ((fp = fopen(fname, "r")) == NULL) {
565 sprintf(msg, "%s: unable to open host file %s", progname, fname);
571 fprintf (stderr, "%s: reading file %s\n", progname, fname);
573 /* Read the file line by line */
575 while ((p = fgets(buf, LINE_MAX, fp)) != NULL) {
578 * Parse the line skipping those that start with '#'.
579 * The rest of the lines in the file should be in the same
580 * format as a /etc/hosts file. We are only concerned with
581 * the first two field, the IP address and the name
584 while ((*p == ' ') || (*p == '\t'))
589 /* Get the name and address */
592 if ((addr = strtok(buf, " \t\n")) != NULL)
593 name = strtok(NULL, " \t\n");
597 /* Check to see if the addr looks like an addr. If not, assume
598 the addr is a name and there is no addr. This way, we can
599 handle files whose lines have "xx.xx.xx.xx hostname" as their
600 first two tokens, and also files that have a hostname as their
601 first token (like .ssh/known_hosts and .rhosts.)
605 if (4 != sscanf(addr, "%d.%d.%d.%d%c", &i, &i, &i, &i, &c))
611 /*printf ("\"%s\" \"%s\"\n", name, addr);*/
613 /* Create a new target using first the name then the address */
618 if (new == NULL && addr != NULL)
621 /* Add it to the list if we got one */
629 /* Close the file and return the list */
637 delete_duplicate_hosts (ping_target *list)
639 ping_target *head = list;
642 for (rest = head; rest; rest = rest->next)
644 struct sockaddr_in *i1 = (struct sockaddr_in *) &(rest->address);
645 unsigned long ip1 = i1->sin_addr.s_addr;
647 static ping_target *rest2;
648 for (rest2 = rest; rest2; rest2 = rest2->next)
650 if (rest2 && rest2->next)
652 struct sockaddr_in *i2 = (struct sockaddr_in *)
653 &(rest2->next->address);
654 unsigned long ip2 = i2->sin_addr.s_addr;
659 fprintf (stderr, "%s: deleted duplicate: %s\n",
660 progname, rest2->next->name);
661 rest2->next = rest2->next->next;
674 * Generate a list ping targets consisting of all of the entries on
678 * A list of all of the hosts on this net.
682 subnetHostsList(int base, int subnet_width)
686 /* Local Variables */
688 char hostname[BUFSIZ];
689 char address[BUFSIZ];
690 struct hostent *hent;
694 ping_target *list = NULL;
696 if (subnet_width < 24)
699 "%s: pinging %u hosts is a bad idea; please use a subnet mask of 24 bits\n"
700 " or more (255 hosts max.)\n",
701 progname, 1L << (32 - subnet_width));
704 else if (subnet_width > 30)
706 fprintf (stderr, "%s: a subnet of %d bits doesn't make sense:"
707 " try \"subnet/24\" or \"subnet/29\".\n",
708 progname, subnet_width);
714 fprintf (stderr, "%s: adding %d-bit subnet\n", progname, subnet_width);
716 /* Get our hostname */
718 if (gethostname(hostname, BUFSIZ)) {
719 fprintf(stderr, "%s: unable to get local hostname\n", progname);
723 /* Get our IP address and convert it to a string */
725 if ((hent = gethostbyname(hostname)) == NULL) {
726 fprintf(stderr, "%s: unable to lookup our IP address\n", progname);
729 strcpy(address, inet_ntoa(*((struct in_addr *)hent->h_addr_list[0])));
731 /* Construct targets for all addresses in this subnet */
734 for (i = 0; i < subnet_width; i++)
735 mask |= (1L << (31-i));
737 /* If no base IP specified, assume localhost. */
739 base = ((((unsigned char) hent->h_addr_list[0][0]) << 24) |
740 (((unsigned char) hent->h_addr_list[0][1]) << 16) |
741 (((unsigned char) hent->h_addr_list[0][2]) << 8) |
742 (((unsigned char) hent->h_addr_list[0][3])));
744 for (i = 255; i >= 0; i--) {
745 int ip = (base & 0xFFFFFF00) | i;
747 if ((ip & mask) != (base & mask)) /* not in the mask range at all */
749 if ((ip & ~mask) == 0) /* broadcast address */
751 if ((ip & ~mask) == ~mask) /* broadcast address */
754 sprintf (address, "%d.%d.%d.%d",
755 (ip>>24)&255, (ip>>16)&255, (ip>>8)&255, (ip)&255);
758 fprintf(stderr, "%s: subnet: %s (%d.%d.%d.%d & %d.%d.%d.%d / %d)\n",
761 (base>>24)&255, (base>>16)&255, (base>>8)&255, base&mask&255,
762 (mask>>24)&255, (mask>>16)&255, (mask>>8)&255, mask&255,
765 p = address + strlen(address) + 1;
768 new = newHost(address);
781 * Initialize the ping sensor.
784 * A newly allocated ping_info structure or null if an error occured.
787 static ping_target *parse_mode (Bool ping_works_p);
793 Bool socket_initted_p = False;
795 /* Local Variables */
797 ping_info *pi = NULL; /* The new ping_info struct */
798 ping_target *pt; /* Used to count the targets */
800 /* Create the ping info structure */
802 if ((pi = (ping_info *) calloc(1, sizeof(ping_info))) == NULL) {
803 fprintf(stderr, "%s: Out of memory\n", progname);
804 goto ping_init_error;
807 /* Create the ICMP socket */
809 if ((pi->icmpsock = socket(AF_INET, SOCK_RAW, IPPROTO_ICMP)) >= 0) {
810 socket_initted_p = True;
818 pi->pid = getpid() & 0xFFFF;
820 pi->timeout = get_integer_resource("pingTimeout", "PingTimeout");
822 /* Generate a list of targets */
824 pi->targets = parse_mode (socket_initted_p);
825 pi->targets = delete_duplicate_hosts (pi->targets);
828 /* Make sure there is something to ping */
830 if (pi->targets == NULL) {
831 goto ping_init_error;
834 /* Count the targets */
847 /* Handle initialization errors here */
860 * pi - The ping information strcuture.
861 * host - The name or IP address of the host to ping (in ascii).
865 sendping(ping_info *pi, ping_target *pt)
868 /* Local Variables */
875 * Note, we will send the character name of the host that we are
876 * pinging in the packet so that we don't have to keep track of the
877 * name or do an address lookup when it comes back.
880 int pcktsiz = sizeof(struct ICMP) + sizeof(struct timeval) +
881 strlen(pt->name) + 1;
883 /* Create the ICMP packet */
885 if ((packet = (u_char *) malloc(pcktsiz)) == (void *) 0)
886 return; /* Out of memory */
887 icmph = (struct ICMP *) packet;
888 ICMP_TYPE(icmph) = ICMP_ECHO;
889 ICMP_CODE(icmph) = 0;
890 ICMP_CHECKSUM(icmph) = 0;
891 ICMP_ID(icmph) = pi->pid;
892 ICMP_SEQ(icmph) = pi->seq++;
893 gettimeofday((struct timeval *) &packet[sizeof(struct ICMP)],
894 (struct timezone *) 0);
895 strcpy((char *) &packet[sizeof(struct ICMP) + sizeof(struct timeval)],
897 ICMP_CHECKSUM(icmph) = checksum((u_short *)packet, pcktsiz);
901 if ((result = sendto(pi->icmpsock, packet, pcktsiz, 0,
902 &pt->address, sizeof(pt->address))) != pcktsiz) {
905 sprintf(errbuf, "%s: error sending ping to %s", progname, pt->name);
912 * Catch a signal and do nothing.
915 * sig - The signal that was caught.
925 * Compute the checksum on a ping packet.
928 * packet - A pointer to the packet to compute the checksum for.
929 * size - The size of the packet.
932 * The computed checksum
937 checksum(u_short *packet, int size)
940 /* Local Variables */
942 register int nleft = size;
943 register u_short *w = packet;
944 register int sum = 0;
948 * Our algorithm is simple, using a 32 bit accumulator (sum), we add
949 * sequential 16 bit words to it, and at the end, fold back all the
950 * carry bits from the top 16 bits into the lower 16 bits.
958 /* mop up an odd byte, if necessary */
961 *(u_char *)(&answer) = *(u_char *)w ;
962 *(1 + (u_char *)(&answer)) = 0;
966 /* add back carry outs from top 16 bits to low 16 bits */
968 sum = (sum >> 16) + (sum & 0xffff); /* add hi 16 to low 16 */
969 sum += (sum >> 16); /* add carry */
970 answer = ~sum; /* truncate to 16 bits */
978 * Look for ping replies.
980 * Retrieve all outstanding ping replies.
983 * si - Information about the sonar.
984 * pi - Ping information.
985 * ttl - The time each bogie is to live on the screen
988 * A Bogie list of all the machines that replied.
992 getping(sonar_info *si, ping_info *pi)
995 /* Local Variables */
997 struct sockaddr from;
1000 u_char packet[1024];
1002 struct timeval *then;
1009 struct sigaction sa;
1010 struct itimerval it;
1012 /* Set up a signal to interupt our wait for a packet */
1014 sigemptyset(&sa.sa_mask);
1016 sa.sa_handler = sigcatcher;
1017 if (sigaction(SIGALRM, &sa, 0) == -1) {
1019 sprintf(msg, "%s: unable to trap SIGALRM", progname);
1024 /* Set up a timer to interupt us if we don't get a packet */
1026 it.it_interval.tv_sec = 0;
1027 it.it_interval.tv_usec = 0;
1028 it.it_value.tv_sec = 0;
1029 it.it_value.tv_usec = pi->timeout;
1031 setitimer(ITIMER_REAL, &it, NULL);
1033 /* Wait for a result packet */
1035 fromlen = sizeof(from);
1036 while (! timer_expired &&
1037 (result = recvfrom(pi->icmpsock, packet, sizeof(packet),
1038 0, &from, &fromlen)) > 0) {
1040 /* Check the packet */
1042 gettimeofday(&now, (struct timezone *) 0);
1043 ip = (struct ip *) packet;
1045 iphdrlen = ip->ip_hl << 2;
1046 /* On DEC OSF1 4.0, the preceeding line needs to be
1047 iphdrlen = (ip->ip_vhl & 0x0F) << 2;
1048 but I don't know how to do this portably. -- jwz.
1051 icmph = (struct ICMP *) &packet[iphdrlen];
1053 /* Was the packet a reply?? */
1055 if (ICMP_TYPE(icmph) != ICMP_ECHOREPLY) {
1056 /* Ignore anything but ICMP Replies */
1057 continue; /* Nope */
1060 /* Was it for us? */
1062 if (ICMP_ID(icmph) != pi->pid) {
1063 /* Ignore packets not set from us */
1064 continue; /* Nope */
1067 /* Copy the name of the bogie */
1070 strdup((char *) &packet[iphdrlen +
1071 + sizeof(struct ICMP)
1072 + sizeof(struct timeval)])) == NULL) {
1073 fprintf(stderr, "%s: Out of memory\n", progname);
1077 /* If the name is an IP addr, try to resolve it. */
1081 if (4 == sscanf(name, " %d.%d.%d.%d %c",
1082 &iip[0], &iip[1], &iip[2], &iip[3], &c))
1084 unsigned char ip[4];
1086 ip[0] = iip[0]; ip[1] = iip[1]; ip[2] = iip[2]; ip[3] = iip[3];
1087 h = gethostbyaddr ((char *) ip, 4, AF_INET);
1088 if (h && h->h_name && *h->h_name)
1091 name = strdup (h->h_name);
1096 /* Create the new Bogie and add it to the list we are building */
1098 if ((new = newBogie(name, 0, si->current, si->TTL)) == NULL)
1103 /* Compute the round trip time */
1105 then = (struct timeval *) &packet[iphdrlen +
1106 sizeof(struct ICMP)];
1107 new->distance = delta(then, &now) / 100;
1108 if (new->distance == 0)
1109 new->distance = 2; /* HACK */
1121 * si - Sonar Information.
1122 * pi - Ping Information.
1125 * A list of hosts that replied to pings or null if there were none.
1129 ping(sonar_info *si, void *vpi)
1133 * This tries to distribute the targets evely around the field of the
1137 ping_info *pi = (ping_info *) vpi;
1138 static ping_target *ptr = NULL;
1140 int tick = si->current * -1 + 1;
1141 if ((ptr == NULL) && (tick == 1))
1144 if (pi->numtargets <= 90) {
1145 int xdrant = 90 / pi->numtargets;
1146 if ((tick % xdrant) == 0) {
1147 if (ptr != (ping_target *) 0) {
1153 } else if (pi->numtargets > 90) {
1154 if (ptr != (ping_target *) 0) {
1160 /* Get the results */
1162 return getping(si, pi);
1165 #endif /* HAVE_PING */
1168 * Calculate the difference between two timevals in microseconds.
1171 * then - The older timeval.
1172 * now - The newer timeval.
1175 * The difference between the two in microseconds.
1179 delta(struct timeval *then, struct timeval *now)
1181 return (((now->tv_sec - then->tv_sec) * 1000000) +
1182 (now->tv_usec - then->tv_usec));
1186 * Initialize the simulation mode.
1193 /* Local Variables */
1198 /* Create the simulation info structure */
1200 if ((si = (sim_info *) calloc(1, sizeof(sim_info))) == NULL) {
1201 fprintf(stderr, "%s: Out of memory\n", progname);
1207 si->numA = get_integer_resource("teamACount", "TeamACount");
1208 if ((si->teamA = (sim_target *)calloc(si->numA, sizeof(sim_target)))
1211 fprintf(stderr, "%s: Out of Memory\n", progname);
1214 si->teamAID = get_string_resource("teamAName", "TeamAName");
1215 for (i = 0; i < si->numA; i++) {
1216 if ((si->teamA[i].name = (char *) malloc(strlen(si->teamAID) + 4))
1219 fprintf(stderr, "%s: Out of Memory\n", progname);
1222 sprintf(si->teamA[i].name, "%s%03d", si->teamAID, i+1);
1223 si->teamA[i].nexttick = (int) (90.0 * random() / RAND_MAX);
1224 si->teamA[i].nextdist = (int) (100.0 * random() / RAND_MAX);
1225 si->teamA[i].movedonsweep = -1;
1230 si->numB = get_integer_resource("teamBCount", "TeamBCount");
1231 if ((si->teamB = (sim_target *)calloc(si->numB, sizeof(sim_target)))
1234 fprintf(stderr, "%s: Out of Memory\n", progname);
1237 si->teamBID = get_string_resource("teamBName", "TeamBName");
1238 for (i = 0; i < si->numB; i++) {
1239 if ((si->teamB[i].name = (char *) malloc(strlen(si->teamBID) + 4))
1242 fprintf(stderr, "%s: Out of Memory\n", progname);
1245 sprintf(si->teamB[i].name, "%s%03d", si->teamBID, i+1);
1246 si->teamB[i].nexttick = (int) (90.0 * random() / RAND_MAX);
1247 si->teamB[i].nextdist = (int) (100.0 * random() / RAND_MAX);
1248 si->teamB[i].movedonsweep = -1;
1257 * Initialize the Sonar.
1260 * dpy - The X display.
1261 * win - The X window;
1264 * A sonar_info strcuture or null if memory allocation problems occur.
1268 init_sonar(Display *dpy, Window win)
1271 /* Local Variables */
1274 XWindowAttributes xwa;
1278 double s1, s2, v1, v2;
1280 /* Create the Sonar information structure */
1282 if ((si = (sonar_info *) calloc(1, sizeof(sonar_info))) == NULL) {
1283 fprintf(stderr, "%s: Out of memory\n", progname);
1287 /* Initialize the structure for the current environment */
1292 XGetWindowAttributes(dpy, win, &xwa);
1293 si->cmap = xwa.colormap;
1294 si->width = xwa.width;
1295 si->height = xwa.height;
1296 si->centrex = si->width / 2;
1297 si->centrey = si->height / 2;
1298 si->maxx = si->centrex + MY_MIN(si->centrex, si->centrey) - 10;
1299 si->minx = si->centrex - MY_MIN(si->centrex, si->centrey) + 10;
1300 si->maxy = si->centrey + MY_MIN(si->centrex, si->centrey) - 10;
1301 si->miny = si->centrey - MY_MIN(si->centrex, si->centrey) + 10;
1302 si->radius = si->maxx - si->centrex;
1308 if (((si->font = XLoadQueryFont(dpy, get_string_resource ("font", "Font")))
1310 ((si->font = XLoadQueryFont(dpy, "fixed")) == NULL)) {
1311 fprintf(stderr, "%s: can't load an appropriate font\n", progname);
1315 /* Get the delay between animation frames */
1317 si->delay = get_integer_resource ("delay", "Integer");
1319 if (si->delay < 0) si->delay = 0;
1320 si->TTL = get_integer_resource("ttl", "TTL");
1322 /* Create the Graphics Contexts that will be used to draw things */
1325 get_pixel_resource ("sweepColor", "SweepColor", dpy, si->cmap);
1326 si->hi = XCreateGC(dpy, win, GCForeground, &gcv);
1327 gcv.font = si->font->fid;
1328 si->text = XCreateGC(dpy, win, GCForeground|GCFont, &gcv);
1329 gcv.foreground = get_pixel_resource("scopeColor", "ScopeColor",
1331 si->erase = XCreateGC (dpy, win, GCForeground, &gcv);
1332 gcv.foreground = get_pixel_resource("gridColor", "GridColor",
1334 si->grid = XCreateGC (dpy, win, GCForeground, &gcv);
1336 /* Compute pixel values for fading text on the display */
1338 XParseColor(dpy, si->cmap,
1339 get_string_resource("textColor", "TextColor"), &start);
1340 XParseColor(dpy, si->cmap,
1341 get_string_resource("scopeColor", "ScopeColor"), &end);
1343 rgb_to_hsv (start.red, start.green, start.blue, &h1, &s1, &v1);
1344 rgb_to_hsv (end.red, end.green, end.blue, &h2, &s2, &v2);
1346 si->text_steps = get_integer_resource("textSteps", "TextSteps");
1347 if (si->text_steps < 0 || si->text_steps > 255)
1348 si->text_steps = 10;
1350 si->text_colors = (XColor *) calloc(si->text_steps, sizeof(XColor));
1351 make_color_ramp (dpy, si->cmap,
1354 si->text_colors, &si->text_steps,
1355 False, True, False);
1357 /* Compute the pixel values for the fading sweep */
1359 XParseColor(dpy, si->cmap,
1360 get_string_resource("sweepColor", "SweepColor"), &start);
1362 rgb_to_hsv (start.red, start.green, start.blue, &h1, &s1, &v1);
1364 si->sweep_degrees = get_integer_resource("sweepDegrees", "Degrees");
1365 if (si->sweep_degrees <= 0) si->sweep_degrees = 20;
1366 if (si->sweep_degrees > 350) si->sweep_degrees = 350;
1368 si->sweep_segs = get_integer_resource("sweepSegments", "SweepSegments");
1369 if (si->sweep_segs < 1 || si->sweep_segs > 255)
1370 si->sweep_segs = 255;
1372 si->sweep_colors = (XColor *) calloc(si->sweep_segs, sizeof(XColor));
1373 make_color_ramp (dpy, si->cmap,
1376 si->sweep_colors, &si->sweep_segs,
1377 False, True, False);
1385 * Update the location of a simulated bogie.
1389 updateLocation(sim_target *t)
1394 xtick = (int) (3.0 * random() / RAND_MAX) - 1;
1395 xdist = (int) (11.0 * random() / RAND_MAX) - 5;
1396 if (((t->nexttick + xtick) < 90) && ((t->nexttick + xtick) >= 0))
1397 t->nexttick += xtick;
1399 t->nexttick -= xtick;
1400 if (((t->nextdist + xdist) < 100) && ((t->nextdist+xdist) >= 0))
1401 t->nextdist += xdist;
1403 t->nextdist -= xdist;
1407 * The simulator. This uses information in the sim_info to simulate a bunch
1408 * of bogies flying around on the screen.
1412 * TODO: It would be cool to have the two teams chase each other around and
1417 simulator(sonar_info *si, void *vinfo)
1420 /* Local Variables */
1426 sim_info *info = (sim_info *) vinfo;
1430 for (i = 0; i < info->numA; i++) {
1431 t = &info->teamA[i];
1432 if ((t->movedonsweep != si->sweepnum) &&
1433 (t->nexttick == (si->current * -1))) {
1434 new = newBogie(strdup(t->name), t->nextdist, si->current, si->TTL);
1439 t->movedonsweep = si->sweepnum;
1445 for (i = 0; i < info->numB; i++) {
1446 t = &info->teamB[i];
1447 if ((t->movedonsweep != si->sweepnum) &&
1448 (t->nexttick == (si->current * -1))) {
1449 new = newBogie(strdup(t->name), t->nextdist, si->current, si->TTL);
1454 t->movedonsweep = si->sweepnum;
1464 * Compute the X coordinate of the label.
1467 * si - The sonar info block.
1468 * label - The label that will be drawn.
1469 * x - The x coordinate of the bogie.
1472 * The x coordinate of the start of the label.
1476 computeStringX(sonar_info *si, char *label, int x)
1479 int width = XTextWidth(si->font, label, strlen(label));
1480 return x - (width / 2);
1484 * Compute the Y coordinate of the label.
1487 * si - The sonar information.
1488 * y - The y coordinate of the bogie.
1491 * The y coordinate of the start of the label.
1494 /* TODO: Add smarts to keep label in sonar screen */
1497 computeStringY(sonar_info *si, int y)
1500 int fheight = si->font->ascent + si->font->descent;
1501 return y + 5 + fheight;
1505 * Draw a Bogie on the radar screen.
1508 * si - Sonar Information.
1509 * draw - A flag to indicate if the bogie should be drawn or erased.
1510 * name - The name of the bogie.
1511 * degrees - The number of degrees that it should apprear at.
1512 * distance - The distance the object is from the centre.
1513 * ttl - The time this bogie has to live.
1514 * age - The time this bogie has been around.
1518 DrawBogie(sonar_info *si, int draw, char *name, int degrees,
1519 int distance, int ttl, int age)
1522 /* Local Variables */
1526 int ox = si->centrex;
1527 int oy = si->centrey;
1530 /* Compute the coordinates of the object */
1533 distance = (log((double) distance) / 10.0) * si->radius;
1534 x = ox + ((double) distance * cos(4.0 * ((double) degrees)/57.29578));
1535 y = oy - ((double) distance * sin(4.0 * ((double) degrees)/57.29578));
1537 /* Set up the graphics context */
1541 /* Here we attempt to compute the distance into the total life of
1542 * object that we currently are. This distance is used against
1543 * the total lifetime to compute a fraction which is the index of
1544 * the color to draw the bogie.
1547 if (si->current <= degrees)
1548 delta = (si->current - degrees) * -1;
1550 delta = 90 + (degrees - si->current);
1551 delta += (age * 90);
1552 index = (si->text_steps - 1) * ((float) delta / (90.0 * (float) ttl));
1554 XSetForeground(si->dpy, gc, si->text_colors[index].pixel);
1559 /* Draw (or erase) the Bogie */
1561 XFillArc(si->dpy, si->win, gc, x, y, 5, 5, 0, 360 * 64);
1562 XDrawString(si->dpy, si->win, gc,
1563 computeStringX(si, name, x),
1564 computeStringY(si, y), name, strlen(name));
1569 * Draw the sonar grid.
1572 * si - Sonar information block.
1576 drawGrid(sonar_info *si)
1579 /* Local Variables */
1582 int width = si->maxx - si->minx;
1583 int height = si->maxy - si->miny;
1585 /* Draw the circles */
1587 XDrawArc(si->dpy, si->win, si->grid, si->minx - 10, si->miny - 10,
1588 width + 20, height + 20, 0, (360 * 64));
1590 XDrawArc(si->dpy, si->win, si->grid, si->minx, si->miny,
1591 width, height, 0, (360 * 64));
1593 XDrawArc(si->dpy, si->win, si->grid,
1594 (int) (si->minx + (.166 * width)),
1595 (int) (si->miny + (.166 * height)),
1596 (unsigned int) (.666 * width), (unsigned int)(.666 * height),
1599 XDrawArc(si->dpy, si->win, si->grid,
1600 (int) (si->minx + (.333 * width)),
1601 (int) (si->miny + (.333 * height)),
1602 (unsigned int) (.333 * width), (unsigned int) (.333 * height),
1605 /* Draw the radial lines */
1607 for (i = 0; i < 360; i += 10)
1609 XDrawLine(si->dpy, si->win, si->grid, si->centrex, si->centrey,
1610 (int) (si->centrex +
1611 (si->radius + 10) * (cos((double) i / 57.29578))),
1612 (int) (si->centrey -
1613 (si->radius + 10)*(sin((double) i / 57.29578))));
1615 XDrawLine(si->dpy, si->win, si->grid,
1616 (int) (si->centrex + si->radius *
1617 (cos((double) i / 57.29578))),
1618 (int) (si->centrey - si->radius *
1619 (sin((double) i / 57.29578))),
1620 (int) (si->centrex +
1621 (si->radius + 10) * (cos((double) i / 57.29578))),
1622 (int) (si->centrey -
1623 (si->radius + 10) * (sin((double) i / 57.29578))));
1627 * Update the Sonar scope.
1630 * si - The Sonar information.
1631 * bl - A list of bogies to add to the scope.
1635 Sonar(sonar_info *si, Bogie *bl)
1638 /* Local Variables */
1643 /* Check for expired tagets and remove them from the visable list */
1646 for (bp = si->visable; bp != NULL; bp = bp->next) {
1649 * Remove it from the visable list if it's expired or we have
1650 * a new target with the same name.
1655 if (((bp->tick == si->current) && (++bp->age >= bp->ttl)) ||
1656 (findNode(bl, bp->name) != NULL)) {
1657 DrawBogie(si, 0, bp->name, bp->tick,
1658 bp->distance, bp->ttl, bp->age);
1660 si->visable = bp->next;
1662 prev->next = bp->next;
1668 /* Draw the sweep */
1671 int seg_deg = (si->sweep_degrees * 64) / si->sweep_segs;
1672 int start_deg = si->current * 4 * 64;
1673 if (seg_deg <= 0) seg_deg = 1;
1674 for (i = 0; i < si->sweep_segs; i++) {
1675 XSetForeground(si->dpy, si->hi, si->sweep_colors[i].pixel);
1676 XFillArc(si->dpy, si->win, si->hi, si->minx, si->miny,
1677 si->maxx - si->minx, si->maxy - si->miny,
1678 start_deg + (i * seg_deg),
1682 /* Remove the trailing wedge the sonar */
1683 XFillArc(si->dpy, si->win, si->erase, si->minx, si->miny,
1684 si->maxx - si->minx, si->maxy - si->miny,
1685 start_deg + (i * seg_deg),
1689 /* Move the new targets to the visable list */
1691 for (bp = bl; bp != (Bogie *) 0; bp = bl) {
1693 bp->next = si->visable;
1697 /* Draw the visable targets */
1699 for (bp = si->visable; bp != NULL; bp = bp->next) {
1700 if (bp->age < bp->ttl) /* grins */
1701 DrawBogie(si, 1, bp->name, bp->tick, bp->distance, bp->ttl,bp->age);
1704 /* Redraw the grid */
1710 static ping_target *
1711 parse_mode (Bool ping_works_p)
1713 char *source = get_string_resource ("ping", "Ping");
1716 ping_target *hostlist = 0;
1718 if (!source) source = strdup("");
1720 if (!*source || !strcmp (source, "default"))
1723 if (ping_works_p) /* if root or setuid, ping will work. */
1724 source = strdup("subnet/29,/etc/hosts");
1727 source = strdup("simulation");
1731 end = source + strlen(source);
1737 unsigned int n0=0, n1=0, n2=0, n3=0, m=0;
1741 *next != ',' && *next != ' ' && *next != '\t' && *next != '\n';
1748 fprintf (stderr, "%s: parsing %s\n", progname, token);
1750 if (!strcmp (token, "simulation"))
1756 "%s: this program must be setuid to root for `ping mode' to work.\n"
1757 " Running in `simulation mode' instead.\n",
1762 if ((4 == sscanf (token, "%d.%d.%d/%d %c", &n0,&n1,&n2, &m,&d)) ||
1763 (5 == sscanf (token, "%d.%d.%d.%d/%d %c", &n0,&n1,&n2,&n3,&m,&d)))
1765 /* subnet: A.B.C.D/M
1768 unsigned long ip = (n0 << 24) | (n1 << 16) | (n2 << 8) | n3;
1769 new = subnetHostsList(ip, m);
1771 else if (4 == sscanf (token, "%d.%d.%d.%d %c", &n0, &n1, &n2, &n3, &d))
1775 new = newHost (token);
1777 else if (!strcmp (token, "subnet"))
1779 new = subnetHostsList(0, 24);
1781 else if (1 == sscanf (token, "subnet/%d %c", &m))
1783 new = subnetHostsList(0, m);
1785 else if (*token == '.' || *token == '/' || !stat (token, &st))
1789 new = readPingHostsFile (token);
1793 /* not an existant file - must be a host name
1795 new = newHost (token);
1800 ping_target *nn = new;
1801 while (nn && nn->next)
1803 nn->next = hostlist;
1810 while (token < end &&
1811 (*token == ',' || *token == ' ' ||
1812 *token == '\t' || *token == '\n'))
1822 * Main screen saver hack.
1825 * dpy - The X display.
1826 * win - The X window.
1830 screenhack(Display *dpy, Window win)
1833 /* Local Variables */
1836 struct timeval start, finish;
1840 debug_p = get_boolean_resource ("debug", "Debug");
1843 sensor_info = (void *) init_ping();
1848 if ((sensor_info = (void *) init_sim()) == NULL)
1852 if ((si = init_sonar(dpy, win)) == (sonar_info *) 0)
1860 /* Call the sensor and display the results */
1862 gettimeofday(&start, (struct timezone *) 0);
1863 bl = sensor(si, sensor_info);
1866 /* Set up and sleep for the next one */
1868 si->current = (si->current - 1) % 90;
1869 if (si->current == 0)
1872 gettimeofday(&finish, (struct timezone *) 0);
1873 sleeptime = si->delay - delta(&start, &finish);
1874 screenhack_handle_events (dpy);