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, 2001
32 * by Stephen Martin (smartin@vanderfleet-martin.net).
33 * Permission to use, copy, modify, distribute, and sell this software and its
34 * documentation for any purpose is hereby granted without fee, provided that
35 * the above copyright notice appear in all copies and that both that
36 * copyright notice and this permission notice appear in supporting
37 * documentation. No representations are made about the suitability of this
38 * software for any purpose. It is provided "as is" without express or
43 * Version 1.0 April 27, 1998.
45 * - Submitted to RedHat Screensaver Contest
47 * Version 1.1 November 3, 1998.
48 * - Added simulation mode.
49 * - Added enhancements by Thomas Bahls <thommy@cs.tu-berlin.de>
50 * - Fixed huge memory leak.
51 * - Submitted to xscreensavers
54 * - All ping code is now ifdef-ed by the compile time symbol HAVE_PING;
55 * use -DHAVE_PING to include it when you compile.
56 * - Sweep now uses gradients.
57 * - Fixed portability problems with icmphdr on some systems.
58 * - removed lowColor option/resource.
59 * - changed copyright notice so that it could be included in the xscreensavers
62 * Version 1.3 November 16, 1998.
63 * - All ping code is now ifdef-ed by the compile time symbol PING use -DPING
64 * to include it when you compile.
65 * - Sweep now uses gradients.
66 * - Fixed portability problems with icmphdr on some systems.
67 * - removed lowcolour option/resource.
68 * - changed copyright notice so that it could be included in the xscreensavers
71 * Version 1.4 November 18, 1998.
72 * - More ping portability fixes.
74 * Version 1.5 November 19, 1998.
75 * - Synced up with jwz's changes.
76 * - Now need to define HAVE_PING to compile in the ping stuff.
79 /* These are computed by configure now:
92 #include "screenhack.h"
96 #if defined(HAVE_ICMP) || defined(HAVE_ICMPHDR)
101 # include <sys/types.h>
102 # include <sys/time.h>
103 # include <sys/ipc.h>
104 # include <sys/shm.h>
105 # include <sys/socket.h>
106 # include <netinet/in_systm.h>
107 # include <netinet/in.h>
108 # include <netinet/ip.h>
109 # include <netinet/ip_icmp.h>
110 # include <netinet/udp.h>
111 # include <arpa/inet.h>
113 #endif /* HAVE_ICMP || HAVE_ICMPHDR */
119 #define MY_MIN(a,b) ((a)<(b)?(a - 50):(b - 10))
122 # define LINE_MAX 2048
127 #if defined(HAVE_ICMP)
130 # define ICMP_TYPE(p) (p)->icmp_type
131 # define ICMP_CODE(p) (p)->icmp_code
132 # define ICMP_CHECKSUM(p) (p)->icmp_cksum
133 # define ICMP_ID(p) (p)->icmp_id
134 # define ICMP_SEQ(p) (p)->icmp_seq
135 #elif defined(HAVE_ICMPHDR)
137 # define ICMP icmphdr
138 # define ICMP_TYPE(p) (p)->type
139 # define ICMP_CODE(p) (p)->code
140 # define ICMP_CHECKSUM(p) (p)->checksum
141 # define ICMP_ID(p) (p)->un.echo.id
142 # define ICMP_SEQ(p) (p)->un.echo.sequence
149 # if defined(__DECC) || defined(_IP_VHL)
150 /* This is how you do it on DEC C, and possibly some BSD systems. */
151 # define IP_HDRLEN(ip) ((ip)->ip_vhl & 0x0F)
153 /* This is how you do it on everything else. */
154 # define IP_HDRLEN(ip) ((ip)->ip_hl)
156 #endif /* HAVE_PING */
159 /* Forward References */
162 static u_short checksum(u_short *, int);
164 static long delta(struct timeval *, struct timeval *);
167 /* Data Structures */
172 * This represents an object that is visable on the scope.
175 typedef struct Bogie {
176 char *name; /* The name of the thing being displayed */
177 int distance; /* The distance to this thing (0 - 100) */
178 int tick; /* The tick that it was found on */
179 int ttl; /* The time to live */
180 int age; /* How long it's been around */
181 struct Bogie *next; /* The next one in the list */
187 * This contains all of the runtime information about the sonar scope.
191 Display *dpy; /* The X display */
192 Window win; /* The window */
193 GC hi, /* The leading edge of the sweep */
194 lo, /* The trailing part of the sweep */
195 erase, /* Used to erase things */
196 grid, /* Used to draw the grid */
197 text; /* Used to draw text */
198 Colormap cmap; /* The colormap */
199 XFontStruct *font; /* The font to use for the labels */
200 int text_steps; /* How many steps to fade text. */
201 XColor *text_colors; /* Pixel values used to fade text */
202 int sweep_degrees; /* How much of the circle the sweep uses */
203 int sweep_segs; /* How many gradients in the sweep. */
204 XColor *sweep_colors; /* The sweep pixel values */
205 int width, height; /* Window dimensions */
206 int minx, miny, maxx, maxy, /* Bounds of the scope */
207 centrex, centrey, radius; /* Parts of the scope circle */
208 Bogie *visable; /* List of visable objects */
209 int current; /* Current position of sweep */
210 int sweepnum; /* The current id of the sweep */
211 int delay; /* how long between each frame of the anim */
213 int TTL; /* The number of ticks that bogies are visible
214 on the screen before they fade away. */
217 static Bool debug_p = False;
221 * Variables to support the differnt Sonar modes.
224 Bogie *(*sensor)(sonar_info *, void *); /* The current sensor */
225 void *sensor_info; /* Information about the sensor */
228 * A list of targets to ping.
231 typedef struct ping_target {
232 char *name; /* The name of the target */
234 struct sockaddr address; /* The address of the target */
235 #endif /* HAVE_PING */
236 struct ping_target *next; /* The next one in the list */
244 * This contains the information for the ping sensor.
248 int icmpsock; /* Socket for sending pings */
249 int pid; /* Our process ID */
250 int seq; /* Packet sequence number */
251 int timeout; /* Timeout value for pings */
252 ping_target *targets; /* List of targets to ping */
253 int numtargets; /* The number of targets to ping */
256 /* Flag to indicate that the timer has expired on us */
258 static int timer_expired;
260 #endif /* HAVE_PING */
263 * A list of targets for the simulator
266 typedef struct sim_target {
267 char *name; /* The name of the target */
268 int nexttick; /* The next tick that this will be seen */
269 int nextdist; /* The distance on that tick */
270 int movedonsweep; /* The number of the sweep this last moved */
274 * Simulator Information.
276 * This contains the information for the simulator mode.
280 sim_target *teamA; /* The bogies for the A team */
281 int numA; /* The number of bogies in team A */
282 char *teamAID; /* The identifier for bogies in team A */
283 sim_target *teamB; /* The bogies for the B team */
284 int numB; /* The number of bogies in team B */
285 char *teamBID; /* The identifier for bogies in team B */
288 /* Name of the Screensaver hack */
290 char *progclass="sonar";
292 /* Application Defaults */
294 char *defaults [] = {
295 ".background: #000000",
296 ".sweepColor: #00FF00",
298 "*scopeColor: #003300",
299 "*gridColor: #00AA00",
300 "*textColor: #FFFF00",
306 "*textSteps: 80", /* npixels */
307 "*sweepSegments: 80", /* npixels */
309 "*pingTimeout: 3000",
321 /* Options passed to this program */
323 XrmOptionDescRec options [] = {
324 {"-background", ".background", XrmoptionSepArg, 0 },
325 {"-sweep-color", ".sweepColor", XrmoptionSepArg, 0 },
326 {"-scope-color", ".scopeColor", XrmoptionSepArg, 0 },
327 {"-grid-color", ".gridColor", XrmoptionSepArg, 0 },
328 {"-text-color", ".textColor", XrmoptionSepArg, 0 },
329 {"-ttl", ".ttl", XrmoptionSepArg, 0 },
330 {"-font", ".font", XrmoptionSepArg, 0 },
332 {"-ping-timeout", ".pingTimeout", XrmoptionSepArg, 0 },
333 #endif /* HAVE_PING */
334 {"-team-a-name", ".teamAName", XrmoptionSepArg, 0 },
335 {"-team-b-name", ".teamBName", XrmoptionSepArg, 0 },
336 {"-team-a-count", ".teamACount", XrmoptionSepArg, 0 },
337 {"-team-b-count", ".teamBCount", XrmoptionSepArg, 0 },
339 {"-ping", ".ping", XrmoptionSepArg, 0 },
340 {"-debug", ".debug", XrmoptionNoArg, "True" },
345 * Create a new Bogie and set some initial values.
348 * name - The name of the bogie.
349 * distance - The distance value.
350 * tick - The tick value.
351 * ttl - The time to live value.
354 * The newly allocated bogie or null if a memory problem occured.
358 newBogie(char *name, int distance, int tick, int ttl)
361 /* Local Variables */
365 /* Allocate a bogie and initialize it */
367 if ((new = (Bogie *) calloc(1, sizeof(Bogie))) == NULL) {
368 fprintf(stderr, "%s: Out of Memory\n", progname);
372 new->distance = distance;
376 new->next = (Bogie *) 0;
384 * b - The bogie to free.
391 if (b->name != (char *) 0)
397 * Find a bogie by name in a list.
399 * This does a simple linear search of the list for a given name.
402 * bl - The Bogie list to search.
403 * name - The name to look for.
406 * The requested Bogie or null if it wasn't found.
410 findNode(Bogie *bl, char *name)
413 /* Local Variables */
417 /* Abort if the list is empty or no name is given */
419 if ((name == NULL) || (bl == NULL))
422 /* Search the list for the desired name */
426 if (strcmp(p->name, name) == 0)
439 * Lookup the address for a ping target;
442 * target - The ping_target fill in the address for.
445 * 1 if the host was successfully resolved, 0 otherwise.
449 lookupHost(ping_target *target)
452 struct hostent *hent;
454 /* Local Variables */
456 struct sockaddr_in *iaddr;
458 /* Set up the target address we first assume that the name is the
459 IP address as a string */
461 iaddr = (struct sockaddr_in *) &(target->address);
462 iaddr->sin_family = AF_INET;
463 if ((iaddr->sin_addr.s_addr = inet_addr(target->name)) >= 0) {
465 ip[3] = iaddr->sin_addr.s_addr >> 24 & 255;
466 ip[2] = iaddr->sin_addr.s_addr >> 16 & 255;
467 ip[1] = iaddr->sin_addr.s_addr >> 8 & 255;
468 ip[0] = iaddr->sin_addr.s_addr & 255;
469 hent = gethostbyaddr (ip, 4, AF_INET);
470 if (hent && hent->h_name && *hent->h_name) {
471 target->name = strdup (hent->h_name);
476 /* Conversion of IP address failed, try to look the host up by name */
478 hent = gethostbyname(target->name);
480 fprintf(stderr, "%s: could not resolve host %s\n",
481 progname, target->name);
484 memcpy(&iaddr->sin_addr, hent->h_addr_list[0],
485 sizeof(iaddr->sin_addr));
493 * Create a target for a host.
496 * name - The name of the host.
499 * A newly allocated target or null if the host could not be resolved.
506 /* Local Variables */
508 ping_target *target = NULL;
510 /* Create the target */
512 if ((target = calloc(1, sizeof(ping_target))) == NULL) {
513 fprintf(stderr, "%s: Out of Memory\n", progname);
514 goto target_init_error;
516 if ((target->name = strdup(name)) == NULL) {
517 fprintf(stderr, "%s: Out of Memory\n", progname);
518 goto target_init_error;
521 /* Lookup the host */
523 if (! lookupHost(target))
524 goto target_init_error;
530 struct sockaddr_in *iaddr = (struct sockaddr_in *) &(target->address);
531 unsigned long ip = iaddr->sin_addr.s_addr;
532 fprintf (stderr, "%s: added host %d.%d.%d.%d (%s)\n", progname,
533 ip & 255, ip >> 8 & 255, ip >> 16 & 255, ip >> 24 & 255,
539 /* Handle errors here */
548 * Generate a list of ping targets from the entries in a file.
551 * fname - The name of the file. This file is expected to be in the same
552 * format as /etc/hosts.
555 * A list of targets to ping or null if an error occured.
559 readPingHostsFile(char *fname)
561 /* Local Variables */
566 ping_target *list = NULL;
570 /* Make sure we in fact have a file to process */
572 if ((fname == NULL) || (fname[0] == '\0')) {
573 fprintf(stderr, "%s: invalid ping host file name\n", progname);
579 if ((fp = fopen(fname, "r")) == NULL) {
581 sprintf(msg, "%s: unable to open host file %s", progname, fname);
587 fprintf (stderr, "%s: reading file %s\n", progname, fname);
589 /* Read the file line by line */
591 while ((p = fgets(buf, LINE_MAX, fp)) != NULL) {
594 * Parse the line skipping those that start with '#'.
595 * The rest of the lines in the file should be in the same
596 * format as a /etc/hosts file. We are only concerned with
597 * the first two field, the IP address and the name
600 while ((*p == ' ') || (*p == '\t'))
605 /* Get the name and address */
608 if ((addr = strtok(buf, " \t\n")) != NULL)
609 name = strtok(NULL, " \t\n");
613 /* Check to see if the addr looks like an addr. If not, assume
614 the addr is a name and there is no addr. This way, we can
615 handle files whose lines have "xx.xx.xx.xx hostname" as their
616 first two tokens, and also files that have a hostname as their
617 first token (like .ssh/known_hosts and .rhosts.)
621 if (4 != sscanf(addr, "%d.%d.%d.%d%c", &i, &i, &i, &i, &c))
627 /*printf ("\"%s\" \"%s\"\n", name, addr);*/
629 /* Create a new target using first the name then the address */
634 if (new == NULL && addr != NULL)
637 /* Add it to the list if we got one */
645 /* Close the file and return the list */
653 delete_duplicate_hosts (ping_target *list)
655 ping_target *head = list;
658 for (rest = head; rest; rest = rest->next)
660 struct sockaddr_in *i1 = (struct sockaddr_in *) &(rest->address);
661 unsigned long ip1 = i1->sin_addr.s_addr;
663 static ping_target *rest2;
664 for (rest2 = rest; rest2; rest2 = rest2->next)
666 if (rest2 && rest2->next)
668 struct sockaddr_in *i2 = (struct sockaddr_in *)
669 &(rest2->next->address);
670 unsigned long ip2 = i2->sin_addr.s_addr;
675 fprintf (stderr, "%s: deleted duplicate: %s\n",
676 progname, rest2->next->name);
677 rest2->next = rest2->next->next;
690 * Generate a list ping targets consisting of all of the entries on
694 * A list of all of the hosts on this net.
698 subnetHostsList(int base, int subnet_width)
702 /* Local Variables */
704 char hostname[BUFSIZ];
705 char address[BUFSIZ];
706 struct hostent *hent;
710 ping_target *list = NULL;
712 if (subnet_width < 24)
715 "%s: pinging %u hosts is a bad idea; please use a subnet mask of 24 bits\n"
716 " or more (255 hosts max.)\n",
717 progname, (1L << (32 - subnet_width)) - 1);
720 else if (subnet_width > 30)
722 fprintf (stderr, "%s: a subnet of %d bits doesn't make sense:"
723 " try \"subnet/24\" or \"subnet/29\".\n",
724 progname, subnet_width);
730 fprintf (stderr, "%s: adding %d-bit subnet\n", progname, subnet_width);
732 /* Get our hostname */
734 if (gethostname(hostname, BUFSIZ)) {
735 fprintf(stderr, "%s: unable to get local hostname\n", progname);
739 /* Get our IP address and convert it to a string */
741 if ((hent = gethostbyname(hostname)) == NULL) {
742 fprintf(stderr, "%s: unable to lookup our IP address\n", progname);
745 strcpy(address, inet_ntoa(*((struct in_addr *)hent->h_addr_list[0])));
747 /* Construct targets for all addresses in this subnet */
750 for (i = 0; i < subnet_width; i++)
751 mask |= (1L << (31-i));
753 /* If no base IP specified, assume localhost. */
755 base = ((((unsigned char) hent->h_addr_list[0][0]) << 24) |
756 (((unsigned char) hent->h_addr_list[0][1]) << 16) |
757 (((unsigned char) hent->h_addr_list[0][2]) << 8) |
758 (((unsigned char) hent->h_addr_list[0][3])));
760 for (i = 255; i >= 0; i--) {
761 int ip = (base & 0xFFFFFF00) | i;
763 if ((ip & mask) != (base & mask)) /* not in the mask range at all */
765 if ((ip & ~mask) == 0) /* broadcast address */
767 if ((ip & ~mask) == ~mask) /* broadcast address */
770 sprintf (address, "%d.%d.%d.%d",
771 (ip>>24)&255, (ip>>16)&255, (ip>>8)&255, (ip)&255);
774 fprintf(stderr, "%s: subnet: %s (%d.%d.%d.%d & %d.%d.%d.%d / %d)\n",
777 (base>>24)&255, (base>>16)&255, (base>>8)&255, base&mask&255,
778 (mask>>24)&255, (mask>>16)&255, (mask>>8)&255, mask&255,
781 p = address + strlen(address) + 1;
784 new = newHost(address);
797 * Initialize the ping sensor.
800 * A newly allocated ping_info structure or null if an error occured.
803 static ping_target *parse_mode (Bool ping_works_p);
809 Bool socket_initted_p = False;
811 /* Local Variables */
813 ping_info *pi = NULL; /* The new ping_info struct */
814 ping_target *pt; /* Used to count the targets */
816 /* Create the ping info structure */
818 if ((pi = (ping_info *) calloc(1, sizeof(ping_info))) == NULL) {
819 fprintf(stderr, "%s: Out of memory\n", progname);
820 goto ping_init_error;
823 /* Create the ICMP socket */
825 if ((pi->icmpsock = socket(AF_INET, SOCK_RAW, IPPROTO_ICMP)) >= 0) {
826 socket_initted_p = True;
834 pi->pid = getpid() & 0xFFFF;
836 pi->timeout = get_integer_resource("pingTimeout", "PingTimeout");
838 /* Generate a list of targets */
840 pi->targets = parse_mode (socket_initted_p);
841 pi->targets = delete_duplicate_hosts (pi->targets);
844 /* Make sure there is something to ping */
846 if (pi->targets == NULL) {
847 goto ping_init_error;
850 /* Count the targets */
863 /* Handle initialization errors here */
876 * pi - The ping information strcuture.
877 * host - The name or IP address of the host to ping (in ascii).
881 sendping(ping_info *pi, ping_target *pt)
884 /* Local Variables */
891 * Note, we will send the character name of the host that we are
892 * pinging in the packet so that we don't have to keep track of the
893 * name or do an address lookup when it comes back.
896 int pcktsiz = sizeof(struct ICMP) + sizeof(struct timeval) +
897 strlen(pt->name) + 1;
899 /* Create the ICMP packet */
901 if ((packet = (u_char *) malloc(pcktsiz)) == (void *) 0)
902 return; /* Out of memory */
903 icmph = (struct ICMP *) packet;
904 ICMP_TYPE(icmph) = ICMP_ECHO;
905 ICMP_CODE(icmph) = 0;
906 ICMP_CHECKSUM(icmph) = 0;
907 ICMP_ID(icmph) = pi->pid;
908 ICMP_SEQ(icmph) = pi->seq++;
909 gettimeofday((struct timeval *) &packet[sizeof(struct ICMP)],
910 (struct timezone *) 0);
911 strcpy((char *) &packet[sizeof(struct ICMP) + sizeof(struct timeval)],
913 ICMP_CHECKSUM(icmph) = checksum((u_short *)packet, pcktsiz);
917 if ((result = sendto(pi->icmpsock, packet, pcktsiz, 0,
918 &pt->address, sizeof(pt->address))) != pcktsiz) {
921 sprintf(errbuf, "%s: error sending ping to %s", progname, pt->name);
928 * Catch a signal and do nothing.
931 * sig - The signal that was caught.
941 * Compute the checksum on a ping packet.
944 * packet - A pointer to the packet to compute the checksum for.
945 * size - The size of the packet.
948 * The computed checksum
953 checksum(u_short *packet, int size)
956 /* Local Variables */
958 register int nleft = size;
959 register u_short *w = packet;
960 register int sum = 0;
964 * Our algorithm is simple, using a 32 bit accumulator (sum), we add
965 * sequential 16 bit words to it, and at the end, fold back all the
966 * carry bits from the top 16 bits into the lower 16 bits.
974 /* mop up an odd byte, if necessary */
977 *(u_char *)(&answer) = *(u_char *)w ;
978 *(1 + (u_char *)(&answer)) = 0;
982 /* add back carry outs from top 16 bits to low 16 bits */
984 sum = (sum >> 16) + (sum & 0xffff); /* add hi 16 to low 16 */
985 sum += (sum >> 16); /* add carry */
986 answer = ~sum; /* truncate to 16 bits */
994 * Look for ping replies.
996 * Retrieve all outstanding ping replies.
999 * si - Information about the sonar.
1000 * pi - Ping information.
1001 * ttl - The time each bogie is to live on the screen
1004 * A Bogie list of all the machines that replied.
1008 getping(sonar_info *si, ping_info *pi)
1011 /* Local Variables */
1013 struct sockaddr from;
1016 u_char packet[1024];
1018 struct timeval *then;
1025 struct sigaction sa;
1026 struct itimerval it;
1030 /* Set up a signal to interupt our wait for a packet */
1032 sigemptyset(&sa.sa_mask);
1034 sa.sa_handler = sigcatcher;
1035 if (sigaction(SIGALRM, &sa, 0) == -1) {
1037 sprintf(msg, "%s: unable to trap SIGALRM", progname);
1042 /* Set up a timer to interupt us if we don't get a packet */
1044 it.it_interval.tv_sec = 0;
1045 it.it_interval.tv_usec = 0;
1046 it.it_value.tv_sec = 0;
1047 it.it_value.tv_usec = pi->timeout;
1049 setitimer(ITIMER_REAL, &it, NULL);
1051 /* Wait for a result packet */
1053 fromlen = sizeof(from);
1054 while (! timer_expired) {
1055 tv.tv_usec=pi->timeout;
1058 FD_SET(pi->icmpsock,&rfds);
1059 /* only wait a little while, in case we raced with the timer expiration.
1060 From Valentijn Sessink <valentyn@openoffice.nl> */
1061 if (select(pi->icmpsock+1, &rfds, NULL, NULL, &tv) >0) {
1062 result = recvfrom(pi->icmpsock, packet, sizeof(packet),
1063 0, &from, &fromlen);
1065 /* Check the packet */
1067 gettimeofday(&now, (struct timezone *) 0);
1068 ip = (struct ip *) packet;
1069 iphdrlen = IP_HDRLEN(ip) << 2;
1070 icmph = (struct ICMP *) &packet[iphdrlen];
1072 /* Was the packet a reply?? */
1074 if (ICMP_TYPE(icmph) != ICMP_ECHOREPLY) {
1075 /* Ignore anything but ICMP Replies */
1076 continue; /* Nope */
1079 /* Was it for us? */
1081 if (ICMP_ID(icmph) != pi->pid) {
1082 /* Ignore packets not set from us */
1083 continue; /* Nope */
1086 /* Copy the name of the bogie */
1089 strdup((char *) &packet[iphdrlen +
1090 + sizeof(struct ICMP)
1091 + sizeof(struct timeval)])) == NULL) {
1092 fprintf(stderr, "%s: Out of memory\n", progname);
1096 /* If the name is an IP addr, try to resolve it. */
1100 if (4 == sscanf(name, " %d.%d.%d.%d %c",
1101 &iip[0], &iip[1], &iip[2], &iip[3], &c))
1103 unsigned char ip[4];
1105 ip[0] = iip[0]; ip[1] = iip[1]; ip[2] = iip[2]; ip[3] = iip[3];
1106 h = gethostbyaddr ((char *) ip, 4, AF_INET);
1107 if (h && h->h_name && *h->h_name)
1110 name = strdup (h->h_name);
1115 /* Create the new Bogie and add it to the list we are building */
1117 if ((new = newBogie(name, 0, si->current, si->TTL)) == NULL)
1122 /* Compute the round trip time */
1124 then = (struct timeval *) &packet[iphdrlen +
1125 sizeof(struct ICMP)];
1126 new->distance = delta(then, &now) / 100;
1127 if (new->distance == 0)
1128 new->distance = 2; /* HACK */
1141 * si - Sonar Information.
1142 * pi - Ping Information.
1145 * A list of hosts that replied to pings or null if there were none.
1149 ping(sonar_info *si, void *vpi)
1153 * This tries to distribute the targets evely around the field of the
1157 ping_info *pi = (ping_info *) vpi;
1158 static ping_target *ptr = NULL;
1160 int tick = si->current * -1 + 1;
1161 if ((ptr == NULL) && (tick == 1))
1164 if (pi->numtargets <= 90) {
1165 int xdrant = 90 / pi->numtargets;
1166 if ((tick % xdrant) == 0) {
1167 if (ptr != (ping_target *) 0) {
1173 } else if (pi->numtargets > 90) {
1174 if (ptr != (ping_target *) 0) {
1180 /* Get the results */
1182 return getping(si, pi);
1185 #endif /* HAVE_PING */
1188 * Calculate the difference between two timevals in microseconds.
1191 * then - The older timeval.
1192 * now - The newer timeval.
1195 * The difference between the two in microseconds.
1199 delta(struct timeval *then, struct timeval *now)
1201 return (((now->tv_sec - then->tv_sec) * 1000000) +
1202 (now->tv_usec - then->tv_usec));
1206 * Initialize the simulation mode.
1213 /* Local Variables */
1218 /* Create the simulation info structure */
1220 if ((si = (sim_info *) calloc(1, sizeof(sim_info))) == NULL) {
1221 fprintf(stderr, "%s: Out of memory\n", progname);
1227 si->numA = get_integer_resource("teamACount", "TeamACount");
1228 if ((si->teamA = (sim_target *)calloc(si->numA, sizeof(sim_target)))
1231 fprintf(stderr, "%s: Out of Memory\n", progname);
1234 si->teamAID = get_string_resource("teamAName", "TeamAName");
1235 for (i = 0; i < si->numA; i++) {
1236 if ((si->teamA[i].name = (char *) malloc(strlen(si->teamAID) + 4))
1239 fprintf(stderr, "%s: Out of Memory\n", progname);
1242 sprintf(si->teamA[i].name, "%s%03d", si->teamAID, i+1);
1243 si->teamA[i].nexttick = (int) (90.0 * random() / RAND_MAX);
1244 si->teamA[i].nextdist = (int) (100.0 * random() / RAND_MAX);
1245 si->teamA[i].movedonsweep = -1;
1250 si->numB = get_integer_resource("teamBCount", "TeamBCount");
1251 if ((si->teamB = (sim_target *)calloc(si->numB, sizeof(sim_target)))
1254 fprintf(stderr, "%s: Out of Memory\n", progname);
1257 si->teamBID = get_string_resource("teamBName", "TeamBName");
1258 for (i = 0; i < si->numB; i++) {
1259 if ((si->teamB[i].name = (char *) malloc(strlen(si->teamBID) + 4))
1262 fprintf(stderr, "%s: Out of Memory\n", progname);
1265 sprintf(si->teamB[i].name, "%s%03d", si->teamBID, i+1);
1266 si->teamB[i].nexttick = (int) (90.0 * random() / RAND_MAX);
1267 si->teamB[i].nextdist = (int) (100.0 * random() / RAND_MAX);
1268 si->teamB[i].movedonsweep = -1;
1277 * Initialize the Sonar.
1280 * dpy - The X display.
1281 * win - The X window;
1284 * A sonar_info strcuture or null if memory allocation problems occur.
1288 init_sonar(Display *dpy, Window win)
1291 /* Local Variables */
1294 XWindowAttributes xwa;
1298 double s1, s2, v1, v2;
1300 /* Create the Sonar information structure */
1302 if ((si = (sonar_info *) calloc(1, sizeof(sonar_info))) == NULL) {
1303 fprintf(stderr, "%s: Out of memory\n", progname);
1307 /* Initialize the structure for the current environment */
1312 XGetWindowAttributes(dpy, win, &xwa);
1313 si->cmap = xwa.colormap;
1314 si->width = xwa.width;
1315 si->height = xwa.height;
1316 si->centrex = si->width / 2;
1317 si->centrey = si->height / 2;
1318 si->maxx = si->centrex + MY_MIN(si->centrex, si->centrey) - 10;
1319 si->minx = si->centrex - MY_MIN(si->centrex, si->centrey) + 10;
1320 si->maxy = si->centrey + MY_MIN(si->centrex, si->centrey) - 10;
1321 si->miny = si->centrey - MY_MIN(si->centrex, si->centrey) + 10;
1322 si->radius = si->maxx - si->centrex;
1328 if (((si->font = XLoadQueryFont(dpy, get_string_resource ("font", "Font")))
1330 ((si->font = XLoadQueryFont(dpy, "fixed")) == NULL)) {
1331 fprintf(stderr, "%s: can't load an appropriate font\n", progname);
1335 /* Get the delay between animation frames */
1337 si->delay = get_integer_resource ("delay", "Integer");
1339 if (si->delay < 0) si->delay = 0;
1340 si->TTL = get_integer_resource("ttl", "TTL");
1342 /* Create the Graphics Contexts that will be used to draw things */
1345 get_pixel_resource ("sweepColor", "SweepColor", dpy, si->cmap);
1346 si->hi = XCreateGC(dpy, win, GCForeground, &gcv);
1347 gcv.font = si->font->fid;
1348 si->text = XCreateGC(dpy, win, GCForeground|GCFont, &gcv);
1349 gcv.foreground = get_pixel_resource("scopeColor", "ScopeColor",
1351 si->erase = XCreateGC (dpy, win, GCForeground, &gcv);
1352 gcv.foreground = get_pixel_resource("gridColor", "GridColor",
1354 si->grid = XCreateGC (dpy, win, GCForeground, &gcv);
1356 /* Compute pixel values for fading text on the display */
1358 XParseColor(dpy, si->cmap,
1359 get_string_resource("textColor", "TextColor"), &start);
1360 XParseColor(dpy, si->cmap,
1361 get_string_resource("scopeColor", "ScopeColor"), &end);
1363 rgb_to_hsv (start.red, start.green, start.blue, &h1, &s1, &v1);
1364 rgb_to_hsv (end.red, end.green, end.blue, &h2, &s2, &v2);
1366 si->text_steps = get_integer_resource("textSteps", "TextSteps");
1367 if (si->text_steps < 0 || si->text_steps > 255)
1368 si->text_steps = 10;
1370 si->text_colors = (XColor *) calloc(si->text_steps, sizeof(XColor));
1371 make_color_ramp (dpy, si->cmap,
1374 si->text_colors, &si->text_steps,
1375 False, True, False);
1377 /* Compute the pixel values for the fading sweep */
1379 XParseColor(dpy, si->cmap,
1380 get_string_resource("sweepColor", "SweepColor"), &start);
1382 rgb_to_hsv (start.red, start.green, start.blue, &h1, &s1, &v1);
1384 si->sweep_degrees = get_integer_resource("sweepDegrees", "Degrees");
1385 if (si->sweep_degrees <= 0) si->sweep_degrees = 20;
1386 if (si->sweep_degrees > 350) si->sweep_degrees = 350;
1388 si->sweep_segs = get_integer_resource("sweepSegments", "SweepSegments");
1389 if (si->sweep_segs < 1 || si->sweep_segs > 255)
1390 si->sweep_segs = 255;
1392 si->sweep_colors = (XColor *) calloc(si->sweep_segs, sizeof(XColor));
1393 make_color_ramp (dpy, si->cmap,
1396 si->sweep_colors, &si->sweep_segs,
1397 False, True, False);
1405 * Update the location of a simulated bogie.
1409 updateLocation(sim_target *t)
1414 xtick = (int) (3.0 * random() / RAND_MAX) - 1;
1415 xdist = (int) (11.0 * random() / RAND_MAX) - 5;
1416 if (((t->nexttick + xtick) < 90) && ((t->nexttick + xtick) >= 0))
1417 t->nexttick += xtick;
1419 t->nexttick -= xtick;
1420 if (((t->nextdist + xdist) < 100) && ((t->nextdist+xdist) >= 0))
1421 t->nextdist += xdist;
1423 t->nextdist -= xdist;
1427 * The simulator. This uses information in the sim_info to simulate a bunch
1428 * of bogies flying around on the screen.
1432 * TODO: It would be cool to have the two teams chase each other around and
1437 simulator(sonar_info *si, void *vinfo)
1440 /* Local Variables */
1446 sim_info *info = (sim_info *) vinfo;
1450 for (i = 0; i < info->numA; i++) {
1451 t = &info->teamA[i];
1452 if ((t->movedonsweep != si->sweepnum) &&
1453 (t->nexttick == (si->current * -1))) {
1454 new = newBogie(strdup(t->name), t->nextdist, si->current, si->TTL);
1459 t->movedonsweep = si->sweepnum;
1465 for (i = 0; i < info->numB; i++) {
1466 t = &info->teamB[i];
1467 if ((t->movedonsweep != si->sweepnum) &&
1468 (t->nexttick == (si->current * -1))) {
1469 new = newBogie(strdup(t->name), t->nextdist, si->current, si->TTL);
1474 t->movedonsweep = si->sweepnum;
1484 * Compute the X coordinate of the label.
1487 * si - The sonar info block.
1488 * label - The label that will be drawn.
1489 * x - The x coordinate of the bogie.
1492 * The x coordinate of the start of the label.
1496 computeStringX(sonar_info *si, char *label, int x)
1499 int width = XTextWidth(si->font, label, strlen(label));
1500 return x - (width / 2);
1504 * Compute the Y coordinate of the label.
1507 * si - The sonar information.
1508 * y - The y coordinate of the bogie.
1511 * The y coordinate of the start of the label.
1514 /* TODO: Add smarts to keep label in sonar screen */
1517 computeStringY(sonar_info *si, int y)
1520 int fheight = si->font->ascent + si->font->descent;
1521 return y + 5 + fheight;
1525 * Draw a Bogie on the radar screen.
1528 * si - Sonar Information.
1529 * draw - A flag to indicate if the bogie should be drawn or erased.
1530 * name - The name of the bogie.
1531 * degrees - The number of degrees that it should apprear at.
1532 * distance - The distance the object is from the centre.
1533 * ttl - The time this bogie has to live.
1534 * age - The time this bogie has been around.
1538 DrawBogie(sonar_info *si, int draw, char *name, int degrees,
1539 int distance, int ttl, int age)
1542 /* Local Variables */
1546 int ox = si->centrex;
1547 int oy = si->centrey;
1550 /* Compute the coordinates of the object */
1553 distance = (log((double) distance) / 10.0) * si->radius;
1554 x = ox + ((double) distance * cos(4.0 * ((double) degrees)/57.29578));
1555 y = oy - ((double) distance * sin(4.0 * ((double) degrees)/57.29578));
1557 /* Set up the graphics context */
1561 /* Here we attempt to compute the distance into the total life of
1562 * object that we currently are. This distance is used against
1563 * the total lifetime to compute a fraction which is the index of
1564 * the color to draw the bogie.
1567 if (si->current <= degrees)
1568 delta = (si->current - degrees) * -1;
1570 delta = 90 + (degrees - si->current);
1571 delta += (age * 90);
1572 index = (si->text_steps - 1) * ((float) delta / (90.0 * (float) ttl));
1574 XSetForeground(si->dpy, gc, si->text_colors[index].pixel);
1579 /* Draw (or erase) the Bogie */
1581 XFillArc(si->dpy, si->win, gc, x, y, 5, 5, 0, 360 * 64);
1582 XDrawString(si->dpy, si->win, gc,
1583 computeStringX(si, name, x),
1584 computeStringY(si, y), name, strlen(name));
1589 * Draw the sonar grid.
1592 * si - Sonar information block.
1596 drawGrid(sonar_info *si)
1599 /* Local Variables */
1602 int width = si->maxx - si->minx;
1603 int height = si->maxy - si->miny;
1605 /* Draw the circles */
1607 XDrawArc(si->dpy, si->win, si->grid, si->minx - 10, si->miny - 10,
1608 width + 20, height + 20, 0, (360 * 64));
1610 XDrawArc(si->dpy, si->win, si->grid, si->minx, si->miny,
1611 width, height, 0, (360 * 64));
1613 XDrawArc(si->dpy, si->win, si->grid,
1614 (int) (si->minx + (.166 * width)),
1615 (int) (si->miny + (.166 * height)),
1616 (unsigned int) (.666 * width), (unsigned int)(.666 * height),
1619 XDrawArc(si->dpy, si->win, si->grid,
1620 (int) (si->minx + (.333 * width)),
1621 (int) (si->miny + (.333 * height)),
1622 (unsigned int) (.333 * width), (unsigned int) (.333 * height),
1625 /* Draw the radial lines */
1627 for (i = 0; i < 360; i += 10)
1629 XDrawLine(si->dpy, si->win, si->grid, si->centrex, si->centrey,
1630 (int) (si->centrex +
1631 (si->radius + 10) * (cos((double) i / 57.29578))),
1632 (int) (si->centrey -
1633 (si->radius + 10)*(sin((double) i / 57.29578))));
1635 XDrawLine(si->dpy, si->win, si->grid,
1636 (int) (si->centrex + si->radius *
1637 (cos((double) i / 57.29578))),
1638 (int) (si->centrey - si->radius *
1639 (sin((double) i / 57.29578))),
1640 (int) (si->centrex +
1641 (si->radius + 10) * (cos((double) i / 57.29578))),
1642 (int) (si->centrey -
1643 (si->radius + 10) * (sin((double) i / 57.29578))));
1647 * Update the Sonar scope.
1650 * si - The Sonar information.
1651 * bl - A list of bogies to add to the scope.
1655 Sonar(sonar_info *si, Bogie *bl)
1658 /* Local Variables */
1663 /* Check for expired tagets and remove them from the visable list */
1666 for (bp = si->visable; bp != NULL; bp = (bp ? bp->next : 0)) {
1669 * Remove it from the visable list if it's expired or we have
1670 * a new target with the same name.
1675 if (((bp->tick == si->current) && (++bp->age >= bp->ttl)) ||
1676 (findNode(bl, bp->name) != NULL)) {
1677 DrawBogie(si, 0, bp->name, bp->tick,
1678 bp->distance, bp->ttl, bp->age);
1680 si->visable = bp->next;
1682 prev->next = bp->next;
1689 /* Draw the sweep */
1692 int seg_deg = (si->sweep_degrees * 64) / si->sweep_segs;
1693 int start_deg = si->current * 4 * 64;
1694 if (seg_deg <= 0) seg_deg = 1;
1695 for (i = 0; i < si->sweep_segs; i++) {
1696 XSetForeground(si->dpy, si->hi, si->sweep_colors[i].pixel);
1697 XFillArc(si->dpy, si->win, si->hi, si->minx, si->miny,
1698 si->maxx - si->minx, si->maxy - si->miny,
1699 start_deg + (i * seg_deg),
1703 /* Remove the trailing wedge the sonar */
1704 XFillArc(si->dpy, si->win, si->erase, si->minx, si->miny,
1705 si->maxx - si->minx, si->maxy - si->miny,
1706 start_deg + (i * seg_deg),
1710 /* Move the new targets to the visable list */
1712 for (bp = bl; bp != (Bogie *) 0; bp = bl) {
1714 bp->next = si->visable;
1718 /* Draw the visable targets */
1720 for (bp = si->visable; bp != NULL; bp = bp->next) {
1721 if (bp->age < bp->ttl) /* grins */
1722 DrawBogie(si, 1, bp->name, bp->tick, bp->distance, bp->ttl,bp->age);
1725 /* Redraw the grid */
1731 static ping_target *
1732 parse_mode (Bool ping_works_p)
1734 char *source = get_string_resource ("ping", "Ping");
1737 ping_target *hostlist = 0;
1739 if (!source) source = strdup("");
1741 if (!*source || !strcmp (source, "default"))
1744 if (ping_works_p) /* if root or setuid, ping will work. */
1745 source = strdup("subnet/29,/etc/hosts");
1748 source = strdup("simulation");
1752 end = source + strlen(source);
1759 unsigned int n0=0, n1=0, n2=0, n3=0, m=0;
1761 # endif /* HAVE_PING */
1764 *next != ',' && *next != ' ' && *next != '\t' && *next != '\n';
1771 fprintf (stderr, "%s: parsing %s\n", progname, token);
1773 if (!strcmp (token, "simulation"))
1779 "%s: this program must be setuid to root for `ping mode' to work.\n"
1780 " Running in `simulation mode' instead.\n",
1786 if ((4 == sscanf (token, "%d.%d.%d/%d %c", &n0,&n1,&n2, &m,&d)) ||
1787 (5 == sscanf (token, "%d.%d.%d.%d/%d %c", &n0,&n1,&n2,&n3,&m,&d)))
1789 /* subnet: A.B.C.D/M
1792 unsigned long ip = (n0 << 24) | (n1 << 16) | (n2 << 8) | n3;
1793 new = subnetHostsList(ip, m);
1795 else if (4 == sscanf (token, "%d.%d.%d.%d %c", &n0, &n1, &n2, &n3, &d))
1799 new = newHost (token);
1801 else if (!strcmp (token, "subnet"))
1803 new = subnetHostsList(0, 24);
1805 else if (1 == sscanf (token, "subnet/%d %c", &m))
1807 new = subnetHostsList(0, m);
1809 else if (*token == '.' || *token == '/' || !stat (token, &st))
1813 new = readPingHostsFile (token);
1817 /* not an existant file - must be a host name
1819 new = newHost (token);
1824 ping_target *nn = new;
1825 while (nn && nn->next)
1827 nn->next = hostlist;
1832 #endif /* HAVE_PING */
1835 while (token < end &&
1836 (*token == ',' || *token == ' ' ||
1837 *token == '\t' || *token == '\n'))
1847 * Main screen saver hack.
1850 * dpy - The X display.
1851 * win - The X window.
1855 screenhack(Display *dpy, Window win)
1858 /* Local Variables */
1861 struct timeval start, finish;
1865 debug_p = get_boolean_resource ("debug", "Debug");
1869 sensor_info = (void *) init_ping();
1870 # else /* !HAVE_PING */
1872 parse_mode (0); /* just to check argument syntax */
1873 # endif /* !HAVE_PING */
1878 if ((sensor_info = (void *) init_sim()) == NULL)
1882 if ((si = init_sonar(dpy, win)) == (sonar_info *) 0)
1890 /* Call the sensor and display the results */
1892 gettimeofday(&start, (struct timezone *) 0);
1893 bl = sensor(si, sensor_info);
1896 /* Set up and sleep for the next one */
1898 si->current = (si->current - 1) % 90;
1899 if (si->current == 0)
1902 gettimeofday(&finish, (struct timezone *) 0);
1903 sleeptime = si->delay - delta(&start, &finish);
1904 screenhack_handle_events (dpy);