pkg://WindowMaker-applets-1.0-836.1.src.rpm:2095562/wmnet-1.06.tar.gz
info downloads
wmnet-1.06/ 40755 2376 2442 0 7104417303 10675 5 ustar kaos kaos wmnet-1.06/README 100644 2376 2442 10054 7104415112 11666 0 ustar kaos kaos wmnet -- network monitor for WindowMaker using kernel IP accounting
for Linux, FreeBSD, and OpenBSD. version 1.06
Jesse B. Off <joff@iastate.edu> 8/9/1998
Katharine Osborne <kaos@digitalkaos.net> 4/5/2000
This little program polls network statistics and does a few things with
the data it gets. It has small blinking lights for the rx and tx of IP
packets, a digital speedometer of your polled stat's current
speed and a bar graph like xload et. al which has a
tx speed graph from bottom-up and rx speed graph from the top-down.
The speedometer keeps track of the current speed per second and shows
it in a color corresponding to which of rx or tx that has the highest
speed at the moment. Also, the graph is drawn in a way that the highest
speed is drawn on top of the other while the other is in the background.
Depending on whether you are running ppp or ethernet
connections, you should set the -x parameter to about 1.5 times the
high speed of your connection... the default is 6000 which will be
stupid if you're on a ethernet line with a max of about 800 kb/sec.
I've found the best for an ethernet line is '-x 10000000 -l' Having
the logarithmic scale lets you see any speed of traffic from a telnet
session to downloadeding something from across the hall at 600 kb/sec.
I tried to keep this is as small and efficient as possible CPU time on my
K5 PR100 with the default poll time of 25000 microseconds (1 microsecond
== 1 millionth of a second.) is less than 20 seconds per 24 hours
Which is less than even wmmixer uses for me.
wmnet now uses drivers to get stats. The existing stat driver from previous
versions has been moved to the ipfwadm driver. To get some generic IP
accounting rules using ipfwadm:
ipfwadm -A in -i -S 0.0.0.0/0
ipfwadm -A out -i -D 0.0.0.0/0
I have also included a couple drivers for Linux 2.1. You can either use
ipchains or general device stats received from /proc/net/dev. If you don't
want to fool around with IP chains, use the devstats driver and specify the
interface to monitor useing the --device option. To get a generic set of ip
chains rules for the ipchains driver:
ipchains -N acctin
ipchains -N acctout
ipchains -I input 1 -j acctin
ipchains -I output 1 -j acctout
ipchains -I acctin 1
ipchains -I acctout 1
There is also the pppstats driver available for both Linux 2.0 and 2.1.
If you just want general monitoring of your ppp devices, use this driver.
In version 1.04+ I have added (among others) the --promisc option.
This makes your IP accounting rules apply across the whole of your
network segment. This could be useful for monitoring your whole subnet
traffic bandwidth. However, using this option as a normal user requires
wmnet to be suid root, which is something many people dispise so it is
not suid by default. To make wmnet suid, as root:
chmod u+s /usr/X11R6/bin/wmnet
Please only do this if you need to. I did write this program with it
possibly being suid in mind so I am fairly confident that this can be
suid without any security concerns. But then again, thats what they all
say. Read the code then judge for yourself if need be, I WONT have
it done automatically for you. Really the only 'if' is the GNU libc
getopt_long() function.
For those afterstep users out there using wmnet, you may have noticed that
when wmnet is swallowed, the whole thing is not visible. This is due to
the afterstep wharf's inability to swallow a dock.app as large as wmnet.
(Sorry guys, theres nothing I can do about that!) Theres supposedly an
unofficial patch around for afterstep that allows it to fully display,
consult your local afterstep guru on the what and where.
Much thanks goes to Vladimir Popov for writing the OpenBSD patch.
Consult the man page for additional documentation.
homepage for wmnet:
http://www.digitalkaos.net/linux/wmnet/
TO INSTALL from tar.gz:
tar xfzv wmnet-1.06.tar.gz
cd wmnet-1.06
xmkmf
make
strip wmnet
make install
make install.man
NOTE: you may wanna change config.h to change the compiled in drivers.
ideas/comments/bug reports -----> kaos@digitalkaos.net
http://www.digitalkaos.net/linux/wmnet/
wmnet-1.06/XPM/ 40755 2376 2442 0 6541756171 11356 5 ustar kaos kaos wmnet-1.06/XPM/arrow.xbm 100644 2376 2442 307 6540560031 13260 0 ustar kaos kaos #define arrow_width 14
#define arrow_height 9
static unsigned char arrow_bits[] = {
0x08, 0x04, 0x1c, 0x04, 0x3e, 0x04, 0x7f, 0x04, 0x08, 0x04, 0x88, 0x3f,
0x08, 0x1f, 0x08, 0x0e, 0x08, 0x04};
wmnet-1.06/Changelog 100644 2376 2442 3147 7104415340 12610 0 ustar kaos kaos 3/24/1998 -- First release, wrote this yesterday, so it may have
some bugs.
3/25/1998 -- added logarithmic scaling.
some touch ups on the updateSpeedometer() to be a
little more helpful
added a little more width to the speedometer display
from a report that the text sometimes was drawn off
the scale (couldnt confirm, is it fixed?)
fixed prob for speeds > 9.9 megabytes per second (I
think... I can't go that fast myself
Made default maxspeed 6000 which I assume is better
for modems.
5/11/1998 -- I witnessed the little problem with the speedometer
going off into the main window so I set a clipmask
Still don't understand how it could go off..I'm
using a fixed size font...
5/13/1998 -- Modified the way it gets its stats from /proc/net/ip_acct
You now have to give it explicit accounting rule numbers
through the -T and -R options or else it defaults to the
fist two in tx, rx order, best just to make sure
you set the -T and -R options.
5/15/1998 -- Completed interface rewrite, definitely have more graphing
space, but I dont know if I like it yet.
5/16/1998 -- Added shaded graphs, xload style. Its a lot prettier!
8/6/1998 -- Put in the stat driver interface and some drivers
5/4/2000 -- Added support for OpenBSD, thanks to Vladimir Popov
wmnet-1.06/wmnet.c 100644 2376 2442 64015 7104416532 12321 0 ustar kaos kaos /* wmnet -- X IP accounting monitor
* Copyright 1998 Jesse B. Off
* Copyright 2000 Katharine Osborne
*
* $Id: wmnet.c,v 1.28 1998/10/07 03:42:28 joff Exp joff $
*
* This software is released under the GNU Public License agreement.
* No warranties, whatever.... you know the usuals.... this is free
* software. if you use it, great... if you wanna make a change to it,
* great, but please send me the diff.
*
* CHANGELOG:
* 3/24/1998 -- First release, wrote this yesterday, so it may have
* some bugs.
* 3/25/1998 -- added logarithmic scaling.
* some touch ups on the updateSpeedometer() to be a
* little more helpful
* added a little more width to the speedometer display
* from a report that the text sometimes was drawn off
* the scale (couldnt confirm, is it fixed?)
* fixed prob for speeds > 9.9 megabytes per second (I
* think... I can't go that fast myself
* Made default maxspeed 6000 which I assume is better
* for modems.
* 5/11/1998 -- I witnessed the little problem with the speedometer
* going off into the main window so I set a clipmask
* Still don't understand how it could go off..I'm
* using a fixed size font...
* 5/13/1998 -- Modified the way it gets its stats from /proc/net/ip_acct
* You now have to give it explicit accounting rule numbers
* through the -T and -R options or else it defaults to the
* fist two in tx, rx order, best just to make sure
* you set the -T and -R options.
* 5/15/1998 -- Completed interface rewrite, definitely have more graphing
* space, but I dont know if I like it yet.
* 5/16/1998 -- Added shaded graphs, xload style. Its a lot prettier!
* 5/20/1998 -- Fixed afterstep wharfability problem... should also atleast
* display in other WM's
* 6/16/1998 -- Fixed handling of WM_DELETE_WINDOW, strtol() to strtoul(),
* and now uses getopt_long.
* 6/16/1998 -- Put in --withdrawn and --normalstate options to explicitly
* set the type. Still tries to auto-detect wmaker though.
* 6/16/1998 -- Put in --execute and --promisc options.
* 6/17/1998 -- Some code clean-ups.
* 6/18/1998 -- Implemented a labeling mechanism.
* 6/18/1998 -- Slowed down the speedometer display... it was getting annoying.
* 6/23/1998 -- Split up to wmnet.c and wmnet.h
* 8/5/1998 -- New options --device and --driver
* 5/4/2000 -- Support added for OpenBSD
*/
#include<stdlib.h>
#include<stdio.h>
#include<X11/X.h>
#include<X11/Xlib.h>
#include<X11/Xutil.h>
#include<X11/Xatom.h>
#if defined (__FreeBSD__) || defined (__OpenBSD__)
# include<sys/socket.h>
# include"getopt.h"
#else
# include<getopt.h>
#endif
#include<net/if.h>
#include<signal.h>
#include<unistd.h>
#include<string.h>
#include<math.h>
#include<sys/time.h>
#include<sys/socket.h>
#include<sys/types.h>
#include<sys/ioctl.h>
#include<sys/wait.h>
#include<X11/extensions/shape.h>
#include "XPM/arrow.xbm"
#include "wmnet.h"
/* Called on exit() from atexit() */
void exit_func(void) {
XCloseDisplay(dpy);
}
/* Generic signal handler, if its a SIGCHLD, do a wait() to remove the zombie */
void got_signal(int x) {
if(x == SIGCHLD) {
wait(NULL);
return;
} else exit(7);
}
/* Does generic setting up of wmnet, (option parsing) and calls setupX() */
void setup_wmnet(int argc, char **argv) {
int c;
XColor thecolor;
struct sigaction signal_action;
char *txcolorString = NULL, *rxcolorString = NULL, *labelfgcolorString = NULL, *labelbgcolorString = NULL;
char *parser = NULL;
#ifdef linux
const struct option long_options[19] = {
#else
const struct option long_options[17] = {
#endif
{"device", required_argument, NULL, 'W'},
{"label", required_argument, NULL, 'L'},
{"labelfg", required_argument, NULL, 'F'},
{"labelbg", required_argument, NULL, 'B'},
{"logscale", no_argument, NULL, 'l'},
{"help", no_argument, NULL, 'h'},
{"execute", required_argument, NULL, 'e'},
#ifdef linux
{"txrule", required_argument, NULL, 'T'},
{"rxrule", required_argument, NULL, 'R'},
#endif
{"txcolor", required_argument, NULL, 't'},
{"rxcolor", required_argument, NULL, 'r'},
{"maxrate", required_argument, NULL, 'x'},
{"withdrawn", no_argument, NULL, 'w'},
{"normalstate", no_argument, NULL, 'n'},
{"promisc", required_argument, NULL, 'p'},
{"unpromisc", required_argument, NULL, 'u'},
{"driver", required_argument, NULL, 'D'},
{"version", no_argument, NULL, 'v'},
{0, 0, 0, 0}
};
/* Get options */
#ifdef linux
while((c = getopt_long(argc, argv, "W:F:B:L:vp:u:wnle:R:T:r:t:D:d:x:h", long_options, NULL)) != EOF) {
#else
while((c = getopt_long(argc, argv, "W:F:B:L:vp:u:wnle:r:t:D:d:x:h", long_options, NULL)) != EOF) {
#endif
switch(c) {
case 'v':
printf("wmnet 1.06\n"
"Copyright (C) 1998, 2000 Jesse B. Off, Katharine Osborne <kaos@digitalkaos.net>\n"
"This program is released under the terms of the GNU Public License.\n");
exit(14);
break;
case 'W':
device = strdup(optarg);
break;
case 'D':
parser = strdup(optarg);
break;
#ifdef linux
case 'T':
out_rule = strtoul(optarg, NULL, 10);
out_rule_string = strdup(optarg);
break;
case 'R':
in_rule = strtoul(optarg, NULL, 10);
in_rule_string = strdup(optarg);
break;
#endif
case 'L':
graphbox_height = 35;
if (label == NULL) {
label = strdup(optarg);
} else {
fprintf(stderr, "wmnet: duplicate --label\n");
exit(22);
}
break;
case 'B':
if (labelbgcolorString == NULL) {
labelbgcolorString = (char *)alloca(strlen(optarg)+1);
strncpy(labelbgcolorString, optarg, strlen(optarg)+1);
} else {
fprintf(stderr, "wmnet: duplicate --labelbg\n");
exit(23);
}
break;
case 'F':
if (labelfgcolorString == NULL) {
labelfgcolorString = (char *)alloca(strlen(optarg)+1);
strncpy(labelfgcolorString, optarg, strlen(optarg)+1);
} else {
fprintf(stderr, "wmnet: duplicate --labelfg\n");
exit(23);
}
break;
case 'l':
logscale = True;
break;
case 'r':
if (rxcolorString == NULL) {
rxcolorString = (char *)alloca(strlen(optarg)+1);
strncpy(rxcolorString, optarg, strlen(optarg)+1);
} else {
fprintf(stderr, "wmnet: duplicate --rxcolor\n");
exit(18);
}
break;
case 't':
if (txcolorString == NULL) {
txcolorString = (char *)alloca(strlen(optarg)+1);
strncpy(txcolorString, optarg, strlen(optarg)+1);
} else {
fprintf(stderr, "wmnet: duplicate --rxcolor\n");
exit(19);
}
break;
case 'x':
maxRate = strtoul(optarg, NULL, 10);
break;
case 'd':
delayTime = strtoul(optarg, NULL, 10);
/* Having delayTime > 950000 causes some weirdness */
delayTime = delayTime > 950000 ? 950000 : delayTime;
break;
case 'e':
if (click_command == NULL) {
click_command = strdup(optarg);
} else {
fprintf(stderr, "wmnet: duplicate --execute\n");
exit(17);
}
break;
case 'w':
specified_state = WithdrawnState;
break;
case 'n':
specified_state = NormalState;
break;
case 'u':
{
int fds;
struct ifreq ifr;
strncpy(ifr.ifr_name, optarg, IFNAMSIZ );
ifr.ifr_name[IFNAMSIZ-1] = 0;
if ((fds = socket(AF_INET, SOCK_DGRAM, 0)) == -1 || ioctl(fds, SIOCGIFFLAGS, &ifr) == -1 ) {
perror("wmnet");
exit(20);
}
if ((ifr.ifr_flags & IFF_PROMISC) != 0) { /* Is promiscuous mode not already unset? */
ifr.ifr_flags &= ~IFF_PROMISC;
if (geteuid() != 0) {
fprintf(stderr, "wmnet: this must be suid or you must be root!\n");
}
if(ioctl(fds, SIOCSIFFLAGS, &ifr) != 0) {
fprintf(stderr, "wmnet: cannot unset promiscuous mode on %s\n", optarg);
exit(21);
}
}
close(fds);
}
break;
case 'p':
{
int fds;
struct ifreq ifr;
strncpy(ifr.ifr_name, optarg, IFNAMSIZ );
ifr.ifr_name[IFNAMSIZ-1] = 0;
if ((fds = socket(AF_INET, SOCK_DGRAM, 0)) == -1 || ioctl(fds, SIOCGIFFLAGS, &ifr) == -1 ) {
perror("wmnet");
exit(16);
}
if ((ifr.ifr_flags & IFF_PROMISC) == 0) { /* Is promiscuous mode not already set? */
ifr.ifr_flags |= IFF_PROMISC;
if (geteuid() != 0) {
fprintf(stderr, "wmnet: this must be suid or you must be root!\n");
}
if(ioctl(fds, SIOCSIFFLAGS, &ifr) != 0) {
fprintf(stderr, "wmnet: cannot set promiscuous mode on %s\n", optarg);
exit(13);
}
}
close(fds);
}
break;
default:
printf("wmnet-- v1.06 Katharine Osborne <kaos@digitalkaos.net>\n"
"http://www.digitalkaos.net/linux/wmnet/\n"
"-----------------------------------------------------\n"
" -h, --help this help\n"
" -v, --version display version information\n"
" -L, --label=LABEL display LABEL on bottom of window\n"
" -F, --labelfg=COLOR foreground color for the label\n"
" -B, --labelbg=COLOR background color for the label\n"
" -e, --execute=COMMAND run COMMAND on click\n"
#ifdef linux
" -T, --txrule=RULE accounting rule number (ipfwadm) or\n"
" IP chain name (ipchains) to monitor for tx\n"
" -R, --rxrule=RULE accounting rule number (ipfwadm) or\n"
" IP chain name (ipchains) to monitor for rx\n"
#endif
" -W, --device=DEVICE monitor DEVICE for stats (devstats,kmem,pppstats)\n"
" -w, --withdrawn start up in withdrawn state\n"
" -n, --normalstate start up in normal, shaped state\n"
" -t, --txcolor=COLOR color for tx\n"
" -r, --rxcolor=COLOR color for rx\n"
" -x, --maxrate=BYTES max transfer rate for graph scale (default 6000)\n"
" -p, --promisc=DEVICE put DEVICE into promiscuous mode to apply\n"
" accounting rules to all network packets\n"
" -u, --unpromisc=DEVICE turn off promiscuous mode on DEVICE\n"
" -D, --driver=DRIVER use DRIVER to get statistics\n"
" -l, --logscale use a logarithmic scale (great for ethernet\n"
" connections with -x 10000000)\n"
" -d DELAY delay time for polling statistics\n"
" in microseconds (default 25000)\n"
"\n");
printf("Compiled in drivers: [%s]\n\n", available_drivers());
printf("Report bugs to joff@iastate.edu\n");
exit(3);
}
}
/* Relinquish suid privileges if there */
seteuid(getuid());
stat_gather = setup_driver(parser);
if (txcolorString == NULL) txcolorString = "white";
if (rxcolorString == NULL) rxcolorString = "red";
if (labelfgcolorString == NULL) labelfgcolorString = "white";
if (labelbgcolorString == NULL) labelbgcolorString = "black";
/* Change dir to /, security precaution, and common courtesy */
if (chdir("/") == -1) {
perror("wmnet: chdir()");
exit(16);
}
/* Open X Display */
if ((dpy = XOpenDisplay(NULL)) == NULL) {
fprintf(stderr,"wmnet: doh...can't connect to X server, giving up\n");
exit(1);
}
/* assure ourself for a graceful exit */
if (atexit(exit_func)) {
fprintf(stderr,"wmnet: atexit() failed\n");
exit(6);
}
signal_action.sa_handler = got_signal;
sigemptyset(&signal_action.sa_mask);
signal_action.sa_flags = (SA_NOCLDSTOP|SA_RESTART);
#ifdef linux
signal_action.sa_restorer = NULL;
#endif
if ((sigaction(SIGCHLD, &signal_action, NULL) == -1) ||
(sigaction(SIGINT, &signal_action, NULL) == -1) ||
(sigaction(SIGTERM, &signal_action, NULL) == -1)) {
fprintf(stderr,"wmnet: couldn't set signal handler\n");
exit(8);
}
/* Setup initial foreground color */
if(rxcolorString) {
if(!XParseColor(dpy, DefaultColormap(dpy, screen), rxcolorString, &thecolor)) {
fprintf(stderr, "wmnet: what the heck is %s for a color?\n", rxcolorString);
exit(12);
}
shadesOf(&thecolor, rx_pixel);
}
if(txcolorString) {
if(!XParseColor(dpy, DefaultColormap(dpy, screen), txcolorString, &thecolor)) {
fprintf(stderr, "wmnet: what the heck is %s for a color?\n", txcolorString);
exit(5);
}
shadesOf(&thecolor, tx_pixel);
}
if(labelfgcolorString) {
if(!XParseColor(dpy, DefaultColormap(dpy, screen), labelfgcolorString, &thecolor)) {
fprintf(stderr, "wmnet: what the heck is %s for a color?\n", labelfgcolorString);
exit(24);
}
XAllocColor(dpy, DefaultColormap(dpy, screen), &thecolor);
labelfg_pixel = thecolor.pixel;
}
if(labelbgcolorString) {
if(!XParseColor(dpy, DefaultColormap(dpy, screen), labelbgcolorString, &thecolor)) {
fprintf(stderr, "wmnet: what the heck is %s for a color?\n", labelbgcolorString);
exit(25);
}
XAllocColor(dpy, DefaultColormap(dpy, screen), &thecolor);
labelbg_pixel = thecolor.pixel;
}
/* usleep() in between polls to /proc/net/ip_acct */
if (delayTime <= 0) delayTime = 25000;
/* Setup the X windows, GC's, initial states, etc */
setupX();
XSetCommand(dpy, main_window, argv, argc);
/* Get the initial stats for startup */
stat_gather();
/* Rock n Roll */
XMapWindow(dpy, main_window);
}
/* Called from setup_wmnet() to initialize the X windows stuff */
void setupX(void) {
XWMHints hints;
XSizeHints shints;
XGCValues gcv;
XColor color;
XRectangle bound = { 0, 0, 56, 56 };
screen = DefaultScreen(dpy);
delete_atom = XInternAtom(dpy, "WM_DELETE_WINDOW", False);
if (delete_atom == None) {
fprintf(stderr,"wmnet: I need WindowMaker running! (or at least some window manager)\n");
exit(2);
}
if (XInternAtom(dpy,"_WINDOWMAKER_WM_FUNCTION", True) != None) {
if (specified_state == -1) specified_state = WithdrawnState;
} else {
if (specified_state == -1) specified_state = NormalState;
}
root_window = DefaultRootWindow(dpy);
createWin(&main_window);
color.red = color.green = color.blue = 12000;
XAllocColor(dpy, DefaultColormap(dpy, screen), &color);
darkgrey_pixel = color.pixel;
color.red = color.green = color.blue = 32000;
XAllocColor(dpy, DefaultColormap(dpy, screen), &color);
grey_pixel = color.pixel;
if ((arrow = XCreateBitmapFromData(dpy, root_window, arrow_bits, arrow_width, arrow_height)) == None) {
fprintf(stderr, "wmnet: unable to create arrow bitmap\n");
exit(11);
}
gcv.graphics_exposures = False;
gcv.foreground = tx_pixel[HIGH_INTENSITY];
gcv.background = darkgrey_pixel;
gcv.font = XLoadFont(dpy, "5x8");
graphics_context = XCreateGC(dpy, root_window, (GCFont|GCGraphicsExposures|GCForeground|GCBackground), &gcv);
black_pixel = BlackPixel(dpy, screen);
white_pixel = WhitePixel(dpy, screen);
hints.window_group = main_window;
hints.initial_state = specified_state;
if (specified_state == WithdrawnState) {
createWin(&icon_window);
visible_window = &icon_window;
hints.icon_window = icon_window;
} else {
visible_window = &main_window;
hints.icon_window = None;
}
hints.flags = WindowGroupHint | StateHint | IconWindowHint;
XSetWMHints(dpy,main_window,&hints);
XSetWMProtocols(dpy, main_window, &delete_atom, 1);
shints.min_width = 64;
shints.min_height = 64;
shints.max_width = 64;
shints.max_height = 64;
shints.flags = PMinSize | PMaxSize;
XSetWMNormalHints(dpy, main_window, &shints);
XStoreName(dpy, main_window, "wmnet");
XShapeCombineRectangles(dpy, *visible_window, ShapeBounding, 4, 4, &bound, 1, ShapeBounding, 0);
XSelectInput(dpy, *visible_window, (ExposureMask|ButtonPressMask));
XMapSubwindows(dpy, *visible_window);
}
/* Utility function to create a window for setupX() */
void createWin(Window *win) {
XClassHint classHint;
XSetWindowAttributes windowAttrib;
*win = XCreateSimpleWindow(dpy, root_window, 10, 10, 64, 64, 0, 0, 0);
classHint.res_name = "wmnet";
classHint.res_class = "WMNET";
windowAttrib.background_pixmap = ParentRelative;
XChangeWindowAttributes(dpy, *win, CWBackPixmap, &windowAttrib);
XSetClassHint(dpy, *win, &classHint);
}
/* Handles Expose events, repaints the window */
void redraw(XExposeEvent *ee) {
static XRectangle cliprect = { 4, 51, 56, 9 };
XSetForeground(dpy, graphics_context, darkgrey_pixel);
/* if (wmaker_present == False) XFillRectangle(dpy, *visible_window, graphics_context, 0, 0, 64, 64); */
XFillRectangle(dpy, *visible_window, graphics_context, GRAPHBOX_X, GRAPHBOX_Y, GRAPHBOX_WIDTH, GRAPHBOX_HEIGHT);
XSetForeground(dpy, graphics_context, black_pixel);
XFillRectangle(dpy, *visible_window, graphics_context, TOPBOX_X, TOPBOX_Y, TOPBOX_WIDTH, TOPBOX_HEIGHT);
XDrawLine(dpy, *visible_window, graphics_context, GRAPHBOX_X_LEFT, GRAPHBOX_Y_TOP, GRAPHBOX_X_LEFT, GRAPHBOX_Y_BOTTOM);
XDrawPoint(dpy, *visible_window, graphics_context, GRAPHBOX_X_RIGHT, GRAPHBOX_Y_TOP);
if (label) {
XSetForeground(dpy, graphics_context, labelbg_pixel);
XFillRectangle(dpy, *visible_window, graphics_context, LABEL_X, LABEL_Y, LABEL_WIDTH, LABEL_HEIGHT);
XSetClipRectangles(dpy, graphics_context, 0, 0, &cliprect, 1, Unsorted);
XSetForeground(dpy, graphics_context, labelfg_pixel);
XDrawString(dpy, *visible_window, graphics_context, 5, 58, label, strlen(label));
XSetClipMask(dpy, graphics_context, None);
}
XSetForeground(dpy, graphics_context, white_pixel);
XDrawLine(dpy, *visible_window, graphics_context, GRAPHBOX_X_RIGHT, GRAPHBOX_Y_BOTTOM, GRAPHBOX_X_RIGHT, (GRAPHBOX_Y_TOP + 1));
XDrawLine(dpy, *visible_window, graphics_context, GRAPHBOX_X_LEFT, GRAPHBOX_Y_BOTTOM, GRAPHBOX_X_RIGHT, GRAPHBOX_Y_BOTTOM);
XSetForeground(dpy, graphics_context, grey_pixel);
XSetBackground(dpy, graphics_context, black_pixel);
XCopyPlane(dpy, arrow, *visible_window, graphics_context, 7, 0, 7, 9, 53, 5, 1);
XCopyPlane(dpy, arrow, *visible_window, graphics_context, 0, 0, 7, 9, 46, 5, 1);
}
/* Main loop that is called every delaytime. This calls stat_gather() and updateSpeedometer() when needed
* and takes care of the displaying and scrolling the graph */
void tock(void) {
unsigned long since;
int y, yy;
unsigned long rate_rx, rate_tx;
double percent_tx, percent_rx;
/* static array containing the last 8 samples... for use in averaging and smoothing the graph a little */
static unsigned long lifo_in[8] = { 0, 0, 0, 0, 0, 0, 0, 0 };
static unsigned long lifo_out[8] = { 0, 0, 0, 0, 0, 0, 0, 0 };
static unsigned int t = 0, blank = 0;
if (gettimeofday(&timenow, NULL)) {
perror("wmnet: gettimeofday()");
exit(10);
}
since = (timenow.tv_sec * 1000000L + timenow.tv_usec) - (timelast.tv_sec * 1000000L + timelast.tv_usec);
if (since > displayDelay) {
lifo_in[t] = diffbytes_in * (1000000L / since);
lifo_out[t] = diffbytes_out * (1000000L / since);
t = (t + 1) % 8;
/* in */
rate_rx = (lifo_in[0] + lifo_in[1] + lifo_in[2] + lifo_in[3] + lifo_in[4] + lifo_in[5] + lifo_in[6] + lifo_in[7]) / (unsigned long)8;
if(logscale) percent_rx = (log10( ((rate_rx * 10000/ maxRate) < 1) ? 1 : ((double)rate_rx / (double)maxRate) * 10000.) / 4.);
else percent_rx = (double)(rate_rx) / maxRate;
y = GRAPH_Y_BOTTOM - (GRAPH_HEIGHT * percent_rx) ;
y = y < GRAPH_Y_UPPER ? GRAPH_Y_UPPER : y;
/* out */
rate_tx = (lifo_out[0] + lifo_out[1] + lifo_out[2] + lifo_out[3] + lifo_out[4] + lifo_out[5] + lifo_out[6] + lifo_out[7]) / (unsigned long)8;
if(logscale) percent_tx = (log10( ((rate_tx * 10000 / maxRate ) < 1) ? 1 : ((double)rate_tx / (double)maxRate * 10000.)) / 4.);
else percent_tx = (double)(rate_tx) / maxRate;
yy = GRAPH_Y_UPPER + (GRAPH_HEIGHT * percent_tx) ;
yy = yy > GRAPH_Y_BOTTOM ? GRAPH_Y_BOTTOM : yy;
/* only update the speedometer every 7th displayDelay */
if (t == 7) updateSpeedometer(rate_rx, rate_tx);
/* blank var is just for stopping executing the X* funcs when the disp is all black */
if ((y == GRAPH_Y_BOTTOM && yy == GRAPH_Y_UPPER) && (diffbytes_in + diffbytes_out) == 0) blank++; else blank = 0;
if (blank < (GRAPH_WIDTH + 1) ) {
XCopyArea(dpy, *visible_window, *visible_window, graphics_context, GRAPH_X + 1,
GRAPH_Y, GRAPH_WIDTH - 1, GRAPH_HEIGHT, GRAPH_X, GRAPH_Y);
XSetForeground(dpy, graphics_context, darkgrey_pixel);
XDrawLine(dpy, *visible_window, graphics_context, GRAPH_X_RIGHT, y, GRAPH_X_RIGHT, yy);
if (( (yy == GRAPH_Y_UPPER && diffbytes_out > 0 && rate_rx > rate_tx) || (rate_rx >= rate_tx && yy != GRAPH_Y_UPPER)) ) {
drawColoredLine(GRAPH_Y_UPPER, yy, tx_pixel);
}
if ( y != GRAPH_Y_BOTTOM || diffbytes_in > 0) {
drawColoredLine(GRAPH_Y_BOTTOM, y, rx_pixel);
}
if (( (yy == GRAPH_Y_UPPER && diffbytes_out > 0) || (rate_rx < rate_tx && yy != GRAPH_Y_UPPER)) ) {
drawColoredLine(GRAPH_Y_UPPER, yy, tx_pixel);
}
}
diffbytes_in = diffbytes_out = 0;
timelast = timenow;
}
if (!stat_gather()) { /* Anything change? */
current_rx = rx;
current_tx = tx;
XSetBackground(dpy, graphics_context, black_pixel);
if(current_tx == True) {
XSetForeground(dpy, graphics_context, tx_pixel[HIGH_INTENSITY]);
XCopyPlane(dpy, arrow, *visible_window, graphics_context, 7, 0, 7, 9, 53, 5, 1);
/* XFillRectangle(dpy, *visible_window, graphics_context, 55, 5, 4, 4); */
}
else {
XSetForeground(dpy, graphics_context, grey_pixel);
XCopyPlane(dpy, arrow, *visible_window, graphics_context, 7, 0, 7, 9, 53, 5, 1);
}
if(current_rx == True) {
XSetForeground(dpy, graphics_context, rx_pixel[HIGH_INTENSITY]);
XCopyPlane(dpy, arrow, *visible_window, graphics_context, 0, 0, 7, 9, 46, 5, 1);
/* XFillRectangle(dpy, *visible_window, graphics_context, 55, 12, 4, 4); */
}
else {
XSetForeground(dpy, graphics_context, grey_pixel);
XCopyPlane(dpy, arrow, *visible_window, graphics_context, 0, 0, 7, 9, 46, 5, 1);
}
}
}
/* paints the speedometer area with whichever is greater, rxRate or txRate */
int updateSpeedometer(int rxRate, int txRate) {
double rate;
char astring[10];
unsigned long color;
static XRectangle cliprect = { 4, 5, 37, 8 };
static int rxRate_last = 0 , txRate_last = 0;
static Bool clear = True, collectandreturn = True;
/* This is ugly, I don't like this, but it slows the speedometer down a touch */
if (collectandreturn == True) {
txRate_last = txRate;
rxRate_last = rxRate;
collectandreturn = False;
return 1;
}
collectandreturn = True;
if (txRate > rxRate) {
rate = (txRate + txRate_last) / 2000.;
color = tx_pixel[HIGH_INTENSITY];
} else {
rate = (rxRate + rxRate_last) / 2000.;
color = rx_pixel[HIGH_INTENSITY];
}
if (!clear) {
XSetForeground(dpy, graphics_context, black_pixel);
XFillRectangle(dpy, *visible_window, graphics_context, 4, 5, 37, 9);
}
if (rate < .1) {
clear = True;
return(1);
} else if (rate < 1.) {
snprintf(astring, 10, "%db/s", (unsigned int)(rate * 1000.));
} else if (rate >= 1. && rate < 10.)
snprintf(astring, 10, "%1.2fk/s", rate);
else if (rate >= 10. && rate < 100.)
snprintf(astring, 10, "%2.1fk/s", rate);
else if (rate >= 100. && rate < 1000.)
snprintf(astring, 10, "%dk/s", (unsigned int)rate);
else if (rate > 1000. && rate < 10000.)
snprintf(astring, 10, "%1.2fM/s", (rate / 1000.));
else if (rate > 10000. && rate < 100000.)
snprintf(astring, 10, "%2.1fM/s", (rate / 1000.));
else sprintf(astring, "XXXX");
XSetForeground(dpy, graphics_context, color);
XSetClipRectangles(dpy, graphics_context, 0, 0, &cliprect, 1, Unsorted);
XDrawString(dpy, *visible_window, graphics_context, 4, 13, astring, strlen(astring));
XSetClipMask(dpy, graphics_context, None);
clear = False;
return(0);
}
/* called from within tock to draw the shaded lines making up our bar-graph */
void drawColoredLine(int y1, int y2, unsigned long *shadecolor) {
int subline[4], i;
static unsigned int linebreaks[3] = { 50, 90, 100 };
subline[0] = y1;
for(i = 0; i < 3; i++) {
if (y1 > y2) subline[i+1] = y1 - (((y1 - y2) * linebreaks[i]) / 100);
else subline[i+1] = y1 + (((y2 - y1) * linebreaks[i]) / 100);
XSetForeground(dpy, graphics_context, shadecolor[i]);
XDrawLine(dpy, *visible_window, graphics_context, GRAPH_X_RIGHT, subline[i], GRAPH_X_RIGHT, subline[i+1]);
}
}
/* Returns in returnarray a 3 value array containing 3 shades (low, normal, and high) of XColor shade.
* Called from setup_wmnet on startup and never called again.
*/
void shadesOf(XColor *shade, unsigned long *returnarray) {
XAllocColor(dpy, DefaultColormap(dpy, screen), shade);
returnarray[HIGH_INTENSITY] = shade->pixel;
shade->red = (8 * shade->red / 10);
shade->green = (8 * shade->green / 10);
shade->blue = (8 * shade->blue / 10);
XAllocColor(dpy, DefaultColormap(dpy, screen), shade);
returnarray[NORMAL_INTENSITY] = shade->pixel;
shade->red = 8 * shade->red / 10;
shade->green = 8 * shade->green / 10;
shade->blue = 8 * shade->blue / 10;
XAllocColor(dpy, DefaultColormap(dpy, screen), shade);
returnarray[LOW_INTENSITY] = shade->pixel;
}
/* Here is main, clear at the bottom. Handles the event loop and calls tock() every delayTime milliseconds */
int main(int argc, char ** argv) {
unsigned int done = False;
XEvent event;
setup_wmnet(argc, argv);
while(!done) {
while(XPending(dpy)) {
XNextEvent(dpy, &event);
switch(event.type) {
case Expose:
redraw((XExposeEvent *)&event);
break;
case ClientMessage:
if(event.xclient.data.l[0] == delete_atom)
done = True;
break;
case ButtonPress:
if(event.xbutton.button == Button1 && click_command != NULL) {
if (fork() == 0) {
execl("/bin/sh", "sh", "-c", click_command, NULL);
perror("wmnet: execl()");
exit(15);
}
}
break;
}
}
/* Wait for a bit, updating is done in tock() */
usleep(delayTime);
tock();
}
return 0;
}
wmnet-1.06/wmnet.h 100644 2376 2442 6771 7104416642 12315 0 ustar kaos kaos /* wmnet -- X IP accounting monitor
* Copyright 1998, 2000 Jesse B. Off, Katharine Osborne
* <kaos@digitalkaos.net>
*
* $Id: wmnet.h,v 1.2 1998/10/06 00:06:12 joff Exp $
*
* This software is released under the GNU Public License agreement.
* No warranties, whatever.... you know the usuals.... this is free
* software. if you use it, great... if you wanna make a change to it,
* great, but please send me the diff. If you put it on a distributed
* CD, great... I'd appreciate a copy of the CD though ;).
*
*/
#define TOPBOX_X 4
#define TOPBOX_Y 4
#define TOPBOX_WIDTH 56
#define TOPBOX_HEIGHT 11
/* Graphing area extents */
#define GRAPHBOX_X 4
#define GRAPHBOX_Y 15
#define GRAPHBOX_WIDTH 56
#define GRAPHBOX_HEIGHT graphbox_height
#define GRAPHBOX_X_RIGHT (GRAPHBOX_X + GRAPHBOX_WIDTH - 1)
#define GRAPHBOX_X_LEFT (GRAPHBOX_X)
#define GRAPHBOX_Y_TOP (GRAPHBOX_Y)
#define GRAPHBOX_Y_BOTTOM (GRAPHBOX_Y + GRAPHBOX_HEIGHT - 1)
/* Graphing area minus the borders */
#define GRAPH_X (GRAPHBOX_X + 1)
#define GRAPH_Y (GRAPHBOX_Y)
#define GRAPH_WIDTH (GRAPHBOX_WIDTH - 2)
#define GRAPH_HEIGHT (GRAPHBOX_HEIGHT - 1)
#define GRAPH_X_LEFT (GRAPH_X)
#define GRAPH_X_RIGHT (GRAPH_X + GRAPH_WIDTH - 1)
#define GRAPH_Y_UPPER (GRAPH_Y)
#define GRAPH_Y_BOTTOM (GRAPH_Y + GRAPH_HEIGHT - 1)
/* Label area box */
#define LABEL_X (GRAPHBOX_X_LEFT)
#define LABEL_Y (GRAPHBOX_Y_BOTTOM + 1)
#define LABEL_WIDTH (GRAPHBOX_WIDTH)
#define LABEL_HEIGHT 11
#define LABEL_X_LEFT (LABEL_X_LEFT)
#define LABEL_X_RIGHT (LABEL_X_LEFT + LABEL_WIDTH - 1)
#define LABEL_Y_TOP (LABEL_Y)
#define LABEL_Y_BOTTOM (LABEL_Y + LABEL_HEIGHT - 1)
#define LOW_INTENSITY 0
#define NORMAL_INTENSITY 1
#define HIGH_INTENSITY 2
/* X Stuff */
Display *dpy;
Window root_window, main_window, icon_window, *visible_window;
Font thefont;
Pixmap arrow;
Atom delete_atom;
int screen, specified_state = -1;
GC graphics_context;
unsigned long tx_pixel[3], rx_pixel[3], labelfg_pixel, labelbg_pixel, black_pixel, white_pixel, darkgrey_pixel, grey_pixel;
typedef int (*parser_func)(void);
/* I know statically declared buffers are against GNU coding standards, so sue me */
char buffer[256], *click_command = NULL, *label = NULL;
struct timeval timenow, timelast;
unsigned long totalbytes_in, totalbytes_out, lastbytes_in, lastbytes_out;
unsigned long totalpackets_in, totalpackets_out, lastpackets_in, lastpackets_out;
unsigned int diffpackets_in, diffpackets_out, diffbytes_in, diffbytes_out;
unsigned int delayTime = 25000, displayDelay = 55000, maxRate = 6000;
unsigned int out_rule = 2, in_rule = 1, graphbox_height = 44; /* number of rule in /proc/net/ip_acct to use */
char *in_rule_string = NULL, *out_rule_string = NULL, *device=NULL;
Bool current_tx = False, current_rx = False, rx, tx, logscale = False;
parser_func stat_gather;
void exit_func(void);
void got_signal(int x);
void setup_wmnet(int argc, char **argv);
void setupX(void);
void createWin(Window *win);
int updateStats(void);
void redraw(XExposeEvent *ee);
void tock(void);
int updateSpeedometer(int rxRate, int txRate);
void drawColoredLine(int y1, int y2, unsigned long *shadecolor);
void shadesOf(XColor *shade, unsigned long *returnarray);
extern parser_func setup_driver(char *parser);
extern char * available_drivers(void);
wmnet-1.06/Imakefile 100644 2376 2442 1163 7104413425 12605 0 ustar kaos kaos DEPLIBS = $(DEPXLIB)
CC = gcc -Wall
#ifdef LinuxArchitecture
STD_DEFINES = -Dlinux
DEFINES = -Dlinux_libc5
#if LinuxCLibMajorVersion > 5
DEFINES = -Dlinux_libc6
#endif
LOCAL_LIBRARIES = $(XLIB) -lm
#endif
#if defined (FreeBSDArchitecture) || defined (OpenBSDArchitecture)
LOCAL_LIBRARIES = $(XLIB) -lm -lkvm
INSTPGMFLAGS = -s -g kmem -m 2755
#endif
LINTLIBS = $(LINTXLIB)
#if defined (FreeBSDArchitecture) || defined (OpenBSDArchitecture)
SRCS = wmnet.c drivers.c getopt.c getopt1.c
OBJS = wmnet.o drivers.o getopt.o getopt1.o
#else
SRCS = wmnet.c drivers.c
OBJS = wmnet.o drivers.o
#endif
ComplexProgramTarget(wmnet)
wmnet-1.06/wmnet.man 100644 2376 2442 15232 7104414467 12654 0 ustar kaos kaos .\" -*-Nroff-*-
.\"
.TH wmnet 1x "4 May 2000"
.SH NAME
wmnet \- an IP accounting monitoring tool
.SH SYNOPSIS
.B wmnet
.RB [\| -h,--help \|]
.RB [\| -v,--version \|]
.RB [\| -T,--txrule=\fINUM \|]
.RB [\| -R,--rxrule=\fINUM \|]
.RB [\| -l,--logscale \|]
.RB [\| -t,--txcolor=\fICOLOR \|]
.RB [\| -r,--rxcolor=\fICOLOR \|]
.RB [\| -d\ \fIDELAY \|]
.RB [\| -x,--maxrate=\fIBYTES \|]
.RB [\| -F,--labelfg=\fICOLOR \|]
.RB [\| -B,--labelbg=\fICOLOR \|]
.RB [\| -L,--label=\fILABEL \|]
.RB [\| -e,--execute=\fICOMMAND \|]
.RB [\| -p,--promisc=\fIDEVICE \|]
.RB [\| -u,--unpromisc=\fIDEVICE \|]
.RB [\| -w,--withdrawn\ |\ -n,--normalstate \|]
.RB [\| -D,--driver=\fIDRIVER \|]
.RB [\| -W,--device=\fIDEVICE \|]
.SH DESCRIPTION
\fBwmnet\fP polls network statistics and does a few things with
the data it gets. It has small blinking lights for the rx and tx of IP
packets, a digital speedometer of your networks current
speed and a bar graph like xload plotting your throughput. It
has a tx speed graph from bottom-up and rx speed graph from the top-down.
The speedometer keeps track of the current speed per second and shows
it in a color corresponding to which of rx or tx that has the highest
speed at the moment. Also, the graph is drawn in a way that the highest
speed is drawn on top of the other while the other is in the background.
.SS OPTIONS
.TP
.B \-h,--help
displays a brief help message
.TP
.B -v,--version
displays version information
.TP
.B \-T,--txrule=\fINUM or NAME
in the case of the ipfwadm driver, this is the accounting rule number
to monitor for tx. For the ipchains driver, this is the chain name to
watch.
.TP
.B \-R,--rxrule=\fINUM or NAME
in the case of the ipfwadm driver, this is the accounting rule number
to monitor for rx. For the ipchains, this is the chain name to watch.
.TP
.B \-t,--txcolor=\fICOLOR
specifies the tx color
.TP
.B \-r,--rxcolor=\fICOLOR
specifies the rx color
.TP
.B \-x,--maxrate=\fIBYTES
maximum transfer rate for graph scale. Defaults to 6000, which should
be in the right area for modem connections. The key is to experiment
with this setting and the --logscale option to get the kind of graph
that fits your connection type. A general rule of thumb is to set this
to 4 to 5 times greater than your maximum throughput. The author finds
using --logscale and --maxrate=10000000 to work nicely for the entire range
of his dorms ethernet based connection to the internet.
.TP
.B \-l,--logscale
sets logarithmic scale, which is good for fast connections. This will
allow, for example, the graph still being informative at extremely low
speeds (telnet), and extremely fast speeds (local FTP) simultaneously
without the scale constantly being blank or solid at those respective
extremes.
.TP
.B -L,--label=\fILABEL
prints a given text label on the bottom of the window
.TP
.B -F,--labelfg=\fICOLOR
specifies the color for the text of the label
.TP
.B -B,--labelbg=\fICOLOR
specifies the color for the background of the label text
.TP
.B --withdrawn
.TP
.B --normalstate
sets the initial state of wmnet. WMnet tries to automatically determine which
state to start up in by starting up in withdrawn state if a WindowMaker
defined atom is present, and in normalstate otherwise. This behavior is
overriden by specifying one of these options.
.TP
.B -e,--execute=\fICOMMAND
executes \fICOMMAND \fPon a single click from button 1 (left mouse button).
.TP
.B -u,--unpromisc=\fIDEVICE
.TP
.B -p,--promisc=\fIDEVICE
put \fIDEVICE \fPin promiscuous mode to start applying accounting rules to all
network packets on your network segment. You either need to be root or
have the wmnet binary suid root to use this feature. This option may be
given more than once on the command line to specify more than one device.
.TP
.B \-d \fIDELAY
delay time for polling /proc/net/ip_account (in
microseconds). Defaults to 25000, that is 0.025 seconds, or 40 Hz
.TP
.B -D,--driver=\fIDRIVER
use \fIDRIVER \fP to get the stats we monitor. Compiled in drivers can be listed
with the -h switch.
.TP
.B -W,--device=\fIDEVICE
watch statistics for \fIDEVICE \fP. This option is only used for certain
stat drivers, namely: kmem, devstats, and pppstats. The ipchains and ipfwadm
stat drivers do not use this parameter.
.SH STAT DRIVERS
wmnet uses different stat drivers to get the stats it needs to monitor your
network. Exactly what drivers are available is determined at compile time. The
driver wmnet ultimately uses at runtime is dependent on your system. There
are 4 drivers specific to Linux and 1 to *BSD. The driver used can be overridden
by the --driver option. The available drivers are \fIpppstats, devstats, ipfwadm,
ipchains\fP and \fIkmem\fP.
.TP
.B pppstats
this driver works on Linux 2.0 or Linux 2.1 for ONLY ppp type devices.
Specify the \fI--device\fP option for the interface to monitor. By default it
uses interface ppp0. Please note, that if the ppp device is not available or active, wmnet
will continue to try in the hopes that it is only temporarily offline.
.TP
.B devstats
use this driver on Linux 2.1 kernels for any interface. Pass the \fI--device\fP option
for the device you want monitored, otherwise, the default is eth0. This will be available
for ONLY Linux 2.1 kernels and will always be there on those kernels.
.TP
.B ipfwadm
use this driver on Linux 2.0 kernels compiled with IP accounting. It won't work on Linux 2.1.
You'll also need to specify the \fI--txrule\fP and \fI--rxrule\fP options. By default, wmnet uses
the first two rules it finds.
.TP
.B ipchains
this driver will only work in Linux 2.1 kernels with IP chains compiled in. You'll want to also
specify the \fI--txrule\fP and \fI--rxrule\fP options and specify the chain names. By default it
uses the chains "acctin" and "acctout"
There must be at least one rule on the named ipchain, if there is more
than one rule in the specified chain, it uses the first. The chain
must not immediately return to the parent chain, it has to pass through a rule first.
Otherwise, the kernel will not collect the stats we need.
.TP
.B kmem
this driver is available on FreeBSD and OpenBSD systems and must be passed
a device through the \fI--device\fP option. By default, it uses ec0 but
will accept any valid device name.
.SH FILES
.TP
.I /proc/net/ip_acct /proc/net/dev /proc/net/ipchains
kernel net accounting information
.SH AUTHORS
\fBwmnet\fP was created by \fIJesse B. Off <joff@iastate.edu>\fP and is
maintained by \fIKatharine Osborne <kaos@digitalkaos.net>\fP.
This manpange was originally written by \fIMarcelo Magallon
<mmagallo@debian.org>\fP for the \fIDebian Project\fP, and is GNU
Copyright 1998 Marcelo Magallon and later modifed by \fIJesse Off\fP
and \fIKatharine Osborne\fP for WMnet versions 1.05 and above.
.SH "SEE ALSO"
.BR wmaker (1x)
wmnet-1.06/drivers.c 100644 2376 2442 33231 7104413425 12637 0 ustar kaos kaos /* wmnet -- X IP accounting monitor
* Copyright 1998 Jesse B. Off <joff@iastate.edu>
*
* $Id: drivers.c,v 1.1 1998/10/07 03:42:21 joff Exp joff $
*
* This software is released under the GNU Public License agreement.
* No warranties, whatever.... you know the usuals.... this is free
* software. if you use it, great... if you wanna make a change to it,
* great, but please send me the diff.
*/
#include<stdlib.h>
#include<stdio.h>
#include<string.h>
#include<X11/Xlib.h>
#include<fcntl.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<sys/socket.h>
#include<unistd.h>
#include"config.h"
/* For FreeBSD */
#ifdef USE_KVM
#include<net/if.h>
#include<kvm.h>
#include<nlist.h>
kvm_t *kvmfd;
struct nlist symbols[] = {
{ "_ifnet" },
{ NULL }
};
unsigned long ifnet_savedaddr;
int kvm_test(void);
int kvm_updateStats(void);
#endif /* USE_KVM */
#ifdef USE_LINUX_PPP
#include<net/ppp_defs.h>
#ifdef linux_libc5
# include<linux/if_ppp.h>
#else
# include<net/if_ppp.h>
#endif
#include<sys/ioctl.h>
int pppfd;
int ppp_test(void);
int updateStats_ppp(void);
static struct ifpppstatsreq ppp_stats_req;
#endif
#define ACCOUNT_IN_FOUND 1
#define ACCOUNT_OUT_FOUND 2
extern char buffer[256];
extern char *in_rule_string, *out_rule_string, *device;
extern unsigned long totalbytes_in, totalbytes_out, lastbytes_in, lastbytes_out;
extern unsigned long totalpackets_in, totalpackets_out, lastpackets_in, lastpackets_out;
extern unsigned int diffpackets_in, diffpackets_out, diffbytes_in, diffbytes_out;
extern unsigned int out_rule, in_rule; /* number of rule in /proc/net/ip_acct to use */
extern Bool current_tx, current_rx, rx, tx;
char *available_drivers(void);
#ifdef USE_IPFWADM
int updateStats_ipfwadm(void);
int ipfwadm_test(void);
#endif
#ifdef USE_IPCHAINS
int updateStats_ipchains(void);
int ipchains_test(void);
#endif
#ifdef USE_2_1_DEV
int updateStats_dev(void);
int dev_test(void);
#endif
typedef int (*parser_func)(void);
static struct drivers_struct {
char * name;
parser_func function;
parser_func test;
} drivers[] = {
#ifdef USE_2_1_DEV
{"devstats", updateStats_dev, dev_test},
#endif
#ifdef USE_IPFWADM
{"ipfwadm", updateStats_ipfwadm, ipfwadm_test},
#endif
#ifdef USE_IPCHAINS
{"ipchains", updateStats_ipchains, ipchains_test},
#endif
#ifdef USE_LINUX_PPP
{"pppstats",updateStats_ppp, ppp_test},
#endif
#ifdef USE_KVM
{"kmem",kvm_updateStats, kvm_test},
#endif
{NULL, NULL}
};
char* available_drivers(void) {
int ind = 0;
int len = 0;
char *string, *ptr;
while(drivers[ind].name != NULL) {
len += strlen(drivers[ind].name) + 1;
ind++;
}
ptr = string = (char *)malloc(len);
*string = '\0';
ind = 0;
while(drivers[ind].name != NULL) {
strcpy(string, drivers[ind].name);
string += strlen(drivers[ind].name);
*string++ = ',';
ind++;
}
*(--string) = '\0';
return ptr;
}
parser_func find_driver(void) {
int ind = 0;
while(drivers[ind].name != NULL) {
if(drivers[ind].test()) {
return drivers[ind].function;
}
ind++;
}
fprintf(stderr, "wmnet: no appropriate stat driver found\n");
exit(30);
}
parser_func setup_driver(char * parser_name) {
int ind = 0;
if (parser_name == NULL) return find_driver();
while(drivers[ind].name != NULL) {
if(!strcmp(parser_name, drivers[ind].name)) {
if (drivers[ind].test()) return drivers[ind].function;
fprintf(stderr, "wmnet: driver %s not appropriate for this machine\n", parser_name);
exit(18);
}
ind++;
}
fprintf(stderr, "wmnet: no driver %s\n", parser_name);
exit(18);
}
#ifdef linux
/* All the data gathering is done in here.
* Return True if no change to tx/rx.
* Return False if display will need to be updated.
*/
#ifdef USE_IPFWADM
int ipfwadm_test(void) {
if(open("/proc/net/ip_acct", O_RDONLY) == -1) return False;
fprintf(stderr, "wmnet: using ipfwadm driver to monitor accounting rules %d and %d\n", in_rule, out_rule);
return True;
}
int updateStats_ipfwadm(void) {
FILE *ip_acct;
unsigned int flag = 0, lineno = 0;
unsigned int offset = 37;
char *ptr;
rx = False;
tx = False;
if ((ip_acct = fopen("/proc/net/ip_acct", "r")) == NULL) {
fprintf(stderr, "wmnet: /proc/net/ip_acct unavailable\n"
"You either don't have IP accounting compiled in, or this isn't a 2.0 linux kernel.\n");
exit(4);
}
/* IP Accounting Rules for 2.0.x linux kernels*/
while(flag != (ACCOUNT_IN_FOUND|ACCOUNT_OUT_FOUND) && fgets(buffer, 256, ip_acct)) {
switch(lineno == out_rule ? ACCOUNT_OUT_FOUND : ( lineno == in_rule ? ACCOUNT_IN_FOUND : -1 ) ) {
case ACCOUNT_IN_FOUND:
/* accounting in */
flag |= ACCOUNT_IN_FOUND;
while(buffer[offset++] != ' ');
offset += 18;
totalpackets_in = strtoul(&buffer[offset], &ptr, 10);
if (totalpackets_in == lastpackets_in) break;
totalbytes_in = strtoul(ptr, NULL, 10);
diffpackets_in += totalpackets_in - lastpackets_in;
diffbytes_in += totalbytes_in - lastbytes_in;
lastpackets_in = totalpackets_in;
lastbytes_in = totalbytes_in;
rx = True;
break;
case ACCOUNT_OUT_FOUND:
/* accounting out */
flag |= ACCOUNT_OUT_FOUND;
while(buffer[offset++] != ' ');
offset += 18;
totalpackets_out = strtoul(&buffer[offset], &ptr, 10);
if (totalpackets_out == lastpackets_out) break;
totalbytes_out = strtoul(ptr, NULL, 10);
diffpackets_out += totalpackets_out - lastpackets_out;
diffbytes_out += totalbytes_out - lastbytes_out;
lastpackets_out = totalpackets_out;
lastbytes_out = totalbytes_out;
tx = True;
break;
}
lineno++;
offset = 37;
}
if(flag != (ACCOUNT_IN_FOUND|ACCOUNT_OUT_FOUND)) {
fprintf(stderr,"wmnet: couldn't find %s accounting rule to monitor in /proc/net/ip_acct\n",
(flag == ACCOUNT_IN_FOUND) ? "the TX" : ((flag == ACCOUNT_OUT_FOUND) ? "the RX" : "a single"));
exit(4);
}
fclose(ip_acct);
/* return True if no change to tx/rx
* return False if display will need to be updated
*/
return((rx == current_rx) && (tx == current_tx));
}
#endif /* USE_IPFWADM */
#ifdef USE_IPCHAINS
int ipchains_test(void) {
if (open("/proc/net/ip_fwchains",O_RDONLY) == -1) return False;
if (in_rule_string == NULL) in_rule_string = "acctin";
if (out_rule_string == NULL) out_rule_string = "acctout";
fprintf(stderr, "wmnet: using ipchains driver to monitor chains %s and %s\n", in_rule_string, out_rule_string);
return True;
}
/* ipchains parser mostly from Bjoern Kriews <bkr@cut.de> */
int updateStats_ipchains(void) {
FILE *ip_acct;
unsigned int flag = 0;
static char name[32];
unsigned long pack, bytes;
rx = False;
tx = False;
if ((ip_acct = fopen("/proc/net/ip_fwchains", "r")) == NULL) {
fprintf(stderr, "/proc/net/ip_fwchains does not exist?\n"
"Do you have IP accounting in your kernel?\n");
exit(4);
}
/* IP Chain Rules for Linux kernel 2_1.x */
while(flag != (ACCOUNT_IN_FOUND|ACCOUNT_OUT_FOUND) && fgets(buffer, 256, ip_acct)) {
*name = 0;
sscanf(buffer, "%30s %*s - %*d %*d %*d %*d %lu %*d %lu",
name, &pack, &bytes);
if(strcmp(name, in_rule_string) == 0) {
flag |= ACCOUNT_IN_FOUND;
totalpackets_in = pack;
if (totalpackets_in != lastpackets_in) {
totalbytes_in = bytes;
diffpackets_in += totalpackets_in - lastpackets_in;
diffbytes_in += totalbytes_in - lastbytes_in;
lastpackets_in = totalpackets_in;
lastbytes_in = totalbytes_in;
rx = True;
}
} else if (strcmp(name, out_rule_string) == 0) {
flag |= ACCOUNT_OUT_FOUND;
totalpackets_out = pack;
if (totalpackets_out != lastpackets_out) {
totalbytes_out = bytes;
diffpackets_out += totalpackets_out - lastpackets_out;
diffbytes_out += totalbytes_out - lastbytes_out;
lastpackets_out = totalpackets_out;
lastbytes_out = totalbytes_out;
tx = True;
}
}
}
if(flag != (ACCOUNT_IN_FOUND|ACCOUNT_OUT_FOUND)) {
fprintf(stderr,"I couldn't find %s IP chain to monitor in /proc/net/ip_fwchains.\n",
(flag == ACCOUNT_IN_FOUND) ? "the TX" : ((flag == ACCOUNT_OUT_FOUND) ? "the RX" : "a single"));
exit(4);
}
fclose(ip_acct);
/* return True if no change to tx/rx
* return False if display will need to be updated
*/
return((rx == current_rx) && (tx == current_tx));
}
#endif /* USE_IPCHAINS */
#ifdef USE_2_1_DEV
int updateStats_dev(void) {
FILE *dev;
char *ptr;
unsigned int flag = 0;
char *name;
rx = False;
tx = False;
if ((dev = fopen("/proc/net/dev", "r")) == NULL) {
fprintf(stderr, "/proc/net/dev does not exist?\n"
"Perhaps we are not running Linux?\n");
exit(4);
}
/* the first two lines we can skip */
fgets(buffer, 256, dev);
fgets(buffer, 256, dev);
/* IP Chain Rules for Linux kernel 2_1.x */
while(flag != (ACCOUNT_IN_FOUND|ACCOUNT_OUT_FOUND) && fgets(buffer, 256, dev)) {
ptr = buffer;
while(*ptr == ' ') ptr++;
name = ptr;
while(*ptr != ':') ptr++;
*ptr = '\0';
if (!strcmp(name, device)) {
flag = (ACCOUNT_IN_FOUND|ACCOUNT_OUT_FOUND);
totalpackets_in = strtoul(&buffer[15], NULL, 10);
if (totalpackets_in != lastpackets_in) {
totalbytes_in = strtoul(&buffer[7], NULL, 10);
diffpackets_in += totalpackets_in - lastpackets_in;
diffbytes_in += totalbytes_in - lastbytes_in;
lastpackets_in = totalpackets_in;
lastbytes_in = totalbytes_in;
rx = True;
}
totalpackets_out = strtoul(&buffer[74], NULL, 10);
if (totalpackets_out != lastpackets_out) {
totalbytes_out = strtoul(&buffer[66], NULL, 10);
diffpackets_out += totalpackets_out - lastpackets_out;
diffbytes_out += totalbytes_out - lastbytes_out;
lastpackets_out = totalpackets_out;
lastbytes_out = totalbytes_out;
tx = True;
}
}
}
fclose(dev);
/* return True if no change to tx/rx
* return False if display will need to be updated
*/
return((rx == current_rx) && (tx == current_tx));
}
int dev_test(void) {
int devfd;
if((devfd = open("/proc/net/dev", O_RDONLY)) == -1) return False;
read(devfd, buffer, 36);
if(buffer[35] == '|') return False;
if(device == NULL) device = "eth0";
fprintf(stderr, "wmnet: using devstats driver to monitor %s\n", device);
return True;
}
#endif /* USE_2_1_DEV */
#ifdef USE_LINUX_PPP
int ppp_test(void) {
pppfd = socket(AF_INET, SOCK_DGRAM, 0);
if(device == NULL) device = "ppp0";
strncpy(ppp_stats_req.ifr__name, device, 15);
ppp_stats_req.stats_ptr =(caddr_t) &ppp_stats_req.stats;
fprintf(stderr, "wmnet: using pppstats driver to monitor %s\n", device);
return True;
}
int updateStats_ppp(void) {
if(ioctl(pppfd, SIOCGPPPSTATS, &ppp_stats_req) != 0) {
return False;
}
totalpackets_in = ppp_stats_req.stats.p.ppp_ipackets;
if (totalpackets_in != lastpackets_in) {
totalbytes_in = ppp_stats_req.stats.p.ppp_ibytes;
diffpackets_in += totalpackets_in - lastpackets_in;
diffbytes_in += totalbytes_in - lastbytes_in;
lastpackets_in = totalpackets_in;
lastbytes_in = totalbytes_in;
rx = True;
}
totalpackets_out = ppp_stats_req.stats.p.ppp_opackets;
if (totalpackets_out != lastpackets_out) {
totalbytes_out =ppp_stats_req.stats.p.ppp_obytes;
diffpackets_out += totalpackets_out - lastpackets_out;
diffbytes_out += totalbytes_out - lastbytes_out;
lastpackets_out = totalpackets_out;
lastbytes_out = totalbytes_out;
tx = True;
}
/* return True if no change to tx/rx
* return False if display will need to be updated
*/
return((rx == current_rx) && (tx == current_tx));
}
#endif /* USE_LINUX_PPP */
#endif /* linux */
#ifdef USE_KVM
int kvm_test(void) {
if (((kvmfd = kvm_open(NULL, NULL, NULL, O_RDONLY, buffer)) == NULL) ||
(kvm_nlist(kvmfd, symbols) < 0) ||
kvm_read(kvmfd, (unsigned long)symbols[0].n_value, &ifnet_savedaddr, sizeof(unsigned long)) == -1 ) return False;
if(device == NULL) device = "ec0";
fprintf(stderr, "wmnet: using kmem driver to monitor %s\n", device);
return True;
}
int kvm_updateStats(void) {
struct ifnet * ifnet = (struct ifnet *)buffer;
unsigned long ifnet_addr = ifnet_savedaddr;
char devname[16];
int flag = 0;
while (ifnet_addr && flag != (ACCOUNT_IN_FOUND|ACCOUNT_OUT_FOUND)) {
kvm_read(kvmfd, ifnet_addr, buffer, sizeof(struct ifnet));
#ifdef __OpenBSD__
snprintf(devname, 15, "%s", ifnet->if_xname);
#else
kvm_read(kvmfd, (unsigned long)ifnet->if_name, devname, 15);
snprintf(devname, 15, "%s%d", devname, ifnet->if_unit);
#endif
if(!strncmp(devname, device, strlen(device))) { /* we found our struct */
totalpackets_in =ifnet->if_ipackets;
if (totalpackets_in != lastpackets_in) {
totalbytes_in = ifnet->if_ibytes;
diffpackets_in += totalpackets_in - lastpackets_in;
diffbytes_in += totalbytes_in - lastbytes_in;
lastpackets_in = totalpackets_in;
lastbytes_in = totalbytes_in;
rx = True;
}
totalpackets_out = ifnet->if_opackets;
if (totalpackets_out != lastpackets_out) {
totalbytes_out =ifnet->if_obytes;
diffpackets_out += totalpackets_out - lastpackets_out;
diffbytes_out += totalbytes_out - lastbytes_out;
lastpackets_out = totalpackets_out;
lastbytes_out = totalbytes_out;
tx = True;
}
flag = (ACCOUNT_IN_FOUND|ACCOUNT_OUT_FOUND);
} else {
#ifdef __OpenBSD__
ifnet_addr = (unsigned long)ifnet->if_list.tqe_next;
#else
ifnet_addr = (unsigned long)ifnet->if_next;
#endif
}
}
/* return True if no change to tx/rx
* return False if display will need to be updated
*/
return((rx == current_rx) && (tx == current_tx));
}
#endif
wmnet-1.06/config.h 100644 2376 2442 3432 7104413425 12413 0 ustar kaos kaos #if defined (__FreeBSD__) || defined (__OpenBSD__)
/* Our only FreeBSD driver, this goes straight into kernel memory
* and reads the raw structures from right underneath the kernel using the
* kvm library. This made the code a require a little more thought, but
* the end result is a statistics driver thats faster than the linux ones
* (with the possible exception of the LINUX_PPP driver). However, none
* of them really vary by any appreciable amount. You can monitor whole
* interfaces only with this driver.
*/
# define USE_KVM
#endif
#ifdef linux
/* this driver uses a socket ioctl() to get stats from a ppp type interface
* Define this if you will be using wmnet mostly to watch your ppp stats.
* The advantage to this driver is that you don't need to mess around with
* IP accounting rules.
*/
#define USE_LINUX_PPP
/* This driver uses the 2.0 kernel's IP accounting rules to gather data
* You set two rules up using the ipfwadm command and wmnet will watch
* them. You DO need a 2.0 kernel and IP accounting enabled in your kernel
*/
#define USE_IPFWADM
/* If you have a 2.1 kernel, you've probably noticed that IP accounting
* and the ipfwadm command won't work anymore. These have been superceded
* by the ipchains mechanism. Define this if you want IP chains support,
* you have a 2.1 kernel, and you have set up two chains (read README)
*/
#define USE_IPCHAINS
/* Define this if you have a 2.1 kernel and wish to use the stats from
* /proc/net/dev. In the 2.1 kernels, /proc/net/dev now has a bytes field
* (2.0 only had a packets field) which enables us to use this driver as
* a generic interface watcher. With this, you don't have to fool around with
* ipchains if you don't want to or haven't it enabled
*/
#define USE_2_1_DEV
#endif /* linux */
wmnet-1.06/getopt.h 100644 2376 2442 10754 6607317205 12503 0 ustar kaos kaos /* Declarations for getopt.
Copyright (C) 1989,90,91,92,93,94,96,97 Free Software Foundation, Inc.
This file is part of the GNU C Library.
The GNU C Library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public License as
published by the Free Software Foundation; either version 2 of the
License, or (at your option) any later version.
The GNU C Library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public
License along with the GNU C Library; see the file COPYING.LIB. If not,
write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
Boston, MA 02111-1307, USA. */
#ifndef _GETOPT_H
#define _GETOPT_H 1
#ifdef __cplusplus
extern "C" {
#endif
/* For communication from `getopt' to the caller.
When `getopt' finds an option that takes an argument,
the argument value is returned here.
Also, when `ordering' is RETURN_IN_ORDER,
each non-option ARGV-element is returned here. */
extern char *optarg;
/* Index in ARGV of the next element to be scanned.
This is used for communication to and from the caller
and for communication between successive calls to `getopt'.
On entry to `getopt', zero means this is the first call; initialize.
When `getopt' returns -1, this is the index of the first of the
non-option elements that the caller should itself scan.
Otherwise, `optind' communicates from one call to the next
how much of ARGV has been scanned so far. */
extern int optind;
/* Callers store zero here to inhibit the error message `getopt' prints
for unrecognized options. */
extern int opterr;
/* Set to an option character which was unrecognized. */
extern int optopt;
/* Describe the long-named options requested by the application.
The LONG_OPTIONS argument to getopt_long or getopt_long_only is a vector
of `struct option' terminated by an element containing a name which is
zero.
The field `has_arg' is:
no_argument (or 0) if the option does not take an argument,
required_argument (or 1) if the option requires an argument,
optional_argument (or 2) if the option takes an optional argument.
If the field `flag' is not NULL, it points to a variable that is set
to the value given in the field `val' when the option is found, but
left unchanged if the option is not found.
To have a long-named option do something other than set an `int' to
a compiled-in constant, such as set a value from `optarg', set the
option's `flag' field to zero and its `val' field to a nonzero
value (the equivalent single-letter option character, if there is
one). For long options that have a zero `flag' field, `getopt'
returns the contents of the `val' field. */
struct option
{
#if defined (__STDC__) && __STDC__
const char *name;
#else
char *name;
#endif
/* has_arg can't be an enum because some compilers complain about
type mismatches in all the code that assumes it is an int. */
int has_arg;
int *flag;
int val;
};
/* Names for the values of the `has_arg' field of `struct option'. */
#define no_argument 0
#define required_argument 1
#define optional_argument 2
#if defined (__STDC__) && __STDC__
#ifdef __GNU_LIBRARY__
/* Many other libraries have conflicting prototypes for getopt, with
differences in the consts, in stdlib.h. To avoid compilation
errors, only prototype getopt for the GNU C library. */
extern int getopt (int argc, char *const *argv, const char *shortopts);
#else /* not __GNU_LIBRARY__ */
extern int getopt ();
#endif /* __GNU_LIBRARY__ */
extern int getopt_long (int argc, char *const *argv, const char *shortopts,
const struct option *longopts, int *longind);
extern int getopt_long_only (int argc, char *const *argv,
const char *shortopts,
const struct option *longopts, int *longind);
/* Internal only. Users should not call this directly. */
extern int _getopt_internal (int argc, char *const *argv,
const char *shortopts,
const struct option *longopts, int *longind,
int long_only);
#else /* not __STDC__ */
extern int getopt ();
extern int getopt_long ();
extern int getopt_long_only ();
extern int _getopt_internal ();
#endif /* __STDC__ */
#ifdef __cplusplus
}
#endif
#endif /* _GETOPT_H */
wmnet-1.06/getopt.c 100644 2376 2442 72763 6607332064 12506 0 ustar kaos kaos /* Getopt for GNU.
NOTE: getopt is now part of the C library, so if you don't know what
"Keep this file name-space clean" means, talk to roland@gnu.ai.mit.edu
before changing it!
Copyright (C) 1987, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97
Free Software Foundation, Inc.
The GNU C Library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public License as
published by the Free Software Foundation; either version 2 of the
License, or (at your option) any later version.
The GNU C Library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public
License along with the GNU C Library; see the file COPYING.LIB. If not,
write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
Boston, MA 02111-1307, USA. */
/* This tells Alpha OSF/1 not to define a getopt prototype in <stdio.h>.
Ditto for AIX 3.2 and <stdlib.h>. */
#ifndef _NO_PROTO
#define _NO_PROTO
#endif
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#if !defined (__STDC__) || !__STDC__
/* This is a separate conditional since some stdc systems
reject `defined (const)'. */
#ifndef const
#define const
#endif
#endif
#include <stdio.h>
/* Comment out all this code if we are using the GNU C Library, and are not
actually compiling the library itself. This code is part of the GNU C
Library, but also included in many other GNU distributions. Compiling
and linking in this code is a waste when using the GNU C library
(especially if it is a shared library). Rather than having every GNU
program understand `configure --with-gnu-libc' and omit the object files,
it is simpler to just do this in the source for each such file. */
#define GETOPT_INTERFACE_VERSION 2
#if !defined (_LIBC) && defined (__GLIBC__) && __GLIBC__ >= 2
#include <gnu-versions.h>
#if _GNU_GETOPT_INTERFACE_VERSION == GETOPT_INTERFACE_VERSION
#define ELIDE_CODE
#endif
#endif
#ifndef ELIDE_CODE
/* This needs to come after some library #include
to get __GNU_LIBRARY__ defined. */
#ifdef __GNU_LIBRARY__
/* Don't include stdlib.h for non-GNU C libraries because some of them
contain conflicting prototypes for getopt. */
#include <stdlib.h>
#include <unistd.h>
#endif /* GNU C library. */
#ifdef VMS
#include <unixlib.h>
#if HAVE_STRING_H - 0
#include <string.h>
#endif
#endif
#if defined (WIN32) && !defined (__CYGWIN32__)
/* It's not Unix, really. See? Capital letters. */
#include <windows.h>
#define getpid() GetCurrentProcessId()
#endif
#ifndef _
/* This is for other GNU distributions with internationalized messages.
When compiling libc, the _ macro is predefined. */
#ifdef HAVE_LIBINTL_H
# include <libintl.h>
# define _(msgid) gettext (msgid)
#else
# define _(msgid) (msgid)
#endif
#endif
/* This version of `getopt' appears to the caller like standard Unix `getopt'
but it behaves differently for the user, since it allows the user
to intersperse the options with the other arguments.
As `getopt' works, it permutes the elements of ARGV so that,
when it is done, all the options precede everything else. Thus
all application programs are extended to handle flexible argument order.
Setting the environment variable POSIXLY_CORRECT disables permutation.
Then the behavior is completely standard.
GNU application programs can use a third alternative mode in which
they can distinguish the relative order of options and other arguments. */
#include "getopt.h"
/* For communication from `getopt' to the caller.
When `getopt' finds an option that takes an argument,
the argument value is returned here.
Also, when `ordering' is RETURN_IN_ORDER,
each non-option ARGV-element is returned here. */
char *optarg = NULL;
/* Index in ARGV of the next element to be scanned.
This is used for communication to and from the caller
and for communication between successive calls to `getopt'.
On entry to `getopt', zero means this is the first call; initialize.
When `getopt' returns -1, this is the index of the first of the
non-option elements that the caller should itself scan.
Otherwise, `optind' communicates from one call to the next
how much of ARGV has been scanned so far. */
/* 1003.2 says this must be 1 before any call. */
int optind = 1;
/* Formerly, initialization of getopt depended on optind==0, which
causes problems with re-calling getopt as programs generally don't
know that. */
int __getopt_initialized = 0;
/* The next char to be scanned in the option-element
in which the last option character we returned was found.
This allows us to pick up the scan where we left off.
If this is zero, or a null string, it means resume the scan
by advancing to the next ARGV-element. */
static char *nextchar;
/* Callers store zero here to inhibit the error message
for unrecognized options. */
int opterr = 1;
/* Set to an option character which was unrecognized.
This must be initialized on some systems to avoid linking in the
system's own getopt implementation. */
int optopt = '?';
/* Describe how to deal with options that follow non-option ARGV-elements.
If the caller did not specify anything,
the default is REQUIRE_ORDER if the environment variable
POSIXLY_CORRECT is defined, PERMUTE otherwise.
REQUIRE_ORDER means don't recognize them as options;
stop option processing when the first non-option is seen.
This is what Unix does.
This mode of operation is selected by either setting the environment
variable POSIXLY_CORRECT, or using `+' as the first character
of the list of option characters.
PERMUTE is the default. We permute the contents of ARGV as we scan,
so that eventually all the non-options are at the end. This allows options
to be given in any order, even with programs that were not written to
expect this.
RETURN_IN_ORDER is an option available to programs that were written
to expect options and other ARGV-elements in any order and that care about
the ordering of the two. We describe each non-option ARGV-element
as if it were the argument of an option with character code 1.
Using `-' as the first character of the list of option characters
selects this mode of operation.
The special argument `--' forces an end of option-scanning regardless
of the value of `ordering'. In the case of RETURN_IN_ORDER, only
`--' can cause `getopt' to return -1 with `optind' != ARGC. */
static enum
{
REQUIRE_ORDER, PERMUTE, RETURN_IN_ORDER
} ordering;
/* Value of POSIXLY_CORRECT environment variable. */
static char *posixly_correct;
#ifdef __GNU_LIBRARY__
/* We want to avoid inclusion of string.h with non-GNU libraries
because there are many ways it can cause trouble.
On some systems, it contains special magic macros that don't work
in GCC. */
#include <string.h>
#define my_index strchr
#else
/* Avoid depending on library functions or files
whose names are inconsistent. */
char *getenv ();
extern int strncmp(const char *s1, const char *s2, size_t len);
static char *
my_index (str, chr)
const char *str;
int chr;
{
while (*str)
{
if (*str == chr)
return (char *) str;
str++;
}
return 0;
}
/* If using GCC, we can safely declare strlen this way.
If not using GCC, it is ok not to declare it. */
#ifdef __GNUC__
/* Note that Motorola Delta 68k R3V7 comes with GCC but not stddef.h.
That was relevant to code that was here before. */
#if !defined (__STDC__) || !__STDC__
/* gcc with -traditional declares the built-in strlen to return int,
and has done so at least since version 2.4.5. -- rms. */
extern int strlen (const char *);
#endif /* not __STDC__ */
#endif /* __GNUC__ */
#endif /* not __GNU_LIBRARY__ */
/* Handle permutation of arguments. */
/* Describe the part of ARGV that contains non-options that have
been skipped. `first_nonopt' is the index in ARGV of the first of them;
`last_nonopt' is the index after the last of them. */
static int first_nonopt;
static int last_nonopt;
#ifdef _LIBC
/* Bash 2.0 gives us an environment variable containing flags
indicating ARGV elements that should not be considered arguments. */
/* Defined in getopt_init.c */
extern char *__getopt_nonoption_flags;
static int nonoption_flags_max_len;
static int nonoption_flags_len;
static int original_argc;
static char *const *original_argv;
extern pid_t __libc_pid;
/* Make sure the environment variable bash 2.0 puts in the environment
is valid for the getopt call we must make sure that the ARGV passed
to getopt is that one passed to the process. */
static void
__attribute__ ((unused))
store_args_and_env (int argc, char *const *argv)
{
/* XXX This is no good solution. We should rather copy the args so
that we can compare them later. But we must not use malloc(3). */
original_argc = argc;
original_argv = argv;
}
text_set_element (__libc_subinit, store_args_and_env);
# define SWAP_FLAGS(ch1, ch2) \
if (nonoption_flags_len > 0) \
{ \
char __tmp = __getopt_nonoption_flags[ch1]; \
__getopt_nonoption_flags[ch1] = __getopt_nonoption_flags[ch2]; \
__getopt_nonoption_flags[ch2] = __tmp; \
}
#else /* !_LIBC */
# define SWAP_FLAGS(ch1, ch2)
#endif /* _LIBC */
/* Exchange two adjacent subsequences of ARGV.
One subsequence is elements [first_nonopt,last_nonopt)
which contains all the non-options that have been skipped so far.
The other is elements [last_nonopt,optind), which contains all
the options processed since those non-options were skipped.
`first_nonopt' and `last_nonopt' are relocated so that they describe
the new indices of the non-options in ARGV after they are moved. */
#if defined (__STDC__) && __STDC__
static void exchange (char **);
#endif
static void
exchange (argv)
char **argv;
{
int bottom = first_nonopt;
int middle = last_nonopt;
int top = optind;
char *tem;
/* Exchange the shorter segment with the far end of the longer segment.
That puts the shorter segment into the right place.
It leaves the longer segment in the right place overall,
but it consists of two parts that need to be swapped next. */
#ifdef _LIBC
/* First make sure the handling of the `__getopt_nonoption_flags'
string can work normally. Our top argument must be in the range
of the string. */
if (nonoption_flags_len > 0 && top >= nonoption_flags_max_len)
{
/* We must extend the array. The user plays games with us and
presents new arguments. */
char *new_str = malloc (top + 1);
if (new_str == NULL)
nonoption_flags_len = nonoption_flags_max_len = 0;
else
{
memcpy (new_str, __getopt_nonoption_flags, nonoption_flags_max_len);
memset (&new_str[nonoption_flags_max_len], '\0',
top + 1 - nonoption_flags_max_len);
nonoption_flags_max_len = top + 1;
__getopt_nonoption_flags = new_str;
}
}
#endif
while (top > middle && middle > bottom)
{
if (top - middle > middle - bottom)
{
/* Bottom segment is the short one. */
int len = middle - bottom;
register int i;
/* Swap it with the top part of the top segment. */
for (i = 0; i < len; i++)
{
tem = argv[bottom + i];
argv[bottom + i] = argv[top - (middle - bottom) + i];
argv[top - (middle - bottom) + i] = tem;
SWAP_FLAGS (bottom + i, top - (middle - bottom) + i);
}
/* Exclude the moved bottom segment from further swapping. */
top -= len;
}
else
{
/* Top segment is the short one. */
int len = top - middle;
register int i;
/* Swap it with the bottom part of the bottom segment. */
for (i = 0; i < len; i++)
{
tem = argv[bottom + i];
argv[bottom + i] = argv[middle + i];
argv[middle + i] = tem;
SWAP_FLAGS (bottom + i, middle + i);
}
/* Exclude the moved top segment from further swapping. */
bottom += len;
}
}
/* Update records for the slots the non-options now occupy. */
first_nonopt += (optind - last_nonopt);
last_nonopt = optind;
}
/* Initialize the internal data when the first call is made. */
#if defined (__STDC__) && __STDC__
static const char *_getopt_initialize (int, char *const *, const char *);
#endif
static const char *
_getopt_initialize (argc, argv, optstring)
int argc;
char *const *argv;
const char *optstring;
{
/* Start processing options with ARGV-element 1 (since ARGV-element 0
is the program name); the sequence of previously skipped
non-option ARGV-elements is empty. */
first_nonopt = last_nonopt = optind;
nextchar = NULL;
posixly_correct = getenv ("POSIXLY_CORRECT");
/* Determine how to handle the ordering of options and nonoptions. */
if (optstring[0] == '-')
{
ordering = RETURN_IN_ORDER;
++optstring;
}
else if (optstring[0] == '+')
{
ordering = REQUIRE_ORDER;
++optstring;
}
else if (posixly_correct != NULL)
ordering = REQUIRE_ORDER;
else
ordering = PERMUTE;
#ifdef _LIBC
if (posixly_correct == NULL
&& argc == original_argc && argv == original_argv)
{
if (nonoption_flags_max_len == 0)
{
if (__getopt_nonoption_flags == NULL
|| __getopt_nonoption_flags[0] == '\0')
nonoption_flags_max_len = -1;
else
{
const char *orig_str = __getopt_nonoption_flags;
int len = nonoption_flags_max_len = strlen (orig_str);
if (nonoption_flags_max_len < argc)
nonoption_flags_max_len = argc;
__getopt_nonoption_flags =
(char *) malloc (nonoption_flags_max_len);
if (__getopt_nonoption_flags == NULL)
nonoption_flags_max_len = -1;
else
{
memcpy (__getopt_nonoption_flags, orig_str, len);
memset (&__getopt_nonoption_flags[len], '\0',
nonoption_flags_max_len - len);
}
}
}
nonoption_flags_len = nonoption_flags_max_len;
}
else
nonoption_flags_len = 0;
#endif
return optstring;
}
/* Scan elements of ARGV (whose length is ARGC) for option characters
given in OPTSTRING.
If an element of ARGV starts with '-', and is not exactly "-" or "--",
then it is an option element. The characters of this element
(aside from the initial '-') are option characters. If `getopt'
is called repeatedly, it returns successively each of the option characters
from each of the option elements.
If `getopt' finds another option character, it returns that character,
updating `optind' and `nextchar' so that the next call to `getopt' can
resume the scan with the following option character or ARGV-element.
If there are no more option characters, `getopt' returns -1.
Then `optind' is the index in ARGV of the first ARGV-element
that is not an option. (The ARGV-elements have been permuted
so that those that are not options now come last.)
OPTSTRING is a string containing the legitimate option characters.
If an option character is seen that is not listed in OPTSTRING,
return '?' after printing an error message. If you set `opterr' to
zero, the error message is suppressed but we still return '?'.
If a char in OPTSTRING is followed by a colon, that means it wants an arg,
so the following text in the same ARGV-element, or the text of the following
ARGV-element, is returned in `optarg'. Two colons mean an option that
wants an optional arg; if there is text in the current ARGV-element,
it is returned in `optarg', otherwise `optarg' is set to zero.
If OPTSTRING starts with `-' or `+', it requests different methods of
handling the non-option ARGV-elements.
See the comments about RETURN_IN_ORDER and REQUIRE_ORDER, above.
Long-named options begin with `--' instead of `-'.
Their names may be abbreviated as long as the abbreviation is unique
or is an exact match for some defined option. If they have an
argument, it follows the option name in the same ARGV-element, separated
from the option name by a `=', or else the in next ARGV-element.
When `getopt' finds a long-named option, it returns 0 if that option's
`flag' field is nonzero, the value of the option's `val' field
if the `flag' field is zero.
The elements of ARGV aren't really const, because we permute them.
But we pretend they're const in the prototype to be compatible
with other systems.
LONGOPTS is a vector of `struct option' terminated by an
element containing a name which is zero.
LONGIND returns the index in LONGOPT of the long-named option found.
It is only valid when a long-named option has been found by the most
recent call.
If LONG_ONLY is nonzero, '-' as well as '--' can introduce
long-named options. */
int
_getopt_internal (argc, argv, optstring, longopts, longind, long_only)
int argc;
char *const *argv;
const char *optstring;
const struct option *longopts;
int *longind;
int long_only;
{
optarg = NULL;
if (optind == 0 || !__getopt_initialized)
{
if (optind == 0)
optind = 1; /* Don't scan ARGV[0], the program name. */
optstring = _getopt_initialize (argc, argv, optstring);
__getopt_initialized = 1;
}
/* Test whether ARGV[optind] points to a non-option argument.
Either it does not have option syntax, or there is an environment flag
from the shell indicating it is not an option. The later information
is only used when the used in the GNU libc. */
#ifdef _LIBC
#define NONOPTION_P (argv[optind][0] != '-' || argv[optind][1] == '\0' \
|| (optind < nonoption_flags_len \
&& __getopt_nonoption_flags[optind] == '1'))
#else
#define NONOPTION_P (argv[optind][0] != '-' || argv[optind][1] == '\0')
#endif
if (nextchar == NULL || *nextchar == '\0')
{
/* Advance to the next ARGV-element. */
/* Give FIRST_NONOPT & LAST_NONOPT rational values if OPTIND has been
moved back by the user (who may also have changed the arguments). */
if (last_nonopt > optind)
last_nonopt = optind;
if (first_nonopt > optind)
first_nonopt = optind;
if (ordering == PERMUTE)
{
/* If we have just processed some options following some non-options,
exchange them so that the options come first. */
if (first_nonopt != last_nonopt && last_nonopt != optind)
exchange ((char **) argv);
else if (last_nonopt != optind)
first_nonopt = optind;
/* Skip any additional non-options
and extend the range of non-options previously skipped. */
while (optind < argc && NONOPTION_P)
optind++;
last_nonopt = optind;
}
/* The special ARGV-element `--' means premature end of options.
Skip it like a null option,
then exchange with previous non-options as if it were an option,
then skip everything else like a non-option. */
if (optind != argc && !strcmp (argv[optind], "--"))
{
optind++;
if (first_nonopt != last_nonopt && last_nonopt != optind)
exchange ((char **) argv);
else if (first_nonopt == last_nonopt)
first_nonopt = optind;
last_nonopt = argc;
optind = argc;
}
/* If we have done all the ARGV-elements, stop the scan
and back over any non-options that we skipped and permuted. */
if (optind == argc)
{
/* Set the next-arg-index to point at the non-options
that we previously skipped, so the caller will digest them. */
if (first_nonopt != last_nonopt)
optind = first_nonopt;
return -1;
}
/* If we have come to a non-option and did not permute it,
either stop the scan or describe it to the caller and pass it by. */
if (NONOPTION_P)
{
if (ordering == REQUIRE_ORDER)
return -1;
optarg = argv[optind++];
return 1;
}
/* We have found another option-ARGV-element.
Skip the initial punctuation. */
nextchar = (argv[optind] + 1
+ (longopts != NULL && argv[optind][1] == '-'));
}
/* Decode the current option-ARGV-element. */
/* Check whether the ARGV-element is a long option.
If long_only and the ARGV-element has the form "-f", where f is
a valid short option, don't consider it an abbreviated form of
a long option that starts with f. Otherwise there would be no
way to give the -f short option.
On the other hand, if there's a long option "fubar" and
the ARGV-element is "-fu", do consider that an abbreviation of
the long option, just like "--fu", and not "-f" with arg "u".
This distinction seems to be the most useful approach. */
if (longopts != NULL
&& (argv[optind][1] == '-'
|| (long_only && (argv[optind][2] || !my_index (optstring, argv[optind][1])))))
{
char *nameend;
const struct option *p;
const struct option *pfound = NULL;
int exact = 0;
int ambig = 0;
int indfound = -1;
int option_index;
for (nameend = nextchar; *nameend && *nameend != '='; nameend++)
/* Do nothing. */ ;
/* Test all long options for either exact match
or abbreviated matches. */
for (p = longopts, option_index = 0; p->name; p++, option_index++)
if (!strncmp (p->name, nextchar, nameend - nextchar))
{
if ((unsigned int) (nameend - nextchar)
== (unsigned int) strlen (p->name))
{
/* Exact match found. */
pfound = p;
indfound = option_index;
exact = 1;
break;
}
else if (pfound == NULL)
{
/* First nonexact match found. */
pfound = p;
indfound = option_index;
}
else
/* Second or later nonexact match found. */
ambig = 1;
}
if (ambig && !exact)
{
if (opterr)
fprintf (stderr, _("%s: option `%s' is ambiguous\n"),
argv[0], argv[optind]);
nextchar += strlen (nextchar);
optind++;
optopt = 0;
return '?';
}
if (pfound != NULL)
{
option_index = indfound;
optind++;
if (*nameend)
{
/* Don't test has_arg with >, because some C compilers don't
allow it to be used on enums. */
if (pfound->has_arg)
optarg = nameend + 1;
else
{
if (opterr)
if (argv[optind - 1][1] == '-')
/* --option */
fprintf (stderr,
_("%s: option `--%s' doesn't allow an argument\n"),
argv[0], pfound->name);
else
/* +option or -option */
fprintf (stderr,
_("%s: option `%c%s' doesn't allow an argument\n"),
argv[0], argv[optind - 1][0], pfound->name);
nextchar += strlen (nextchar);
optopt = pfound->val;
return '?';
}
}
else if (pfound->has_arg == 1)
{
if (optind < argc)
optarg = argv[optind++];
else
{
if (opterr)
fprintf (stderr,
_("%s: option `%s' requires an argument\n"),
argv[0], argv[optind - 1]);
nextchar += strlen (nextchar);
optopt = pfound->val;
return optstring[0] == ':' ? ':' : '?';
}
}
nextchar += strlen (nextchar);
if (longind != NULL)
*longind = option_index;
if (pfound->flag)
{
*(pfound->flag) = pfound->val;
return 0;
}
return pfound->val;
}
/* Can't find it as a long option. If this is not getopt_long_only,
or the option starts with '--' or is not a valid short
option, then it's an error.
Otherwise interpret it as a short option. */
if (!long_only || argv[optind][1] == '-'
|| my_index (optstring, *nextchar) == NULL)
{
if (opterr)
{
if (argv[optind][1] == '-')
/* --option */
fprintf (stderr, _("%s: unrecognized option `--%s'\n"),
argv[0], nextchar);
else
/* +option or -option */
fprintf (stderr, _("%s: unrecognized option `%c%s'\n"),
argv[0], argv[optind][0], nextchar);
}
nextchar = (char *) "";
optind++;
optopt = 0;
return '?';
}
}
/* Look at and handle the next short option-character. */
{
char c = *nextchar++;
char *temp = my_index (optstring, c);
/* Increment `optind' when we start to process its last character. */
if (*nextchar == '\0')
++optind;
if (temp == NULL || c == ':')
{
if (opterr)
{
if (posixly_correct)
/* 1003.2 specifies the format of this message. */
fprintf (stderr, _("%s: illegal option -- %c\n"),
argv[0], c);
else
fprintf (stderr, _("%s: invalid option -- %c\n"),
argv[0], c);
}
optopt = c;
return '?';
}
/* Convenience. Treat POSIX -W foo same as long option --foo */
if (temp[0] == 'W' && temp[1] == ';')
{
char *nameend;
const struct option *p;
const struct option *pfound = NULL;
int exact = 0;
int ambig = 0;
int indfound = 0;
int option_index;
/* This is an option that requires an argument. */
if (*nextchar != '\0')
{
optarg = nextchar;
/* If we end this ARGV-element by taking the rest as an arg,
we must advance to the next element now. */
optind++;
}
else if (optind == argc)
{
if (opterr)
{
/* 1003.2 specifies the format of this message. */
fprintf (stderr, _("%s: option requires an argument -- %c\n"),
argv[0], c);
}
optopt = c;
if (optstring[0] == ':')
c = ':';
else
c = '?';
return c;
}
else
/* We already incremented `optind' once;
increment it again when taking next ARGV-elt as argument. */
optarg = argv[optind++];
/* optarg is now the argument, see if it's in the
table of longopts. */
for (nextchar = nameend = optarg; *nameend && *nameend != '='; nameend++)
/* Do nothing. */ ;
/* Test all long options for either exact match
or abbreviated matches. */
for (p = longopts, option_index = 0; p->name; p++, option_index++)
if (!strncmp (p->name, nextchar, nameend - nextchar))
{
if ((unsigned int) (nameend - nextchar) == strlen (p->name))
{
/* Exact match found. */
pfound = p;
indfound = option_index;
exact = 1;
break;
}
else if (pfound == NULL)
{
/* First nonexact match found. */
pfound = p;
indfound = option_index;
}
else
/* Second or later nonexact match found. */
ambig = 1;
}
if (ambig && !exact)
{
if (opterr)
fprintf (stderr, _("%s: option `-W %s' is ambiguous\n"),
argv[0], argv[optind]);
nextchar += strlen (nextchar);
optind++;
return '?';
}
if (pfound != NULL)
{
option_index = indfound;
if (*nameend)
{
/* Don't test has_arg with >, because some C compilers don't
allow it to be used on enums. */
if (pfound->has_arg)
optarg = nameend + 1;
else
{
if (opterr)
fprintf (stderr, _("\
%s: option `-W %s' doesn't allow an argument\n"),
argv[0], pfound->name);
nextchar += strlen (nextchar);
return '?';
}
}
else if (pfound->has_arg == 1)
{
if (optind < argc)
optarg = argv[optind++];
else
{
if (opterr)
fprintf (stderr,
_("%s: option `%s' requires an argument\n"),
argv[0], argv[optind - 1]);
nextchar += strlen (nextchar);
return optstring[0] == ':' ? ':' : '?';
}
}
nextchar += strlen (nextchar);
if (longind != NULL)
*longind = option_index;
if (pfound->flag)
{
*(pfound->flag) = pfound->val;
return 0;
}
return pfound->val;
}
nextchar = NULL;
return 'W'; /* Let the application handle it. */
}
if (temp[1] == ':')
{
if (temp[2] == ':')
{
/* This is an option that accepts an argument optionally. */
if (*nextchar != '\0')
{
optarg = nextchar;
optind++;
}
else
optarg = NULL;
nextchar = NULL;
}
else
{
/* This is an option that requires an argument. */
if (*nextchar != '\0')
{
optarg = nextchar;
/* If we end this ARGV-element by taking the rest as an arg,
we must advance to the next element now. */
optind++;
}
else if (optind == argc)
{
if (opterr)
{
/* 1003.2 specifies the format of this message. */
fprintf (stderr,
_("%s: option requires an argument -- %c\n"),
argv[0], c);
}
optopt = c;
if (optstring[0] == ':')
c = ':';
else
c = '?';
}
else
/* We already incremented `optind' once;
increment it again when taking next ARGV-elt as argument. */
optarg = argv[optind++];
nextchar = NULL;
}
}
return c;
}
}
int
getopt (argc, argv, optstring)
int argc;
char *const *argv;
const char *optstring;
{
return _getopt_internal (argc, argv, optstring,
(const struct option *) 0,
(int *) 0,
0);
}
#endif /* Not ELIDE_CODE. */
#ifdef TEST
/* Compile with -DTEST to make an executable for use in testing
the above definition of `getopt'. */
int
main (argc, argv)
int argc;
char **argv;
{
int c;
int digit_optind = 0;
while (1)
{
int this_option_optind = optind ? optind : 1;
c = getopt (argc, argv, "abc:d:0123456789");
if (c == -1)
break;
switch (c)
{
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
if (digit_optind != 0 && digit_optind != this_option_optind)
printf ("digits occur in two different argv-elements.\n");
digit_optind = this_option_optind;
printf ("option %c\n", c);
break;
case 'a':
printf ("option a\n");
break;
case 'b':
printf ("option b\n");
break;
case 'c':
printf ("option c with value `%s'\n", optarg);
break;
case '?':
break;
default:
printf ("?? getopt returned character code 0%o ??\n", c);
}
}
if (optind < argc)
{
printf ("non-option ARGV-elements: ");
while (optind < argc)
printf ("%s ", argv[optind++]);
printf ("\n");
}
exit (0);
}
#endif /* TEST */
wmnet-1.06/getopt1.c 100644 2376 2442 10704 6607324241 12550 0 ustar kaos kaos /* getopt_long and getopt_long_only entry points for GNU getopt.
Copyright (C) 1987,88,89,90,91,92,93,94,96,97 Free Software Foundation, Inc.
This file is part of the GNU C Library.
The GNU C Library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public License as
published by the Free Software Foundation; either version 2 of the
License, or (at your option) any later version.
The GNU C Library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public
License along with the GNU C Library; see the file COPYING.LIB. If not,
write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
Boston, MA 02111-1307, USA. */
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include "getopt.h"
#if !defined (__STDC__) || !__STDC__
/* This is a separate conditional since some stdc systems
reject `defined (const)'. */
#ifndef const
#define const
#endif
#endif
#include <stdio.h>
/* Comment out all this code if we are using the GNU C Library, and are not
actually compiling the library itself. This code is part of the GNU C
Library, but also included in many other GNU distributions. Compiling
and linking in this code is a waste when using the GNU C library
(especially if it is a shared library). Rather than having every GNU
program understand `configure --with-gnu-libc' and omit the object files,
it is simpler to just do this in the source for each such file. */
#define GETOPT_INTERFACE_VERSION 2
#if !defined (_LIBC) && defined (__GLIBC__) && __GLIBC__ >= 2
#include <gnu-versions.h>
#if _GNU_GETOPT_INTERFACE_VERSION == GETOPT_INTERFACE_VERSION
#define ELIDE_CODE
#endif
#endif
#ifndef ELIDE_CODE
/* This needs to come after some library #include
to get __GNU_LIBRARY__ defined. */
#ifdef __GNU_LIBRARY__
#include <stdlib.h>
#endif
#ifndef NULL
#define NULL 0
#endif
int
getopt_long (argc, argv, options, long_options, opt_index)
int argc;
char *const *argv;
const char *options;
const struct option *long_options;
int *opt_index;
{
return _getopt_internal (argc, argv, options, long_options, opt_index, 0);
}
/* Like getopt_long, but '-' as well as '--' can indicate a long option.
If an option that starts with '-' (not '--') doesn't match a long option,
but does match a short option, it is parsed as a short option
instead. */
int
getopt_long_only (argc, argv, options, long_options, opt_index)
int argc;
char *const *argv;
const char *options;
const struct option *long_options;
int *opt_index;
{
return _getopt_internal (argc, argv, options, long_options, opt_index, 1);
}
#endif /* Not ELIDE_CODE. */
#ifdef TEST
#include <stdio.h>
int
main (argc, argv)
int argc;
char **argv;
{
int c;
int digit_optind = 0;
while (1)
{
int this_option_optind = optind ? optind : 1;
int option_index = 0;
static struct option long_options[] =
{
{"add", 1, 0, 0},
{"append", 0, 0, 0},
{"delete", 1, 0, 0},
{"verbose", 0, 0, 0},
{"create", 0, 0, 0},
{"file", 1, 0, 0},
{0, 0, 0, 0}
};
c = getopt_long (argc, argv, "abc:d:0123456789",
long_options, &option_index);
if (c == -1)
break;
switch (c)
{
case 0:
printf ("option %s", long_options[option_index].name);
if (optarg)
printf (" with arg %s", optarg);
printf ("\n");
break;
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
if (digit_optind != 0 && digit_optind != this_option_optind)
printf ("digits occur in two different argv-elements.\n");
digit_optind = this_option_optind;
printf ("option %c\n", c);
break;
case 'a':
printf ("option a\n");
break;
case 'b':
printf ("option b\n");
break;
case 'c':
printf ("option c with value `%s'\n", optarg);
break;
case 'd':
printf ("option d with value `%s'\n", optarg);
break;
case '?':
break;
default:
printf ("?? getopt returned character code 0%o ??\n", c);
}
}
if (optind < argc)
{
printf ("non-option ARGV-elements: ");
while (optind < argc)
printf ("%s ", argv[optind++]);
printf ("\n");
}
exit (0);
}
#endif /* TEST */