pax_global_header00006660000000000000000000000064127660541660014527gustar00rootroot0000000000000052 comment=b15acf094b8fd2bb09c175baf5c4e36ca01edde8 i2util-1.6/000077500000000000000000000000001276605416600126055ustar00rootroot00000000000000i2util-1.6/.gbp.conf000066400000000000000000000001701276605416600143000ustar00rootroot00000000000000# git-buildpackage default configuration [DEFAULT] # the default branch for upstream sources: upstream-branch = master i2util-1.6/.gitignore000066400000000000000000000012611276605416600145750ustar00rootroot00000000000000# Ignore mac hidden file .DS_Store # Ignore quilt cache directory .pc/ #Ignore autoconf, automake and make results *.o I2util.spec I2util/.deps/ I2util/Makefile I2util/Makefile.in I2util/config.h I2util/config.h.in I2util/libI2util.a I2util/stamp-h.in I2util/stamp-h1 Makefile Makefile.in aclocal.m4 aespasswd/.deps/ aespasswd/Makefile aespasswd/Makefile.in aespasswd/aespasswd autom4te.cache/ config.log config.status config/compile config/config.guess config/config.sub config/depcomp config/install-sh config/missing config/test-driver configure doc/Makefile doc/Makefile.in pfstore/.deps/ pfstore/Makefile pfstore/Makefile.in pfstore/pfstore test/.deps/ test/Makefile test/Makefile.in i2util-1.6/ChangeLog000066400000000000000000001262331276605416600143660ustar00rootroot00000000000000------------------------------------------------------------------------ r203 | aaron | 2008-12-17 15:25:02 -0500 (Wed, 17 Dec 2008) | 3 lines Add a convenience function I2AddrIsLoopback to check whether a given I2Addr has a loopback address. ------------------------------------------------------------------------ r202 | boote | 2008-06-06 17:37:06 -0400 (Fri, 06 Jun 2008) | 4 lines Checked much more strict compile flags and removed nearly all compiler warnings. (on OS X) ------------------------------------------------------------------------ r201 | boote | 2008-04-20 22:06:51 -0400 (Sun, 20 Apr 2008) | 3 lines Now the rest of it... ------------------------------------------------------------------------ r200 | boote | 2008-04-20 10:10:09 -0400 (Sun, 20 Apr 2008) | 5 lines Preparing for a release - will keep this under branches while messing with autoconf to try and get a reasonable 'static' compile out of it - then will cp to tags upon release. ------------------------------------------------------------------------ r199 | boote | 2008-04-09 12:13:07 -0400 (Wed, 09 Apr 2008) | 4 lines adding some initialization of memory into I2addr stuff. jeff ------------------------------------------------------------------------ r198 | boote | 2008-04-04 02:17:55 -0400 (Fri, 04 Apr 2008) | 5 lines Removed complicated rpm build rules - created a todo list for each release. Updated version numbers. ------------------------------------------------------------------------ r197 | boote | 2008-04-02 18:08:06 -0400 (Wed, 02 Apr 2008) | 3 lines Adding a macro for building rpm's. Might as well see if it works... ------------------------------------------------------------------------ r196 | boote | 2008-03-15 16:25:42 -0400 (Sat, 15 Mar 2008) | 3 lines Adding todo list. ------------------------------------------------------------------------ r195 | boote | 2008-02-22 23:49:59 -0500 (Fri, 22 Feb 2008) | 3 lines Adding convienence function to print "[host]:port" for an address. ------------------------------------------------------------------------ r194 | aaron | 2008-01-14 11:33:13 -0500 (Mon, 14 Jan 2008) | 3 lines Add a spec file ------------------------------------------------------------------------ r193 | boote | 2007-05-17 21:26:14 -0400 (Thu, 17 May 2007) | 5 lines Modified to use another variable to determine if the port is set for the I2Addr instead of using the port value. (This was required for unix domain sockets...) ------------------------------------------------------------------------ r192 | boote | 2007-04-06 03:36:53 -0400 (Fri, 06 Apr 2007) | 3 lines Making address functions accept null addr passed in. ------------------------------------------------------------------------ r191 | boote | 2007-03-30 19:26:38 -0400 (Fri, 30 Mar 2007) | 7 lines Modifications needed to make I2util a stand-alone installable library. (First step to creating rpm's and packages for bwctl/owamp.) jeff ------------------------------------------------------------------------ r186 | boote | 2007-02-24 07:37:33 -0500 (Sat, 24 Feb 2007) | 5 lines chdir to directory of man-page. (This is not generally a good solution, but works for our website for now. Eventually this will need to change. Dealing with 'installed' manpages is probably the right way to fix this. ------------------------------------------------------------------------ r184 | boote | 2007-02-01 14:51:00 -0500 (Thu, 01 Feb 2007) | 2 lines sevett edits ------------------------------------------------------------------------ r183 | boote | 2007-01-13 16:42:48 -0500 (Sat, 13 Jan 2007) | 4 lines Merging changes from SC06 into 'head'. jeff ------------------------------------------------------------------------ r181 | boote | 2006-12-19 17:31:35 -0500 (Tue, 19 Dec 2006) | 9 lines Makefile.am: Add sha1P.h into distribution. (Now test apps can run.) api.c: Fixed bug in relative wait time variable used to call select(2). (Was using the wrong function to convert from owptimestamp to timeval. This caused it to be off by unix_epoch.) Did not cause problems in normal operation. ------------------------------------------------------------------------ r177 | boote | 2006-11-08 02:47:59 -0500 (Wed, 08 Nov 2006) | 2 lines solaris port: int types, header file reordering ------------------------------------------------------------------------ r176 | boote | 2006-11-07 00:54:55 -0500 (Tue, 07 Nov 2006) | 2 lines Merging RFC version into HEAD. ------------------------------------------------------------------------ r167 | boote | 2006-10-20 17:46:29 -0400 (Fri, 20 Oct 2006) | 9 lines Adding a utility program for managing a pass-phrase store. The store is not encrypted in any way, although the passphrases are saved in hex. (This is primarily to make it easier for parsing, and dealing with possible different character sets - if you can enter the bytes at a prompt somehow, this will be able to save it.) jeff ------------------------------------------------------------------------ r166 | boote | 2006-10-17 01:19:35 -0400 (Tue, 17 Oct 2006) | 4 lines Better comment. jeff ------------------------------------------------------------------------ r165 | boote | 2006-10-17 01:17:52 -0400 (Tue, 17 Oct 2006) | 5 lines Revert most of pbkdf2 code back to previous version - and fix the single index that was off. (It was only the 'index' of the last incomplete block that was wrong before - there was no reason to switch to base-1 array indexing to fix it.) ------------------------------------------------------------------------ r164 | boote | 2006-10-16 21:21:02 -0400 (Mon, 16 Oct 2006) | 4 lines Adding pbkdf2 test appliation for RFC 3962 test vectors. jeff ------------------------------------------------------------------------ r163 | boote | 2006-10-16 21:19:47 -0400 (Mon, 16 Oct 2006) | 5 lines Fixed a bug in the pbkdf2() impl. Did not work correctly if the derived key length was shorter than the prf-hlen. jeff ------------------------------------------------------------------------ r162 | boote | 2006-10-13 22:34:43 -0400 (Fri, 13 Oct 2006) | 8 lines Adding a pbkdf2 function (and test driver application). I have not been able to find test vectors for this function, so I don't have huge confidence that I wrote it completely correct yet. (I wrote it right from the RFC so I would not have to deal with licensing junk.) jeff ------------------------------------------------------------------------ r161 | boote | 2006-10-12 06:41:34 -0400 (Thu, 12 Oct 2006) | 2 lines Forgot to add sha1P.h... ------------------------------------------------------------------------ r160 | boote | 2006-10-11 03:22:28 -0400 (Wed, 11 Oct 2006) | 4 lines add program to run test vectors. jeff ------------------------------------------------------------------------ r159 | boote | 2006-10-10 19:03:02 -0400 (Tue, 10 Oct 2006) | 4 lines hmac-sha1 implementation and test vectors. jeff ------------------------------------------------------------------------ r158 | boote | 2006-10-03 15:05:47 -0400 (Tue, 03 Oct 2006) | 4 lines Just adding remaining test vectors into sha1 test application. jeff ------------------------------------------------------------------------ r157 | boote | 2006-09-29 21:27:34 -0400 (Fri, 29 Sep 2006) | 4 lines Adding an sha1 implementation and compliance test to I2util. jeff ------------------------------------------------------------------------ r156 | boote | 2006-09-16 02:11:59 -0400 (Sat, 16 Sep 2006) | 2 lines Remove non-union type punning. ------------------------------------------------------------------------ r155 | boote | 2006-09-13 13:39:17 -0400 (Wed, 13 Sep 2006) | 6 lines Removing 'options' stuff. getopt is easier... Added comments for areas of possible type punning problems. jeff ------------------------------------------------------------------------ r154 | boote | 2006-09-12 13:52:48 -0400 (Tue, 12 Sep 2006) | 4 lines Merge jslawins branch into HEAD. (with some minor cleanup due to conflicts.) jeff ------------------------------------------------------------------------ r153 | boote | 2006-07-25 19:53:36 -0400 (Tue, 25 Jul 2006) | 4 lines Updating Boolean type to be intptr_t so get/set funcitions work better. jeff ------------------------------------------------------------------------ r152 | boote | 2006-07-25 18:02:13 -0400 (Tue, 25 Jul 2006) | 13 lines addr.c: Modifed the 64-bit byte swapping code so it does not violate the strict alias rules for gcc's optimizing compiler. (Now, instead of casting a uint8_t * into the uint64_t I do a memcpy and set the memory back into the uint64_t. How is that for un-optimizing...) endpoint.c: Corrected a bug in the tempfile creation. (Failed permissions were not being detected correctly.) jeff ------------------------------------------------------------------------ r149 | boote | 2006-06-19 10:03:19 -0400 (Mon, 19 Jun 2006) | 5 lines Using -j to update saddr.c - perhaps that will make it easier for jslawins to back-merge... jeff ------------------------------------------------------------------------ r148 | boote | 2006-06-19 10:01:41 -0400 (Mon, 19 Jun 2006) | 4 lines Accepting I2SockAddrLen() from jslawins branch into head. jeff ------------------------------------------------------------------------ r147 | boote | 2006-06-19 09:56:27 -0400 (Mon, 19 Jun 2006) | 4 lines pulling jslawins fix into head. (thanks) jeff ------------------------------------------------------------------------ r141 | boote | 2006-06-07 23:53:12 -0400 (Wed, 07 Jun 2006) | 2 lines typo. ------------------------------------------------------------------------ r140 | boote | 2006-06-07 19:25:31 -0400 (Wed, 07 Jun 2006) | 4 lines Incorporate patch from (jeremia@poczta.fm to fix I2SockAddrEqual). jeff ------------------------------------------------------------------------ r135 | boote | 2006-03-15 02:23:41 -0500 (Wed, 15 Mar 2006) | 6 lines Corrected header-file ordering so that the conf.h file gets included before system header files. This allows _LARGEFILE_SOURCE and other posix/STDC flags to be set more easily from autoconf macros. jeff ------------------------------------------------------------------------ r134 | boote | 2006-03-14 15:00:14 -0500 (Tue, 14 Mar 2006) | 17 lines Mostly corrections for 64-bit FreeBSD. (plus one bug fix in endpoint.c) io.c adding include of endpoint.c Fixing buf for skip record allocation. (had MIN where I should have had MAX) Changing type for 'waitfor' variable. - needed for 64-bit. fts.c casting to remove warning on 64-bit owampd.c,owampdP.h,owping.c,owpingP.h change type for 'waitfor' jeff ------------------------------------------------------------------------ r133 | boote | 2006-03-13 16:17:37 -0500 (Mon, 13 Mar 2006) | 14 lines I2util: Created utility function to copy files by fd. (Uses mmap/memcpy so entire copy is in kernel space.) owamp/*: changed post-session processing to use two files if needed to remove records from the datafile. (section 3.8 of owamp draft-14) powstream: Modified to use mmap utility function. (used to use a local function here - bascially moved it to I2util.) jeff ------------------------------------------------------------------------ r132 | boote | 2006-03-09 20:04:28 -0500 (Thu, 09 Mar 2006) | 11 lines Changes to make owamp compile on solaris. (This was much more of a pain than I realized. Solaris does not support quite the same directory API (fts/dirent) as the other systems owamp has been ported to.) Thank goodness FreeBSD has reasonable licensing. (I'm going to go back to FreeBSD/Linux/OS X and make sure I didn't break anything compile-wise before I do any tests of the running code...) jeff ------------------------------------------------------------------------ r130 | boote | 2006-01-06 12:35:10 -0500 (Fri, 06 Jan 2006) | 2 lines add cast to remove compiler warning. ------------------------------------------------------------------------ r128 | boote | 2006-01-04 20:38:18 -0500 (Wed, 04 Jan 2006) | 6 lines Fixed bug with IPv4 mapped IPv6 addresses. (Internally, these are converted into v4 sockaddr structures so the policy matching code gets what it expects. The bug was simply that configure was not initializing the macro that tells the code that generates that structure that it should be setting the sa_len field.) ------------------------------------------------------------------------ r127 | boote | 2006-01-04 19:37:29 -0500 (Wed, 04 Jan 2006) | 10 lines byte swapping functions fail if gcc -O2 is used. I still have not been able to figure out why. (It is very hard to examine variables when optimization is on.) I have broken up the algorithm in to pieces hoping that this will fix it. (will test now) Oh, this also only seems to be a problem on native 64 bit hosts. computers suck. jeff ------------------------------------------------------------------------ r124 | boote | 2005-12-23 14:16:00 -0500 (Fri, 23 Dec 2005) | 18 lines addr.c: comment added owamp/doc: Revised for new release. Added documentation for all new features. owamp/sapi.c: Changed error messages to be more consistent. owamp/stats.c: Modified summary output to report hops instead of TTL. owampd.c: Modified usage message to include new options. owping.c: Modified usage message to include new options. ------------------------------------------------------------------------ r123 | boote | 2005-12-22 23:43:45 -0500 (Thu, 22 Dec 2005) | 22 lines configure: Bumping version Adding library checks for math functions I2util: configure: Adding checks for socket api calls Adding I2Addr abstraction api from owamp (cleaned it up too). owamp: Removed addr abstraction api. Now using I2Addr abstraction api. (localized almost all V4/V6 code into one file!) Found a memory leak in the client FetchSession api. powstream: Modified the signal handling code to properly process the current session when a signal comes in. It catches the signal - stops the session and saves as much of the current session as it can based on the process outlined in the spec. (Saving only packet records earlier than the last actual received packet.) ------------------------------------------------------------------------ r122 | boote | 2005-12-09 19:44:41 -0500 (Fri, 09 Dec 2005) | 23 lines I2Util: table.c (Modify a signed value to an unsigned one for num table elems.) doc: owping - command-line option additions for statistics. added -a multiple percentile options (modified from previous) added -n units option added -M (machine parsable output) owamp: Added stats.c functions and headers. endpoint.c - cleanup Corrected recv session to output missing packet records for early terminated tests. owping.c - totally changed statistics. They now use a fixed amount of memory, and are correct in many cases where they were not before. Added 'jitter' as well. added options. powstream still needs to be modified to use the statistics. jeff ------------------------------------------------------------------------ r121 | boote | 2005-09-29 21:06:31 -0400 (Thu, 29 Sep 2005) | 5 lines autoconf depricated macros I was using. Modified these to use new ones. jeff ------------------------------------------------------------------------ r118 | boote | 2005-08-28 17:08:31 -0400 (Sun, 28 Aug 2005) | 5 lines Added a some explanitory text that mentions the name of the bwctld.keys and owampd.keys file based on feedback from walter (auburn) jeff ------------------------------------------------------------------------ r117 | boote | 2005-07-17 02:55:29 -0400 (Sun, 17 Jul 2005) | 4 lines Adding newline to fprintf output of PERROR code. jeff ------------------------------------------------------------------------ r116 | boote | 2005-07-16 17:34:47 -0400 (Sat, 16 Jul 2005) | 4 lines Adding autoconf magic for determining if the OS syslog supports LOG_PERROR. jeff ------------------------------------------------------------------------ r115 | boote | 2005-07-16 17:29:40 -0400 (Sat, 16 Jul 2005) | 5 lines Adding code to print error messages to stderr in the I2Util error module to handle LOG_PERROR directly if syslog does not provide the functionality. jeff ------------------------------------------------------------------------ r114 | boote | 2005-07-15 11:51:26 -0400 (Fri, 15 Jul 2005) | 36 lines Porting to Solaris... This compiles, I have yet to do any real testing. Once this is checked in, I will make sure these changes don't break Linux/FreeBSD. configure.ac: Adding socket,nsl,rt libraries Adding check for paths.h header file ErrLogSyslog.c: Define LOG_AUTHPRIV and LOG_FTP if they are not defined. Options.c: conf.c: Adding cast from char to int for all isspace/isdigit args. readpassphrase.c: remove cdefs.h. Add check for autoconf paths.h value, include or define _PATH_TTY. Adding cast from char to int for all isspace/isdigit args. bwctl.c: Adding cast from char to int for all isspace/isdigit args. Change setenv to putenv to set POSIXLY_CORRECT for getopt. Check for LOG_PERROR. (Add warning if -r is passed in, and LOG_PERROR is not available.) bwctld.c: Add check for LOG_PERROR. policy.c: Remove fts.h - not even used here, this is an owamp leftover... Adding cast from char to int for all isspace/isdigit args. util.c: Adding cast from char to int for all isspace/isdigit args. ------------------------------------------------------------------------ r113 | boote | 2005-07-14 19:28:08 -0400 (Thu, 14 Jul 2005) | 2 lines Removing cdefs here too... ------------------------------------------------------------------------ r112 | boote | 2005-07-14 19:09:41 -0400 (Thu, 14 Jul 2005) | 2 lines changing stdint to inttypes. Sometimes standards are less than clear... !%##@ ------------------------------------------------------------------------ r111 | boote | 2005-07-14 19:05:53 -0400 (Thu, 14 Jul 2005) | 2 lines Adding include of stdint.h to get the uint* types on linux. ------------------------------------------------------------------------ r110 | boote | 2005-07-14 19:00:43 -0400 (Thu, 14 Jul 2005) | 4 lines Removing reference to sys/cdefs.h. jeff ------------------------------------------------------------------------ r109 | boote | 2005-07-14 18:54:59 -0400 (Thu, 14 Jul 2005) | 6 lines changing all u_int* types to uint* types so they agree with the latest 'C' standard. This is part of a Solaris port - I am about to make sure this still works on Linux/FreeBSD... jeff ------------------------------------------------------------------------ r107 | boote | 2005-04-20 18:50:43 -0400 (Wed, 20 Apr 2005) | 26 lines I2util/ aespasswd.c: Fixed C macro for creating a string out of a constant. doc/*: * Added some NTP details based on user comments. (These are old, I still need to incorporate comments from the Atl workshop. * Made arch diagram a little nicer. owamp/*: Changes to deal with IPC for reporting back skip ranges to control process from the "sender" process. Also, changes for the file format to deal with skip records and of course changes to deal with the modifications to the StopSessions and FetchSession protocols. owampd/*: Forgot to initialize a variable. owping: formatting changes powstream: change iotime to 3. jeff ------------------------------------------------------------------------ r106 | boote | 2005-03-15 16:26:41 -0500 (Tue, 15 Mar 2005) | 4 lines better comments. jeff ------------------------------------------------------------------------ r103 | boote | 2004-09-10 18:20:47 -0400 (Fri, 10 Sep 2004) | 17 lines Merging SERVLESS_CLIENT changes into HEAD. errlog.h: ErrLog.c: Ignore messages with level "none". ErrLogSyslog.c: Add "none" priority conf.h: conf.c: Added str2num function to deal with suffix multiples. i.e. 100k 'k'. Added str2byte function to deal with suffix multiples. i.e. 100k 'k'. (these are different in that 'num' function uses k == 1000, and byte function uses k == 1024. jeff ------------------------------------------------------------------------ r96 | boote | 2004-06-27 21:58:29 -0400 (Sun, 27 Jun 2004) | 4 lines Corrected reset function to return I2Boolean. jeff ------------------------------------------------------------------------ r95 | boote | 2004-06-19 00:53:58 -0400 (Sat, 19 Jun 2004) | 4 lines Some compile errors fixed... will fix the rest next week. jeff ------------------------------------------------------------------------ r92 | boote | 2004-06-09 04:35:03 -0400 (Wed, 09 Jun 2004) | 19 lines I2Util/*: Adding functionality to allow error logs to be "reset" after a process forks. Specifically added this functionality to the "syslog" logger. owampd.conf,owampd.c: Added portrange to owampd. Removed current code that closed file descriptors in child. Did not work correctly - can only close descriptors from other parent/child pipes. Will fix this another time. Added code to reset syslog after fork. endpoint.c: Fixed bad error format string. protocol.c,owampP.h: Fixed a bug that resulted in the server configured port value being lost, and not saved in the owp files with the rest of the TestRequest record. ------------------------------------------------------------------------ r89 | boote | 2004-03-04 12:27:15 -0500 (Thu, 04 Mar 2004) | 4 lines Susan's edits. jeff ------------------------------------------------------------------------ r88 | boote | 2004-03-03 10:52:46 -0500 (Wed, 03 Mar 2004) | 5 lines Rich, the bootstrap file I was saying you needed to change was the one in the top-level dir. This one should be fine. jeff ------------------------------------------------------------------------ r87 | rcarlson | 2004-03-03 10:43:39 -0500 (Wed, 03 Mar 2004) | 2 lines changed bootstrap file for I2util per Jeff Boote comments ------------------------------------------------------------------------ r86 | rcarlson | 2004-03-02 17:47:40 -0500 (Tue, 02 Mar 2004) | 3 lines updated configure.ac to include I2UTILINC functions. This should allow the NDT web100srv.c code to use the LoadConf function. ------------------------------------------------------------------------ r84 | boote | 2004-02-25 12:56:06 -0500 (Wed, 25 Feb 2004) | 7 lines mandoc.cgi: calls man2html using INC path instead of using full path. *.html: removed 's - futile.... ------------------------------------------------------------------------ r83 | boote | 2004-02-25 09:45:50 -0500 (Wed, 25 Feb 2004) | 6 lines Added check for redirect_url to make sure access checking has happened in apache. (This only works if the cgi is installed as an action handler, if it is a normal cgi, this extra security is impossible. jeff ------------------------------------------------------------------------ r81 | boote | 2004-02-20 20:11:37 -0500 (Fri, 20 Feb 2004) | 13 lines Disabled hyphenation in url references in manpages. The hypphenation broke the url stuff I added to man2html to make url's links in html'd man pages. This all works now, but I can't install it on e2epi because the server feature I need is not activated. I have made a request to websupport for that. To see the man pages for now, take a look at: http://people.internet2.edu/~boote/bwctl.man jeff ------------------------------------------------------------------------ r80 | boote | 2004-02-20 19:47:34 -0500 (Fri, 20 Feb 2004) | 5 lines Adding man conversion tools into CVS... (Actually... I'm going to move this down into I2util after checking in...) jeff ------------------------------------------------------------------------ r78 | boote | 2004-02-17 16:19:38 -0500 (Tue, 17 Feb 2004) | 5 lines Modified to support installing of man pages. This took an upgrade of the autoconf tools. Ugh. jeff ------------------------------------------------------------------------ r77 | boote | 2004-02-16 18:38:24 -0500 (Mon, 16 Feb 2004) | 4 lines Spell checking, and incorporating changes based on Eric's comments. jeff ------------------------------------------------------------------------ r76 | boote | 2004-02-16 11:07:01 -0500 (Mon, 16 Feb 2004) | 7 lines bwctld.c: modified error message. *.man: Added acknowledgments section for NSF grant disclaimer. jeff ------------------------------------------------------------------------ r75 | boote | 2004-02-13 19:12:02 -0500 (Fri, 13 Feb 2004) | 5 lines Adding the last man pages. bwctld.limits.man is not done yet, but it is getting close. jeff ------------------------------------------------------------------------ r74 | boote | 2004-02-08 19:57:05 -0500 (Sun, 08 Feb 2004) | 4 lines bwctl.c: changing so remotehost is attached to the -c/-s options bwctl.1: checkpoint ------------------------------------------------------------------------ r73 | boote | 2004-02-08 17:41:26 -0500 (Sun, 08 Feb 2004) | 2 lines Adding manpage for aespasswd. ------------------------------------------------------------------------ r71 | boote | 2003-12-19 14:11:10 -0500 (Fri, 19 Dec 2003) | 5 lines Hmm - things were confused. There was a length and a num_elements entry. fixed. jeff ------------------------------------------------------------------------ r70 | boote | 2003-12-19 14:03:29 -0500 (Fri, 19 Dec 2003) | 5 lines Wow - I can't believe this wasn't an issue before. (num_elements was not initialized in the table init code.) jeff ------------------------------------------------------------------------ r69 | boote | 2003-12-19 11:15:44 -0500 (Fri, 19 Dec 2003) | 4 lines Added a '.' prefix to the lockfile name. jeff ------------------------------------------------------------------------ r68 | boote | 2003-12-19 11:10:10 -0500 (Fri, 19 Dec 2003) | 5 lines Adding an error message if the identity is not found and the -d flag was specified. jeff ------------------------------------------------------------------------ r67 | boote | 2003-12-19 10:53:51 -0500 (Fri, 19 Dec 2003) | 4 lines Fixed core-dump if the conf file is empty. jeff ------------------------------------------------------------------------ r66 | boote | 2003-12-19 03:53:45 -0500 (Fri, 19 Dec 2003) | 4 lines fixed bugs. jeff ------------------------------------------------------------------------ r65 | boote | 2003-12-19 03:40:20 -0500 (Fri, 19 Dec 2003) | 9 lines I2util/*: Adding aespasswd into autoconf files. I2util/aespasswd/*: Now works on FreeBSD - need to test Linux. bwctl/bwctlP.h: Clean-up comments. jeff ------------------------------------------------------------------------ r64 | boote | 2003-12-19 02:57:21 -0500 (Fri, 19 Dec 2003) | 9 lines I2util/conf.[ch] Adding a WriteKeyLine function. I2util/aespasswd/* Adding an aespasswd command for managing keyfiles. bwctl/bwctl.c Making some error messages pretty. jeff ------------------------------------------------------------------------ r63 | boote | 2003-12-17 23:26:11 -0500 (Wed, 17 Dec 2003) | 6 lines Now compiles on Linux. termios suck. jeff ------------------------------------------------------------------------ r62 | boote | 2003-12-17 22:21:39 -0500 (Wed, 17 Dec 2003) | 4 lines Fixed compile errors. jeff ------------------------------------------------------------------------ r61 | boote | 2003-12-17 16:21:13 -0500 (Wed, 17 Dec 2003) | 16 lines I2util: Added conf file handling routines, hex encode/decode, md5, readpassphrase... Basically lots of things that owamp and bwctl will both use. Modified bwctl to use the I2util versions of these functions. Modified bwctl to do aeskeys with either a keyfile or a passphrase. Modified bwctld to do aeskeys with a keyfile. (These changes have not even been compiled yet since I did this on my laptop. I will be checking in updates to this after actually testing it.) jeff ------------------------------------------------------------------------ r60 | boote | 2003-11-16 19:29:17 -0500 (Sun, 16 Nov 2003) | 2 lines blah ------------------------------------------------------------------------ r59 | boote | 2003-11-16 00:26:02 -0500 (Sun, 16 Nov 2003) | 5 lines Adding test for "loopback" to allow a test. "loopback" is implicitly trusted to an extent. jeff ------------------------------------------------------------------------ r58 | boote | 2003-10-20 12:09:57 -0400 (Mon, 20 Oct 2003) | 6 lines saddr.h: added comment policy.c: fixed bug in MSGCLAIM message decoding. jeff ------------------------------------------------------------------------ r56 | boote | 2003-06-13 21:52:39 -0400 (Fri, 13 Jun 2003) | 10 lines I2util/table.[ch]: Added a HashClean function to clean out a hash table. powstream.c: Added some diagnostics to find out why fread is failing on the partial session file. Also modified the Hash table to be cleaned on error. jeff ------------------------------------------------------------------------ r53 | boote | 2003-03-19 21:29:00 -0500 (Wed, 19 Mar 2003) | 4 lines Merging VERS5 into head. Wahoo!!! jeff ------------------------------------------------------------------------ r38 | boote | 2002-11-26 13:23:06 -0500 (Tue, 26 Nov 2002) | 5 lines Adding more detailed error reporting - removing "connect" of recv udp socket. Added socket compare function into I2Util. jeff ------------------------------------------------------------------------ r37 | owamp | 2002-11-07 17:41:25 -0500 (Thu, 07 Nov 2002) | 4 lines Fixed a bug in how syslog.h was included. jeff ------------------------------------------------------------------------ r36 | boote | 2002-11-05 18:01:08 -0500 (Tue, 05 Nov 2002) | 4 lines Added functionality to specify syslog facilities/priorities by name. jeff ------------------------------------------------------------------------ r34 | karp | 2002-09-23 10:48:51 -0400 (Mon, 23 Sep 2002) | 2 lines Cosmetic changes (tiny). ------------------------------------------------------------------------ r32 | boote | 2002-08-09 21:19:30 -0400 (Fri, 09 Aug 2002) | 4 lines see last ci. jeff ------------------------------------------------------------------------ r31 | boote | 2002-08-09 15:19:55 -0400 (Fri, 09 Aug 2002) | 21 lines I2util: made random use raw io so forked processes could read from the same fd without problems. added readn/writen functions from owamp owamp: made everything use I2 versions of readn/writen removed get_timestamp_func from ctx - we are not using it. stopped forks from closing all open descriptors owampd/owping: PolicyInit was core dumping because we were calling it with an errhand and it was expecting a ctx... I changed the apps to call it with a ctx. jeff ------------------------------------------------------------------------ r30 | boote | 2002-08-08 16:50:29 -0400 (Thu, 08 Aug 2002) | 9 lines I2util: added a va_list logging function. owamp: changed the OWPError function to be a macro and removed the OWPErrorLine function. The I2ErrLog stuff is used by the OWPError macro. jeff ------------------------------------------------------------------------ r29 | boote | 2002-08-08 14:16:03 -0400 (Thu, 08 Aug 2002) | 15 lines Modified the random functions to be relative to a random "context". Modified the OWPErr functions to exclusively use the I2Err functions. (The OWPErr functions are simply a wrapper around the I2Err functions - unfortunately they can't be macros due to the var-args...) This means if you want to have an application defined error function, you have to define the I2ErrHandler yourself, and assign it to eh in the OWPContext. This actually simplified things quite a bit. I would almost like to go through and remove all the OWPError and OWPErrLine calls and replace them with I2 varients - may do that later, doesn't seem worth it right now. It would make the __FILE__ and __LINE__ macro's cleaner. jeff ------------------------------------------------------------------------ r28 | boote | 2002-08-08 13:50:55 -0400 (Thu, 08 Aug 2002) | 5 lines Actually removed the lines of code I replaced - before they were just ifdef'd out. jeff ------------------------------------------------------------------------ r27 | boote | 2002-08-08 13:47:03 -0400 (Thu, 08 Aug 2002) | 9 lines Modified the I2ErrLog stuff to support a level or priority. You can access this by using the new I2ErrLogT(eh,level,code,fmt,...) error reporting macro/function. (You know things are good when you actually remove lines of code to add additional functionality.) jeff ------------------------------------------------------------------------ r26 | boote | 2002-08-07 18:25:12 -0400 (Wed, 07 Aug 2002) | 9 lines Added an autoconfig check to ensure a kernel random device is available. random.h will fail to compile if autoconfig doesn't find one. (Don't update your local copy until I check in changes to owamp - I changed the RAND* macro's to have I2 at the beginning.) jeff ------------------------------------------------------------------------ r25 | karp | 2002-08-06 14:14:42 -0400 (Tue, 06 Aug 2002) | 7 lines Added randomness source initialization support, and updated affected code elsewhere. The proper order of events now is: 1. OWPContextInitialize() [calls I2RandomSourceInit()] 2. repeated calls to I2RandomBytes() [not affected by any subsequent changes in underlying randomness source] ------------------------------------------------------------------------ r24 | karp | 2002-08-05 15:47:30 -0400 (Mon, 05 Aug 2002) | 2 lines Tiny - forgot to add a cast ------------------------------------------------------------------------ r23 | karp | 2002-08-05 15:40:48 -0400 (Mon, 05 Aug 2002) | 2 lines Re-did I2RandomBytes to use /dev/urandom ------------------------------------------------------------------------ r22 | boote | 2002-08-05 13:48:30 -0400 (Mon, 05 Aug 2002) | 8 lines Test sessions seem to work - owping doesn't wait for the test session to finish - but if you wait until the -datadir/SID.i file is renamed to -datadir/SID you do get a complete file. I need to modify the file-buffering some, and owping needs to be modified to wait for the test session to complete. jeff ------------------------------------------------------------------------ r21 | karp | 2002-07-22 16:10:07 -0400 (Mon, 22 Jul 2002) | 2 lines Remove debug checks (no longer needed). ------------------------------------------------------------------------ r20 | karp | 2002-07-22 11:43:06 -0400 (Mon, 22 Jul 2002) | 2 lines Added casts to pacify compiler. ------------------------------------------------------------------------ r19 | karp | 2002-07-17 23:09:47 -0400 (Wed, 17 Jul 2002) | 2 lines Minor clarifications in comments. ------------------------------------------------------------------------ r18 | karp | 2002-07-14 23:48:35 -0400 (Sun, 14 Jul 2002) | 4 lines Fixed a bug in hashatom() - it was sensitive to bytes outside the ones being hashed. Minor addition for easier debugging. ------------------------------------------------------------------------ r17 | boote | 2002-06-21 20:18:57 -0400 (Fri, 21 Jun 2002) | 4 lines Oops - one check too many. jeff ------------------------------------------------------------------------ r16 | boote | 2002-06-21 20:17:40 -0400 (Fri, 21 Jun 2002) | 4 lines added checks to make sure table is not modified from within iterate. jeff ------------------------------------------------------------------------ r15 | boote | 2002-06-19 03:17:41 -0400 (Wed, 19 Jun 2002) | 44 lines Tolya - I corrected some problems with the table code, and added some features. There was a mistake in the init function - you only used one malloc, and pointed the "buckets" pointer to the memory just past the I2table record. The problem is that there is nothing making sure that the memory just past the I2table record is aligned properly for pointers (the type of the array). There are two ways to fix this - one, add something to the end of the structure to ensure the next memory is aligned, or just malloc the buckets array seperately. (the extra malloc seemed easier, so that is what I did.) Another mistake in the init function was that you called exit. A library function should almost never call exit - let the calling environment handle the errors, just report them. In this case, it is very easy to just return NULL if there is a problem. I simplified the cmp function slightly - there was no reason to check for the MIN of the sizes in the bcmp (which I changed to memcmp) since you already know the sizes are equal or the first part of the || would have caused the value to be returned already. (lazy evaluation) In init - I reordered the primes array check for sizes so you don't have to have the extra 509, and the bogus INT_MAX in the array. Not really necessary, but I had a hard time following the logic each time I looked at it before. hash_close - I made it take an I2table instead of a pointer to an I2table. It wasn't clear to me why you had it the other way... I also removed the if checkes before the free'ing of the pointers. (If those pointers were NULL you would have core dumped from the lines before the if, because those pointers are dereferenced.) I added a hash_delete function so you can remove a key/value pair from the hash. (I added the iterate function earlier - you probably noticed.) I didn't do it, but I think it would be much cleaner to implement your hash printing using the hash_iterate function. Then you could take the hash_print function pointer out of the hash table structure. Also - you could take the I2binding structure out of the header file since it wouldn't be needed. Everything else I did was purely cosmetic - defined types for the function pointers and things along those lines. jeff ------------------------------------------------------------------------ r14 | boote | 2002-06-18 13:57:58 -0400 (Tue, 18 Jun 2002) | 7 lines Added I2hash_iterate function - this is similar to the "print" function, but allows you to specify a different function to call each time you call hash_iterate. It also lets you terminate the iteration by returning false from the function. jeff ------------------------------------------------------------------------ r13 | boote | 2002-06-14 17:06:39 -0400 (Fri, 14 Jun 2002) | 5 lines fix for __attribute__ check... I had put it in the config.h.in file, but since that is dynamically generated, it didn't work too well.... jeff ------------------------------------------------------------------------ r12 | boote | 2002-06-10 19:54:17 -0400 (Mon, 10 Jun 2002) | 4 lines Removed compiler warnings. jeff ------------------------------------------------------------------------ r11 | boote | 2002-06-02 14:42:17 -0400 (Sun, 02 Jun 2002) | 33 lines Reorganizing things... Tolya - when you create new files please put a $Id$ comment header at the beginning of the file. (I don't really care that much if you use the comment script, but I really want the version number in there - it makes it much easier to determin how out-of-date printout's are.) Also - I moved your arithmatic out of I2util and put it into owamp - it is difficult to imagine something more specific to owamp. I2util is for code that is likely to be used for projects completely unrelated to owamp. I'm thinking more and more about rolling all the owpcontrib code right into the owamp directory, but I decided to leave it alone for now. Let me know if you have opionions one way or the other about it. Oh - I also broke up api.c into 3 files: api.c capi.c sapi.c api.c contains functions that are used by capi.c and sapi.c. capi.c is client api functions and sapi.c is server api functions. Now that I've reorganized the code to more easily digestable chunks, I'm going to start taking some of the code from owampd and putting it in sapi.c, and extending it to actually start test sessions. (I probably won't get enough done today to check in again today - in fact, considering what I will be doing, it will probably be a few days before I check-in again.) jeff ------------------------------------------------------------------------ r10 | karp | 2002-05-31 18:27:50 -0400 (Fri, 31 May 2002) | 2 lines Added support for arithmetic functions. ------------------------------------------------------------------------ r9 | boote | 2002-04-30 12:42:59 -0400 (Tue, 30 Apr 2002) | 15 lines owping first real check-in. Not real functional, but at least gives an outline. Does not implement policy hooks yet. (Should be able to use exact same ones as owampd after cleanup.) I2util/I2util/ table.c:made sure default compare function doesn't overrun memory. owping/ Makefile.am: added localaddr template - still working on code. owping.c: organized. localaddr.[ch] localaddr template. owpingP.h: typedefs for owping. jeff ------------------------------------------------------------------------ r8 | boote | 2002-04-30 09:43:49 -0400 (Tue, 30 Apr 2002) | 17 lines Removed references to old table symbols are replaced them with I2hash_init etc... (I need to verify this compiles on a system up there - so expect another ci shortly.) I also changed the table code to use the I2ErrLog stuff instead of OWPError. Tolya - I think it would be much cleaner to remove the hash functions from owampd - and put them all into access.[ch]. I don't see any reason why owamp_read_ip2class, owamp_read_class2limits, and read_passwd_file couldn't call I2hash_init themselves and return the hash_table as the return value of the function. You could still call I2hash_print for debugging purposes - but the code could be much cleaner this way. What do you think? jeff ------------------------------------------------------------------------ r7 | boote | 2002-04-29 18:08:49 -0400 (Mon, 29 Apr 2002) | 21 lines Adding Tolya's hash table into the I2util library. Modified the symbols to start with I2. Makefile.am: added table.h as installable. ErrLog.c: Corrected comment. I2util/ Makefile.am: added table.c source. Options.c,options.h: Added stringtoUint converter. Made stringtoint converter use strtol instead of less predictable sscanf Corrected arg printing routine to deal with varargs. util.h: added include of table.h ------------------------------------------------------------------------ r6 | boote | 2002-04-26 18:47:18 -0400 (Fri, 26 Apr 2002) | 13 lines Adding ability for an -option to take variable args after it. i.e. owping -sender sendaddr [sendserv] In this example 1 or 2 args. To do this - the arg description lists the max number of args it will take - and it specifies it as a negative number in the description record. This library will eventually have to be documented to some extent - I'm hoping doxygen is easy... jeff ------------------------------------------------------------------------ r5 | boote | 2002-04-24 18:14:27 -0400 (Wed, 24 Apr 2002) | 4 lines Build for libI2util.a jeff ------------------------------------------------------------------------ r4 | boote | 2002-04-24 13:44:54 -0400 (Wed, 24 Apr 2002) | 4 lines Adding mach dep code. jeff ------------------------------------------------------------------------ r3 | boote | 2002-04-23 16:56:13 -0400 (Tue, 23 Apr 2002) | 4 lines Beginnings of a utility library. I don't have build files for it yet - tomorrow. jeff ------------------------------------------------------------------------ r2 | boote | 2002-04-23 16:52:24 -0400 (Tue, 23 Apr 2002) | 11 lines import of until library. Based on a utility library distributed with the "volsh" code from UCAR. http://www.scd.ucar.edu/vets/vg/Software/volsh I have used this in the past - and it seemed silly not to use it since it is freely distributed. jeff ------------------------------------------------------------------------ r1 | (no author) | 2002-04-23 16:52:24 -0400 (Tue, 23 Apr 2002) | 1 line New repository initialized by cvs2svn. ------------------------------------------------------------------------ i2util-1.6/I2util.spec.in000066400000000000000000000020361276605416600152370ustar00rootroot00000000000000Name: I2util Version: @VERSION@ Release: 1%{?dist} Summary: I2 Utility Library License: distributable, see LICENSE Group: Development/Libraries Source0: I2util-%{version}.tar.gz BuildRoot: %{_tmppath}/%{name}-%{version}-%{release}-buildroot %description I2 Utility library. Currently contains: * error logging * command-line parsing * threading * random number support * hash table support The error logging and command-line parsing are taken from a utility library that is distributed with the "volsh" code from UCAR. http://www.scd.ucar.edu/vets/vg/Software/volsh %prep %setup -q %build %configure %install rm -rf $RPM_BUILD_ROOT %makeinstall %clean rm -rf $RPM_BUILD_ROOT %files %defattr(-,root,root,-) #%doc Changes LICENSE README %doc README %{_bindir}/* %{_libdir}/libI2util.a %{_mandir}/man1/* %{_includedir}/* %changelog * Fri Aug 20 2010 Tom Throckmorton 1.1-1 - minor spec changes only * Fri Jan 11 2008 aaron@internet2.edu 1.0-1 - Initial RPM i2util-1.6/I2util/000077500000000000000000000000001276605416600137555ustar00rootroot00000000000000i2util-1.6/I2util/ErrLog.c000066400000000000000000000473621276605416600153270ustar00rootroot00000000000000/* * $Id$ */ /************************************************************************ * * * Copyright (C) 2002 * * Internet2 * * All Rights Reserved * * * ************************************************************************/ /* * File: ErrLog.c * * Author: Jeff Boote * Internet2 * * Date: Tue Apr 23 09:11:05 2002 * * Description: * Generic error logging routines. * * * Based on code from UCAR DCS tools. Copyright information * from UCAR follows: * * Copyright 2012, University Corporation for Atmospheric Research. * * This software may be used, subject to the terms of OSI's BSD-2 Clause * License located at http://www.opensource.org/licenses/bsd-license.php/ * */ #include #include #include #include #include #include #include "mach_dep.h" /* * May support threading in future. */ static I2ThreadMutex_T MyMutex = I2PTHREAD_MUTEX_INITIALIZER; #define TABLE_SIZE 10 #define MSG_BUF_SIZE 10240 /* * an error table. Error table[0] contains sys_errlist. */ typedef struct ErrTable_ { unsigned start, /* starting index for err_list */ num; /* num elements in err_list */ const char * const *err_list; /* error messags */ } ErrTable; /* * static variables that contain the file name and line number of the most * recently logged error via a call to I2ErrLocation_(). * * N.B. I2ErrLocation_() should never be called directly by a client * of the error module. I2ErrLocation_() is invoked via the macro call * I2ErrLog() which calls I2ErrLocation_() and then immediately calls * I2ErrLogFunction_(). This enables multiple instances of an error * logging session w/out having to maintain the current file and line * number as a separate state variable for each session with some degree * of security. In a threaded environment access to these variables is * locked by I2ErrLocation_() and unlocked by I2ErrLogFunction_(). All of * this is necessary because the only way to automatically generate the * line number and file name information automatically is via and macro * call (as opposed to a function call) and macros don't accept variable * number of arguments */ static const char *errorFile = ""; static const char *errorDate = ""; static int errorLine = 0; /* * An error handle struct. This struct maintains the state of an * error reporting session created via I2ErrOpen() */ typedef struct ErrHandle_ { ErrTable err_tab[TABLE_SIZE]; /* all the error tables */ int err_tab_num; /* num error tables */ int code; /* error code of last error */ const char *program_name; /* name of calling prog */ void *data; /* client data */ I2ErrLogFuncPtr log_func; /* client loggin func */ void *log_func_arg; /* client arg to log func*/ I2ErrRetrieveFuncPtr retrieve_func; /* client fetch func */ void *retrieve_func_arg; /* client arg to retrieve func*/ I2ErrLogResetFuncPtr reset_func; /* reset log_func */ } ErrHandle; /* * fetch an error message associated with a given error code. Return * an empty string if no matching error message is found. */ static const char *get_error(ErrHandle *eh, int error) { int i; unsigned int j; unsigned int errnum; if(error < 0) return(""); errnum = (unsigned int)error; if(!eh){ return strerror(error); } for (i=0; ierr_tab_num; i++) { if(eh->err_tab[i].start > errnum) continue; j = errnum - eh->err_tab[i].start; if ((unsigned)errnum >= eh->err_tab[i].start && j < eh->err_tab[i].num) { return(eh->err_tab[i].err_list[j]); } } return(""); } /* * format an error message converting any `%M' tokens to the error * string associated with error message number `code, and any * `%N' tokens to the ascii representation of the value of `code * * `buf' must have enough space to hold the new string */ static int esnprintf( ErrHandle *eh, char *buf, size_t size_buf, const char *format, int code ) { const char *p1; char *p2; size_t size_p2 = size_buf; int len; for(p1=format, p2=buf; *p1 && (size_p2 > 1); p1++, p2++, size_p2--) { if (*p1 != '%') { *p2 = *p1; continue; } p1++; if (*p1 == 'M') { len =snprintf(p2,size_p2,"%s",get_error(eh,code))-1; p2 += len; size_p2 -= len; } else if (*p1 == 'N') { len = snprintf(p2,size_p2,"%d", code) - 1; p2 += len; size_p2 -= len; } else { *p2++ = '%'; size_p2--; *p2 = *p1; } } *p2 = '\0'; return(strlen(buf)); } static void add_ansiC_errors(ErrHandle *eh) { const char * const *mach_sys_errlist; /* list of errors */ int errlist_size; /* size of $sys_errlist */ /* ** Get the list of system errors supported on this platform */ mach_sys_errlist = I2GetSysErrList(&errlist_size); eh->err_tab_num = 0; (void) I2ErrList( (I2ErrHandle) eh, 0, (unsigned)errlist_size, mach_sys_errlist); } /* ** ** A P I ** */ /* * Function: I2ErrOpen() * * Description: The I2ErrOpen() function starts an error reporting session * and returns an error handle associated with that session. * * The `log_func' argument is a pointer to a logging function * that is to be called whenever an error is logged with the * I2ErrLog() macro. This function may be user-defined or may * be one of the pre-defined functions (I2LogFuncStack_() * or I2LogFuncImmediate_()). * * The `retrieve_func' argument is a pointer to a error * log retrieval function that is invoked to fetch error * messages logged with the function pointed to by * `log_func'. `retrive_func' may be NULL if no such * function exists. * * In Args: * * *program_name A pointer to a character string specifying the * name of the calling program (or any other piece * of information you might wish). * * *log_func A pointer to a user-defined error logging function * as described below. * * *log_func_arg A pointer to user-defined data that is to be passed * to the logging function whenever the logging * function is invoked. * * *retrieve_func A pointer to a user-defined error retrieval function * as described below. * * *ret_func_arg A pointer to user-defined data that is to be passed * to the retrieval function whenever the retrieval * function is invoked. * * * Out Args: * * Return Values: An error handle is returned upon success. Otherwise * NULL is returned and the global variable `errno' * is set accordingly * * Side Effects: * * * The Logging Function * * The logging function pointed to by `log_func' is called indirectly * by the I2ErrLog() macro to log error messages. The `program_name' * parameter points to the array pointed to by the parameter of the * same name passed to I2ErrOpen(). The logging function is also provided * provided with the name of the file from whence I2ErrOpen() was * called, `file', as well as the line number, `line', the date the * file was compiled, `date', the error message to be logged, `msg', * the user-defined logging function argument passed to I2ErrOpen(), * `arg', and a hook for any state context the logging function * needs to maintain, `data'. * * In Args: * * *program_name A pointer to the character string passed to * I2ErrOpen() as its first argument. * * *file A pointer to a string containing the name of the * file from whence I2ErrLog() was called. * * line An integer indicating the line number within * `file' from whence I2ErrLog() was called. * * *date A pointer to a string containing the date (of the * file from which I2ErrLog() was called) was compiled. * * *msg A pointer to string containing the error message * to be logged. * * *arg A pointer to the `log_func_arg' argument passed to * I2ErrOpen() * * **data A pointer to a pointer to be used by the logging * function in any desired manner. `*data' is NULL * unless changed by the logging function * * The Retrieval Function * * The retrieval function pointed to by `retrieve_func' is invoked * whenever the error messages logged by the logging function are * to be retrieved. The retrieval function is passed the same hook, * `data', for maintaining state information as the logging function, * and the user-defined argument, `arg', passed to the I2ErrOpen() * function as `retreive_func_arg'. * * The retrieval function should return a pointer to an area of * dynamically allocated memory containing a character string * representing the error messages logged with previous calls * to the logging function. The caller will free the memory * returned by the retrieval function. * * In Args * * *arg A pointer to the `retrieve_func_arg' argument passed to * I2ErrOpen() * * **data A pointer to a pointer to be used by the retrieval * function in any desired manner. `*data' is NULL * unless changed by the logging function * */ I2ErrHandle I2ErrOpen( const char *program_name, I2ErrLogFuncPtr log_func, void *log_func_arg, I2ErrRetrieveFuncPtr retrieve_func, void *retrieve_func_arg ) { ErrHandle *eh; if (! log_func) { errno = EINVAL; return(NULL); } if (! (eh = malloc(sizeof(ErrHandle)))) { return(NULL); } eh->code = 0; eh->program_name = program_name; eh->log_func = log_func; eh->log_func_arg = log_func_arg; eh->retrieve_func = retrieve_func; eh->retrieve_func_arg = retrieve_func_arg; eh->data = NULL; /* * add the Standard C Library error messages */ add_ansiC_errors(eh); return((I2ErrHandle) eh); } /* * Function: I2ErrSetResetFunc * * Description: * Used to assign the "reset" function. Not used, so it * was not useful to add to the "open". (Plus, it would * be hard to make "open" backward compat.) * * In Args: * * Out Args: * * Scope: * Returns: * Side Effect: */ void I2ErrSetResetFunc( I2ErrHandle dpeh, I2ErrLogResetFuncPtr reset_func ) { ErrHandle *eh = (ErrHandle *) dpeh; eh->reset_func = reset_func; return; } /* * Function: I2ErrReset * * Description: * If there is a "reset_func" assigned to the ErrHandle, * call it. * * In Args: * * Out Args: * * Scope: * Returns: * Side Effect: */ I2ErrHandle I2ErrReset( I2ErrHandle dpeh ) { ErrHandle *eh = (ErrHandle *) dpeh; if(eh->reset_func){ if(!(eh->reset_func(eh->log_func_arg, &(eh->data)))){ I2ErrClose(dpeh); return NULL; } } return dpeh; } /* * Function: I2ErrClose() * * Description: This function closes the error handling session associated * with `dpeh'. * * In Args: * * dpeh An error handle returned via a call to I2ErrOpen(). * * Out Args: * * Return Values: * * Side Effects: */ void I2ErrClose(I2ErrHandle dpeh) { ErrHandle *eh = (ErrHandle *) dpeh; if (eh) free(eh); } /* * Function: I2ErrRep() * * Description: The I2ErrRep() function calls the client retrieval function * (if one exists) passed to I2ErrOpen() for the error * handling session associated with `dpeh'. I2ErrRep() copies * the program name, followed by a ":", followed by a space, * followed by the character string returned by the client * retrieval function, followed by a newline, to the file * pointer, `fp'. The character string returned by the * retrieval function is then freed with a call to free(). * * In Args: * * dpeh An error handle returned via a call to I2ErrOpen(). * * fp A pointer to a file stream. * * Out Args: * * Return Values: * * Side Effects: */ void I2ErrRep( I2ErrHandle dpeh, FILE *fp ) { ErrHandle *eh = (ErrHandle *) dpeh; char *msg; if (! eh) return; I2ThreadMutexLock(&MyMutex); if (eh->retrieve_func) { msg = eh->retrieve_func(eh->retrieve_func_arg, &(eh->data)); (void) fprintf(fp, "%s:\n", eh->program_name); (void) fprintf(fp, "%s\n", msg); free(msg); } I2ThreadMutexUnlock(&MyMutex); } /* * Function: I2ErrGetMsg() * * Description: The I2ErrGetMsg() function calls the client retrieval function * (if one exists) passed to I2ErrOpen() for the error * handling session associated with `dpeh'. I2ErrGetMsg() returns * to the caller the value returned to it by the client * retrieval function (an address in dynamically allocated memory * of a character string). The caller is responsible for freeing * the memory returned by I2ErrGetMsg(). * * In Args: * * dpeh An error handle returned via a call to I2ErrOpen(). * * Out Args: * * Return Values: I2ErrGetMsg() returns NULL if no retrieval function * exists. * * Side Effects: */ char *I2ErrGetMsg( I2ErrHandle dpeh ) { ErrHandle *eh = (ErrHandle *) dpeh; char *msg; I2ThreadMutexLock(&MyMutex); if (eh && eh->retrieve_func) { msg = eh->retrieve_func(eh->retrieve_func_arg, &(eh->data)); } else { msg = NULL; } I2ThreadMutexUnlock(&MyMutex); return(msg); } /* * Function: I2ErrGetCode() * * Description: The I2ErrGetCode() function returns the error number currently * associated with the error handle, `dpeh'. * * N.B. the error code returned is the error code stored from * the most *recent* call to I2ErrLog() or I2ErrLogP(). If * you are nesting calls to these functions only the error * code from the outer-most logging function is available - i.e * inner calls get overwritten. * * In Args: * * dpeh An error handle returned via a call to I2ErrOpen(). * * Out Args: * * Return Values: I2ErrGetCode() returns an integer. * * Side Effects: */ int I2ErrGetCode( I2ErrHandle dpeh ) { ErrHandle *eh = (ErrHandle *) dpeh; return(eh->code); } /* * I2ErrList() * * Adds an error list to the error table. 'start' should be the first * valid error number for this table. The values 0 - 1000 are reserved. * The index into 'err_list' is calculated by subtracting 'start' * from the error number. Thus if you add a list with 'start' equal * to 1001 and later invoke ESprintf with 'code' equal to 1001 the * error message referenced will be 'err_list[0]' * * on entry * start : first valid error number * num : number of elements in 'err_list'. * **err_list : address of error list * * on exit * return : -1 => table full, else OK. */ int I2ErrList( I2ErrHandle dpeh, unsigned start, unsigned num, const char * const *err_list ) { ErrHandle *eh = (ErrHandle *) dpeh; if (! eh) return(0); if (eh->err_tab_num >= TABLE_SIZE -1) { return(-1); /* table full */ } eh->err_tab[eh->err_tab_num].start = start; eh->err_tab[eh->err_tab_num].num = num; eh->err_tab[eh->err_tab_num].err_list = err_list; eh->err_tab_num++; return(0); } /* * Function: I2ErrLocation_ * * Description: The I2ErrLocation_() records the file name, `file', line * number, `line', and compilation date, `date' reported by * the I2ErrLog() macro. This function should never be * called directly by the user himself. * * In Args: * * *file A pointer to a character string containing a file * name. * * *date A pointer to a character string containing the * compiliation date of `file' * * line An integer specifying a line number within the * file, `file'. * * Out Args: * * Return Values: * * Side Effects: * * I2ErrLocation_() writes the global, static variables, * `errorFile', `errorDate', and `errorLine'. In order to * be thread-save this function should lock these variables * before attemping to write them (it does if `THREADS_ENABLE' * is defined). The variables should then * remain locked until unlocked by I2ErrLogFunction() or * I2ErrLogPFunction(). */ void I2ErrLocation_( const char *file, const char *date, int line ) { I2ThreadMutexLock(&MyMutex); errorFile = file; errorDate = date; errorLine = line; } /* * Function: I2ErrLogPFunction_() * * Description: The I2ErrLogPFunction() is identical to the I2ErrLogFunction() * except that it is invoked by the I2LogPErr() macro which * takes an additional error code argument that is passed * on to I2ErrLogPFunction_(), `code' * * `code' may be any valid value of the system global * variable, `errno', or it may be an error code made valid * by a call to I2ErrList(). * * * * In Args: * * dpeh An error handle returned via a call to I2ErrOpen(). * * code An integer indicating the error number. * * *format A pointer to a character string containing formating * information. * * ... variable arguments as indicated in `format' * * Out Args: * * Return Values: * * Side Effects: */ void I2ErrLogVT( I2ErrHandle dpeh, int level, int code, const char *format, va_list ap ) { ErrHandle *eh = (ErrHandle *) dpeh; char new_format[MSG_BUF_SIZE]; char buf[MSG_BUF_SIZE]; struct I2ErrLogEvent event; if(level == I2LOG_NONE) return; event.mask = 0; if(!code) code = errno; else{ event.code = code; event.mask |= I2CODE; } (void)esnprintf(eh,new_format,sizeof(new_format),format,code); /* * deal with variable args */ (void) vsnprintf(buf,sizeof(buf),new_format,ap); if(!eh){ fwrite(buf,sizeof(char),strlen(buf),stderr); fwrite("\n",sizeof(char),1,stderr); I2ThreadMutexUnlock(&MyMutex); return; } eh->code = code; event.name = eh->program_name; event.mask |= I2NAME; event.file = errorFile; event.mask |= I2FILE; event.line = errorLine; event.mask |= I2LINE; event.date = errorDate; event.mask |= I2DATE; event.msg = buf; event.mask |= I2MSG; if(level > -1 && level < 8){ event.level = level; event.mask |= I2LEVEL; } eh->log_func( &event, eh->log_func_arg, &(eh->data) ); I2ThreadMutexUnlock(&MyMutex); return; } void I2ErrLogTFunction_( I2ErrHandle dpeh, int level, int code, const char *format, ... ) { va_list ap; va_start(ap, format); I2ErrLogVT(dpeh,level,code,format,ap); va_end(ap); return; } /* * Function: I2ErrLogPFunction_() * * Description: The I2ErrLogPFunction() is identical to the I2ErrLogFunction() * except that it is invoked by the I2LogPErr() macro which * takes an additional error code argument that is passed * on to I2ErrLogPFunction_(), `code' * * `code' may be any valid value of the system global * variable, `errno', or it may be an error code made valid * by a call to I2ErrList(). * * * * In Args: * * dpeh An error handle returned via a call to I2ErrOpen(). * * code An integer indicating the error number. * * *format A pointer to a character string containing formating * information. * * ... variable arguments as indicated in `format' * * Out Args: * * Return Values: * * Side Effects: */ void I2ErrLogPFunction_( I2ErrHandle dpeh, int code, const char *format, ... ) { va_list ap; va_start(ap, format); I2ErrLogVT(dpeh,-1,code,format,ap); va_end(ap); return; } /* * Function: I2ErrLogFunction_() * * Description: The I2ErrLogFunction() converts and formats its arguments * under the control of `format'. I2ErrLogFunction_() * then invokes the client-supplied logging function associated * with `dpeh' and passes it the formatted argument string. * * `format' is a character string which accepts an identical * syntax to that of Standard C's *printf family of functions. * Additionaly, `format' may contain instances of the format * specifier, "%M", which are replaced by the UNIX system * error message associated with `errno', and instances of * the specifier "%N", which are replaced with the ascii value * of `errno'. * * I2ErrLogFunction() is never invoked directly by the user. * Instead, it is invoked via the I2ErrLog() macro, which * calls I2ErrLocation_() first, passing it the error location * information. * * * * In Args: * * dpeh An error handle returned via a call to I2ErrOpen(). * * *format A pointer to a character string containing formating * information. * * ... variable arguments as indicated in `format' * * Out Args: * * Return Values: * * Side Effects: */ void I2ErrLogFunction_( I2ErrHandle dpeh, const char *format, ... ) { va_list ap; va_start(ap, format); I2ErrLogVT(dpeh,-1,0,format,ap); va_end(ap); return; } i2util-1.6/I2util/ErrLogImmediate.c000066400000000000000000000076631276605416600171460ustar00rootroot00000000000000/* * $Id$ */ /************************************************************************ * * * Copyright (C) 2002 * * Internet2 * * All Rights Reserved * * * ************************************************************************/ /* * File: ErrLogImmediate.c * * Author: Jeff Boote * Internet2 * * Date: Tue Apr 23 10:27:23 2002 * * Description: This file defines an "immediate-mode" logging * function to be used as the `log_func' argument * to the I2OpenErr() function. * * Modified from code writen by John Clyne at UCAR... * * * Based on code from UCAR DCS tools. Copyright information * from UCAR follows: * * Copyright 2012, University Corporation for Atmospheric Research. * * This software may be used, subject to the terms of OSI's BSD-2 Clause * License located at http://www.opensource.org/licenses/bsd-license.php/ */ #include #include #include #include #include /* * Function: I2ErrLogImmediate() * * Description: The I2ErrLogImmediate() function is a client logging function * that may be passed to I2OpenErr() as the `log_func' argument. * * Upon invocation, I2ErrLogImmediate() writes a logging message * via a call to fprintf(). The behavior of I2ErrLogImmediate() * may be controlled by the structure pointed to by `arg'. The * members of the structure pointed to by `arg' that may be * set include: * * *fp A file pointer passed to be passed to * fprintf() * * line_info A bit mask indicating how each output * line should be formatted. The mask * is a bitwise inclusive OR of the * valid attribute bits. If line_info * is zero nothing is printed. * * tformat A format string as defined by * strftime used to format the local * time if the `line_info' attribute * I2RTIME is set. * * Valid attribute mask bits include: * * I2NAME * I2FILE * I2LINE * I2DATE * I2RTIME * I2MSG * * If I2NAME is set `ev->name', followed by a ":" is * copied to `arg->fp'. * * If I2FILE is set the string "FILE=", followed by * `ev->file', followed by ",", followed by a space is copied * to `arg->fp'. * * If I2LINE is set the string "LINE=", followed by the ascii * representation of `ev->line', followed by ",", followed by * a space is copied to `arg->fp'. * * If I2DATE is set the string "DATE=", followed by * `ev->date', followed by ",", followed by a space is copied * to `arg->fp'. * * If I2RTIME is set the string "RTIME=", followed by * `time', followed by ",", followed by a space is copied * to `arg->fp', where `time' is string formatted by * arg->tformat. * * If I2MSG is set `ev->msg' is copied to `arg->fp. * * Finally, a trailing newline is copied to `arg->fp' * * * In Args: * * *arg A pointer to a I2LogImmediateAttr structure. * * Out Args: * * Return Values: * * Side Effects: */ void I2ErrLogImmediate( struct I2ErrLogEvent *ev, void *arg, void **data __attribute__((unused)) ) { I2LogImmediateAttr *la = (I2LogImmediateAttr *) arg; FILE *fp = la->fp; if(! fp) return; if(ev->mask & la->line_info & I2NAME) fprintf(fp, "%s: ", ev->name); if(ev->mask & la->line_info & I2FILE) fprintf(fp, "FILE=%s, ", ev->file); if(ev->mask & la->line_info & I2LINE) fprintf(fp, "LINE=%d, ", ev->line); if(ev->mask & la->line_info & I2DATE) fprintf(fp, "DATE=%s, ", ev->date); if(la->line_info & I2RTIME){ time_t curr; struct tm *tm; char ftime[64]; time(&curr); tm = localtime(&curr); if( strftime(ftime,sizeof(ftime),la->tformat,tm)) fprintf(fp, "RTIME=%s, ", ftime); } if(ev->mask & la->line_info & I2MSG) fprintf(fp, "%s", ev->msg); if(la->line_info && !(la->line_info & I2NONL)) fprintf(fp, "\n"); fflush(fp); } i2util-1.6/I2util/ErrLogSyslog.c000066400000000000000000000245641276605416600165270ustar00rootroot00000000000000/* * $Id$ */ /************************************************************************ * * * Copyright (C) 2002 * * Internet2 * * All Rights Reserved * * * ************************************************************************/ /* * File: ErrLogSyslog.c * * Author: Jeff Boote * Internet2 * * Date: Tue Apr 23 11:05:18 2002 * * Description: This file defines a "syslog-mode" logging * function to be used as the `log_func' argument * to the I2OpenErr() function. * * Modified from code writen by John Clyne at UCAR... * * * Based on code from UCAR DCS tools. Copyright information * from UCAR follows: * * Copyright 2012, University Corporation for Atmospheric Research. * * This software may be used, subject to the terms of OSI's BSD-2 Clause * License located at http://www.opensource.org/licenses/bsd-license.php/ * */ #include #ifdef HAVE_SYSLOG_NAMES /* utilP.h indirectly includes syslog.h, define SYSLOG_NAMES before */ #define SYSLOG_NAMES #endif #include #include #include #include #include #include /* * I prefer to get these arrays from syslog.h... But, they doesn't exist on * all systems. I do what I can. * * If it isn't in the system's syslog.h - I have taken the portion I need * from freebsd. */ #ifndef HAVE_SYSLOG_NAMES /* * Copyright (c) 1982, 1986, 1988, 1993 * The Regents of the University of California. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. All advertising materials mentioning features or use of this software * must display the following acknowledgement: * This product includes software developed by the University of * California, Berkeley and its contributors. * 4. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * @(#)syslog.h 8.1 (Berkeley) 6/2/93 */ typedef struct _code { const char *c_name; int c_val; } CODE; static CODE prioritynames[] = { { "alert", LOG_ALERT, }, { "crit", LOG_CRIT, }, { "debug", LOG_DEBUG, }, { "emerg", LOG_EMERG, }, { "err", LOG_ERR, }, { "error", LOG_ERR, }, /* DEPRECATED */ { "info", LOG_INFO, }, { "notice", LOG_NOTICE, }, { "panic", LOG_EMERG, }, /* DEPRECATED */ { "warn", LOG_WARNING, }, /* DEPRECATED */ { "warning", LOG_WARNING, }, { NULL, -1, } }; #ifndef LOG_AUTHPRIV #define LOG_AUTHPRIV LOG_AUTH #endif #ifndef LOG_FTP #define LOG_FTP LOG_DAEMON #endif static CODE facilitynames[] = { { "auth", LOG_AUTH, }, { "authpriv", LOG_AUTHPRIV, }, { "cron", LOG_CRON, }, { "daemon", LOG_DAEMON, }, { "ftp", LOG_FTP, }, { "kern", LOG_KERN, }, { "lpr", LOG_LPR, }, { "mail", LOG_MAIL, }, { "news", LOG_NEWS, }, { "syslog", LOG_SYSLOG, }, { "user", LOG_USER, }, { "uucp", LOG_UUCP, }, { "local0", LOG_LOCAL0, }, { "local1", LOG_LOCAL1, }, { "local2", LOG_LOCAL2, }, { "local3", LOG_LOCAL3, }, { "local4", LOG_LOCAL4, }, { "local5", LOG_LOCAL5, }, { "local6", LOG_LOCAL6, }, { "local7", LOG_LOCAL7, }, { NULL, -1, } }; #endif /* * Function: I2ErrLogSyslogFacility * * Description: Given a string name, looks for the integer id that matches. * * In Args: * * Out Args: * * Scope: * Returns: integer id : -1 on error. * Side Effect: */ int I2ErrLogSyslogFacility( const char *name ) { CODE *ptr = facilitynames; int val=-1; while(ptr->c_name){ if(strncasecmp(ptr->c_name,name,strlen(ptr->c_name)) == 0){ val = ptr->c_val; break; } ptr++; } return val; } /* * Function: I2ErrLogSyslogFacilityName * * Description: Given an integer, return a "name" for the facility that * matches that integer. * * In Args: * * Out Args: * * Scope: * Returns: const char * (static memory) or NULL * Side Effect: */ const char *I2ErrLogSyslogFacilityName( int fac ) { CODE *ptr = facilitynames; while(ptr->c_name){ if(ptr->c_val == fac) return ptr->c_name; ptr++; } return NULL; } /* * Function: I2ErrLogSyslogPriority * * Description: Given a string name, looks for the integer id that matches. * * In Args: * * Out Args: * * Scope: * Returns: integer id : -1 on error. * Side Effect: */ int I2ErrLogSyslogPriority( const char *name ) { CODE *ptr = prioritynames; int val=-1; if(strncasecmp(name,"none",5) == 0){ val = I2LOG_NONE; } else{ while(ptr->c_name){ if(strncasecmp(ptr->c_name,name,strlen(ptr->c_name)) == 0){ val = ptr->c_val; break; } ptr++; } } return val; } /* * Function: I2ErrLogSyslogPriorityName * * Description: Given an integer, return a "name" for the "priority" that * matches that integer. * * In Args: * * Out Args: * * Scope: * Returns: const char * (static memory) or NULL * Side Effect: */ const char *I2ErrLogSyslogPriorityName( int fac ) { CODE *ptr = prioritynames; static char *none = "none"; if(fac == I2LOG_NONE){ return none; } while(ptr->c_name){ if(ptr->c_val == fac) return ptr->c_name; ptr++; } return NULL; } /* * Function: I2ErrLogSyslog() * * Description: The I2ErrLogSyslog() function is a client logging function * that may be passed to DPOpenErr() as the `log_func' argument. * * Upon invocation, I2ErrLogSyslog() writes a logging message * to the system log via a call to syslog(). The behavior of * I2ErrLogSyslog() * may be controlled by the structure pointed to by `arg'. The * members of the structure pointed to by `arg' that may be * set include: * * * *ident A string passed as the first parameter * to openlog() the first time * I2ErrLogSys() is called iff ident * is not NULL. * * logopt An integer passed as the second * parameter to openlog iff ident * is not NULL. * * facility An integer passed as the third * parameter to openlog iff ident is * not NULL. * * priority An integer log priority passed to * syslog as its first argument. * * line_info A bit mask indicating how each output * line should be formatted. The mask * is a bitwise inclusive OR of the * valid attribute bits. If line_info * is zero nothing is printed. * * Valid attribute mask bits include: * * I2NAME * I2FILE * I2LINE * I2DATE * I2RTIME * I2MSG * * If I2NAME is set `program_name', followed by a ":" is * copied to `arg->fp'. * * If I2FILE is set the string "FILE=", followed by * `file', followed by ",", followed by a space is copied * to `arg->fp'. * * If I2LINE is set the string "LINE=", followed by the ascii * representation of `line', followed by ",", followed by * a space is copied to `arg->fp'. * * If I2DATE is set the string "DATE=", followed by * `date', followed by ",", followed by a space is copied * to `arg->fp'. * * If I2RTIME is set the string "RTIME=", followed by * `time', followed by ",", followed by a space is copied * to `arg->fp', where `time' is string formatted by * arg->tformat. * * If I2MSG is set `msg' is copied to `arg->fp. * * * In Args: * * *arg A pointer to a I2ErrLogSyslogAttr structure. * * Out Args: * * Return Values: * * Side Effects: */ void I2ErrLogSyslog( struct I2ErrLogEvent *ev, void *arg, void **data ) { I2ErrLogSyslogAttr *sa = (I2ErrLogSyslogAttr *) arg; char buf[4096], *bufptr; size_t size=sizeof(buf); int rc; int prio; bufptr = buf; if(*data == NULL && sa->ident){ openlog(sa->ident, sa->logopt, sa->facility); *data = (void *) 1; } if(ev->mask & sa->line_info & I2NAME) { rc = snprintf(bufptr,size,"%s: ", ev->name); bufptr += rc; size -= rc; } if(ev->mask & sa->line_info & I2FILE){ rc = snprintf(bufptr,size,"FILE=%s, ", ev->file); bufptr += rc; size -= rc; } if(ev->mask & sa->line_info & I2LINE){ rc = snprintf(bufptr,size,"LINE=%d, ", ev->line); bufptr += rc; size -= rc; } if(ev->mask & sa->line_info & I2DATE){ rc = snprintf(bufptr,size,"DATE=%s, ", ev->date); bufptr += rc; size -= rc; } if(sa->line_info & I2RTIME){ time_t curr; struct tm *tm; char ftime[64]; time(&curr); tm = localtime(&curr); if( strftime(ftime,sizeof(ftime),sa->tformat,tm)){ rc = snprintf(bufptr,size,"RTIME=%s, ",ftime); bufptr += rc; size -= rc; } } if(ev->mask & sa->line_info & I2MSG){ rc = sprintf(bufptr, "%s", ev->msg); bufptr += rc; } if(bufptr == buf) return; if(ev->mask & I2LEVEL) prio = ev->level; else prio = sa->priority; if(prio != I2LOG_NONE && sa->report_level >= prio) syslog(prio, "%s", buf); #ifndef HAVE_SYSLOG_PERROR if(sa->logopt | LOG_PERROR){ fprintf(stderr,"%s\n", buf); } #endif return; } /* * Function: I2ErrResetSyslog * * Description: * Used to reset syslog error logging. Useful in case of * forking etc... * * In Args: * * Out Args: * * Scope: * Returns: * Side Effect: */ I2Boolean I2ErrLogSyslogReset( void *arg __attribute__((unused)), void **data ) { closelog(); *data = NULL; return True; } i2util-1.6/I2util/Makefile.am000066400000000000000000000031511276605416600160110ustar00rootroot00000000000000# # $Id$ # ######################################################################### # # # Copyright (C) 2002 # # Internet2 # # All Rights Reserved # # # ######################################################################### # # File: Makefile.am # # Author: Jeff Boote # Internet2 # # Date: Wed Apr 24 09:50:44 EDT 2002 # # Description: libI2util build description. #include $(top_srcdir)/config/Make-rules AM_CPPFLAGS = -I$(top_builddir) -I$(top_srcdir) MACH_SOURCES = mach_dep.c mach_dep.h lib_LIBRARIES = libI2util.a libI2util_a_SOURCES = utilP.h ErrLog.c ErrLogImmediate.c ErrLogSyslog.c \ random.c io.c saddr.c md5.c readpassphrase.c hex.c \ conf.c addr.c sha1.c hmac-sha1.c pbkdf2.c table.c \ $(MACH_SOURCES) I2utilincludedir = $(pkgincludedir) I2utilinclude_HEADERS = Pthread.h errlog.h errlogimmediate.h errlogsyslog.h \ mach_dep.h io.h random.h saddr.h table.h md5.h \ readpassphrase.h conf.h hex.h util.h addr.h sha1.h \ sha1P.h hmac-sha1.h pbkdf2.h if I2THREADS_ENABLE MACH_SOURCES += Pthread.c endif # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # i2util-1.6/I2util/Pthread.c000066400000000000000000000072641276605416600155210ustar00rootroot00000000000000/* * $Id$ */ /************************************************************************ * * * Copyright (C) 2002 * * Internet2 * * All Rights Reserved * * * ************************************************************************/ /* * File: Pthread.c * * Author: Jeff Boote * Internet2 * * Date: Tue Apr 23 14:01:41 2002 * * Description: * * * Based on code from UCAR DCS tools. Copyright information * from UCAR follows: * * Copyright 2012, University Corporation for Atmospheric Research. * * This software may be used, subject to the terms of OSI's BSD-2 Clause * License located at http://www.opensource.org/licenses/bsd-license.php/ */ #include "Pthread.h" #include #ifdef I2THREADS_ENABLE int I2ThreadCreate( I2Thread_T *thread, I2ThreadAttr_T *attr, void *(*start)(void *), void *arg, const char *msg ) { int rc; rc = pthread_create(thread, attr, start, arg); #ifdef DEBUG fprintf( stderr, "Created thread (%lx), rc=%d, msg=%s\n", (unsigned long) *thread, rc, msg ); #endif if (rc < 0) return(-1); return(0); } int I2ThreadJoin( I2Thread_T thread, void **retval, const char *msg ) { int rc; rc = pthread_join(thread, retval); #ifdef DEBUG fprintf( stderr, "Joined thread (%lx), rc=%d, msg=%s\n", (unsigned long) thread, rc, msg ); #endif return(0); } I2Thread_T I2ThreadSelf() { return(pthread_self()); } int I2ThreadMutexInit( I2ThreadMutex_T *mutex, I2ThreadMutexattr_T *attr ) { return(pthread_mutex_init(mutex, attr)); } int I2ThreadMutexLock( I2ThreadMutex_T *mutex ) { return(pthread_mutex_lock(mutex)); } int I2ThreadMutexUnlock( I2ThreadMutex_T *mutex ) { return(pthread_mutex_unlock(mutex)); } int I2ThreadAttrInit( I2ThreadAttr_T *attr ) { return(pthread_attr_init(attr)); } int I2ThreadAttrSetDetatchState( I2ThreadAttr_T *attr, int detach ) { return(pthread_attr_setdetachstate(attr, detach)); } int I2ThreadCondDestroy( I2ThreadCond_T *cond ) { return(pthread_cond_destroy(cond)); } int I2ThreadMutexDestroy( I2ThreadMutex_T *mutex ) { return(pthread_mutex_destroy(mutex)); } int I2ThreadCondInit( I2ThreadCond_T *cond, I2ThreadCondattr_T *attr ) { return(pthread_cond_init(cond, attr)); } int I2ThreadCondSignal( I2ThreadCond_T *cond ) { return(pthread_cond_signal(cond)); } int I2ThreadCondWait( I2ThreadCond_T *cond, I2ThreadMutex_T *mutex ) { return(pthread_cond_wait(cond, mutex)); } #else /* I2THREADS_ENABLE */ /* * Hopefully we don't need these - but if macro versions don't work * they are still here... */ #if defined(NOT) && NOT int I2ThreadCreate( I2Thread_T *thread, I2ThreadAttr_T *attr, void *(*start)(void *), void *arg, const char *msg ) { *thread = (I2Thread_T)NULL; start(arg); return(0); } int I2ThreadJoin( I2Thread_T thread, void **retval, const char *msg ) { return(0); } I2Thread_T I2ThreadSelf() { return(0); } int I2ThreadMutexInit( I2ThreadMutex_T *mutex, I2ThreadMutexattr_T *attr ) { return(0); } int I2ThreadMutexLock( I2ThreadMutex_T *mutex ) { return(0); } int I2ThreadMutexUnlock( I2ThreadMutex_T *mutex ) { return(0); } int I2ThreadAttrInit( I2ThreadAttr_T *attr ) { return(0); } int I2ThreadAttrSetDetatchState( I2ThreadAttr_T *attr, int detach ) { return(0); } int I2ThreadCondDestroy( I2ThreadCond_T *cond ) { return(0); } int I2ThreadMutexDestroy( I2ThreadMutex_T *mutex ) { return(0); } int I2ThreadCondInit( I2ThreadCond_T *cond, I2ThreadCondattr_T *attr ) { return(0); } int I2ThreadCondSignal( I2ThreadCond_T *cond ) { return(0); } int I2ThreadCondWait( I2ThreadCond_T *cond, I2ThreadMutex_T *mutex ) { return(0); } #endif /* NOT */ #endif i2util-1.6/I2util/Pthread.h000066400000000000000000000062721276605416600155240ustar00rootroot00000000000000/* * $Id$ */ /************************************************************************ * * * Copyright (C) 2002 * * Internet2 * * All Rights Reserved * * * ************************************************************************/ /* * File: Pthread.h * * Author: Jeff Boote * Internet2 * * Date: Tue Apr 23 10:17:50 2002 * * Description: * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #ifndef _I2Pthread_H_ #define _I2Pthread_H_ #include BEGIN_C_DECLS #ifndef I2THREADS_ENABLE typedef int I2Thread_T; typedef int I2ThreadAttr_T; typedef int I2ThreadMutex_T; typedef int I2ThreadMutexattr_T; typedef int I2ThreadCond_T; typedef int I2ThreadCondattr_T; #define I2PTHREAD_MUTEX_INITIALIZER 0 #define I2ThreadCreate(thread,attr,start,arg,msg) (void)0 #define I2ThreadJoin(thread,retval,msg) (void)0 #define I2ThreadSelf() (void)0 #define I2ThreadMutexInit(mutex,attr) (void)0 #define I2ThreadMutexLock(mutex) ((void)(0 != *(mutex))) #define I2ThreadMutexUnlock(mutex) (void)0 #define I2ThreadAttrInit(attr) (void)0 #define I2ThreadAttrSetDetatchState(attr,detach) (void)0 #define I2ThreadCondDestroy(cond) (void)0 #define I2ThreadMutexDestroy(mutex) (void)0 #define I2ThreadCondInit(cond,attr) (void)0 #define I2ThreadCondSignal(cond) (void)0 #define I2ThreadCondWait(cond,mutex) (void)0 #else /* THREADS_ENABLE */ #include typedef pthread_t I2Thread_T; typedef pthread_attr_t I2ThreadAttr_T; typedef pthread_mutex_t I2ThreadMutex_T; typedef pthread_mutexattr_t I2ThreadMutexattr_T; typedef pthread_cond_t I2ThreadCond_T; typedef pthread_condattr_t I2ThreadCondattr_T; #define I2PTHREAD_MUTEX_INITIALIZER PTHREAD_MUTEX_INITIALIZER extern int I2ThreadCreate( I2Thread_T *thread, I2ThreadAttr_T *attr, void *(*start)(void *), void *arg, const char *msg ); extern int I2ThreadJoin( I2Thread_T thread, void **retval, const char *msg ); extern I2Thread_T I2ThreadSelf(); extern int I2ThreadMutexInit( I2ThreadMutex_T *mutex, I2ThreadMutexattr_T *attr ); extern int I2ThreadMutexLock( I2ThreadMutex_T *mutex ); extern int I2ThreadMutexUnlock( I2ThreadMutex_T *mutex ); extern int I2ThreadAttrInit(I2ThreadAttr_T *attr); extern int I2ThreadAttrSetDetatchState( I2ThreadAttr_T *attr, int detach ); extern int I2ThreadCondDestroy( I2ThreadCond_T *cond ); extern int I2ThreadMutexDestroy( I2ThreadMutex_T *mutex ); extern int I2ThreadCondInit( I2ThreadCond_T *cond, I2ThreadCondattr_T *attr ); extern int I2ThreadCondSignal( I2ThreadCond_T *cond ); extern int I2ThreadCondWait( I2ThreadCond_T *cond, I2ThreadMutex_T *mutex ); #endif /* I2THREADS_ENABLE */ END_C_DECLS #endif i2util-1.6/I2util/addr.c000066400000000000000000000724701276605416600150450ustar00rootroot00000000000000/* ** ex: set tabstop=4 ai expandtab softtabstop=4 shiftwidth=4: ** $Id$ */ /************************************************************************ * * * Copyright (C) 2005 * * Internet2 * * All Rights Reserved * * * ************************************************************************/ /* ** File: addr.c ** ** Author: Jeff W. Boote ** ** Date: Tue Dec 20 11:55:21 MST 2005 ** ** Description: ** Address abstraction API. (Everybody needs one, right?) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #include #include #include #include #include #include #include /* * Data structures */ typedef struct I2AddrRec I2AddrRec; struct I2AddrRec{ I2ErrHandle eh; I2Boolean node_set; char node[NI_MAXHOST+1]; I2Boolean port_set; uint16_t port_value; char port[NI_MAXSERV+1]; I2Boolean ai_free; /* free ai list directly...*/ struct addrinfo *ai; struct sockaddr *saddr; socklen_t saddrlen; int so_type; /* socktype saddr works with */ int so_protocol; /* protocol saddr works with */ I2Boolean passive; I2Boolean fd_user; int fd; }; static void _I2AddrClearAI( I2Addr addr ) { if(!addr) return; if(addr->ai){ if(!addr->ai_free){ freeaddrinfo(addr->ai); }else{ struct addrinfo *ai, *next; ai = addr->ai; while(ai){ next = ai->ai_next; if(ai->ai_addr) free(ai->ai_addr); if(ai->ai_canonname) free(ai->ai_canonname); free(ai); ai = next; } } } addr->ai = NULL; addr->saddr = NULL; addr->saddrlen = 0; addr->ai_free = False; return; } void I2AddrFree( I2Addr addr ) { if(!addr) return; _I2AddrClearAI(addr); if((addr->fd >= 0) && !addr->fd_user){ if(close(addr->fd) < 0){ I2ErrLogT(addr->eh,LOG_WARNING, errno,":close(%d)",addr->fd); } } free(addr); return; } static I2Addr _I2AddrAlloc( I2ErrHandle eh ) { I2Addr addr = calloc(1,sizeof(struct I2AddrRec)); if(!addr){ I2ErrLogT(eh,LOG_ERR,I2EUNKNOWN, ": calloc(1,%d): %M",sizeof(struct I2AddrRec)); return NULL; } addr->eh = eh; addr->node_set = 0; strncpy(addr->node,"unknown",sizeof(addr->node)); addr->port_set = addr->port_value = 0; strncpy(addr->port,"unknown",sizeof(addr->port)); addr->ai_free = 0; addr->ai = NULL; addr->saddr = NULL; addr->saddrlen = 0; addr->fd_user = 0; addr->fd= -1; return addr; } static struct addrinfo* CopyAddrRec( I2ErrHandle eh, const struct addrinfo *src ) { struct addrinfo *dst = calloc(1,sizeof(struct addrinfo)); if(!dst){ I2ErrLogT(eh,LOG_ERR,errno, ": calloc(1,sizeof(struct addrinfo))"); return NULL; } *dst = *src; if(src->ai_addr){ dst->ai_addr = malloc(src->ai_addrlen); if(!dst->ai_addr){ I2ErrLogT(eh,LOG_ERR,errno, "malloc(%u): %s",src->ai_addrlen, strerror(errno)); free(dst); return NULL; } memcpy(dst->ai_addr,src->ai_addr,src->ai_addrlen); dst->ai_addrlen = src->ai_addrlen; } else dst->ai_addrlen = 0; if(src->ai_canonname){ int len = strlen(src->ai_canonname); if(len > NI_MAXHOST){ I2ErrLogT(eh,LOG_WARNING, I2EUNKNOWN, ":Invalid canonname!"); dst->ai_canonname = NULL; }else{ dst->ai_canonname = malloc(sizeof(char)*(len+1)); if(!dst->ai_canonname){ I2ErrLogT(eh,LOG_WARNING, errno,": malloc(sizeof(%d)",len+1); dst->ai_canonname = NULL; }else strcpy(dst->ai_canonname,src->ai_canonname); } } dst->ai_next = NULL; return dst; } I2Addr I2AddrCopy( I2Addr from ) { I2Addr to; struct addrinfo **aip; struct addrinfo *ai; if(!from) return NULL; if( !(to = _I2AddrAlloc(from->eh))) return NULL; if(from->node_set){ strncpy(to->node,from->node,sizeof(to->node)); to->node_set = True; } if(from->port_set){ strncpy(to->port,from->port,sizeof(to->port)); to->port_value = from->port_value; to->port_set = True; } aip = &to->ai; ai = from->ai; while(ai){ to->ai_free = 1; *aip = CopyAddrRec(from->eh,ai); if(!*aip){ I2AddrFree(to); return NULL; } if(ai->ai_addr == from->saddr){ to->saddr = (*aip)->ai_addr; to->saddrlen = (*aip)->ai_addrlen; } aip = &(*aip)->ai_next; ai = ai->ai_next; } to->fd = from->fd; if(to->fd > -1) to->fd_user = True; return to; } I2Addr I2AddrByNode( I2ErrHandle eh, const char *node ) { I2Addr addr; char buff[NI_MAXHOST+1]; const char *nptr=node; char *pptr=NULL; char *s1,*s2; if(!node) return NULL; if(!(addr=_I2AddrAlloc(eh))) return NULL; strncpy(buff,node,sizeof(buff)); /* * Pull off port if specified. If syntax doesn't match URL like * node:port - ipv6( [node]:port) - then just assume whole string * is nodename and let getaddrinfo report problems later. * (This service syntax is specified by rfc2396 and rfc2732.) */ /* * First try ipv6 syntax since it is more restrictive. */ if( (s1 = strchr(buff,'['))){ s1++; if(strchr(s1,'[')) goto NOPORT; if(!(s2 = strchr(s1,']'))) goto NOPORT; *s2++='\0'; if(strchr(s2,']')) goto NOPORT; if(*s2++ != ':') goto NOPORT; nptr = s1; pptr = s2; } /* * Now try ipv4 style. */ else if( (s1 = strchr(buff,':'))){ *s1++='\0'; /* second ':' indicates a v6 address with no port specified */ if(strchr(s1,':')) goto NOPORT; nptr = buff; pptr = s1; } NOPORT: /* * Set hostname if it was specified. */ if(nptr && strlen(nptr)){ strncpy(addr->node,nptr,sizeof(addr->node)); addr->node_set = 1; } if(pptr && strlen(pptr)){ int tint; char *tstr=NULL; tint = strtol(pptr,&tstr,10); if(!tstr || (pptr == tstr) || (tint < 0) || (tint > (int)0xffff)){ addr->port_set = addr->port_value = 0; } else{ addr->port_set = True; addr->port_value = (uint16_t)tint; strncpy(addr->port,pptr,sizeof(addr->port)); } } return addr; } I2Addr I2AddrByWildcard( I2ErrHandle eh, int socktype, const char *servname ) { struct addrinfo *ai=NULL; struct addrinfo hints; I2Addr addr; int ai_err; memset(&hints,0,sizeof(struct addrinfo)); hints.ai_family = AF_UNSPEC; hints.ai_socktype = socktype; hints.ai_flags = AI_PASSIVE; if( (ai_err = getaddrinfo(NULL,servname,&hints,&ai)!=0) || !ai){ I2ErrLogT(eh,LOG_ERR,I2EUNKNOWN, "getaddrinfo(): %s",gai_strerror(ai_err)); return NULL; } if( !(addr = _I2AddrAlloc(eh))){ freeaddrinfo(ai); return NULL; } addr->ai = ai; addr->passive = True; return addr; } static void _I2AddrSetNodePort( I2Addr addr ) { int gai; char *pptr=NULL; char *tstr=NULL; int tint; if(!addr->saddr || (addr->node_set && addr->port_set)){ return; } if(addr->saddr->sa_family == AF_UNIX){ strncpy(addr->node,"unixsock",sizeof(addr->node)); strncpy(addr->port,"unnamed",sizeof(addr->port)); addr->node_set = True; addr->port_set = True; addr->port_value = 0; } else{ gai = getnameinfo(addr->saddr,addr->saddrlen, addr->node,sizeof(addr->node), addr->port,sizeof(addr->port), NI_NUMERICSERV); if (gai != 0) { gai = getnameinfo(addr->saddr,addr->saddrlen, addr->node,sizeof(addr->node), addr->port,sizeof(addr->port), NI_NUMERICHOST|NI_NUMERICSERV); } if (gai != 0) { I2ErrLogT(addr->eh,LOG_WARNING,I2EUNKNOWN, "getnameinfo(): %s",gai_strerror(gai)); strncpy(addr->node,"unknown",sizeof(addr->node)); strncpy(addr->port,"unknown",sizeof(addr->port)); } else{ addr->node_set = True; pptr = addr->port; tstr = NULL; tint = strtol(pptr,&tstr,10); if(!tstr || (pptr == tstr) || (tint < 0) || (tint > (int)0xffff)){ addr->port_set = addr->port_value = 0; } else{ addr->port_set = True; addr->port_value = (uint16_t)tint; } } } return; } /* * Function: I2AddrBySAddr * * Description: * Construct an I2Addr record given a sockaddr struct. * * In Args: * Set socktype == 0 if it doesn't matter. (but realize * this is here because the saddr will probably by used * to create a socket... * * Out Args: * * Scope: * Returns: * Side Effect: */ I2Addr I2AddrBySAddr( I2ErrHandle eh, struct sockaddr *saddr, socklen_t saddrlen, int socktype, int protocol ) { I2Addr addr; struct addrinfo *ai=NULL; struct sockaddr_in v4addr; if(!saddr){ return NULL; } switch(saddr->sa_family){ #ifdef AF_INET6 struct sockaddr_in6 v6addr; case AF_INET6: if(saddrlen < sizeof(v6addr)){ I2ErrLogT(eh,LOG_ERR,EINVAL,"invalid saddrlen for addr family"); return NULL; } /* * If this is a mapped addr - create a sockaddr_in * instead of the sockaddr_in6. (This is so addr * matching will work in other parts of the code, and * users of v4 will not be confused by security limits * on v6 addresses causing problems.) */ memcpy(&v6addr,saddr,sizeof(v6addr)); if(IN6_IS_ADDR_V4MAPPED(&v6addr.sin6_addr)){ memset(&v4addr,0,sizeof(v4addr)); #ifdef HAVE_STRUCT_SOCKADDR_SA_LEN v4addr.sin_len = sizeof(v4addr); #endif v4addr.sin_family = AF_INET; v4addr.sin_port = v6addr.sin6_port; memcpy(&v4addr.sin_addr.s_addr, &v6addr.sin6_addr.s6_addr[12],4); saddr = (struct sockaddr*)&v4addr; saddrlen = sizeof(v4addr); } break; #endif /* fall through */ case AF_INET: case AF_UNIX: break; default: I2ErrLogT(eh,LOG_ERR,EINVAL,"Invalid addr family"); return NULL; break; } if(!(addr = _I2AddrAlloc(eh))) return NULL; if(!(ai = calloc(1,sizeof(struct addrinfo)))){ I2ErrLogT(addr->eh,LOG_ERR,I2EUNKNOWN, "malloc():%s",strerror(errno)); (void)I2AddrFree(addr); return NULL; } if(!(addr->saddr = calloc(1,saddrlen))){ I2ErrLogT(addr->eh,LOG_ERR,I2EUNKNOWN, "malloc():%s",strerror(errno)); (void)I2AddrFree(addr); (void)free(ai); return NULL; } memcpy(addr->saddr,saddr,saddrlen); ai->ai_addr = addr->saddr; addr->saddrlen = saddrlen; ai->ai_addrlen = saddrlen; ai->ai_flags = 0; ai->ai_family = saddr->sa_family; ai->ai_socktype = socktype; ai->ai_protocol = protocol; ai->ai_canonname = NULL; ai->ai_next = NULL; addr->ai = ai; addr->ai_free = True; addr->so_type = socktype; addr->so_protocol = protocol; _I2AddrSetNodePort(addr); return addr; } static I2Addr ByAnySockFD( I2ErrHandle eh, int fd, I2Boolean close_on_free, struct sockaddr *saddr, socklen_t saddrlen) { int so_type; socklen_t so_typesize = sizeof(so_type); I2Addr addr; /* * *BSD getsockname/getpeername returns 0 size for AF_UNIX. * fake a sockaddr to describe this. */ if(!saddrlen){ saddr->sa_family = AF_UNIX; /* * Set the size of this "fake" sockaddr to include * the sa_family member. (and possibly the sa_len member) */ saddrlen = (char*)&saddr->sa_family - (char*)saddr; saddrlen += sizeof(saddr->sa_family); #ifdef HAVE_STRUCT_SOCKADDR_SA_LEN if(saddrlen <= (socklen_t)((char*)&saddr->sa_len - (char*)saddr)){ saddrlen = (char*)&saddr->sa_len - (char*)saddr; saddrlen += sizeof(saddr->sa_len); } saddr->sa_len = saddrlen; #endif } if(getsockopt(fd,SOL_SOCKET,SO_TYPE, (void*)&so_type,&so_typesize) != 0){ I2ErrLogT(eh,LOG_ERR,errno,"getsockopt(): %M"); return NULL; } addr = I2AddrBySAddr(eh,saddr,saddrlen,so_type,0); if(!addr) return NULL; addr->fd_user = !close_on_free; addr->fd = fd; return addr; } I2Addr I2AddrBySockFD( I2ErrHandle eh, int fd, I2Boolean close_on_free ) { struct sockaddr_storage sbuff; socklen_t saddrlen = sizeof(sbuff); if(getpeername(fd,(void*)&sbuff,&saddrlen) != 0){ I2ErrLogT(eh,LOG_ERR,errno,"getpeername(): %M"); return NULL; } return ByAnySockFD(eh,fd,close_on_free,(struct sockaddr *)&sbuff,saddrlen); } I2Addr I2AddrByLocalSockFD( I2ErrHandle eh, int fd, I2Boolean close_on_free ) { struct sockaddr_storage sbuff; socklen_t saddrlen = sizeof(sbuff); if(getsockname(fd,(void*)&sbuff,&saddrlen) != 0){ I2ErrLogT(eh,LOG_ERR,errno,"getsockname(): %M"); return NULL; } return ByAnySockFD(eh,fd,close_on_free,(struct sockaddr *)&sbuff,saddrlen); } /* * Function: I2AddrSetSAddr * * Description: * * In Args: * * Out Args: * * Scope: * Returns: * Side Effect: * Does not copy the memory and does not directly free it. * (It is expected that this memory points at the saddr * portion of one of the getaddrinfo structures returned * from I2AddrAddrInfo.) */ I2Boolean I2AddrSetSAddr( I2Addr addr, struct sockaddr *saddr, socklen_t saddr_len ) { if(addr->fd > -1){ I2ErrLogT(addr->eh,LOG_ERR,EINVAL, "I2AddrSetSAddr: Addr already associated with socket: %M"); return False; } if(!addr->ai){ I2ErrLogT(addr->eh,LOG_ERR,EINVAL, "I2AddrSetSAddr: AddrInfo not set: %M"); return False; } addr->saddr = saddr; addr->saddrlen = saddr_len; /* * reset node/port based on new saddr */ addr->node_set = False; addr->port_set = addr->port_value = 0; _I2AddrSetNodePort(addr); return True; } /* * Function: I2AddrSetFD * * Description: * * In Args: * * Out Args: * * Scope: * Returns: * Side Effect: */ I2Boolean I2AddrSetFD( I2Addr addr, int fd, I2Boolean close_on_free ) { if(!addr) return False; if((fd > -1) && (fd != addr->fd) && (addr->fd > -1)){ I2ErrLogT(addr->eh,LOG_ERR,EINVAL, "I2AddrSetFD: Addr already associated with socket: %M"); return False; } addr->fd = fd; addr->fd_user = !close_on_free; return True; } /* * Function: I2AddrSetPort * * Description: * * In Args: * * Out Args: * * Scope: * Returns: * Side Effect: */ I2Boolean I2AddrSetPort( I2Addr addr, uint16_t p ) { uint16_t sp; if(!addr) return False; if(addr->fd > -1){ I2ErrLogT(addr->eh,LOG_ERR,EINVAL, "I2AddrSetPort: Addr already associated with socket: %M"); return False; } /* * If saddr is already set - than modify the port. */ if(addr->saddr){ I2SockUnion sau_mem; I2SockUnion *sau; if( !(sau = I2SockAddrToSockUnion(addr->saddr, addr->saddrlen,&sau_mem))){ I2ErrLogT(addr->eh,LOG_ERR,EINVAL, "I2AddrSetPort: Unable to decode sockaddr"); return False; } /* * decode v4 and v6 sockaddrs. */ sp = htons(p); switch(sau->sa.sa_family){ #ifdef AF_INET6 case AF_INET6: sau->sin6.sin6_port = sp; break; #endif case AF_INET: sau->sin.sin_port = sp; break; default: I2ErrLogT(addr->eh,LOG_ERR,EINVAL, "I2AddrSetPort: Invalid address family"); return False; } if( !I2SockUnionToSockAddr(sau,&addr->saddrlen,addr->saddr)){ return False; } } snprintf(addr->port,sizeof(addr->port),"%u",p); addr->port_set = True; addr->port_value = p; return True; } /* * Function: I2AddrPort * * Description: * * In Args: * * Out Args: * * Scope: * Returns: * Side Effect: */ uint16_t I2AddrPort( I2Addr addr ) { if(!addr) return 0; return addr->port_value; } /* * Function: I2AddrSetProtocol * * Description: * * In Args: * * Out Args: * * Scope: * Returns: * Side Effect: */ I2Boolean I2AddrSetProtocol( I2Addr addr, int protocol ) { if(!addr) return False; if(addr->so_protocol == protocol) return True; /* * If so_protocol was "unset" before, then this is a simple assignment * even for an associated socket. */ if(!addr->so_protocol){ addr->so_protocol = protocol; return True; } /* * Otherwise, make sure this assignment is happening *before* actual * association with a socket/saddr. */ if(addr->fd > -1){ I2ErrLogT(addr->eh,LOG_ERR,EINVAL, "I2AddrSetProtocol: Addr already associated with socket: %M"); return False; } if(addr->saddr){ I2ErrLogT(addr->eh,LOG_ERR,EINVAL, "I2AddrSetProtocol: Addr already associated with saddr: %M"); return False; } _I2AddrClearAI(addr); addr->so_protocol = protocol; return True; } /* * Function: I2AddrProtocol * * Description: * * In Args: * * Out Args: * * Scope: * Returns: * Side Effect: */ int I2AddrProtocol( I2Addr addr ) { if(!addr) return 0; return addr->so_protocol; } /* * Function: I2AddrSetSocktype * * Description: * * In Args: * * Out Args: * * Scope: * Returns: * Side Effect: */ I2Boolean I2AddrSetSocktype( I2Addr addr, int so_type ) { if(!addr) return False; if(addr->so_type == so_type) return True; /* * If so_type was "unset" before, then this is a simple assignment * even for an associated socket. */ if(!addr->so_type){ addr->so_type = so_type; return True; } if(addr->fd > -1){ I2ErrLogT(addr->eh,LOG_ERR,EINVAL, "I2AddrSetSocktype: Addr already associated with socket: %M"); return False; } if(addr->saddr){ I2ErrLogT(addr->eh,LOG_ERR,EINVAL, "I2AddrSetSocktype: Addr already associated with saddr: %M"); return False; } _I2AddrClearAI(addr); addr->so_type = so_type; return True; } /* * Function: I2AddrSocktype * * Description: * Retrieves so_socktype. * * In Args: * * Out Args: * * Scope: * Returns: * Side Effect: */ int I2AddrSocktype( I2Addr addr ) { if(!addr) return 0; return addr->so_type; } /* * Function: I2AddrSetPassive * * Description: * * In Args: * * Out Args: * * Scope: * Returns: * Side Effect: */ I2Boolean I2AddrSetPassive( I2Addr addr, I2Boolean passive ) { if(!addr) return False; if(addr->passive == passive) return True; if(addr->fd > -1){ I2ErrLogT(addr->eh,LOG_ERR,EINVAL, "I2AddrSetPassive: Addr already associated with socket: %M"); return False; } if(addr->saddr){ I2ErrLogT(addr->eh,LOG_ERR,EINVAL, "I2AddrSetPassive: Addr already associated with saddr: %M"); return False; } _I2AddrClearAI(addr); addr->passive = passive; return True; } /* * Function: I2AddrFD * * Description: * Retrieves the fd associated with the I2Addr. * * In Args: * * Out Args: * * Scope: * Returns: * Side Effect: */ int I2AddrFD( I2Addr addr ) { if(!addr || (addr->fd < 0)) return -1; return addr->fd; } /* * Function: I2AddrSAddr * * Description: * This function retrieves the sockaddr associated with the given * I2Addr. (If the saddr has not been set, it returns null.) * * In Args: * * Out Args: * * Scope: * Returns: * Side Effect: */ struct sockaddr * I2AddrSAddr( I2Addr addr, socklen_t *saddr_len ) { socklen_t len_mem; socklen_t *len = &len_mem; if(saddr_len){ len = saddr_len; } if(addr && addr->saddr){ *len = addr->saddrlen; return addr->saddr; } *len = 0; return NULL; } /* * Function: I2AddrNodeName * * Description: * This function gets a char* node name for a given I2Addr. * The len parameter is an in/out parameter. * * In Args: * * Out Args: * * Scope: * Returns: * Side Effect: */ char * I2AddrNodeName( I2Addr addr, char *buf, size_t *len ) { int i; assert(buf); assert(len); assert(*len > 0); if(!addr){ goto bail; } if(!addr->node_set){ _I2AddrSetNodePort(addr); } if(addr->node_set){ *len = MIN(*len,sizeof(addr->node)); strncpy(buf,addr->node,*len); for(i = 0; i < strlen(buf); i++) { if (buf[i] == '%') { buf[i] = '\0'; *len = i; } } return buf; } bail: *len = 0; buf[0] = '\0'; return NULL; } /* * Function: I2AddrServName * * Description: * This function gets a char* service name for a given I2Addr. * The len parameter is an in/out parameter. * * In Args: * * Out Args: * * Scope: * Returns: * Side Effect: */ char * I2AddrServName( I2Addr addr, char *buf, size_t *len ) { assert(buf); assert(len); assert(*len > 0); if(!addr){ goto bail; } if(!addr->port_set){ _I2AddrSetNodePort(addr); } if(addr->port_set){ *len = MIN(*len,sizeof(addr->port)); strncpy(buf,addr->port,*len); return buf; } bail: *len = 0; buf[0] = '\0'; return NULL; } /* * Function: I2AddrNodeServName * * Description: * This function gets a char* complete IP:port name for a given * I2Addr. The len parameter is an in/out parameter. * * In Args: * * Out Args: * * Scope: * Returns: * Side Effect: */ char * I2AddrNodeServName( I2Addr addr, char *buf, size_t *len ) { size_t newlen; assert(buf); assert(len); assert(*len > 0); if(!addr){ goto bail; } if(!addr->node_set || !addr->port_set){ _I2AddrSetNodePort(addr); } if(!addr->node_set || !addr->port_set){ goto bail; } newlen = strlen("[]:") + strlen(addr->node) + strlen(addr->port); *len = MIN(*len,newlen); strncpy(buf,"[",*len); strncat(buf,addr->node,*len); strncat(buf,"]:",*len); strncat(buf,addr->port,*len); return buf; bail: *len = 0; buf[0] = '\0'; return NULL; } /* * Function: I2AddrAddrInfo * * Description: * * In Args: * def_node: only used if internal node is not set * def_serv: only used if internal port not set * * Out Args: * * Scope: * Returns: * Side Effect: */ struct addrinfo *I2AddrAddrInfo( I2Addr addr, char *def_node, char *def_serv ) { struct addrinfo hints; char *host=NULL; char *port=NULL; int gai; if(!addr){ return NULL; } if(addr->ai) return addr->ai; memset(&hints,0,sizeof(hints)); hints.ai_family = AF_UNSPEC; if(addr->so_type){ hints.ai_socktype = addr->so_type; } else{ hints.ai_socktype = SOCK_STREAM; } if(addr->so_protocol){ hints.ai_protocol = addr->so_protocol; } if(addr->passive){ hints.ai_flags = AI_PASSIVE; } if(addr->node_set && (strncmp(addr->node,"unknown",sizeof(addr->node)))){ host = addr->node; } else if(def_node){ host = def_node; } if(addr->port_set && (strncmp(addr->port,"unknown",sizeof(addr->port)))){ port = addr->port; } else if(def_serv){ port = def_serv; } /* * Some implementations allow this and give you a bogus connection * to localhost. I prefer the quick fail. */ if(!host && !addr->passive){ return NULL; } if(((gai = getaddrinfo(host,port,&hints,&addr->ai)) != 0) || !addr->ai){ I2ErrLogT(addr->eh,LOG_ERR,I2EUNKNOWN,"getaddrinfo(): %s", gai_strerror(gai)); return NULL; } addr->ai_free = 0; return addr->ai; } /* * Function: I2AddrSockLen * * Description: * Return socket address length (for use in calling accept etc...) * or 0 if it doesn't refer to a socket yet. * * In Args: * * Out Args: * * Scope: * Returns: * Side Effect: */ extern socklen_t I2AddrSockLen( I2Addr addr ) { if(addr && addr->saddr){ return addr->saddrlen; } return 0; } /* * TODO: optimize byte swapping by using BYTE_ORDER macro * i.e. * #if (BYTE_ORDER == BIG_ENDIAN) * do_nothing * #else * do_this * #endif */ /* * Deal with network ordering of 64 bit int's. */ uint64_t I2htonll( uint64_t h64 ) { uint64_t n64=0; uint32_t l32; uint32_t h32; uint8_t *t8; /* Use t8 to byte address the n64 */ t8 = (uint8_t *)&n64; /* set low-order bytes */ l32 = (uint32_t)(h64 & 0xFFFFFFFFUL); l32 = htonl(l32); /* set high-order bytes */ h64 >>=32; h32 = (uint32_t)(h64 & 0xFFFFFFFFUL); h32 = htonl(h32); memcpy(&t8[0],&h32,4); memcpy(&t8[4],&l32,4); return n64; } uint64_t I2ntohll( uint64_t n64 ) { uint64_t h64; char *t8 = (char *)&n64; uint32_t t32; /* High order bytes */ memcpy(&t32,&t8[0],4); h64 = ntohl(t32); h64 <<= 32; /* Low order bytes */ memcpy(&t32,&t8[4],4); h64 |= ntohl(t32); return h64; } /* * Function: I2AddrIsLoopback * * Description: * Check whether an address is for a loopback interface. * * In Args: * * Out Args: * * Scope: * Returns: * 1 if true, 0 if false * Side Effect: */ int I2AddrIsLoopback( I2Addr addr ) { struct sockaddr *saddr; socklen_t saddrlen; if(!(saddr = I2AddrSAddr(addr,&saddrlen))){ return 0; } return I2SockAddrIsLoopback(saddr, saddrlen); } i2util-1.6/I2util/addr.h000066400000000000000000000133111276605416600150370ustar00rootroot00000000000000/* * ex: set tabstop=4 ai expandtab softtabstop=4 shiftwidth=4: * -*- mode: c-basic-indent: 4; tab-width: 4; indent-tabls-mode: nil -*- * $Id$ */ /************************************************************************ * * * Copyright (C) 2005 * * Internet2 * * All Rights Reserved * * * ************************************************************************/ /* ** File: addr.h ** ** Author: Jeff W. Boote ** ** Date: Tue Dec 20 12:04:12 MST 2005 ** ** Description: * Abstraction layer for addresses. Useful for keeping * network address code localized to one part of the * code. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #ifndef I2ADDR_H #define I2ADDR_H #include #include #include typedef struct I2AddrRec *I2Addr; /* * The I2AddrBy* functions are used to allow the addr API to more * adequately manage the memory associated with the many different ways * of specifying an address - and to provide a uniform way to specify an * address. * * These functions return NULL on failure. (They call the error handler * to specify the reason.) */ extern I2Addr I2AddrByNode( I2ErrHandle eh, const char *node /* dns or valid char representation of addr */ ); extern I2Addr I2AddrByWildcard( I2ErrHandle eh, int socktype, const char *servname ); extern I2Addr I2AddrBySAddr( I2ErrHandle eh, struct sockaddr *saddr, socklen_t saddr_len, int socktype, int protocol ); /* * Copies an I2Addr. If the src I2Addr represents a connected socket, * the copy will as well. However, as with the AddrBy*FD functions * free'ing the copy I2Addr will not close the fd. */ extern I2Addr I2AddrCopy( I2Addr src ); /* * Return the address for the remote side of a socket connection * (getpeername) * Only copies the address portion of the I2Addr record, does not * represent the actual connected socket. */ extern I2Addr I2AddrBySockFD( I2ErrHandle eh, int fd, /* fd must be an already connected socket */ I2Boolean close_on_free ); /* * Return the address for the local side of a socket connection * (getsockname) * Only copies the address portion of the I2Addr record, does not * represent the actual connected socket. */ extern I2Addr I2AddrByLocalSockFD( I2ErrHandle eh, int fd, /* fd must be an already connected socket */ I2Boolean close_on_free ); /* * Addr access functions. * The set functions are only valid *before* a real socket is associated * with the Addr. So, the internal fd cannot be set upon entrance. */ extern I2Boolean I2AddrSetSAddr( I2Addr addr, struct sockaddr *saddr, socklen_t saddr_len ); extern I2Boolean I2AddrSetFD( I2Addr addr, int fd, I2Boolean close_on_free ); extern I2Boolean I2AddrSetPort( I2Addr addr, uint16_t port ); extern uint16_t I2AddrPort( I2Addr addr ); extern I2Boolean I2AddrSetSocktype( I2Addr addr, int so_type ); extern int I2AddrSocktype( I2Addr addr ); extern I2Boolean I2AddrSetProtocol( I2Addr addr, int protocol ); extern int I2AddrProtocol( I2Addr addr ); extern I2Boolean I2AddrSetPassive( I2Addr addr, I2Boolean passive ); extern struct addrinfo *I2AddrAddrInfo( I2Addr addr, char *def_node, char *def_serv ); extern struct sockaddr *I2AddrSAddr( I2Addr addr, socklen_t *saddr_len ); extern char * I2AddrNodeName( I2Addr addr, char *buf, size_t *len /* in/out parameter for buf len */ ); extern char * I2AddrServName( I2Addr addr, char *buf, size_t *len /* in/out parameter for buf len */ ); extern char * I2AddrNodeServName( I2Addr addr, char *buf, size_t *len ); /* * return FD for given I2Addr or -1 if it doesn't refer to a socket yet. */ extern int I2AddrFD( I2Addr addr ); /* * return socket address length (for use in calling accept etc...) * or 0 if it doesn't refer to a socket yet. */ extern socklen_t I2AddrSockLen( I2Addr addr ); extern void I2AddrFree( I2Addr addr ); #ifndef htonll #define htonll(x) I2htonll(x) #endif #ifndef ntohll #define ntohll(x) I2ntohll(x) #endif extern uint64_t I2htonll( uint64_t h64 ); extern uint64_t I2ntohll( uint64_t n64 ); extern int I2AddrIsLoopback( I2Addr addr ); #endif /* I2ADDR_H */ i2util-1.6/I2util/conf.c000066400000000000000000000464321276605416600150570ustar00rootroot00000000000000/* * $Id$ */ /************************************************************************ * * * Copyright (C) 2003 * * Internet2 * * All Rights Reserved * * * ************************************************************************/ /* * File: conf.c * * Author: Jeff W. Boote * Internet2 * * Date: Tue Sep 9 16:13:25 MDT 2003 * * Description: * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #include #include #include #include #include #include #include #include /* * Function: I2GetConfLine * * Description: * Read a single line from a file fp. remove leading whitespace, * skip blank lines and comment lines. Put the result in the * char buffer pointed at by lbuf, growing it as necessary. * * In Args: * * Out Args: * * Scope: * Returns: * Side Effect: */ int I2GetConfLine( I2ErrHandle eh, FILE *fp, int rc, char **lbuf, size_t *lbuf_max ) { int c; char *line = *lbuf; size_t i=0; while((c = fgetc(fp)) != EOF){ /* * If c is a newline - increment the row-counter. * If lbuf already has content - break out, otherwise * this was a leading blank line, continue until there * is content. */ if(c == '\n'){ rc++; if(i) break; continue; } /* * swallow comment lines */ if(!i && c == '#'){ while((c = fgetc(fp)) != EOF){ if(c == '\n'){ rc++; break; } } continue; } /* * swallow leading whitespace */ if(!i && isspace((int)c)){ continue; } /* * Check for line continuation. */ if(c == '\\'){ if(fgetc(fp) == '\n'){ rc++; continue; } I2ErrLogP(eh,EINVAL,"Invalid use of \'\\\'"); return -rc; } /* * make sure lbuf is large enough for this content */ if(i+2 > *lbuf_max){ while(i+2 > *lbuf_max){ *lbuf_max += I2LINEBUFINC; } *lbuf = realloc(line,sizeof(char) * *lbuf_max); if(!*lbuf){ if(line){ free(line); } I2ErrLog(eh,"realloc(%u): %M",*lbuf_max); return -rc; } line = *lbuf; } /* * copy char */ line[i++] = c; } if(!i){ return 0; } line[i] = '\0'; if(c == EOF){ rc++; } return rc; } /* * Function: I2ReadConfVar * * Description: * Read the next non-comment line from the config file. The file * should be in the format of: * key [value] [#blah comment] * * key and value are delineated by whitespace. All leading and * trailing whitespace is ignored. A trailing comment is legal and * all charactors between a # and the trailing \n are ignored. * * In Args: * * Out Args: * * Scope: * Returns: * Side Effect: */ int I2ReadConfVar( FILE *fp, int rc, char *key, char *val, size_t max, char **lbuf, size_t *lbuf_max ) { char *line; if((rc = I2GetConfLine(NULL,fp,rc,lbuf,lbuf_max)) > 0){ /* * Pull off key. */ if(!(line = strtok(*lbuf,I2WSPACESET))){ rc = -rc; goto DONE; } /* * Ensure key is not too long. */ if(strlen(line)+1 > max){ rc = -rc; goto DONE; } strcpy(key,line); if((line = strtok(NULL,I2WSPACESET))){ /* * If there is no "value" for this key, then * a comment is valid. */ if(*line == '#'){ val[0] = '\0'; goto DONE; } /* * Ensure value is not too long. */ if(strlen(line)+1 > max){ rc = -rc; goto DONE; } strcpy(val,line); } else{ val[0] = '\0'; } /* * Ensure there is no trailing data */ if((line = strtok(NULL,I2WSPACESET))){ /* * Comments are the only valid token. */ if(*line != '#'){ rc = -rc; } } } DONE: return rc; } /* * This is very similar to I2GetConfLine but does not allow line * continuation - and copies comment/blank lines to tofp. */ static int parsefileline( I2ErrHandle eh, FILE *fp, int rc, char **lbuf, size_t *lbuf_max, FILE *tofp ) { int c; size_t i; char *line = *lbuf; size_t nc=0; /* number of "significant" chars in the line */ size_t ns=0; /* number of leading spaces */ while((c = fgetc(fp)) != EOF){ /* * If c is a newline - increment the row-counter. * If lbuf already has content - break out, otherwise * this was a blank line, continue until there * is content. */ if(c == '\n'){ rc++; if(nc) break; /* don't worry about leading spaces for blank lines */ if(tofp) fprintf(tofp,"\n"); ns=0; continue; } /* * swallow comment lines */ if(!nc && c == '#'){ if(tofp){ /* preserve leading spaces */ for(i=0;i *lbuf_max){ while(nc+2 > *lbuf_max){ *lbuf_max += I2LINEBUFINC; } *lbuf = realloc(line,sizeof(char) * *lbuf_max); if(!*lbuf){ if(line){ free(line); } I2ErrLog(eh,"realloc(%u): %M",*lbuf_max); return -rc; } line = *lbuf; } /* * copy char */ line[nc++] = c; } if(!nc){ return 0; } line[nc] = '\0'; if(c == EOF){ rc++; } return rc; } /* * Function: I2ParseKeyFile * * Description: * Read a single line from a file fp. remove leading whitespace, * skip blank lines and comment lines. Put the result in the * char buffer pointed at by lbuf, growing it as necessary. * * Read a single identity/key from the keyfile. If tofp is set, * then copy all "unmatched" lines from fp to tofp while parsing * the file. If id_query is set, only return the entry that * matches (if any does) skipping all others - and copying them * to tofp if needed. A quick way to simply copy all remaining * records to the tofp is to specify an id_query to a 0 length * string (i.e. id_query[0] == '\0'). * * In Args: * * Out Args: * * Scope: * Returns: * Side Effect: */ int I2ParseKeyFile( I2ErrHandle eh, FILE *fp, int rc, char **lbuf, size_t *lbuf_max, FILE *tofp, const char *id_query, char *id_ret, /* [I2MAXIDENTITYLEN+1] or null */ uint8_t *key_ret /* [I2KEYLEN] or null */ ) { char *line; int i; char rbuf[I2MAXIDENTITYLEN+1]; /* add one extra byte */ char *keystart; uint8_t kbuf[I2KEYLEN]; /* * If there is no keyfile, parsing is very, very fast. */ if(!fp){ return 0; } /* * Fetch each non-blank, non-comment line from the keyfile. * completely validate each line and then determine at the * end of the loop if the caller is interested in this line or not. * (This strict interpretation of the syntax of the keyfile should * help find errors as quickly as possible instead of letting them * hide until they actually bite someone.) */ while((rc = parsefileline(eh,fp,rc,lbuf,lbuf_max,tofp)) > 0){ line = *lbuf; i=0; /* * Can potentially copy I2MAXIDENTITYLEN+1 bytes: rbuf is * sized to handle this and the next 'if' is setup to * detect this error condition. */ while(i <= I2MAXIDENTITYLEN){ if(isspace((int)*line) || (*line == '\0')){ break; } rbuf[i++] = *line++; } if( i > I2MAXIDENTITYLEN){ I2ErrLogP(eh,EINVAL,"Invalid identity name (too long)"); return -rc; } rbuf[i] = '\0'; /* * Get the hexkey */ while(isspace((int)*line)){ line++; } keystart = line; i=0; while(*line != '\0'){ if(isspace((int)*line)){ break; } i++; line++; } /* * If i is not equal to the hex-encoded length of a key... */ if(i != (I2KEYLEN*2)){ I2ErrLogP(eh,EINVAL,"Invalid key length"); return -rc; } /* * Make sure the only thing trailing the key is a comment * or whitespace. */ while(*line != '\0'){ if(*line == '#'){ break; } if(!isspace((int)*line)){ I2ErrLogP(eh,EINVAL,"Invalid chars after key"); return -rc; } line++; } if(!I2HexDecode(keystart,kbuf,I2KEYLEN)){ I2ErrLogP(eh,EINVAL,"Invalid key: not hex?"); return -rc; } /* * If a specific "identity" is being searched for: skip/copy * lines that don't match and continue parsing the file. */ if(id_query && strncmp(rbuf,id_query,I2MAXIDENTITYLEN)){ /* * Write line to tofp, then 'continue' */ if(tofp) fprintf(tofp,"%s\n",*lbuf); continue; } /* * caller is interested in this record - return the values. */ if(id_ret){ strncpy(id_ret,rbuf,sizeof(rbuf)); } if(key_ret){ memcpy(key_ret,kbuf,I2KEYLEN); } break; } return rc; } /* * Function: I2WriteKeyLine * * Description: * * In Args: * * Out Args: * * Scope: * Returns: * Side Effect: */ int I2WriteKeyLine( I2ErrHandle eh, FILE *fp, const char *id, const uint8_t *key ) { int ret; char hbuf[(I2KEYLEN*2)+1]; /* size for hex version */ if(!id || (id[0] == '\0') || (strlen(id) > I2MAXIDENTITYLEN)){ I2ErrLogP(eh,EINVAL,"I2WriteKeyLine(): Invalid identity name"); return -1; } I2HexEncode(hbuf,key,I2KEYLEN); /* * if fprintf has an error, set ret < 0 for a failure return. */ ret = fprintf(fp,"%s\t%s\n",id,hbuf); if(ret > 0) ret = 0; return ret; } /* * Function: I2ParsePFFile * * Description: * Read a single line from a file fp. remove leading whitespace, * skip blank lines and comment lines. Put the result in the * char buffer pointed at by lbuf, growing it as necessary. * * Read a single identity/pass-phrase from the pffile. If tofp * is set, then copy all "unmatched" lines from fp to tofp while * parsing the file. If id_query is set, only return the entry that * matches (if any does) skipping all others - and copying them * to tofp if needed. A quick way to simply copy all remaining * records to the tofp is to specify an id_query to a 0 length * string (i.e. id_query[0] == '\0'). * * The entry that is returned currently breaks the line, so * *lbuf can not just be written back to the file directly. * * In Args: * * Out Args: * * Scope: * Returns: * Side Effect: */ int I2ParsePFFile( I2ErrHandle eh, FILE *filep, FILE *tofilep, int rc, const char *id_query, char **id_ret, /* points in lbuf */ char **pf_ret, /* points in lbuf */ size_t *pf_len, char **lbuf, size_t *lbuf_max ) { char *line; char *ts; char *hex; char *pf; size_t id_len; size_t hex_len; size_t idq_len; size_t hex_oset; /* * If there is no pffile, parsing is very, very fast. */ if(!filep){ return 0; } if(id_query){ idq_len = strlen(id_query); } /* * Fetch each non-blank, non-comment line from the pffile. * * Completely validate each line and then determine at the * end of the loop if the caller is interested in this line or not. * (This strict interpretation of the syntax of the pffile should * help find errors as quickly as possible instead of letting them * hide until they actually bite someone.) * * Valid syntax is: * */ while((rc = parsefileline(eh,filep,rc,lbuf,lbuf_max,tofilep)) > 0){ size_t used,needed; /* * line starts with id */ line = *lbuf; /* * Find beginning of hex-pf */ id_len = strcspn(line,I2WSPACESET); hex = line + id_len; /* * Must be at least one space separator */ if(!isspace((int)*hex)){ return -rc; } /* * If a specific "identity" is being searched for: skip/copy * lines that don't match and continue parsing the file. */ if(id_query && ((idq_len == 0) || strncmp(line,id_query,MIN(id_len,idq_len)))){ /* * Write line to tofilep, then 'continue' */ if(tofilep) fprintf(tofilep,"%s\n",*lbuf); continue; } /* Terminate id, then eat trailing white-space */ *hex = '\0'; hex++; while(isspace((int)*hex)){ hex++; } hex_oset = hex - line; /* how long is the hex-pf */ hex_len = strcspn(hex,I2WSPACESET); /* * eat trailing white-space - and terminate hex-pf */ ts = hex + hex_len; while(isspace((int)*ts)){ *ts = '\0'; ts++; } /* * hex can not be nul, must be multiple of 2, * and must be the last thing on the line. */ if(!hex_len || (hex_len % 2) || (*ts != '\0')){ return -rc; } /* * Make sure there is enough room after full line in lbuf to hold * return pf. (ts currently points at the terminating nul * byte for the full line.) */ used = (ts - *lbuf) + 1; needed = (hex_len / 2); /* * make sure lbuf is large enough for this content */ if((used + needed) > *lbuf_max){ while((used + needed) > *lbuf_max){ *lbuf_max += I2LINEBUFINC; } *lbuf = realloc(line,sizeof(char) * *lbuf_max); if(!*lbuf){ if(line){ free(line); } I2ErrLog(eh,"realloc(%u): %M",*lbuf_max); return -rc; } line = *lbuf; } /* * Terminate id, and point pf to beginning of binary pf * to be returned. */ hex = line + hex_oset; pf = line + used; if(!I2HexDecode(hex,(uint8_t *)pf,hex_len/2)){ I2ErrLogP(eh,EINVAL,"Invalid key: not hex?"); return -rc; } if(id_ret){ *id_ret = line; } if(pf_ret){ *pf_ret = pf; } if(pf_len){ *pf_len = hex_len/2; } break; } return rc; } /* * Function: I2WritePFLine * * Description: * * In Args: * * Out Args: * * Scope: * Returns: * Side Effect: */ int I2WritePFLine( I2ErrHandle eh, FILE *fp, const char *id, /* nul terminated */ const uint8_t *bytes, size_t nbytes, char **lbuf, /* memory for hex string */ size_t *lbuf_max ) { int ret; char *line = *lbuf; if(!id || (id[0] == '\0')){ I2ErrLogP(eh,EINVAL,"I2WriteKeyLine(): Invalid identity name"); return -1; } /* * make sure lbuf is large enough for this content */ if((nbytes*2 + 1) > *lbuf_max){ while((nbytes*2 + 1) > *lbuf_max){ *lbuf_max += I2LINEBUFINC; } *lbuf = realloc(line,sizeof(char) * *lbuf_max); if(!*lbuf){ if(line){ free(line); } I2ErrLog(eh,"realloc(%u): %M",*lbuf_max); return -1; } line = *lbuf; } I2HexEncode(line,bytes,nbytes); /* * if fprintf has an error, set ret < 0 for a failure return. */ ret = fprintf(fp,"%s\t%s\n",id,line); if(ret > 0) ret = 0; return ret; } /* * Function: I2StrToNum * * Description: * * In Args: * * Out Args: * * Scope: * Returns: * Side Effect: */ int I2StrToNum( I2numT *limnum, char *limstr ) { size_t silen=0; size_t len; char *endptr; I2numT ret, mult=1; while(isdigit((int)limstr[silen])){ silen++; } len = strlen(limstr); if(len != silen){ /* * Ensure that there is at most one non-digit and that it * is the last char. */ if((len - silen) > 1){ return -1; } switch (tolower(limstr[silen])){ case 'z': mult *= 1000; /* 1e21 */ case 'e': mult *= 1000; /* 1e18 */ case 'p': mult *= 1000; /* 1e15 */ case 't': mult *= 1000; /* 1e12 */ case 'g': mult *= 1000; /* 1e9 */ case 'm': mult *= 1000; /* 1e6 */ case 'k': mult *= 1000; /* 1e3 */ break; default: return -1; /* UNREACHED */ } limstr[silen] = '\0'; } ret = strtoull(limstr, &endptr, 10); if(endptr != &limstr[silen]){ return -1; } if(ret == 0){ *limnum = 0; return 0; } /* Check for overflow. */ *limnum = ret * mult; return ((*limnum)/mult != ret)? (-1) : 0; } /* * Function: I2StrToByte * * Description: * * In Args: * * Out Args: * * Scope: * Returns: * Side Effect: */ int I2StrToByte( I2numT *limnum, char *limstr ) { size_t silen=0; size_t len; char *endptr; I2numT ret, mult=1; while(isdigit((int)limstr[silen])){ silen++; } len = strlen(limstr); if(len != silen){ /* * Ensure that there is at most one non-digit and that it * is the last char. */ if((len - silen) > 1){ return -1; } switch (tolower(limstr[silen])){ case 'z': mult <<= 10; case 'e': mult <<= 10; case 'p': mult <<= 10; case 't': mult <<= 10; case 'g': mult <<= 10; case 'm': mult <<= 10; case 'k': mult <<= 10; break; default: return -1; /* UNREACHED */ } limstr[silen] = '\0'; } ret = strtoull(limstr, &endptr, 10); if(endptr != &limstr[silen]){ return -1; } if(ret == 0){ *limnum = 0; return 0; } /* Check for overflow. */ *limnum = ret * mult; return ((*limnum/mult) != ret)? (-1) : 0; } i2util-1.6/I2util/conf.h000066400000000000000000000067011276605416600150570ustar00rootroot00000000000000/* * $Id$ */ /************************************************************************ * * * Copyright (C) 2003 * * Internet2 * * All Rights Reserved * * * ************************************************************************/ /* * File: conf.h * * Author: Jeff W. Boote * Internet2 * * Date: Tue Sep 16 14:28:48 MDT 2003 * * Description: * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #ifndef _i2_conf_h_ #define _i2_conf_h_ #include #include /* * Growth increment for linebuffer. */ #define I2LINEBUFINC (120) /* * same charactors isspace checks for - useful for strtok splits * of whitespace. */ #define I2WSPACESET "\t\n\v\f\r " /* * Maximum "identity"/"username" charactor length */ #define I2MAXIDENTITYLEN (16) /* * Length of a key in bytes. */ #define I2KEYLEN (16) extern int I2GetConfLine( I2ErrHandle eh, FILE *fp, int rc, char **lbuf, size_t *lbuf_max ); extern int I2ReadConfVar( FILE *fp, int rc, char *key, char *val, size_t max, char **lbuf, size_t *lbuf_max ); /* * lbuf will contain an undisturbed copy of the last line to be parsed in * the file. (It is the callers responsibility to free the memory pointed * to by lbuf after calling this function.) * */ extern int I2ParseKeyFile( I2ErrHandle eh, FILE *fp, int rc, char **lbuf, size_t *lbuf_max, FILE *tofp, /* copy 'to' file, or null */ const char *id_query, char *id_ret, /* [I2MAXIDENTITYLEN+1] or null */ uint8_t *key_ret /* [I2KEYLEN] or null */ ); extern int I2WriteKeyLine( I2ErrHandle eh, FILE *fp, const char *id, /* no more than [I2MAXIDENTITYLEN+1] */ const uint8_t *key /* [I2KEYLEN] */ ); /* * lbuf will NOT contain an undisturbed copy of the last line to be parsed in * the file. lbuf is just a memory buffer to be used by the function, and * realloc'd as needed. * * It is the callers responsibility to free the memory pointed * to by lbuf after calling this function. * */ extern int I2ParsePFFile( I2ErrHandle eh, FILE *fp, FILE *tofp, int rc, const char *id_query, char **id_ret, /* nul terminated, points in lbuf */ char **pf_ret, /* points in lbuf */ size_t *pf_len, char **lbuf, size_t *lbuf_max ); /* * lbuf has same semantics as above, caller must free memory eventually. */ extern int I2WritePFLine( I2ErrHandle eh, FILE *fp, const char *id, const uint8_t *bytes, size_t nbytes, char **lbuf, size_t *lbuf_max ); typedef uint64_t I2numT; /* * These two functions are destructive to the passed in string. * StrToNum interprets k/m/g as base 10 numbers, * StrToBytes interprets k == 1024 etc... */ extern int I2StrToNum( I2numT *numret, char *str ); extern int I2StrToByte( I2numT *numret, char *str ); #endif /* _i2_conf_h_ */ i2util-1.6/I2util/errlog.h000066400000000000000000000104061276605416600154210ustar00rootroot00000000000000/* * $Id$ */ /************************************************************************ * * * Copyright (C) 2002 * * Internet2 * * All Rights Reserved * * * ************************************************************************/ /* * File: errlog.h * * Author: Jeff Boote * Internet2 * * Date: Tue Apr 23 14:21:24 2002 * * Description: * Generic Error logging API. * * Modified from code writen by John Clyne at UCAR... * * Based on code from UCAR DCS tools. Copyright information * from UCAR follows: * * Copyright 2012, University Corporation for Atmospheric Research. * * This software may be used, subject to the terms of OSI's BSD-2 Clause * License located at http://www.opensource.org/licenses/bsd-license.php/ */ #ifndef _i2_errlog_h_ #define _i2_errlog_h_ #include #include #include #include #include BEGIN_C_DECLS /* * TODO: Verify that this is a portable constant to use for LOG_PERROR... */ #ifndef LOG_PERROR #define LOG_PERROR 0x20 #endif #define I2NAME (1L << 0) #define I2FILE (1L << 1) #define I2LINE (1L << 2) #define I2DATE (1L << 3) #define I2RTIME (1L << 4) #define I2MSG (1L << 5) #define I2CODE (1L << 6) #define I2LEVEL (1L << 7) #define I2NONL (1L << 8) /* basically used to disable syslog messages, but will work for others. */ /* set as "priority" to disable *ALL* syslog messages */ #define I2LOG_NONE 8 /* Used as "no error" code. */ #define I2EUNKNOWN 0 /* * mask is bitwise OR of above bitmasks indicating which of the * remaining fields are valid. * (setting level to a negative number disables logging entirely.) */ struct I2ErrLogEvent{ int mask; const char *name; /* I2NAME */ const char *file; /* I2FILE */ int line; /* I2LINE */ const char *date; /* I2DATE */ int code; /* I2CODE */ int level; /* I2LEVEL - matches Syslog priority */ const char *msg; /* I2MSG */ }; typedef void *I2ErrHandle; typedef void (*I2ErrLogFuncPtr) ( /* client logging function */ struct I2ErrLogEvent *err_event, void *arg, void **data ); typedef I2Boolean (*I2ErrLogResetFuncPtr)( /* reset logging function*/ void *arg, void **data ); typedef char *(*I2ErrRetrieveFuncPtr)( /* client fetch func */ void *arg, void **data ); /* * extern void I2ErrLog(eh,fmt,...); */ #define I2ErrLog I2ErrLocation_(__FILE__, __DATE__, __LINE__); \ I2ErrLogFunction_ /* * extern void I2ErrLogP(eh,err_code,fmt,...); */ #define I2ErrLogP I2ErrLocation_(__FILE__, __DATE__, __LINE__); \ I2ErrLogPFunction_ /* * extern void I2ErrLogT(eh,err_level,err_code,fmt,...); */ #define I2ErrLogT I2ErrLocation_(__FILE__,__DATE__,__LINE__); \ I2ErrLogTFunction_ extern I2ErrHandle I2ErrOpen( const char *program_name, I2ErrLogFuncPtr log_func, void *log_func_arg, I2ErrRetrieveFuncPtr retrieve_func, void *retrieve_func_arg ); extern void I2ErrSetResetFunc( I2ErrHandle eh, I2ErrLogResetFuncPtr reset_func ); /* * If the ErrReset function fails, this will return NULL - and the * ErrHandle will be invalid. */ extern I2ErrHandle I2ErrReset( I2ErrHandle eh ); extern void I2ErrClose(I2ErrHandle dpeh); extern void I2ErrRep( I2ErrHandle dpeh, FILE *fp ); extern char *I2ErrGetMsg( I2ErrHandle dpeh ); extern int I2ErrGetCode( I2ErrHandle dpeh ); extern void I2ErrLocation_( const char *file, const char *date, int line ); /* * Function: I2ErrLogVT * * Description: * * In Args: * (setting level to a negative number disables logging entirely.) * * Out Args: * * Scope: * Returns: * Side Effect: */ extern void I2ErrLogVT( I2ErrHandle dpeh, int level, int code, const char *format, va_list ap ); extern void I2ErrLogFunction_( I2ErrHandle dpeh, const char *format, ... ); extern void I2ErrLogPFunction_( I2ErrHandle dpeh, int err_code, const char *format, ... ); extern void I2ErrLogTFunction_( I2ErrHandle dpeh, int priority, int err_code, const char *format, ... ); extern int I2ErrList( I2ErrHandle dpeh, unsigned start, unsigned num, const char * const *err_list ); END_C_DECLS #include #include #endif /* _i2_errlog_h_ */ i2util-1.6/I2util/errlogimmediate.h000066400000000000000000000024351276605416600173030ustar00rootroot00000000000000/* * $Id$ */ /************************************************************************ * * * Copyright (C) 2002 * * Internet2 * * All Rights Reserved * * * ************************************************************************/ /* * File: errlogimmediate.h * * Author: Jeff Boote * Internet2 * * Date: Tue Apr 23 14:44:22 2002 * * Description: This file defines an "immediate-mode" logging * function to be used as the `log_func' argument * to the I2OpenErr() function. * * Modified from code writen by John Clyne at UCAR... * * * Based on code from UCAR DCS tools. Copyright information * from UCAR follows: * * Copyright 2012, University Corporation for Atmospheric Research. * * This software may be used, subject to the terms of OSI's BSD-2 Clause * License located at http://www.opensource.org/licenses/bsd-license.php/ * */ #ifndef _i2_errlogimmediate_h_ #define _i2_errlogimmediate_h_ #include BEGIN_C_DECLS typedef struct I2LogImmediateAttr_ { FILE *fp; unsigned long line_info; const char *tformat; } I2LogImmediateAttr; extern void I2ErrLogImmediate( struct I2ErrLogEvent *ev, void *arg, void **data /* not used */ ); END_C_DECLS #endif /* _i2_errlogimmediate_h_ */ i2util-1.6/I2util/errlogsyslog.h000066400000000000000000000027271276605416600166710ustar00rootroot00000000000000/* * $Id$ */ /************************************************************************ * * * Copyright (C) 2002 * * Internet2 * * All Rights Reserved * * * ************************************************************************/ /* * File: errlogsyslog.h * * Author: Jeff Boote * Internet2 * * Date: Tue Apr 23 14:35:40 2002 * * Description: * Modified from code writen by John Clyne at UCAR... * * * Based on code from UCAR DCS tools. Copyright information * from UCAR follows: * * Copyright 2012, University Corporation for Atmospheric Research. * * This software may be used, subject to the terms of OSI's BSD-2 Clause * License located at http://www.opensource.org/licenses/bsd-license.php/ * */ #ifndef _i2_errlogsyslog_h_ #define _i2_errlogsyslog_h_ BEGIN_C_DECLS typedef struct I2ErrLogSyslogAttr_ { const char *ident; int logopt; int facility; int priority; int report_level; unsigned long line_info; const char *tformat; } I2ErrLogSyslogAttr; extern void I2ErrLogSyslog( struct I2ErrLogEvent *ev, void *arg, void **data ); extern I2Boolean I2ErrLogSyslogReset( void *arg, void **data ); extern int I2ErrLogSyslogFacility( const char *name ); const char *I2ErrLogSyslogFacilityName( int fac ); extern int I2ErrLogSyslogPriority( const char *name ); const char *I2ErrLogSyslogPriorityName( int prio ); END_C_DECLS #endif /* _i2_errlogsyslog_h_ */ i2util-1.6/I2util/hex.c000066400000000000000000000047301276605416600147110ustar00rootroot00000000000000/* * $Id$ */ /************************************************************************ * * * Copyright (C) 2003 * * Internet2 * * All Rights Reserved * * * ************************************************************************/ /* * File: hex.c * * Author: Jeff W. Boote * Internet2 * * Date: Tue Dec 16 15:45:00 MST 2003 * * Description: * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #include #include /* * buff must be at least (nbytes*2) +1 long or memory will be over-run. */ void I2HexEncode( char *buff, const uint8_t *bytes, size_t nbytes ) { char hex[]="0123456789abcdef"; size_t i; for(i=0;i> 4]; *buff++ = hex[*bytes++ & 0x0f]; } *buff = '\0'; } /* * Function: I2HexDecode * * Description: * Decode hex chars into bytes. Return True on success, False on error. * * It is valid to pass the same memory in for buff and bytes. On * input buff should hold the hex encoded string, on output the * memory will hold the bytes. (It will take half the memory...) * * In Args: * * Out Args: * * Scope: * Returns: * Side Effect: */ I2Boolean I2HexDecode( const char *buff, uint8_t *bytes, size_t nbytes ) { char hex[]="0123456789abcdef"; unsigned int i,j,offset; char a; uint8_t byte; for(i=0;i #include /* * Function: I2HexEncode * * takes 'nbytes' in 'bytes' and returns a hex representation of them in 'buff'. * * buff must be at least (nbytes*2)+1 in size or memory will overrun. */ extern void I2HexEncode( char *hexstr, const uint8_t *bytes, size_t nbytes ); /* * Function: I2HexDecode * * Decode hex chars into bytes. Return True on success, False on error. */ extern I2Boolean I2HexDecode( const char *hexstr, uint8_t *bytes, size_t nbytes ); #endif /* _i2_hex_h_ */ i2util-1.6/I2util/hmac-sha1.c000066400000000000000000000160131276605416600156640ustar00rootroot00000000000000/* * ex: set tabstop=4 ai expandtab softtabstop=4 shiftwidth=4: * -*- mode: c-basic-indent: 4; tab-width: 4; indent-tabls-mode: nil -*- * $Id$ */ /************************************************************************ * * * Copyright (C) 2006 * * Internet2 * * All Rights Reserved * * * ************************************************************************/ /* * File: hmac-sha1.c * * Author: Jeff W. Boote * Internet2 * * Date: Sat Oct 07 12:35:24 MDT 2006 * * Description: * HMAC-SHA1 implementation. From rfc2104: * 2. Definition of HMAC * * The definition of HMAC requires a cryptographic hash function, which * we denote by H, and a secret key K. We assume H to be a cryptographic * hash function where data is hashed by iterating a basic compression * function on blocks of data. We denote by B the byte-length of such * blocks (B=64 for all the above mentioned examples of hash functions), * and by L the byte-length of hash outputs (L=16 for MD5, L=20 for * SHA-1). The authentication key K can be of any length up to B, the * block length of the hash function. Applications that use keys longer * than B bytes will first hash the key using H and then use the * resultant L byte string as the actual key to HMAC. In any case the * minimal recommended length for K is L bytes (as the hash output * length). See section 3 for more information on keys. * * We define two fixed and different strings ipad and opad as follows * (the 'i' and 'o' are mnemonics for inner and outer): * * ipad = the byte 0x36 repeated B times * opad = the byte 0x5C repeated B times. * * To compute HMAC over the data `text' we perform * * H(K XOR opad, H(K XOR ipad, text)) * * Namely, * * (1) append zeros to the end of K to create a B byte string * (e.g., if K is of length 20 bytes and B=64, then K will be * appended with 44 zero bytes 0x00) * (2) XOR (bitwise exclusive-OR) the B byte string computed in step * (1) with ipad * (3) append the stream of data 'text' to the B byte string resulting * from step (2) * (4) apply H to the stream generated in step (3) * (5) XOR (bitwise exclusive-OR) the B byte string computed in * step (1) with opad * (6) append the H result from step (4) to the B byte string * resulting from step (5) * (7) apply H to the stream generated in step (6) and output * the result * * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #include #include #include #include #include /* * The opad is computed using the key during init. It is not used until * 'final' after that. ipad is used to generate the 'inner' sha1 hash. * This is stored in sha1 until 'final' when the hash is generated, and then * the sha1 is reinitialized to generate the 'outer' hash value. */ struct I2HMACSha1ContextRec{ I2ErrHandle eh; I2Sha1Context sha1; uint8_t opad[I2SHA1_BLOCK_SIZE]; }; I2HMACSha1Context I2HMACSha1Alloc( I2ErrHandle eh ) { I2HMACSha1Context hmac = (I2HMACSha1Context)calloc(1, sizeof(struct I2HMACSha1ContextRec)); if(hmac){ hmac->sha1 = I2Sha1Alloc(eh); } if(!hmac || !hmac->sha1){ I2ErrLogT(eh,LOG_ERR,errno, ": calloc(1,%d): %M",sizeof(struct I2HMACSha1ContextRec)); return NULL; } hmac->eh = eh; return hmac; } void I2HMACSha1Free( I2HMACSha1Context hmac ) { if(!hmac) return; I2Sha1Free(hmac->sha1); free(hmac); return; } void I2HMACSha1Init( I2HMACSha1Context hmac, const uint8_t *inkey, uint32_t len ) { uint8_t ipad[I2SHA1_BLOCK_SIZE]; uint8_t key[I2SHA1_BLOCK_SIZE]; uint32_t keylen; uint32_t i; assert(hmac); assert(hmac->sha1); memset(key,0x00,I2SHA1_BLOCK_SIZE); memset(ipad,0x36,I2SHA1_BLOCK_SIZE); memset(hmac->opad,0x5c,I2SHA1_BLOCK_SIZE); /* * If the key is larger than the hash block size, then hash it and * use the hash value as the key. */ if(len > I2SHA1_BLOCK_SIZE){ I2Sha1(inkey,len,key); keylen = I2SHA1_DIGEST_SIZE; } else{ memcpy(key,inkey,len); keylen = len; } /* * Now do the XOR for ipad and opad. opad will be used later - ipad * will be used as the first data to be hashed by sha1. */ for(i=0; i< I2SHA1_BLOCK_SIZE; i++){ ipad[i] ^= key[i]; hmac->opad[i] ^= key[i]; } I2Sha1Init(hmac->sha1); I2Sha1Append(hmac->sha1,ipad,I2SHA1_BLOCK_SIZE); return; } void I2HMACSha1Append( I2HMACSha1Context hmac, const uint8_t *txt, uint32_t len ) { assert(hmac); assert(txt); assert(len); I2Sha1Append(hmac->sha1,txt,len); } void I2HMACSha1Finish( I2HMACSha1Context hmac, uint8_t *digest_ret /* I2HMAC_SHA1_DIGEST_SIZE */ ) { uint8_t opad_digest[I2SHA1_DIGEST_SIZE]; assert(hmac); /* * Get the inner-pad digest */ I2Sha1Finish(hmac->sha1,opad_digest); /* * Reset the sha1 to use for computing the outer-pad digest */ I2Sha1Init(hmac->sha1); I2Sha1Append(hmac->sha1,hmac->opad,I2SHA1_BLOCK_SIZE); I2Sha1Append(hmac->sha1,opad_digest,I2SHA1_DIGEST_SIZE); I2Sha1Finish(hmac->sha1,digest_ret); /* * clean heap */ memset(opad_digest,0,I2SHA1_DIGEST_SIZE); return; } void I2HMACSha1( const uint8_t *key, uint32_t keylen, const uint8_t *txt, uint32_t txtlen, uint8_t *digest_ret ) { /* * Don't really do an alloc - just create the record on the stack * (this means */ struct I2Sha1ContextRec sha1rec; struct I2HMACSha1ContextRec hmacrec; I2HMACSha1Context hmac; memset((void*)&sha1rec,0,sizeof(sha1rec)); memset((void*)&hmacrec,0,sizeof(hmacrec)); hmacrec.sha1 = &sha1rec; hmac = &hmacrec; I2HMACSha1Init(hmac,key,keylen); I2HMACSha1Append(hmac,txt,txtlen); I2HMACSha1Finish(hmac,digest_ret); return; } i2util-1.6/I2util/hmac-sha1.h000066400000000000000000000046731276605416600157020ustar00rootroot00000000000000/* * ex: set tabstop=4 ai expandtab softtabstop=4 shiftwidth=4: * -*- mode: c-basic-indent: 4; tab-width: 4; indent-tabls-mode: nil -*- * $Id$ */ /************************************************************************ * * * Copyright (C) 2006 * * Internet2 * * All Rights Reserved * * * ************************************************************************/ /* * File: hmac-sha1.h * * Author: Jeff W. Boote * Internet2 * * Date: Sat Oct 07 12:33:33 MDT 2006 * * Description: * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #ifndef I2HMAC_SHA1_H #define I2HMAC_SHA1_H #include #include BEGIN_C_DECLS #define I2HMAC_SHA1_DIGEST_SIZE 20 #define I2HMAC_SHA1_BLOCK_SIZE 64 struct I2HMACSha1ContextRec; typedef struct I2HMACSha1ContextRec *I2HMACSha1Context; extern I2HMACSha1Context I2HMACSha1Alloc( I2ErrHandle eh ); extern void I2HMACSha1Free( I2HMACSha1Context hmac ); extern void I2HMACSha1Init( I2HMACSha1Context hmac, const uint8_t *key, uint32_t len ); extern void I2HMACSha1Append( I2HMACSha1Context hmac, const uint8_t *txt, uint32_t len ); extern void I2HMACSha1Finish( I2HMACSha1Context hmac, uint8_t *digest_ret /* I2HMAC_SHA1_DIGEST_SIZE */ ); extern void I2HMACSha1( const uint8_t *key, uint32_t keylen, const uint8_t *txt, uint32_t txtlen, uint8_t *digest_ret ); END_C_DECLS #endif /* I2HMAC_SHA1_H */ i2util-1.6/I2util/io.c000066400000000000000000000141601276605416600145320ustar00rootroot00000000000000/* ** $Id$ */ /************************************************************************ * * * Copyright (C) 2002 * * Internet2 * * All Rights Reserved * * * ************************************************************************/ /* ** File: io.c ** ** Author: Anatoly Karp ** Jeff W. Boote ** ** Date: Wed Apr 24 10:42:12 2002 ** ** Description: This file contains the private functions to ** to facilitate IO that the library needs to do. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #include #include #include #include #include #include #include #include /* * Function: I2Readni * * Description: * Read n bytes from the given fd. If !*retn_on_intr - then the function * will continue to read even through interupts. (This is set to a * pointer value so it can be modified via a signal handler. So, you * can make this function return based on signals you care about.) * * If this function returns due to an interrupt - *retn_on_intr will * be non-zero (although this function won't modify the value). And, * this function will return -1. errno will also be set to EINTR. * * This function will return -1 for all other error conditions * as well. (and errno will be set) * * Short reads returned indicate the fd has reached EOF. (i.e. the * socket is closed if fd is attached to a socket) * * In Args: * * Out Args: * * Scope: * Returns: * Side Effect: */ ssize_t I2Readni( int fd, void *vptr, size_t n, int *retn_on_intr /* pointer so it can be modified via signals */ ) { size_t nleft; ssize_t nread; char *ptr; ptr = vptr; nleft = n; while(nleft > 0){ if((nread = read(fd, ptr, nleft)) < 0){ if((errno == EINTR) && !*retn_on_intr){ /* call read again */ nread = 0; } else{ return(-1); } } else if(nread == 0){ /* EOF */ break; } nleft -= nread; ptr += nread; } return(n - nleft); /* return >= 0 */ } /* * Function: I2Readn * * Description: * Wrapper function for I2Readni if you really don't ever want to * return early from read due to an interrupt. * * In Args: * * Out Args: * * Scope: * Returns: * Side Effect: */ ssize_t I2Readn( int fd, void *vptr, size_t n ) { int intr=0; return I2Readni(fd,vptr,n,&intr); } /* * Function: I2Writeni * * Description: * Write n bytes to the given fd. If !*retn_on_intr - then the function * will continue to write even through interupts. (This is set to a * pointer value so it can be modified via a signal handler. So, you * can make this function return based on signals you care about.) * * If this function returns due to an interrupt - *retn_on_intr will * be non-zero (although this function won't modify the value). And, * this function will return -1. errno will also be set to EINTR. * * This function will return -1 for all other error conditions * as well. (and errno will be set) * * Short reads returned indicate the fd has reached EOF. (i.e. the * socket is closed if fd is attached to a socket) * * * In Args: * * Out Args: * * Scope: * Returns: * Side Effect: */ ssize_t I2Writeni( int fd, const void *vptr, size_t n, int *retn_on_intr ) { size_t nleft; ssize_t nwritten; const char *ptr; ptr = vptr; nleft = n; while(nleft > 0){ if((nwritten = write(fd, ptr, nleft)) <= 0){ if((errno == EINTR) && !*retn_on_intr){ /* call write again */ nwritten = 0; } else{ return(-1); } } nleft -= nwritten; ptr += nwritten; } return(n); } /* * Function: I2Writen * * Description: * Wrapper function for I2Writeni if you really don't ever want to * return early from write due to an interrupt. * * In Args: * * Out Args: * * Scope: * Returns: * Side Effect: */ ssize_t I2Writen( int fd, const void *vptr, size_t n ) { int intr=0; return I2Writeni(fd,vptr,n,&intr); } /* * Function: I2CopyFile * * Description: * Copy one file to another using mmap for speed. * * In Args: * * Out Args: * * Scope: * Returns: * 0 on success * Side Effect: */ int I2CopyFile( I2ErrHandle eh, int tofd, int fromfd, size_t len ) { struct stat sbuf; int rc; void *fptr,*tptr; size_t sbufsize; if((rc = fstat(fromfd,&sbuf)) != 0){ I2ErrLog(eh,"I2CopyFile: fstat: %M, status of from file"); return rc; } sbufsize = (size_t)sbuf.st_size; if(sbuf.st_size != (off_t)sbufsize){ I2ErrLog(eh,"I2CopyFile: filesystem blocksize too large for mmap"); return -1; } if(len == 0){ len = sbufsize; } else{ len = MIN(len,sbufsize); } if((rc = ftruncate(tofd,(off_t)len)) != 0){ I2ErrLog(eh,"I2CopyFile: ftrunctate(%llu): %M, sizing to file",len); return rc; } fptr = mmap(NULL,len,PROT_READ|PROT_WRITE,MAP_SHARED,fromfd,(off_t)0); if(fptr == MAP_FAILED){ I2ErrLog(eh,"I2CopyFile: mmap(from file): %M"); return -1; } tptr = mmap(NULL,len,PROT_READ|PROT_WRITE,MAP_SHARED,tofd,(off_t)0); if(tptr == MAP_FAILED){ I2ErrLog(eh,"I2CopyFile: mmap(to file): %M"); return -1; } memcpy(tptr,fptr,len); if((rc = munmap(fptr,len)) != 0){ I2ErrLog(eh,"I2CopyFile: munmap(from file): %M"); return -1; } if((rc = munmap(tptr,len)) != 0){ I2ErrLog(eh,"I2CopyFile: munmap(to file): %M"); return -1; } return 0; } i2util-1.6/I2util/io.h000066400000000000000000000030621276605416600145360ustar00rootroot00000000000000/* * $Id$ */ /************************************************************************ * * * Copyright (C) 2002 * * Internet2 * * All Rights Reserved * * * ************************************************************************/ /* * File: io.h * * Author: Jeff W. Boote * Internet2 * * Date: Fri Aug 09 12:53:52 MDT 2002 * * Description: * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #ifndef _i2_io_h_ #define _i2_io_h_ #include #include BEGIN_C_DECLS extern ssize_t I2Readni( int fd, void *vptr, size_t n, int *retn_on_intr /* pointer so it can be modified via signals */ ); extern ssize_t I2Readn( int fd, void *vptr, size_t n ); extern ssize_t I2Writeni( int fd, const void *vptr, size_t n, int *retn_on_intr ); extern ssize_t I2Writen( int fd, const void *vptr, size_t n ); extern int I2CopyFile( I2ErrHandle eh, int tofd, int fromfd, size_t len ); END_C_DECLS #endif /* _i2_io_h_ */ i2util-1.6/I2util/mach_dep.c000066400000000000000000000047331276605416600156700ustar00rootroot00000000000000/* * $Id$ */ /************************************************************************ * * * Copyright (C) 2002 * * Internet2 * * All Rights Reserved * * * ************************************************************************/ /* * File: mach_dep.c * * Author: Jeff Boote * Internet2 * * Date: Wed Apr 24 11:36:34 2002 * * Description: This module attempts to isolate all machine * dependencies from platform to platform. * * Based on code from UCAR DCS tools. Copyright information * from UCAR follows: * * Copyright 2012, University Corporation for Atmospheric Research. * * This software may be used, subject to the terms of OSI's BSD-2 Clause * License located at http://www.opensource.org/licenses/bsd-license.php/ */ #include #include #include #include #include #include #include #if !defined(HAVE_DECL_SYS_NERR) || !HAVE_DECL_SYS_NERR static I2ThreadMutex_T MyMutex = I2PTHREAD_MUTEX_INITIALIZER; #endif /* ** Function: I2GetSysErrList() ** ** Description: Return the list of system error messages associated with ** `errno'. The contents of the list returned by this function ** should be copied into applicaiton memory. ** ** In Args: ** ** count A pointer to an integer. ** ** Out Args: ** ** count Pointer to an integer indicating the number of ** entries in the list returned by I2GetSysErrList() ** ** Return Values: ** ** I2GetSysErrList() returns an array of character ** strings. ** ** Side Effects: */ const char * const *I2GetSysErrList( int *count ) { /* * The ANSI Standard does not define the globals `sys_nerr' * and `sys_errlist'. Sigh. Hence there is no real way to * determine the range valid values of `errno'. * Guess large and loop calling strerror... * NUM_ERRORS should be the "largest" errno number for all the * systems we care about. */ #if !defined(HAVE_DECL_SYS_NERR) || !HAVE_DECL_SYS_NERR #define NUM_ERRORS 152 const int sys_nerr = NUM_ERRORS; static char *sys_errlist[NUM_ERRORS]; static int first = 1; int i; /* ** Build the `sys_errlist' for Solaris systems. We only need ** to do this once since the table is immutable */ I2ThreadMutexLock(&MyMutex); if (first) { for(i=0; i * * This software was written by Alexander Peslyak in 2001. No copyright is * claimed, and the software is hereby placed in the public domain. * In case this attempt to disclaim copyright and place the software in the * public domain is deemed null and void, then the software is * Copyright (c) 2001 Alexander Peslyak and it is hereby released to the * general public under the following terms: * * Redistribution and use in source and binary forms, with or without * modification, are permitted. * * There's ABSOLUTELY NO WARRANTY, express or implied. * * (This is a heavily cut-down "BSD license".) * * This differs from Colin Plumb's older public domain implementation in that * no exactly 32-bit integer data type is required (any 32-bit or wider * unsigned integer data type will do), there's no compile-time endianness * configuration, and the function prototypes match OpenSSL's. No code from * Colin Plumb's implementation has been reused; this comment merely compares * the properties of the two independent implementations. * * The primary goals of this implementation are portability and ease of use. * It is meant to be fast, but not as fast as possible. Some known * optimizations are not included to reduce source code size and avoid * compile-time configuration. */ #ifndef HAVE_OPENSSL #include #include "md5.h" /* * The basic MD5 functions. * * F and G are optimized compared to their RFC 1321 definitions for * architectures that lack an AND-NOT instruction, just like in Colin Plumb's * implementation. */ #define F(x, y, z) ((z) ^ ((x) & ((y) ^ (z)))) #define G(x, y, z) ((y) ^ ((z) & ((x) ^ (y)))) #define H(x, y, z) ((x) ^ (y) ^ (z)) #define I(x, y, z) ((y) ^ ((x) | ~(z))) /* * The MD5 transformation for all four rounds. */ #define STEP(f, a, b, c, d, x, t, s) \ (a) += f((b), (c), (d)) + (x) + (t); \ (a) = (((a) << (s)) | (((a) & 0xffffffff) >> (32 - (s)))); \ (a) += (b); /* * SET reads 4 input bytes in little-endian byte order and stores them * in a properly aligned word in host byte order. * * The check for little-endian architectures that tolerate unaligned * memory accesses is just an optimization. Nothing will break if it * doesn't work. */ #if defined(__i386__) || defined(__x86_64__) || defined(__vax__) #define SET(n) \ (*(MD5_u32plus *)&ptr[(n) * 4]) #define GET(n) \ SET(n) #else #define SET(n) \ (ctx->block[(n)] = \ (MD5_u32plus)ptr[(n) * 4] | \ ((MD5_u32plus)ptr[(n) * 4 + 1] << 8) | \ ((MD5_u32plus)ptr[(n) * 4 + 2] << 16) | \ ((MD5_u32plus)ptr[(n) * 4 + 3] << 24)) #define GET(n) \ (ctx->block[(n)]) #endif /* * This processes one or more 64-byte data blocks, but does NOT update * the bit counters. There are no alignment requirements. */ static void *body(I2MD5_CTX *ctx, void *data, unsigned long size) { unsigned char *ptr; MD5_u32plus a, b, c, d; MD5_u32plus saved_a, saved_b, saved_c, saved_d; ptr = data; a = ctx->a; b = ctx->b; c = ctx->c; d = ctx->d; do { saved_a = a; saved_b = b; saved_c = c; saved_d = d; /* Round 1 */ STEP(F, a, b, c, d, SET(0), 0xd76aa478, 7) STEP(F, d, a, b, c, SET(1), 0xe8c7b756, 12) STEP(F, c, d, a, b, SET(2), 0x242070db, 17) STEP(F, b, c, d, a, SET(3), 0xc1bdceee, 22) STEP(F, a, b, c, d, SET(4), 0xf57c0faf, 7) STEP(F, d, a, b, c, SET(5), 0x4787c62a, 12) STEP(F, c, d, a, b, SET(6), 0xa8304613, 17) STEP(F, b, c, d, a, SET(7), 0xfd469501, 22) STEP(F, a, b, c, d, SET(8), 0x698098d8, 7) STEP(F, d, a, b, c, SET(9), 0x8b44f7af, 12) STEP(F, c, d, a, b, SET(10), 0xffff5bb1, 17) STEP(F, b, c, d, a, SET(11), 0x895cd7be, 22) STEP(F, a, b, c, d, SET(12), 0x6b901122, 7) STEP(F, d, a, b, c, SET(13), 0xfd987193, 12) STEP(F, c, d, a, b, SET(14), 0xa679438e, 17) STEP(F, b, c, d, a, SET(15), 0x49b40821, 22) /* Round 2 */ STEP(G, a, b, c, d, GET(1), 0xf61e2562, 5) STEP(G, d, a, b, c, GET(6), 0xc040b340, 9) STEP(G, c, d, a, b, GET(11), 0x265e5a51, 14) STEP(G, b, c, d, a, GET(0), 0xe9b6c7aa, 20) STEP(G, a, b, c, d, GET(5), 0xd62f105d, 5) STEP(G, d, a, b, c, GET(10), 0x02441453, 9) STEP(G, c, d, a, b, GET(15), 0xd8a1e681, 14) STEP(G, b, c, d, a, GET(4), 0xe7d3fbc8, 20) STEP(G, a, b, c, d, GET(9), 0x21e1cde6, 5) STEP(G, d, a, b, c, GET(14), 0xc33707d6, 9) STEP(G, c, d, a, b, GET(3), 0xf4d50d87, 14) STEP(G, b, c, d, a, GET(8), 0x455a14ed, 20) STEP(G, a, b, c, d, GET(13), 0xa9e3e905, 5) STEP(G, d, a, b, c, GET(2), 0xfcefa3f8, 9) STEP(G, c, d, a, b, GET(7), 0x676f02d9, 14) STEP(G, b, c, d, a, GET(12), 0x8d2a4c8a, 20) /* Round 3 */ STEP(H, a, b, c, d, GET(5), 0xfffa3942, 4) STEP(H, d, a, b, c, GET(8), 0x8771f681, 11) STEP(H, c, d, a, b, GET(11), 0x6d9d6122, 16) STEP(H, b, c, d, a, GET(14), 0xfde5380c, 23) STEP(H, a, b, c, d, GET(1), 0xa4beea44, 4) STEP(H, d, a, b, c, GET(4), 0x4bdecfa9, 11) STEP(H, c, d, a, b, GET(7), 0xf6bb4b60, 16) STEP(H, b, c, d, a, GET(10), 0xbebfbc70, 23) STEP(H, a, b, c, d, GET(13), 0x289b7ec6, 4) STEP(H, d, a, b, c, GET(0), 0xeaa127fa, 11) STEP(H, c, d, a, b, GET(3), 0xd4ef3085, 16) STEP(H, b, c, d, a, GET(6), 0x04881d05, 23) STEP(H, a, b, c, d, GET(9), 0xd9d4d039, 4) STEP(H, d, a, b, c, GET(12), 0xe6db99e5, 11) STEP(H, c, d, a, b, GET(15), 0x1fa27cf8, 16) STEP(H, b, c, d, a, GET(2), 0xc4ac5665, 23) /* Round 4 */ STEP(I, a, b, c, d, GET(0), 0xf4292244, 6) STEP(I, d, a, b, c, GET(7), 0x432aff97, 10) STEP(I, c, d, a, b, GET(14), 0xab9423a7, 15) STEP(I, b, c, d, a, GET(5), 0xfc93a039, 21) STEP(I, a, b, c, d, GET(12), 0x655b59c3, 6) STEP(I, d, a, b, c, GET(3), 0x8f0ccc92, 10) STEP(I, c, d, a, b, GET(10), 0xffeff47d, 15) STEP(I, b, c, d, a, GET(1), 0x85845dd1, 21) STEP(I, a, b, c, d, GET(8), 0x6fa87e4f, 6) STEP(I, d, a, b, c, GET(15), 0xfe2ce6e0, 10) STEP(I, c, d, a, b, GET(6), 0xa3014314, 15) STEP(I, b, c, d, a, GET(13), 0x4e0811a1, 21) STEP(I, a, b, c, d, GET(4), 0xf7537e82, 6) STEP(I, d, a, b, c, GET(11), 0xbd3af235, 10) STEP(I, c, d, a, b, GET(2), 0x2ad7d2bb, 15) STEP(I, b, c, d, a, GET(9), 0xeb86d391, 21) a += saved_a; b += saved_b; c += saved_c; d += saved_d; ptr += 64; } while (size -= 64); ctx->a = a; ctx->b = b; ctx->c = c; ctx->d = d; return ptr; } void I2MD5Init(I2MD5_CTX *ctx) { ctx->a = 0x67452301; ctx->b = 0xefcdab89; ctx->c = 0x98badcfe; ctx->d = 0x10325476; ctx->lo = 0; ctx->hi = 0; } void I2MD5Update(I2MD5_CTX *ctx, void *data, unsigned long size) { MD5_u32plus saved_lo; unsigned long used, free; saved_lo = ctx->lo; if ((ctx->lo = (saved_lo + size) & 0x1fffffff) < saved_lo) ctx->hi++; ctx->hi += size >> 29; used = saved_lo & 0x3f; if (used) { free = 64 - used; if (size < free) { memcpy(&ctx->buffer[used], data, size); return; } memcpy(&ctx->buffer[used], data, free); data = (unsigned char *)data + free; size -= free; body(ctx, ctx->buffer, 64); } if (size >= 64) { data = body(ctx, data, size & ~(unsigned long)0x3f); size &= 0x3f; } memcpy(ctx->buffer, data, size); } void I2MD5Final(unsigned char *result, I2MD5_CTX *ctx) { unsigned long used, free; used = ctx->lo & 0x3f; ctx->buffer[used++] = 0x80; free = 64 - used; if (free < 8) { memset(&ctx->buffer[used], 0, free); body(ctx, ctx->buffer, 64); used = 0; free = 64; } memset(&ctx->buffer[used], 0, free - 8); ctx->lo <<= 3; ctx->buffer[56] = ctx->lo; ctx->buffer[57] = ctx->lo >> 8; ctx->buffer[58] = ctx->lo >> 16; ctx->buffer[59] = ctx->lo >> 24; ctx->buffer[60] = ctx->hi; ctx->buffer[61] = ctx->hi >> 8; ctx->buffer[62] = ctx->hi >> 16; ctx->buffer[63] = ctx->hi >> 24; body(ctx, ctx->buffer, 64); result[0] = ctx->a; result[1] = ctx->a >> 8; result[2] = ctx->a >> 16; result[3] = ctx->a >> 24; result[4] = ctx->b; result[5] = ctx->b >> 8; result[6] = ctx->b >> 16; result[7] = ctx->b >> 24; result[8] = ctx->c; result[9] = ctx->c >> 8; result[10] = ctx->c >> 16; result[11] = ctx->c >> 24; result[12] = ctx->d; result[13] = ctx->d >> 8; result[14] = ctx->d >> 16; result[15] = ctx->d >> 24; memset(ctx, 0, sizeof(*ctx)); } #endif i2util-1.6/I2util/md5.h000066400000000000000000000026071276605416600146200ustar00rootroot00000000000000/* * This is an OpenSSL-compatible implementation of the RSA Data Security, Inc. * MD5 Message-Digest Algorithm (RFC 1321). * * Homepage: * http://openwall.info/wiki/people/solar/software/public-domain-source-code/md5 * * Author: * Alexander Peslyak, better known as Solar Designer * * This software was written by Alexander Peslyak in 2001. No copyright is * claimed, and the software is hereby placed in the public domain. * In case this attempt to disclaim copyright and place the software in the * public domain is deemed null and void, then the software is * Copyright (c) 2001 Alexander Peslyak and it is hereby released to the * general public under the following terms: * * Redistribution and use in source and binary forms, with or without * modification, are permitted. * * There's ABSOLUTELY NO WARRANTY, express or implied. * * See md5.c for more information. */ #ifdef HAVE_OPENSSL #include #elif !defined(_MD5_H) #define _MD5_H /* Any 32-bit or wider unsigned integer data type will do */ typedef unsigned int MD5_u32plus; typedef struct { MD5_u32plus lo, hi; MD5_u32plus a, b, c, d; unsigned char buffer[64]; MD5_u32plus block[16]; } I2MD5_CTX; extern void I2MD5Init(I2MD5_CTX *ctx); extern void I2MD5Update(I2MD5_CTX *ctx, void *data, unsigned long size); extern void I2MD5Final(unsigned char *result, I2MD5_CTX *ctx); #endif i2util-1.6/I2util/pbkdf2.c000066400000000000000000000220141276605416600152700ustar00rootroot00000000000000/* * ex: set tabstop=4 ai expandtab softtabstop=4 shiftwidth=4: * -*- mode: c-basic-indent: 4; tab-width: 4; indent-tabls-mode: nil -*- * $Id$ */ /************************************************************************ * * * Copyright (C) 2006 * * Internet2 * * All Rights Reserved * * * ************************************************************************/ /* * File: pbkdf2.c * * Author: Jeff W. Boote * Internet2 * * Date: Fri Oct 13 03:37:53 MDT 2006 * * Description: * * Implementation of PBKDF2 from RFC2898: * * The Internet2 copyright only applies to changes made * to this code. The original copyright follows. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * * 5.2 PBKDF2 * * PBKDF2 applies a pseudorandom function (see Appendix B.1 for an * example) to derive keys. The length of the derived key is essentially * unbounded. (However, the maximum effective search space for the * derived key may be limited by the structure of the underlying * pseudorandom function. See Appendix B.1 for further discussion.) * PBKDF2 is recommended for new applications. * * PBKDF2 (P, S, c, dkLen) * * Options: PRF underlying pseudorandom function (hLen * denotes the length in octets of the * pseudorandom function output) * * Input: P password, an octet string * S salt, an octet string * c iteration count, a positive integer * dkLen intended length in octets of the derived * key, a positive integer, at most * (2^32 - 1) * hLen * * Output: DK derived key, a dkLen-octet string * * Steps: * * 1. If dkLen > (2^32 - 1) * hLen, output "derived key too long" and * stop. * * 2. Let l be the number of hLen-octet blocks in the derived key, * rounding up, and let r be the number of octets in the last * block: * * l = CEIL (dkLen / hLen) , * r = dkLen - (l - 1) * hLen . * * Here, CEIL (x) is the "ceiling" function, i.e. the smallest * integer greater than, or equal to, x. * * 3. For each block of the derived key apply the function F defined * below to the password P, the salt S, the iteration count c, and * the block index to compute the block: * * T_1 = F (P, S, c, 1) , * T_2 = F (P, S, c, 2) , * ... * T_l = F (P, S, c, l) , * * where the function F is defined as the exclusive-or sum of the * first c iterates of the underlying pseudorandom function PRF * applied to the password P and the concatenation of the salt S * and the block index i: * * * F (P, S, c, i) = U_1 \xor U_2 \xor ... \xor U_c * * where * * U_1 = PRF (P, S || INT (i)) , * U_2 = PRF (P, U_1) , * ... * U_c = PRF (P, U_{c-1}) . * * Here, INT (i) is a four-octet encoding of the integer i, most * significant octet first. * * 4. Concatenate the blocks and extract the first dkLen octets to * produce a derived key DK: * * DK = T_1 || T_2 || ... || T_l<0..r-1> * * 5. Output the derived key DK. * * Note. The construction of the function F follows a "belt-and- * suspenders" approach. The iterates U_i are computed recursively to * remove a degree of parallelism from an opponent; they are exclusive- * ored together to reduce concerns about the recursion degenerating * into a small set of values. * */ #include #include #include /* * Function: F * * Description: * Used in step 3 to compute each block of derived key. * * In Args: * * Out Args: * * Scope: * Returns: * Side Effect: */ static void F( I2prf prf, uint32_t prf_hlen, const uint8_t *pw, uint32_t pwlen, const uint8_t *salt, uint32_t saltlen, uint32_t count, uint32_t i, uint8_t *buffer, uint8_t *u ) { uint8_t ival[4]; uint32_t j,k; /* * U_1 = PRF(P, concat(S, INT(i))) */ ival[0] = (i >> 24) & 0xff; ival[1] = (i >> 16) & 0xff; ival[2] = (i >> 8) & 0xff; ival[3] = i & 0xff; /* * Input of U_1 prf is concat(S, INT(i)), Output hmac put in buffer */ memcpy(buffer,salt,saltlen); memcpy(buffer+saltlen,ival,4); (*prf)(pw,pwlen,buffer,saltlen+4,buffer); /* * Initialize return u with U_1 */ memcpy(u,buffer,prf_hlen); /* * U_2..U_{count} */ for(j=2; j<=count; j++){ /* * Input of U_{j} prf is U_{j-1} or buffer, * Output is put back in buffer for the next time around and is * immediately used to xor into the F result. */ (*prf)(pw,pwlen,buffer,prf_hlen,buffer); for(k=0; k 0xffffffff){ rc = EINVAL; goto end; } #endif /* * Allocate needed memory for complete algorithm at this level to * catch errors early. */ if( !(tmpbuff = calloc(MAX(saltlen,prf_hlen)+4,sizeof(uint8_t))) || !(outbuff = calloc(prf_hlen,sizeof(uint8_t)))){ rc = ENOMEM; goto end; } /* * Step 2 * Let l = number of complete blocks * Let r = number of bytes in any final incomplete block */ l = dklen / prf_hlen; r = dklen % prf_hlen; /* * Step 3 and 4 * 3) iterate over all complete blocks to compute complete prf_hlen blocks * 4) increment 'out' to concatenate each resulting T_{i}. * * (Passing pointer directly into dk_ret, to minimize copies.) */ for(i=0; i BEGIN_C_DECLS /* * Type for pseudorandom functions - signature matches I2HMACSha1 * (return 0 on success) */ typedef void (*I2prf)( const uint8_t *key, uint32_t keylen, const uint8_t *txt, uint32_t txtlen, uint8_t *digest_ret ); /* * Implementation of pbkdf2 algorithm. * Returns 0 on success. errno set on failure. Possible errors are: * ENOMEM (Unable to allocate buffer space for algorithm.) * EINVAL (dklen too long) */ extern int I2pbkdf2( I2prf prf, uint32_t prf_hlen, const uint8_t *pw, uint32_t pwlen, const uint8_t *salt, uint32_t saltlen, uint32_t count, uint32_t dklen, uint8_t *dk_ret ); END_C_DECLS #endif /* I2PBKDF2_H */ i2util-1.6/I2util/random.c000066400000000000000000000065441276605416600154120ustar00rootroot00000000000000/* * $Id$ */ /************************************************************************ * * * Copyright (C) 2002 * * Internet2 * * All Rights Reserved * * * ************************************************************************/ /* * File: random.c * * Author: Anatoly Karp * Jeff W. Boote * Internet2 * * Date: Sun Jun 02 11:50:52 MDT 2002 * * Description: * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #include #include #include #include #include #include struct I2RandomSourceRec{ I2ErrHandle eh; int type; int fd; /* used for I2RAND_DEV */ }; /* ** Initialize the source of random bytes. Possible types are: ** I2RAND_DEV - random device (eg, /dev/urandom or /dev/random) - ** is then interpreted as char* pathname of the device. ** I2RAND_EGD - enthropy generating daemon (EGD) - is ** then interpreted as char* pathname to the local socket the EGD daemon ** is listening on. ** Returns 0 on success, or -1 on failure. */ I2RandomSource I2RandomSourceInit(I2ErrHandle eh, int type, void* data) { I2RandomSource rand_src; if(!eh) return NULL; if( !(rand_src = malloc(sizeof(struct I2RandomSourceRec)))){ I2ErrLog(eh,"malloc():%M"); return NULL; } rand_src->eh = eh; rand_src->type = type; switch (type) { case I2RAND_DEV: if(!data) data = I2_RANDOMDEV_PATH; if( (rand_src->fd = open((char *)data, O_RDONLY))<0){ I2ErrLog(eh, "I2randomBytes:open():%M"); return NULL; } break; case I2RAND_EGD: I2ErrLog(eh, "I2randomBytes: I2RAND_EGD not yet implemented"); free(rand_src); return NULL; /* UNREACHED */ default: I2ErrLog(eh, "I2randomBytes:unknown/unsupported random source type"); free(rand_src); return NULL; /* UNREACHED */ } return rand_src; } /* ** This function generates many random bytes and ** places them in the location pointed to by . It is ** a responsibility of the caller to have allocated ** sufficient space. Returns 0 on success, and -1 on failure. */ int I2RandomBytes( I2RandomSource src, unsigned char *ptr, unsigned int count ) { if(!src) return -1; switch (src->type) { case I2RAND_DEV: if (I2Readn(src->fd, ptr, count) != (signed) count) { I2ErrLog(src->eh, "I2randomBytes: I2Readn() failed: %M"); return -1; } break; case I2RAND_EGD: default: /* UNREACHED */ I2ErrLog(src->eh, "I2randomBytes: unknown/unsupported random source type"); return -1; } return 0; } void I2RandomSourceClose( I2RandomSource src ) { if(!src) return; switch (src->type) { case I2RAND_DEV: close(src->fd); break; case I2RAND_EGD: default: /* UNREACHED */ I2ErrLog(src->eh, "I2randomBytes: unknown/unsupported random source type"); } free(src); return; } i2util-1.6/I2util/random.h000066400000000000000000000030721276605416600154100ustar00rootroot00000000000000/* * $Id$ */ /************************************************************************ * * * Copyright (C) 2002 * * Internet2 * * All Rights Reserved * * * ************************************************************************/ /* * File: random.h * * Author: Anatoly Karp * Jeff W. Boote * Internet2 * * Date: Sun Jun 2 12:19:22 MDT 2002 * * Description: * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #ifndef _i2_random_h_ #define _i2_random_h_ #include #include #include #include /* ** Types of randomness sources. */ #define I2RAND_UNINITIALIZED 0 #define I2RAND_DEV 1 #define I2RAND_EGD 2 BEGIN_C_DECLS typedef struct I2RandomSourceRec *I2RandomSource; extern I2RandomSource I2RandomSourceInit( I2ErrHandle eh, int type, void* data ); extern int I2RandomBytes( I2RandomSource src, unsigned char *ptr, unsigned int count ); extern void I2RandomSourceClose( I2RandomSource src ); END_C_DECLS #endif /* _i2_random_h_ */ i2util-1.6/I2util/readpassphrase.c000066400000000000000000000236661276605416600171430ustar00rootroot00000000000000/* * $Id$ */ /************************************************************************ * * * Copyright (C) 2003 * * Internet2 * * All Rights Reserved * * * ************************************************************************/ /* * File: readpassphrase.c * * Author: Jeff Boote * Internet2 * * Date: Wed Dec 10 15:29:10 MST 2003 * * Description: * The Internet2 copyright only applies to changes made * to this code. The original copyright follows. * * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ /* * Copyright (c) 2000 Todd C. Miller * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY * AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL * THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include #include #include #include #include #include #include #include #include #include #include #ifdef HAVE_PATHS_H #include #endif #ifndef _PATH_TTY #define _PATH_TTY "/dev/tty" #endif #ifndef TCSASOFT #define TCSASOFT 0 #endif static volatile sig_atomic_t signo; static void handler(int); char * I2ReadPassPhrase(const char *prompt, char *buf, size_t bufsiz, int flags) { ssize_t nr; int input, output, save_errno; char ch, *p, *end; struct termios term, oterm; struct sigaction sa, saveint, savehup, savequit, saveterm; struct sigaction savetstp, savettin, savettou; /* I suppose we could alloc on demand in this case (XXX). */ if (bufsiz == 0) { errno = EINVAL; return(NULL); } restart: /* * Read and write to /dev/tty if available. If not, read from * stdin and write to stderr unless a tty is required. */ if ((input = output = open(_PATH_TTY, O_RDWR)) == -1) { if (flags & I2RPP_REQUIRE_TTY) { errno = ENOTTY; return(NULL); } input = STDIN_FILENO; output = STDERR_FILENO; } /* * Catch signals that would otherwise cause the user to end * up with echo turned off in the shell. Don't worry about * things like SIGALRM and SIGPIPE for now. */ sigemptyset(&sa.sa_mask); sa.sa_flags = 0; /* don't restart system calls */ sa.sa_handler = handler; (void)sigaction(SIGINT, &sa, &saveint); (void)sigaction(SIGHUP, &sa, &savehup); (void)sigaction(SIGQUIT, &sa, &savequit); (void)sigaction(SIGTERM, &sa, &saveterm); (void)sigaction(SIGTSTP, &sa, &savetstp); (void)sigaction(SIGTTIN, &sa, &savettin); (void)sigaction(SIGTTOU, &sa, &savettou); /* Turn off echo if possible. */ if (tcgetattr(input, &oterm) == 0) { memcpy(&term, &oterm, sizeof(term)); if (!(flags & I2RPP_ECHO_ON)) term.c_lflag &= ~(ECHO | ECHONL); #ifdef VSTATUS if (term.c_cc[VSTATUS] != _POSIX_VDISABLE) term.c_cc[VSTATUS] = _POSIX_VDISABLE; #endif (void)tcsetattr(input, TCSAFLUSH|TCSASOFT, &term); } else { memset(&term, 0, sizeof(term)); memset(&oterm, 0, sizeof(oterm)); } (void)write(output, prompt, strlen(prompt)); end = buf + bufsiz - 1; for (p = buf; (nr = read(input, &ch, 1)) == 1 && ch != '\n' && ch != '\r';) { if (p < end) { if ((flags & I2RPP_SEVENBIT)) ch &= 0x7f; if (isalpha((int)ch)) { if ((flags & I2RPP_FORCELOWER)) ch = tolower(ch); if ((flags & I2RPP_FORCEUPPER)) ch = toupper(ch); } *p++ = ch; } } *p = '\0'; save_errno = errno; if (!(term.c_lflag & ECHO)) (void)write(output, "\n", 1); /* Restore old terminal settings and signals. */ if (memcmp(&term, &oterm, sizeof(term)) != 0) (void)tcsetattr(input, TCSANOW|TCSASOFT, &oterm); (void)sigaction(SIGINT, &saveint, NULL); (void)sigaction(SIGHUP, &savehup, NULL); (void)sigaction(SIGQUIT, &savequit, NULL); (void)sigaction(SIGTERM, &saveterm, NULL); (void)sigaction(SIGTSTP, &savetstp, NULL); (void)sigaction(SIGTTIN, &savettin, NULL); (void)sigaction(SIGTTOU, &savettou, NULL); if (input != STDIN_FILENO) (void)close(input); /* * If we were interrupted by a signal, resend it to ourselves * now that we have restored the signal handlers. */ if (signo) { kill(getpid(), signo); switch (signo) { case SIGTSTP: case SIGTTIN: case SIGTTOU: signo = 0; goto restart; } } errno = save_errno; return(nr == -1 ? NULL : buf); } char * I2ReadPassPhraseAlloc( const char *prompt, int flags, char **lbuf, size_t *lbuf_max ) { ssize_t nr; size_t pf_len = 0; int input, output, save_errno; char *line; char ch, *p; struct termios term, oterm; struct sigaction sa, saveint, savehup, savequit, saveterm; struct sigaction savetstp, savettin, savettou; restart: /* * Read and write to /dev/tty if available. If not, read from * stdin and write to stderr unless a tty is required. */ if ((input = output = open(_PATH_TTY, O_RDWR)) == -1) { if (flags & I2RPP_REQUIRE_TTY) { errno = ENOTTY; return(NULL); } input = STDIN_FILENO; output = STDERR_FILENO; } /* * Catch signals that would otherwise cause the user to end * up with echo turned off in the shell. Don't worry about * things like SIGALRM and SIGPIPE for now. */ sigemptyset(&sa.sa_mask); sa.sa_flags = 0; /* don't restart system calls */ sa.sa_handler = handler; (void)sigaction(SIGINT, &sa, &saveint); (void)sigaction(SIGHUP, &sa, &savehup); (void)sigaction(SIGQUIT, &sa, &savequit); (void)sigaction(SIGTERM, &sa, &saveterm); (void)sigaction(SIGTSTP, &sa, &savetstp); (void)sigaction(SIGTTIN, &sa, &savettin); (void)sigaction(SIGTTOU, &sa, &savettou); /* Turn off echo if possible. */ if (tcgetattr(input, &oterm) == 0) { memcpy(&term, &oterm, sizeof(term)); if (!(flags & I2RPP_ECHO_ON)) term.c_lflag &= ~(ECHO | ECHONL); #ifdef VSTATUS if (term.c_cc[VSTATUS] != _POSIX_VDISABLE) term.c_cc[VSTATUS] = _POSIX_VDISABLE; #endif (void)tcsetattr(input, TCSAFLUSH|TCSASOFT, &term); } else { memset(&term, 0, sizeof(term)); memset(&oterm, 0, sizeof(oterm)); } /* * Write prompt */ (void)write(output, prompt, strlen(prompt)); /* * Read pass-phrase */ p = line = *lbuf; while(((nr = read(input, &ch, 1)) == 1)&&(ch != '\n')&&(ch != '\r')){ /* alloc more memory if required */ if((pf_len+2) > *lbuf_max){ while((pf_len+2) > *lbuf_max){ *lbuf_max += I2LINEBUFINC; } *lbuf = realloc(line,sizeof(char) * *lbuf_max); if(!*lbuf){ if(line){ free(line); } return NULL; } line = *lbuf; p = line + pf_len; } /* modify read char if needed */ if ((flags & I2RPP_SEVENBIT)) ch &= 0x7f; if (isalpha((int)ch)) { if ((flags & I2RPP_FORCELOWER)) ch = tolower(ch); if ((flags & I2RPP_FORCEUPPER)) ch = toupper(ch); } /* save the char */ *p++ = ch; pf_len++; } /* terminate pf */ *p = '\0'; save_errno = errno; if (!(term.c_lflag & ECHO)) (void)write(output, "\n", 1); /* Restore old terminal settings and signals. */ if (memcmp(&term, &oterm, sizeof(term)) != 0) (void)tcsetattr(input, TCSANOW|TCSASOFT, &oterm); (void)sigaction(SIGINT, &saveint, NULL); (void)sigaction(SIGHUP, &savehup, NULL); (void)sigaction(SIGQUIT, &savequit, NULL); (void)sigaction(SIGTERM, &saveterm, NULL); (void)sigaction(SIGTSTP, &savetstp, NULL); (void)sigaction(SIGTTIN, &savettin, NULL); (void)sigaction(SIGTTOU, &savettou, NULL); if (input != STDIN_FILENO) (void)close(input); /* * If we were interrupted by a signal, resend it to ourselves * now that we have restored the signal handlers. */ if (signo) { kill(getpid(), signo); switch (signo) { case SIGTSTP: case SIGTTIN: case SIGTTOU: signo = 0; goto restart; } } errno = save_errno; return(nr == -1 ? NULL : *lbuf); } static void handler(int s) { signo = s; } i2util-1.6/I2util/readpassphrase.h000066400000000000000000000065301276605416600171370ustar00rootroot00000000000000/* * $Id$ */ /************************************************************************ * * * Copyright (C) 2003 * * Internet2 * * All Rights Reserved * * * ************************************************************************/ /* * File: readpassphrase.h * * Author: Jeff Boote * Internet2 * * Date: Wed Dec 10 15:32:58 MST 2003 * * Description: * pulled-in from freebsd. * The Internet2 copyright only applies to changes made * to this code. The original copyright follows. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ /* * Copyright (c) 2000 Todd C. Miller * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY * AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL * THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef _i2_readpassphrase_h_ #define _i2_readpassphrase_h_ #include #define I2RPP_ECHO_OFF 0x00 /* Turn off echo (default). */ #define I2RPP_ECHO_ON 0x01 /* Leave echo on. */ #define I2RPP_REQUIRE_TTY 0x02 /* Fail if there is no tty. */ #define I2RPP_FORCELOWER 0x04 /* Force input to lower case. */ #define I2RPP_FORCEUPPER 0x08 /* Force input to upper case. */ #define I2RPP_SEVENBIT 0x10 /* Strip the high bit from input. */ BEGIN_C_DECLS char * I2ReadPassPhrase(const char *, char *, size_t, int); char * I2ReadPassPhraseAlloc( const char *prompt, int flags, char **lbuf, /* memory pointer - realloc'd if needed */ size_t *lbuf_max /* current len of lbuf */ ); END_C_DECLS #endif /* !_i2_readpassphrase_h_ */ i2util-1.6/I2util/saddr.c000066400000000000000000000167471276605416600152350ustar00rootroot00000000000000/* * $Id$ */ /************************************************************************ * * * Copyright (C) 2002 * * Internet2 * * All Rights Reserved * * * ************************************************************************/ /* * File: saddr.c * * Author: Jeff W. Boote * Internet2 * * Date: Tue Nov 26 07:45:48 MST 2002 * * Description: * * Generic socket functions used here to abstract away addr family * differences. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #include #include #include /* * These first functions are used to copy sockaddr structs in and out of * a union designed to make the rest of the code more ISO C99 compliant. * Specifically - type punning (aliasing) is much more limited than it * used to be to allow for more optimization. (Of course it specifically * de-optimizes my code since I now have to memcpy things instead of * modifying them in place. YUCK!) */ /* * Function: I2SockAddrToSockUnion * * Description: * * In Args: * * Out Args: * * Scope: * Returns: * Side Effect: */ I2SockUnion * I2SockAddrToSockUnion( const struct sockaddr *sa, socklen_t sa_len, I2SockUnion *sau_mem ) { assert(sau_mem); assert(sa); memset(sau_mem,0,sizeof(I2SockUnion)); switch(sa->sa_family){ #ifdef AF_INET6 case AF_INET6: if(sa_len < sizeof(struct sockaddr_in6)) return NULL; memcpy(&sau_mem->sin6,sa,sa_len); break; #endif case AF_INET: if(sa_len < sizeof(struct sockaddr_in)) return NULL; memcpy(&sau_mem->sin,sa,sa_len); break; default: return NULL; } return sau_mem; } /* * Function: I2SockUnionToSockAddr * * Description: * * In Args: * * Out Args: * * Scope: * Returns: * Side Effect: */ struct sockaddr * I2SockUnionToSockAddr( const I2SockUnion *sau, socklen_t *sa_len_in_out, struct sockaddr *sa_mem ) { assert(sau); assert(sa_mem); switch(sau->sa.sa_family){ #ifdef AF_INET6 case AF_INET6: if(*sa_len_in_out < sizeof(struct sockaddr_in6)) return NULL; *sa_len_in_out = sizeof(struct sockaddr_in6); break; #endif case AF_INET: if(*sa_len_in_out < sizeof(struct sockaddr_in)) return NULL; *sa_len_in_out = sizeof(struct sockaddr_in); break; default: return NULL; } memcpy(sa_mem,&sau->sas,*sa_len_in_out); return sa_mem; } /* * Function: I2SockAddrEqual * * Description: * * In Args: * * Out Args: * * Scope: * Returns: * <0 : error/unsupported addr family * 0 : false * >0 : true * Side Effect: */ int I2SockAddrEqual( const struct sockaddr *sa1, socklen_t sa1_len, const struct sockaddr *sa2, socklen_t sa2_len, uint32_t chk_what ) { I2SockUnion sau1_mem, sau2_mem; I2SockUnion *sau1, *sau2; /* * If the lengths are not equal - or the families are not the * same - check if the v6 address is really an encoded v4 address. * If it is - then re-call ourselves with the v4 version directly. */ if((sa1_len != sa2_len) || (sa1->sa_family != sa2->sa_family)){ #ifdef AF_INET6 struct sockaddr_in v4rec; /* * check if sa1 is a mapped addr. */ /* copy sa1 into the union */ if( !(sau1 = I2SockAddrToSockUnion(sa1,sa1_len,&sau1_mem))){ return -1; } if((sau1->sa.sa_family==AF_INET6) && IN6_IS_ADDR_V4MAPPED(&sau1->sin6.sin6_addr)){ memset(&v4rec,0,sizeof(v4rec)); #ifdef HAVE_STRUCT_SOCKADDR_SA_LEN v4rec.sin_len = sizeof(v4rec); #endif v4rec.sin_family = AF_INET; memcpy(&v4rec.sin_addr.s_addr, &sau1->sin6.sin6_addr.s6_addr[12],4); v4rec.sin_port = sau1->sin6.sin6_port; return I2SockAddrEqual((struct sockaddr*)&v4rec, sizeof(v4rec), sa2,sa2_len,chk_what); } /* copy sa1 into the union */ if( !(sau2 = I2SockAddrToSockUnion(sa2,sa2_len,&sau2_mem))){ return -1; } if((sau2->sa.sa_family==AF_INET6) && IN6_IS_ADDR_V4MAPPED(&sau2->sin6.sin6_addr)){ memset(&v4rec,0,sizeof(v4rec)); #ifdef HAVE_STRUCT_SOCKADDR_SA_LEN v4rec.sin_len = sizeof(v4rec); #endif v4rec.sin_family = AF_INET; memcpy(&v4rec.sin_addr.s_addr, &sau2->sin6.sin6_addr.s6_addr[12],4); v4rec.sin_port = sau2->sin6.sin6_port; return I2SockAddrEqual(sa1,sa1_len, (struct sockaddr*)&v4rec, sizeof(v4rec),chk_what); } #endif return 0; } /* copy to union to enable punning */ if( !(sau1 = I2SockAddrToSockUnion(sa1,sa1_len,&sau1_mem)) || !(sau2 = I2SockAddrToSockUnion(sa2,sa2_len,&sau2_mem))){ return -1; } switch(sau1->sa.sa_family){ #ifdef AF_INET6 case AF_INET6: if((chk_what & I2SADDR_ADDR) && (memcmp(&sau1->sin6.sin6_addr,&sau2->sin6.sin6_addr, sizeof(struct in6_addr)) != 0)){ return 0; } if((chk_what & I2SADDR_PORT) && (sau1->sin6.sin6_port != sau2->sin6.sin6_port)){ return 0; } /* * TODO:Do I need to check scope? Won't for now... */ return 1; break; #endif case AF_INET: if((chk_what & I2SADDR_ADDR) && (memcmp(&sau1->sin.sin_addr,&sau2->sin.sin_addr, sizeof(struct in_addr)) != 0)){ return 0; } if((chk_what & I2SADDR_PORT) && (sau1->sin.sin_port != sau2->sin.sin_port)){ return 0; } return 1; break; default: return -1; } return -1; } /* * Function: I2SockAddrIsLoopback * * Description: * * In Args: * * Out Args: * * Scope: * Returns: * <0 : error/unsupported addr family * 0 : false * >0 : true * Side Effect: */ int I2SockAddrIsLoopback( const struct sockaddr *sa, socklen_t sa_len ) { I2SockUnion sau_mem; I2SockUnion *sau; if( !(sau = I2SockAddrToSockUnion(sa,sa_len,&sau_mem))){ return -1; } switch(sau->sa.sa_family){ #ifdef AF_INET6 case AF_INET6: if (IN6_IS_ADDR_V4MAPPED(&sau->sin6.sin6_addr)){ struct sockaddr_in v4rec; memset(&v4rec,0,sizeof(v4rec)); #ifdef HAVE_STRUCT_SOCKADDR_SA_LEN v4rec.sin_len = sizeof(v4rec); #endif v4rec.sin_family = AF_INET; memcpy(&v4rec.sin_addr.s_addr, &sau->sin6.sin6_addr.s6_addr[12],4); v4rec.sin_port = sau->sin6.sin6_port; return I2SockAddrIsLoopback(&sau->sa,sizeof(v4rec)); } return IN6_IS_ADDR_LOOPBACK(&sau->sin6.sin6_addr); break; #endif case AF_INET: return (sau->sin.sin_addr.s_addr == htonl(INADDR_LOOPBACK)); break; default: return -1; } return 0; } i2util-1.6/I2util/saddr.h000066400000000000000000000063101276605416600152230ustar00rootroot00000000000000/* * $Id$ */ /************************************************************************ * * * Copyright (C) 2002 * * Internet2 * * All Rights Reserved * * * ************************************************************************/ /* * File: saddr.h * * Author: Jeff W. Boote * Internet2 * * Date: Tue Nov 26 11:09:26 MST 2002 * * Description: * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #ifndef _i2_saddr_h_ #define _i2_saddr_h_ #include #include #include #include #include BEGIN_C_DECLS #define I2SADDR_ADDR (0x1) #define I2SADDR_PORT (I2SADDR_ADDR<<1) #define I2SADDR_ALL (I2SADDR_ADDR|I2SADDR_PORT) /* * I2SockAddrEqual * This function is used to compare to sockaddrs. chk_what is used * to determine which parts of the sockaddr to look at when comparing. * (The above #define's are used to indicate this.) * * returns: * >0: true * ==0: false * <0: error */ extern int I2SockAddrEqual( const struct sockaddr *sa1, socklen_t sa1_len, const struct sockaddr *sa2, socklen_t sa2_len, uint32_t chk_what ); /* * I2SockAddrIsLoopback * This function is used to determine if the given sockaddr is * a loopback. It currently supports IPv4/IPv6. * * returns: * >0: true * ==0: false * <0: error */ extern int I2SockAddrIsLoopback( const struct sockaddr *sa1, socklen_t sa1_len ); /* * This union is used to remove questionable (struct sockaddr*) type punning. * * If the socket API is ported to the host OS properly - the alignment of * all the elements should match between these at least sa and (sin or sin6) * - but I believe this is more C99 compliant. * * This union needs to contain each sockaddr_XXX type that is used * in the saddr.c and addr.c functions. */ typedef union _I2SockUnion { struct sockaddr sa; struct sockaddr_in sin; struct sockaddr_in6 sin6; struct sockaddr_storage sas; } I2SockUnion; /* * I2SockAddrToSockUnion * This function is used to allow all other functions to deal with * sockaddrs through a union therefore removing 'aliasing' issues * introduced with C99. */ extern I2SockUnion * I2SockAddrToSockUnion( const struct sockaddr *sa, socklen_t sa_len, I2SockUnion *sau_mem ); /* * I2SockUnionToSockAddr * This function is used to return a sockaddr union as a simple sockaddr * when returning the content to the user. */ extern struct sockaddr * I2SockUnionToSockAddr( const I2SockUnion *sau, socklen_t *sa_len_in_out, struct sockaddr *sa_mem ); END_C_DECLS #endif /* _i2_saddr_h_ */ i2util-1.6/I2util/sha1.c000066400000000000000000000223611276605416600147610ustar00rootroot00000000000000/* * ex: set tabstop=4 ai expandtab softtabstop=4 shiftwidth=4: * -*- mode: c-basic-indent: 4; tab-width: 4; indent-tabls-mode: nil -*- * $Id$ */ /************************************************************************ * * * Copyright (C) 2006 * * Internet2 * * All Rights Reserved * * * ************************************************************************/ /* * File: sha1.c * * Author: Jeff W. Boote * Internet2 * * Date: Wed Sep 27 15:23:54 MDT 2006 * * Description: * * Public domain version of SHA-1 from 'entropy'. Modifying * it as needed... (Will change to I2 symbols - and update for C99 * compliance over time.) * * The Internet2 copyright only applies to changes made * to this code. The original copyright follows. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ /* * SHA-1 in C * By Steve Reid * 100% Public Domain * * Test Vectors (from FIPS PUB 180-1) * "abc" * A9993E36 4706816A BA3E2571 7850C26C 9CD0D89D * "abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq" * 84983E44 1C3BD26E BAAE4AA1 F95129E5 E54670F1 * A million repetitions of "a" * 34AA973C D4C4DAA4 F61EEB2B DBAD2731 6534016F */ #include #include #include #include /* * XXX I'm tempted to remove all of the loop unrolling nonsense... * (This kind of optimization is best done by a compiler!) * -jwb */ #define rol(value, bits) (((value) << (bits)) | ((value) >> (32 - (bits)))) /* * blk0() and blk() perform the initial expand. * I got the idea of expanding during the round function from SSLeay */ #if BYTE_ORDER == LITTLE_ENDIAN # define blk0(i) (block[i] = (rol(block[i],24)&0xFF00FF00) \ |(rol(block[i],8)&0x00FF00FF)) #else # define blk0(i) block[i] #endif #define blk(i) (block[i&15] = rol(block[(i+13)&15]^block[(i+8)&15] \ ^block[(i+2)&15]^block[i&15],1)) /* * (R0+R1), R2, R3, R4 are the different operations (rounds) used in SHA1 */ #define R0(v,w,x,y,z,i) \ z+=((w&(x^y))^y)+blk0(i)+0x5A827999+rol(v,5);w=rol(w,30); #define R1(v,w,x,y,z,i) \ z+=((w&(x^y))^y)+blk(i)+0x5A827999+rol(v,5);w=rol(w,30); #define R2(v,w,x,y,z,i) \ z+=(w^x^y)+blk(i)+0x6ED9EBA1+rol(v,5);w=rol(w,30); #define R3(v,w,x,y,z,i) \ z+=(((w|x)&y)|(w&x))+blk(i)+0x8F1BBCDC+rol(v,5);w=rol(w,30); #define R4(v,w,x,y,z,i) \ z+=(w^x^y)+blk(i)+0xCA62C1D6+rol(v,5);w=rol(w,30); /* * Hash a single 512-bit block. This is the core of the algorithm. */ static void sha1_transform( uint32_t state[5], const uint8_t buffer[I2SHA1_BLOCK_SIZE] ) { uint32_t a, b, c, d, e; uint32_t block[16]; assert(buffer != 0); assert(state != 0); /* Copy buffer into integer array */ (void)memcpy(block, buffer, I2SHA1_BLOCK_SIZE); /* Copy sha1->state[] to working vars */ a = state[0]; b = state[1]; c = state[2]; d = state[3]; e = state[4]; /* 4 rounds of 20 operations each. Loop unrolled. */ R0(a,b,c,d,e, 0); R0(e,a,b,c,d, 1); R0(d,e,a,b,c, 2); R0(c,d,e,a,b, 3); R0(b,c,d,e,a, 4); R0(a,b,c,d,e, 5); R0(e,a,b,c,d, 6); R0(d,e,a,b,c, 7); R0(c,d,e,a,b, 8); R0(b,c,d,e,a, 9); R0(a,b,c,d,e,10); R0(e,a,b,c,d,11); R0(d,e,a,b,c,12); R0(c,d,e,a,b,13); R0(b,c,d,e,a,14); R0(a,b,c,d,e,15); R1(e,a,b,c,d,16); R1(d,e,a,b,c,17); R1(c,d,e,a,b,18); R1(b,c,d,e,a,19); R2(a,b,c,d,e,20); R2(e,a,b,c,d,21); R2(d,e,a,b,c,22); R2(c,d,e,a,b,23); R2(b,c,d,e,a,24); R2(a,b,c,d,e,25); R2(e,a,b,c,d,26); R2(d,e,a,b,c,27); R2(c,d,e,a,b,28); R2(b,c,d,e,a,29); R2(a,b,c,d,e,30); R2(e,a,b,c,d,31); R2(d,e,a,b,c,32); R2(c,d,e,a,b,33); R2(b,c,d,e,a,34); R2(a,b,c,d,e,35); R2(e,a,b,c,d,36); R2(d,e,a,b,c,37); R2(c,d,e,a,b,38); R2(b,c,d,e,a,39); R3(a,b,c,d,e,40); R3(e,a,b,c,d,41); R3(d,e,a,b,c,42); R3(c,d,e,a,b,43); R3(b,c,d,e,a,44); R3(a,b,c,d,e,45); R3(e,a,b,c,d,46); R3(d,e,a,b,c,47); R3(c,d,e,a,b,48); R3(b,c,d,e,a,49); R3(a,b,c,d,e,50); R3(e,a,b,c,d,51); R3(d,e,a,b,c,52); R3(c,d,e,a,b,53); R3(b,c,d,e,a,54); R3(a,b,c,d,e,55); R3(e,a,b,c,d,56); R3(d,e,a,b,c,57); R3(c,d,e,a,b,58); R3(b,c,d,e,a,59); R4(a,b,c,d,e,60); R4(e,a,b,c,d,61); R4(d,e,a,b,c,62); R4(c,d,e,a,b,63); R4(b,c,d,e,a,64); R4(a,b,c,d,e,65); R4(e,a,b,c,d,66); R4(d,e,a,b,c,67); R4(c,d,e,a,b,68); R4(b,c,d,e,a,69); R4(a,b,c,d,e,70); R4(e,a,b,c,d,71); R4(d,e,a,b,c,72); R4(c,d,e,a,b,73); R4(b,c,d,e,a,74); R4(a,b,c,d,e,75); R4(e,a,b,c,d,76); R4(d,e,a,b,c,77); R4(c,d,e,a,b,78); R4(b,c,d,e,a,79); /* Add the working vars back into context.state[] */ state[0] += a; state[1] += b; state[2] += c; state[3] += d; state[4] += e; return; } void I2Sha1Free( I2Sha1Context ctx ) { if(!ctx) return; free(ctx); return; } I2Sha1Context I2Sha1Alloc( I2ErrHandle eh ) { I2Sha1Context ctx = (I2Sha1Context)calloc(1, sizeof(struct I2Sha1ContextRec)); if(!ctx){ I2ErrLogT(eh,LOG_ERR,errno, ": calloc(1,%d): %M",sizeof(struct I2Sha1ContextRec)); return NULL; } ctx->eh = eh; return ctx; } /* * sha1_init - Initialize new context */ void I2Sha1Init( I2Sha1Context sha1 ) { assert(sha1 != NULL); /* SHA1 initialization constants */ sha1->state[0] = 0x67452301; sha1->state[1] = 0xEFCDAB89; sha1->state[2] = 0x98BADCFE; sha1->state[3] = 0x10325476; sha1->state[4] = 0xC3D2E1F0; sha1->count[0] = sha1->count[1] = 0; return; } /* * Run your data through this. * XXX - The bits/bytes translation makes this code more complicated than * it needs to be. Is there any reason not to just keep track in bytes * until the end? */ void I2Sha1Append( I2Sha1Context sha1, const uint8_t *data, uint32_t len ) { uint i, j; assert(sha1 != NULL); if (len <= 0) return; /* * Count is used to keep track of the 64 bit length * of message - in bits). See fips 180-1. * Overflow in count[0] is added into count[1]. */ j = sha1->count[0]; if((sha1->count[0] += (len << 3)) < j){ sha1->count[1] += ((len>>29)+1); } /* * If this 'len' fills a complete 512 bit block, then call transform on it. */ j = (j >> 3) & 63; if ((j + len) > 63) { (void)memcpy(&sha1->buffer[j], data, (i = 64-j)); sha1_transform(sha1->state, sha1->buffer); for ( /* */ ; i + 63 < len; i += 64){ sha1_transform(sha1->state, &data[i]); } j = 0; } else { i = 0; } /* * copy the remaining bits of data that have not created a complete block * yet into the buffer so they can be processed on the next call, or * during Finish. */ (void)memcpy(&sha1->buffer[j], &data[i], len - i); return; } /* * Add padding and return the message digest. */ void I2Sha1Finish( I2Sha1Context sha1, uint8_t *digest_ret ) { uint32_t i; uint8_t finalcount[8]; assert(digest_ret != NULL); assert(sha1 != NULL); /* * Pull 64 bit count from sha1->count, and put it in finalcount */ for (i = 0; i < 8; i++) { /* Endian independent */ finalcount[i] = (uint8_t)((sha1->count[(i >= 4 ? 0 : 1)] >> ((3-(i & 3)) * 8) ) & 255); } /* * Append octal 200 (10000000) - End of message byte for SHA-1 */ I2Sha1Append(sha1, (const void *)"\200", 1); /* * Fill remaining block (except last 64 bits) with 0's */ while ((sha1->count[0] & 504) != 448) I2Sha1Append(sha1, (const void *)"\0", 1); /* * Put 'count' in final 64 bits */ I2Sha1Append(sha1, finalcount, 8); /* Should cause a SHA1Transform() */ /* * Return digest */ for (i = 0; i < I2SHA1_DIGEST_SIZE; i++) digest_ret[i] = (uint8_t) ((sha1->state[i>>2] >> ((3-(i & 3)) * 8) ) & 255); /* Wipe variables */ memset(sha1, 0, sizeof(*sha1)); return; } void I2Sha1( const uint8_t *data, uint32_t len, uint8_t *digest_ret ) { /* * Don't really do an Alloc - just create the record on the stack */ struct I2Sha1ContextRec sha1rec; I2Sha1Context sha1 = &sha1rec; memset((void*)sha1,0,sizeof(*sha1)); I2Sha1Init(sha1); I2Sha1Append(sha1,data,len); I2Sha1Finish(sha1,digest_ret); return; } i2util-1.6/I2util/sha1.h000066400000000000000000000053741276605416600147730ustar00rootroot00000000000000/* * ex: set tabstop=4 ai expandtab softtabstop=4 shiftwidth=4: * -*- mode: c-basic-indent: 4; tab-width: 4; indent-tabls-mode: nil -*- * $Id$ */ /************************************************************************ * * * Copyright (C) 2006 * * Internet2 * * All Rights Reserved * * * ************************************************************************/ /* * File: sha1.h * * Author: Jeff W. Boote * Internet2 * * Date: Wed Sep 27 15:27:47 MDT 2006 * * Description: * * Public domain version of SHA-1 from 'entropy'. Modifying * it as needed... (Will change to I2 symbols - and update for C99 * compliance, and COMMENT.) * * Also - changed API to make sha1 context opaque. * * Not aiming for a "complete" sha1 here - just enough to support the * hmac-sha1 needed for owamp. * * The Internet2 copyright only applies to changes made * to this code. The original copyright follows. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ /* * SHA-1 in C * By Steve Reid * 100% Public Domain */ /* $Id$ */ #ifndef I2SHA1_H #define I2SHA1_H #include #define I2SHA1_DIGEST_SIZE 20 #define I2SHA1_BLOCK_SIZE 64 BEGIN_C_DECLS struct I2Sha1ContextRec; typedef struct I2Sha1ContextRec *I2Sha1Context; extern I2Sha1Context I2Sha1Alloc( I2ErrHandle eh ); extern void I2Sha1Free( I2Sha1Context sha1 ); extern void I2Sha1Init( I2Sha1Context sha1 ); extern void I2Sha1Append( I2Sha1Context sha1, const uint8_t *data, uint32_t len ); extern void I2Sha1Finish( I2Sha1Context sha1, uint8_t *digest_ret /* I2SHA1_DIGEST_SIZE */ ); extern void I2Sha1( const uint8_t *data, uint32_t len, uint8_t *digest_ret ); END_C_DECLS #endif /* I2SHA1_H */ i2util-1.6/I2util/sha1P.h000066400000000000000000000032061276605416600151030ustar00rootroot00000000000000/* * ex: set tabstop=4 ai expandtab softtabstop=4 shiftwidth=4: * -*- mode: c-basic-indent: 4; tab-width: 4; indent-tabls-mode: nil -*- * $Id$ */ /************************************************************************ * * * Copyright (C) 2006 * * Internet2 * * All Rights Reserved * * * ************************************************************************/ /* * File: sha1P.h * * Author: Jeff W. Boote * Internet2 * * Date: Sun Oct 08 03:15:21 MDT 2006 * * Description: * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #ifndef I2SHA1P_H #define I2SHA1P_H #include BEGIN_C_DECLS struct I2Sha1ContextRec { I2ErrHandle eh; uint32_t state[5]; uint32_t count[2]; uint8_t buffer[I2SHA1_BLOCK_SIZE]; }; END_C_DECLS #endif /* I2SHA1P_H */ i2util-1.6/I2util/table.c000066400000000000000000000175051276605416600152200ustar00rootroot00000000000000/* ** $Id$ */ /************************************************************************ * * * Copyright (C) 2002 * * Internet2 * * All Rights Reserved * * * ************************************************************************/ /* ** File: table.c ** ** Author: Anatoly Karp ** Jeff W. Boote ** ** Date: Thu Apr 19 13:47:17 EDT 2002 ** ** Description: Simple hash table - implementation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #include "table.h" #include #include #include #include #include #include #include /* * this type is used to hold a single key/value pair. */ typedef struct I2BindingRec I2BindingRec, *I2Binding; struct I2BindingRec{ I2Datum key; I2Datum value; I2Boolean delete; I2Binding next; }; /* Types used to define a hash table. */ struct I2Table { I2ErrHandle eh; I2TableDataSizeT size; size_t hint; I2HashCmpFunc cmp; I2HashFunc hash; I2TableDataSizeT length; I2Binding *buckets; I2Binding freelist; I2Binding *alist; size_t num_alist; size_t size_alist; I2Boolean in_iterate; I2TableDataSizeT delete_nodes; }; /* Static functions (used by default unless specified). */ static int cmpatom( I2Datum x, I2Datum y ) { /* return x != y; */ return (!(x.dsize == y.dsize) || memcmp(x.dptr, y.dptr, x.dsize)); } static uint32_t hashatom( I2Datum key ) { unsigned long i; unsigned char *ptr = (unsigned char *)(key.dptr); unsigned long ret = 0; for (i = 0; i < key.dsize; i++, ptr++) ret += *ptr; return ret; } static int alloc_freelist( I2Table table ) { I2Binding t; unsigned int i; if(table->num_alist <= table->size_alist){ I2Binding *alist; if(!(alist = realloc(table->alist,sizeof(I2Binding)* (table->size_alist+table->hint) ))){ I2ErrLogP(table->eh,errno,"WARNING: realloc(): %M"); return -1; } table->size_alist += table->hint; table->alist = alist; } if(!(t = calloc(sizeof(I2BindingRec),table->hint))){ I2ErrLogP(table->eh,errno,"WARNING: calloc(): %M"); return -1; } table->alist[table->num_alist++] = t; for(i=0;ihint;i++){ t[i].next = table->freelist; table->freelist = &t[i]; } return 0; } static I2Binding alloc_binding( I2Table table ) { I2Binding node; if(!table->freelist && (alloc_freelist(table) != 0)){ return NULL; } node = table->freelist; table->freelist = node->next; node->next = NULL; return node; } static void free_binding( I2Table table, I2Binding node ) { node->next = table->freelist; table->freelist = node; return; } I2TableDataSizeT I2HashNumEntries( I2Table table ) { if(table->delete_nodes > table->length){ I2ErrLogP(table->eh,0, "WARNING: I2HashNumEntries - table invalid!"); return 0; } return table->length - table->delete_nodes; } I2Table I2HashInit( I2ErrHandle eh, size_t hint, int cmp(I2Datum x, I2Datum y), uint32_t hash(I2Datum key) ) { I2Table table; unsigned int i; unsigned int primes[] = {31, 67, 127, 251, 509, 1021, 2053, 4093, 8191, 16381, 32771, 65521}; for(i=I2Number(primes)-1; (i>0) && (primes[i] > hint);i--); table = (void *)calloc(1,sizeof(*table)); if(!table){ I2ErrLogP(eh, ENOMEM, "FATAL: calloc for hash table"); return NULL; } table->buckets = malloc(primes[i]*sizeof(table->buckets[0])); if(!table->buckets){ I2ErrLogP(eh, ENOMEM, "FATAL: malloc for hash buckets"); goto error; } memset(table->buckets,0,primes[i]*sizeof(table->buckets[0])); table->eh = eh; table->size = primes[i]; table->hint = (hint) ? hint : primes[i]; table->cmp = cmp ? cmp : cmpatom; table->hash = hash ? hash : hashatom; table->length = 0; table->freelist = NULL; table->alist = NULL; table->num_alist = table->size_alist = 0; table->in_iterate=False; table->delete_nodes=0; if(alloc_freelist(table) != 0){ goto error; } return table; error: if(table->buckets){ free(table->buckets); } if(table->size_alist){ for(i=0;inum_alist;i++){ free(table->alist[i]); } free(table->alist); } free(table); return NULL; } void I2HashClose( I2Table table ) { unsigned int i; assert(table); assert(!table->in_iterate); free(table->buckets); if(table->size_alist){ for(i=0;inum_alist;i++){ free(table->alist[i]); } free(table->alist); } free(table); return; } int I2HashDelete( I2Table table, I2Datum key ) { I2TableDataSizeT i; I2Binding *p; I2Binding q; assert(table); /* Search table for key. */ i = (*table->hash)(key)%table->size; for (p = &table->buckets[i]; *p; p = &(*p)->next){ if (!(*p)->delete && ((*table->cmp)(key, (*p)->key) == 0)){ break; } } if (!*p) /* not found */ return -1; if(table->in_iterate){ (*p)->delete = True; table->delete_nodes++; return 0; } q = *p; *p = q->next; free_binding(table,q); table->length--; return 0; } /* ** Save a key/value in the hash. Return 0 on success, and -1 on failure. */ int I2HashStore( I2Table table, I2Datum key, I2Datum value ) { I2TableDataSizeT i; I2Binding q; assert(table); assert(!table->in_iterate); i=0; i=~i; if(table->size == i){ I2ErrLogP(table->eh,0,"FATAL: hash table full"); return -1; } /* Search table for key. */ i = (*table->hash)(key)%table->size; for (q = table->buckets[i]; q; q = q->next){ if ((*table->cmp)(key, q->key) == 0) break; } if (q == NULL){ /* not found */ q = alloc_binding(table); if (q == NULL){ return -1; } q->key = key; q->delete = False; q->next = table->buckets[i]; table->buckets[i] = q; table->length++; } q->value = value; return 0; } /* ** Look up the value corresponding to a given key. Returns ** the value datum on success, or NULL on failure. */ I2Boolean I2HashFetch( I2Table table, I2Datum key, I2Datum *ret ) { I2TableDataSizeT i; I2Binding p; assert(table); assert(ret); /* Search table for key. */ i = (*table->hash)(key)%table->size; for (p = table->buckets[i]; p; p = p->next){ if (!p->delete && ((*table->cmp)(key, p->key) == 0)){ break; } } if(!p) return False; *ret = p->value; return True; } void I2HashIterate( I2Table table, I2HashIterateFunc ifunc, void *app_data ) { I2TableDataSizeT i; I2Binding *p; I2Binding q; assert(table); assert(!table->in_iterate); assert(ifunc); table->in_iterate = True; table->delete_nodes = 0; for (i = 0; i < table->size; i++){ for (q = table->buckets[i]; q; q = q->next){ if(q->delete){ continue; } if(!((*ifunc)(q->key,q->value,app_data))) goto done_iterate; } } done_iterate: /* * Now delete any nodes that were removed during the iterate. */ for (i = 0;((i < table->size)&&(table->delete_nodes > 0)); i++){ p = &table->buckets[i]; while(*p && (table->delete_nodes > 0)){ if((*p)->delete){ q = *p; *p = q->next; free_binding(table,q); table->delete_nodes--; table->length--; } else{ p = &(*p)->next; } } } table->in_iterate = False; } void I2HashClean( I2Table table ) { I2TableDataSizeT i; I2Binding *p; I2Binding q; assert(table); assert(!table->in_iterate); for (i = 0;((i < table->size) && (table->length > 0)); i++){ p = &table->buckets[i]; while(*p){ q = *p; *p = q->next; free_binding(table,q); table->length--; } } assert(table->length == 0); return; } i2util-1.6/I2util/table.h000066400000000000000000000064211276605416600152200ustar00rootroot00000000000000/* ** $Id$ */ /************************************************************************ * * * Copyright (C) 2002 * * Internet2 * * All Rights Reserved * * * ************************************************************************/ /* ** File: table.h ** ** Author: Anatoly Karp ** Jeff Boote ** ** Date: Thu Apr 19 13:47:17 EDT 2002 ** ** Description: Simple hash table - header file. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #ifndef _I2util_table_h_ #define _I2util_table_h_ #include typedef struct I2Table *I2Table; typedef uint32_t I2TableDataSizeT; /* ** This type is used to represent keys and values in a hash. */ typedef struct { void *dptr; I2TableDataSizeT dsize; } I2Datum; typedef int (*I2HashCmpFunc)( I2Datum x, I2Datum y ); typedef I2TableDataSizeT (*I2HashFunc)( I2Datum key ); /* * These are basic hash-manipulation functions. */ /* * The I2HashInit function is the initialization function for a new hash. * hint indicates a good guess as to the size of the hash. */ extern I2Table I2HashInit( I2ErrHandle eh, size_t hint, /* guess on number of elements */ I2HashCmpFunc cmp, I2HashFunc hash ); extern I2Boolean I2HashFetch( I2Table hash, I2Datum key, I2Datum *ret ); /* return 0 on success */ extern int I2HashStore( I2Table table, I2Datum key, I2Datum value ); extern int I2HashDelete( I2Table table, I2Datum key ); extern void I2HashClean( I2Table table ); extern I2TableDataSizeT I2HashNumEntries( I2Table table ); extern void I2HashClose( I2Table table ); /* * This function will be called on every key/value pair in the hash as * long as the function returns true. The iteration terminates when this * function returns false. * The app_data passed into this function is the same one that is passed * into I2HashIterate. * * The hash_iterate_func currently has some limitations: * The only modification operation that may be done on the hash during * the iteration is delete. All others will produce errors. * (store/close) */ typedef I2Boolean (*I2HashIterateFunc)( I2Datum key, I2Datum value, void *app_data ); extern void I2HashIterate( I2Table table, I2HashIterateFunc ifunc, void *app_data ); /* * This example shows how a hash of string key/value * pairs can be printed using the I2HashIterate functionality: * * First define the fuction: * * I2Boolean hash_print( * const I2Datum *key, * I2Datum *value, * void *app_data * ) * { * FILE *fp = (FILE*)app_data; * * fprintf(fp,"key=%s\tvalue=%s\n",key->dptr,value->dptr); * * return True; * } * * Then later in the code after storing hash values, to print the hash: * * I2HashIterate(table,hash_print,(void*)stdout); */ #endif i2util-1.6/I2util/util.h000066400000000000000000000034531276605416600151100ustar00rootroot00000000000000/* * $Id$ */ /************************************************************************ * * * Copyright (C) 2002 * * Internet2 * * All Rights Reserved * * * ************************************************************************/ /* * File: util.h * * Author: Jeff Boote * Internet2 * * Date: Tue Apr 23 10:11:16 2002 * * Description: * I2 Utility library. Currently contains: * * error logging * * command-line parsing * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #ifndef _I2_util_h_ #define _I2_util_h_ #include typedef intptr_t I2Boolean; #ifndef False #define False (0) #endif #ifndef True #define True !False #endif #ifndef MIN #define MIN(a,b) ((ab)?a:b) #endif #ifdef __cplusplus #define BEGIN_C_DECLS extern "C" { #define END_C_DECLS } #else #define BEGIN_C_DECLS #define END_C_DECLS #endif #define I2Number(arr) (sizeof(arr)/sizeof(arr[0])) #include #include #include #include #include #include #include #include #include #include #include #endif /* _I2_util_h_ */ i2util-1.6/I2util/utilP.h000066400000000000000000000032361276605416600152270ustar00rootroot00000000000000/* * $Id$ */ /************************************************************************ * * * Copyright (C) 2007 * * Internet2 * * All Rights Reserved * * * ************************************************************************/ /* * File: utilP.h * * Author: Jeff Boote * Internet2 * * Date: Fri Mar 30 16:33:03 MDT 2007 * * Description: * I2 Utility library private header. (Public header * can't include autoconf stuff.) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #ifndef _I2_utilP_h_ #define _I2_utilP_h_ #include #include #ifndef HAVE___ATTRIBUTE__ #define __attribute__(x) #endif /* * Portablility sanity checkes. */ #if !HAVE_GETADDRINFO || !HAVE_SOCKET #error Missing needed networking capabilities! (getaddrinfo and socket) #endif /* * This macro should be set by the autoconf- stuff. * * (This macro will be used to set the "data" of I2RandomSourceInit if * type is I2RAND_DEV.) * */ #ifndef I2_RANDOMDEV_PATH #error "I2RandomBytes currently requires kernel support (EGD support forthcoming)" #endif #endif /* _I2_utilP_h_ */ i2util-1.6/Makefile.am000066400000000000000000000026671276605416600146540ustar00rootroot00000000000000# # $Id$ # ######################################################################### # # # Copyright (C) 2002 # # Internet2 # # All Rights Reserved # # # ######################################################################### # # File: Makefile.am # # Author: Jeff Boote # Internet2 # # Date: Wed Apr 24 09:49:28 EDT 2002 # # Description: toplevel build for I2util library # #include $(top_srcdir)/config/Make-rules ACLOCAL_AMFLAGS = -I config AUTOMAKE_OPTIONS = foreign SUBDIRS = I2util aespasswd pfstore test doc # uncomment when automake is unbroken 1.5 doesn't work with this... # (then remove these from DIST_EXTRA in subdir) #nobase_include_HEADERS = I2util/util.h I2util/Pthread.h I2util/config.h \ # I2util/errlog.h I2util/errlogimmediate.h I2util/errlogsyslog.h \ # I2util/options.h I2util/table.h I2util/random.h I2util/io.h \ # I2util/saddr.h # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # i2util-1.6/README000066400000000000000000000007351276605416600134720ustar00rootroot00000000000000 $Id$ I2 Utility library. Currently contains: * error logging * command-line parsing * threading The error logging and command-line parsing are taken from a utility library that is distributed with the "volsh" code from UCAR. http://www.scd.ucar.edu/vets/vg/Software/volsh I have used this in the past - and it seemed silly not to use it since it is freely distributed. jeff We have locally added: * random number support * hash table support i2util-1.6/README.md000066400000000000000000000005261276605416600140670ustar00rootroot00000000000000#I2 Utility library. Currently contains: * error logging * command-line parsing * threading The error logging and command-line parsing are taken from a utility library that is distributed with the "volsh" code from UCAR. http://www.scd.ucar.edu/vets/vg/Software/volsh We have locally added: * random number support * hash table support i2util-1.6/RELEASE.TODO000066400000000000000000000011461276605416600143560ustar00rootroot00000000000000To make a new release: 1) Edit configure.ac and modify the version number in the macros. 2) Edit doc/index.html and modify the version number 3) check-in all changes 4) svn log > ChangeLog 4.5) Review ChangeLog and edit doc/milestones.html 4.6) check-in doc/milestones 4.7) svn log > ChangeLog 5) check-in ChangeLog 6) tag release ex. "svn cp trunk ../branches/" 7) make dist 8) copy tarball to dist area of website 9) copy tarball to /usr/src/redhat/SOURCES rpmbuild -ba with .spec file copy rpm file to dist area of website 9) update webpages i2util-1.6/TODO.txt000066400000000000000000000014411276605416600141130ustar00rootroot00000000000000getaddrinfo - conditionally compile Ah, ok. It is not v6 per-say, but the RFC 2553 advanced socket-api stuff this is the issue. So, a quick google leads me to believe there are a few reasonable paths forward: * See if early adoption of IPv6 cygwin code is reasonable: http://win6.jp/Cygwin/index.html * Pull over another getaddrinfo implementation and conditionally compile for environments that don't have getaddrinfo. (autoconf pain.) - gnulib (lots here - probably too much and I'm not crazy about license) - http://www.sra.co.jp/people/m-kasahr/getaddrinfo/ (needs testing) -------------------------------------------------------------------------------- Autoconf: Update AC_CHECK_HEADERS (see bwctl) -------------------------------------------------------------------------------- i2util-1.6/aespasswd/000077500000000000000000000000001276605416600145775ustar00rootroot00000000000000i2util-1.6/aespasswd/Makefile.am000066400000000000000000000021441276605416600166340ustar00rootroot00000000000000# # $Id$ # ######################################################################### # # # Copyright (C) 2003 # # Internet2 # # All Rights Reserved # # # ######################################################################### # # File: Makefile.am # # Author: Jeff Boote # Internet2 # # Date: Thu Dec 18 14:28:42 MST 2003 # # Description: AM_CPPFLAGS = $(I2UTILINCS) bin_PROGRAMS = aespasswd aespasswd_SOURCES = aespasswd.c aespasswd_LDADD = $(I2UTILLIBS) $(MALLOCDEBUGLIBS) aespasswd_DEPENDENCIES = $(I2UTILLIBDEPS) # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # i2util-1.6/aespasswd/aespasswd.c000066400000000000000000000175561276605416600167530ustar00rootroot00000000000000/* * $Id$ */ /************************************************************************ * * * Copyright (C) 2003 * * Internet2 * * All Rights Reserved * * * ************************************************************************/ /* * File: aespasswd.c * * Author: Jeff W. Boote * Internet2 * * Date: Thu Dec 18 14:41:59 MST 2003 * * Description: * * License: * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #include #include #include #include #include #include #include #include #include #include #include #include #if defined HAVE_DECL_OPTRESET && !HAVE_DECL_OPTRESET int optreset; #endif static void usage( const char *progname, const char *msg ) { if(msg) fprintf(stderr, "%s: %s\n", progname, msg); fprintf(stderr,"usage: %s %s\n", progname, "[arguments] identity" ); fprintf(stderr,"\n"); fprintf(stderr, " -f fname filename to edit [required option]\n" " -n create keyfile\n" " -d delete given identity from file\n" ); return; } static int do_create = 0; static int do_delete = 0; static char *keyfname; static char *idname; int main( int argc, char **argv ) { char *progname; static char *copts = "hf:nd"; int ch; int lockfd; char lockfname[PATH_MAX]; char *dname; size_t len; struct flock flk; FILE *fromfp; FILE *tofp; uint8_t aeskey[I2KEYLEN]; char *lbuf=NULL; size_t lbuf_max=0; int rc; if((progname = strrchr(argv[0],'/'))){ progname++; }else{ progname = *argv; } opterr = 0; while((ch = getopt(argc,argv,copts)) != -1){ switch (ch) { case 'f': if(!(keyfname = strdup(optarg))){ fprintf(stderr,"%s:%d: malloc(): %s\n", __FILE__,__LINE__, strerror(errno)); exit(errno); } break; case 'n': do_create++; break; case 'd': do_delete++; break; case 'h': case '?': default: usage(progname,""); exit(0); /* UNREACHED */ } } argc -= optind; argv += optind; if(!keyfname){ usage(progname,"-f option is required"); exit(1); } if(argc != 1){ usage(progname,NULL); exit(1); } #define STR(val) #val #define STREXP(val) STR(val) len = strlen(argv[0]); if(len > I2MAXIDENTITYLEN){ usage(progname,"identity can't be more than " STREXP(I2MAXIDENTITYLEN) " characters"); exit(1); } if(!(idname = strdup(argv[0]))){ fprintf(stderr,"%s:%s:%d: malloc(): %s\n", progname,__FILE__,__LINE__, strerror(errno)); exit(errno); } fromfp = fopen(keyfname,"r+"); if(do_create && (fromfp != NULL)){ fprintf(stderr,"%s: -n option specified: %s exists\n\n", progname,keyfname); usage(progname,NULL); exit(1); } if(!do_create && !fromfp){ fprintf(stderr,"%s: Can't open \'%s\': %s\nSee -n option?\n\n", progname,keyfname,strerror(errno)); usage(progname,NULL); exit(1); } /* ensure string is nul terminated when strncpy is used */ memset(lockfname,'\0',sizeof(lockfname)); /* Don't let the last byte be written over */ len = sizeof(lockfname) - 1; /* * copy keyfname to lockfname(used as tmp var here) before calling * dirname to ensure it doesn't modify keyfname. */ strncpy(lockfname,keyfname,len); if(!(dname = dirname(lockfname))){ fprintf(stderr,"%s: dirname(): %s\n",progname,strerror(errno)); exit(1); } /* * what directory are we putting the lockfile in. */ strncpy(lockfname,dname,len); /* * Concatinate lockfile name on. */ len = sizeof(lockfname) - strlen(lockfname) - 1; strncat(lockfname,"/.",len); len -= 2; /* strlen("/.") */ strncat(lockfname,progname,len); len -= strlen(progname); strncat(lockfname,".lock",len); /* * open the lock file (also used as the tempfile). */ lockfd = open(lockfname,O_RDWR|O_CREAT,S_IRUSR|S_IWUSR); if(lockfd < 0){ fprintf(stderr,"open(%s): %s\n",lockfname,strerror(errno)); exit(1); } /* * lock the file */ flk.l_start = 0; flk.l_len = 0; flk.l_type = F_WRLCK; flk.l_whence = SEEK_SET; if(fcntl(lockfd,F_SETLK,&flk) < 0){ fprintf(stderr,"%s: Unable to lock \'%s\': %s\n", progname,lockfname,strerror(errno)); exit(1); } /* * wrap a FILE* around the lockfile */ if(!(tofp = fdopen(lockfd,"r+"))){ fprintf(stderr,"%s: fdopen(): %s\n",progname,strerror(errno)); exit(1); } if(!do_delete){ char *passphrase; char ppbuf[1024]; char prompt[1024]; I2MD5_CTX mdc; size_t pplen; rc = snprintf(prompt,sizeof(prompt), "Enter passphrase for identity '%s': ", idname); if((rc < 0) || ((size_t)rc > sizeof(prompt))){ fprintf(stderr,"%s: Invalid identity '%s'\n", progname,idname); exit(1); } if(!(passphrase = I2ReadPassPhrase(prompt,ppbuf, sizeof(ppbuf),I2RPP_ECHO_OFF))){ fprintf(stderr,"%s: I2ReadPassPhrase(): %s\n", progname,strerror(errno)); exit(1); } pplen = strlen(passphrase); I2MD5Init(&mdc); I2MD5Update(&mdc,(unsigned char *)passphrase,pplen); I2MD5Final((uint8_t *)aeskey,&mdc); } /* * All records that don't match idname will be copied to idname. */ rc = I2ParseKeyFile(NULL,fromfp,0,&lbuf,&lbuf_max,tofp,idname, NULL,NULL); if(rc < 0){ fprintf(stderr,"%s: I2ParseKeyFile('%s'): error line %d\n", progname,keyfname,rc); exit(1); } if(do_delete){ /* * If we are deleting, the identity should have been found. */ if(!rc){ fprintf(stderr,"%s: Identity '%s' not found\n", progname,idname); exit(1); } }else{ /* * Not deleting, add the new/changed key line. */ if(I2WriteKeyLine(NULL,tofp,idname,aeskey) < 0){ fprintf(stderr,"%s:I2WriteKeyLine('%s'): %s\n", progname,keyfname,strerror(errno)); exit(1); } } /* * Copy all remaining records. */ rc = I2ParseKeyFile(NULL,fromfp,rc,&lbuf,&lbuf_max,tofp,idname, NULL,NULL); if(rc != 0){ fprintf(stderr,"%s:I2ParseKeyFile('%s'): error line %d\n", progname,keyfname,rc); exit(1); } /* * Now close the keyfile, and rename the lockfile to the keyfile. */ if(fromfp) fclose(fromfp); rename(lockfname,keyfname); fclose(tofp); exit(0); } i2util-1.6/bootstrap.sh000077500000000000000000000014421276605416600151620ustar00rootroot00000000000000#!/bin/sh # # $Id$ # ######################################################################### # # # Copyright (C) 2002 # # Internet2 # # All Rights Reserved # # # ######################################################################### # # File: bootstrap # # Author: Jeff Boote # Internet2 # # Date: Wed Apr 24 09:47:57 EDT 2002 # # Description: # This script is used to bootstrap the autobuild # process. # case "$1" in ac257) alias autoconf=autoconf257 alias autoheader=autoheader257 alias automake=automake17 alias aclocal=aclocal17 export AUTOCONF=autoconf257 ;; *) ;; esac set -x # libtoolize --copy --force --automake aclocal -I config autoheader automake --foreign --add-missing --copy autoconf rm -rf config.cache i2util-1.6/config/000077500000000000000000000000001276605416600140525ustar00rootroot00000000000000i2util-1.6/config/Make-rules000066400000000000000000000007571276605416600160130ustar00rootroot00000000000000# # $Id$ # ######################################################################### # # # Copyright (C) 2002 # # Internet2 # # All Rights Reserved # # # ######################################################################### # # File: Make-rules # # Author: Jeff Boote # Internet2 # # Date: Wed Apr 24 09:59:44 EDT 2002 # # Description: # # Usage: # # Environment: # # Files: # # Options: AM_CPPFLAGS = -I$(top_builddir) -I$(top_srcdir) i2util-1.6/config/c-attribute.m4000066400000000000000000000010671276605416600165430ustar00rootroot00000000000000dnl dnl $Id$ dnl dnl dnl This macro is used to test for the gcc __attribute__ keyword. dnl AC_DEFUN([I2_C___ATTRIBUTE__], [ AC_MSG_CHECKING(for __attribute__) AC_CACHE_VAL(ac_cv___attribute__, [ AC_COMPILE_IFELSE([AC_LANG_SOURCE([[ #include static void foo(void) __attribute__ ((noreturn)); static void foo(void) { exit(1); } ]])], ac_cv___attribute__=yes, ac_cv___attribute__=no)]) if test "$ac_cv___attribute__" = "yes"; then AC_DEFINE(HAVE___ATTRIBUTE__, 1, [define if your compiler has __attribute__]) fi AC_MSG_RESULT($ac_cv___attribute__) ]) i2util-1.6/config/c-syslog-names.m4000066400000000000000000000013011276605416600171500ustar00rootroot00000000000000dnl dnl $Id$ dnl dnl dnl This macro is used to test for the syslog prioritynames global array dnl AC_DEFUN([I2_C_SYSLOG_NAMES], [ AC_MSG_CHECKING(for syslog names) AC_CACHE_VAL(ac_cv_syslognames, [ AC_COMPILE_IFELSE([AC_LANG_SOURCE([[ #include #define SYSLOG_NAMES #include static void foo(void); static void foo(void) { CODE *ptr = &prioritynames[0]; while(ptr->c_name) ptr++; ptr = &facilitynames[0]; while(ptr->c_name) ptr++; exit(0); } ]])], ac_cv_syslognames=yes, ac_cv_syslognames=no)]) if test "$ac_cv_syslognames" = "yes"; then AC_DEFINE(HAVE_SYSLOG_NAMES, 1, [define if your compiler has syslog names]) fi AC_MSG_RESULT($ac_cv_syslognames) ]) i2util-1.6/config/c-syslog-perror.m4000066400000000000000000000010641276605416600173640ustar00rootroot00000000000000dnl dnl $Id$ dnl dnl dnl This macro is used to test for the syslog LOG_PERROR constant dnl AC_DEFUN([I2_C_SYSLOG_PERROR], [ AC_MSG_CHECKING(for syslog perror availability) AC_CACHE_VAL(ac_cv_syslogperror, [ AC_COMPILE_IFELSE([AC_LANG_SOURCE([[ #include #include #ifndef LOG_PERROR #error "No LOG_PERROR defined" #endif ]])], ac_cv_syslogperror=yes, ac_cv_syslogperror=no)]) if test "$ac_cv_syslogperror" = "yes"; then AC_DEFINE(HAVE_SYSLOG_PERROR, 1, [define if your compiler has syslog names]) fi AC_MSG_RESULT($ac_cv_syslogperror) ]) i2util-1.6/config/randomdev.m4000066400000000000000000000010251276605416600162710ustar00rootroot00000000000000dnl dnl $Id$ dnl dnl dnl This macro is used to test for a kernel random device dnl AC_DEFUN([I2_RANDOMDEV], [ AC_MSG_CHECKING(for kernel random dev) AC_CACHE_VAL(i2_cv_randomdev, [ i2_cv_randomdev="no" for dev in /dev/urandom /dev/srandom /dev/random /dev/srnd /dev/rnd; do if test -c "$dev"; then i2_cv_randomdev=$dev break fi done ]) if test "$i2_cv_randomdev" != "no"; then AC_DEFINE_UNQUOTED(I2_RANDOMDEV_PATH, "$i2_cv_randomdev", [path to kernel random device]) fi AC_MSG_RESULT($i2_cv_randomdev) ]) i2util-1.6/configure.ac000066400000000000000000000054621276605416600151020ustar00rootroot00000000000000# # $Id$ # ######################################################################### # # # Copyright (C) 2002 # # Internet2 # # All Rights Reserved # # # ######################################################################### # # File: configure.ac # # Author: Jeff Boote # Internet2 # # Date: Wed Apr 24 09:32:50 EDT 2002 # # Description: autoconfig input script for I2util build # # Usage: see bootstrap... # # Environment: # # Files: # # # Options: # Process this file with autoconf to produce a configure script. AC_INIT(I2util, 1.6, owamp-bugs@internet2.edu, I2util, https://github.com/perfsonar/i2util/) AC_CONFIG_AUX_DIR(config) AC_CONFIG_MACRO_DIR(config) AM_INIT_AUTOMAKE([no-define]) AC_CONFIG_SRCDIR(I2util/ErrLog.c) AM_CONFIG_HEADER(I2util/config.h) # catch unexpanded macros m4_pattern_forbid([^I2_]) # Insert local symbols I2UTILINCS='-I${top_srcdir}' I2UTIL_dir='${top_srcdir}/I2util' I2UTILLDFLAGS="-L$I2UTIL_dir" I2UTILLIBS="$I2UTILLDFLAGS -lI2util" I2UTILLIBDEPS="$I2UTIL_dir/libI2util.a" AC_SUBST(I2UTILINCS) AC_SUBST(I2UTILLIBS) AC_SUBST(I2UTILLIBDEPS) # Check for kernel support I2_RANDOMDEV # Checks for programs. AC_PROG_CC AC_PROG_RANLIB AC_CANONICAL_HOST AC_DEFINE(_GNU_SOURCE, 1, "Use glibc features.") AC_DEFINE(_LARGEFILE_SOURCE, 1, "Use largefile api.") AM_CONDITIONAL(I2THREADS_ENABLE, false) AS_CASE($host, *-*-solaris*,[dnl AC_DEFINE(__EXTENSIONS__, 1, "get decl for sockaddr_storage on Solaris")dnl AC_DEFINE(_XOPEN_SOURCE, 500, "get decl for msg_control on Solaris")]) # Checks for libraries. AC_SEARCH_LIBS(getaddrinfo, [socket nsl]) AC_SEARCH_LIBS(gethostbyname, nsl) AC_SEARCH_LIBS(socket, socket) # Checks for header files. AC_HEADER_STDC AC_CHECK_HEADERS([errno.h stdlib.h string.h limits.h stddef.h paths.h]) # Checks for typedefs, structures, and compiler characteristics. I2_C___ATTRIBUTE__ AC_C_CONST AC_TYPE_SIZE_T AC_STRUCT_TM I2_C_SYSLOG_NAMES I2_C_SYSLOG_PERROR AC_CHECK_MEMBERS([struct sockaddr.sa_len], , , [#include #include ]) AC_CHECK_DECLS([sys_nerr, sys_errlist], , , [#include #include ]) # Checks for library functions. AC_FUNC_MALLOC AC_FUNC_STRFTIME AC_CHECK_FUNCS([memset strdup strerror strtol strtoul socket getaddrinfo]) # Check for MAN2HTML. The manpages will be compiled to html files if it's # found. AC_CHECK_PROGS([MAN2HTML], [man2html]) AS_IF([test -n "${MAN2HTML}"], [AC_DEFINE(MAN2HTML, 1, [MAN2HTML man-page converter])dnl do_man2html=true]) AM_CONDITIONAL([HAVE_MAN2HTML], test x$do_man2html = xtrue) AC_SUBST(ac_aux_dir) AC_OUTPUT([Makefile I2util/Makefile aespasswd/Makefile pfstore/Makefile doc/Makefile test/Makefile I2util.spec], [test -z "$CONFIG_HEADERS" || echo timestamp > I2util/stamp-h.in]) i2util-1.6/doc/000077500000000000000000000000001276605416600133525ustar00rootroot00000000000000i2util-1.6/doc/Makefile.am000066400000000000000000000023131276605416600154050ustar00rootroot00000000000000# # $Id$ # ######################################################################### # # # Copyright (C) 2004 # # Internet2 # # All Rights Reserved # # # ######################################################################### # # File: Makefile.am # # Author: Jeff Boote # Internet2 # # Date: Tue Feb 17 11:08:20 MST 2004 # # Description: dist_man1_MANS = aespasswd.man pfstore.man SUFFIXES = .man if HAVE_MAN2HTML SUFFIXES += .man.html .man.man.html: man2html -r $< | grep -v Content-type | sed -e 's/..\/man[0-9]\///g' | sed -e 's/\.[0-9]\.html/.man.html/g' > $@ EXTRA_DIST = aespasswd.man.html pfstore.man.html endif # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # i2util-1.6/doc/aespasswd.man000066400000000000000000000066101276605416600160440ustar00rootroot00000000000000.TH aespasswd 1 "2004 Feb 8" .\" The first line of this file must contain the '"[e][r][t][v] line .\" to tell man to run the appropriate filter "t" for table. .\" .\" $Id$ .\" .\"###################################################################### .\"# # .\"# Copyright (C) 2004 # .\"# Internet2 # .\"# All Rights Reserved # .\"# # .\"###################################################################### .\" .\" File: aespasswd.man .\" .\" Author: Jeff Boote .\" Internet2 .\" .\" Date: Sun Feb 08 00:23:56 MST 2004 .\" .\" Description: .\" .SH NAME aespasswd \- Used to create and manage an AES keyfile. .SH SYNOPSIS .B aespasswd [\fI-n\fR] [\fI-d\fR] \fI-f keyfile identity .SH OPTIONS .TP \fB\-n\fR Create the keyfile .TP \fB\-d\fR Delete given identity from keyfile .TP \fB\-f keyfile\fR Specifies file that holds identity/key pairs .SH DESCRIPTION .B aespasswd is used to create and manage files that hold identity/key pairs. It is primarily used to manage the \fIbwctld.keys\fR file for \fBbwctld\fR and the \fIowampd.keys\fR file for \fBowampd\fR. .PP If the \fI\-d\fR option is not specified, then \fBaespasswd\fR prompts the caller for a passphrase. The passphrase is hashed using an internal MD5 algorithm to generate a key that is then saved in the \fIkeyfile\fR associated with the given \fIidentity\fR. If the given \fIidentity\fR already exists in the \fIkeyfile\fR, the previous key is overwritten with the new one. .PP \fIkeyfiles\fR generated by \fBaespasswd\fR are formatted for use with \fBBWCTL\fR and \fBOWAMP\fR. .SH KEYFILE FORMAT \fBaespasswd\fR generates lines of the format: .LP test 54b0c58c7ce9f2a8b551351102ee0938 .PP An \fIidentity\fR, followed by whitespace, followed by a hex encoded 128\-bit number, that is suitable to be used as a symmetric AES key. .PP No other text is allowed on these lines; however, comment lines may be added. Comment lines are any line where the first non-white space character is '\fB#\fR'. .SH EXAMPLES \fBaespasswd \-f /usr/local/etc/bwctld.keys testuser\fP .IP Adds a key for the identity \fItestuser\fR. The user is prompted for a passphrase. If the file does not exist, an error message will be printed and no action will be taken. .LP \fBaespasswd \-f /usr/local/etc/bwctld.keys \-n testuser\fP .IP Creates the file before doing the same as above. If the file already exists, an error message will be printed and no action will be taken. .LP \fBaespasswd \-f /usr/local/etc/bwctld.keys \-d testuser\fP .IP Deletes the identity \fItestuser\fR from the keyfile. If the file does not exist, an error message will be printed and no action will be taken. .LP .SH SECURITY CONSIDERATIONS The keys in the \fIkeyfile\fR are not encrypted in any way. The security of these keys is completely dependent upon the security of the system and the discretion of the system administrator. .SH RESTRICTIONS \fIidentity\fR names are restricted to 16 characters, and passphrases are limited to 1024 characters. .SH SEE ALSO owping(1), owampd(1), bwctl(1), bwctld(1) and the \%http://e2epi.internet2.edu/owamp and \%http://e2epi.internet2.edu/bwctl web sites. .SH ACKNOWLEDGMENTS This material is based in part on work supported by the National Science Foundation (NSF) under Grant No. ANI-0314723. Any opinions, findings and conclusions or recommendations expressed in this material are those of the author(s) and do not necessarily reflect the views of the NSF. i2util-1.6/doc/pfstore.man000066400000000000000000000062771276605416600155450ustar00rootroot00000000000000.\" The first line of this file must contain the '"[e][r][t][v] line .\" to tell man to run the appropriate filter "t" for table. .\" .\" $Id$ .\" .\"###################################################################### .\"# # .\"# Copyright (C) 2006 # .\"# Internet2 # .\"# All Rights Reserved # .\"# # .\"###################################################################### .\" .\" File: pfstore.man .\" .\" Author: Jeff Boote .\" Internet2 .\" .\" Date: Sun Nov 5 15:00:39 MST 2006 .\" .\" Description: .\" .TH pfstore 1 "$Date$" .SH NAME pfstore \- Used to create and manage a pass-phrase store. .SH SYNOPSIS .B pfstore [\fI-n\fR] [\fI-d\fR] \fI-f pfsfile identity .SH OPTIONS .TP \fB\-n\fR Create the file .TP \fB\-d\fR Delete given identity from the store .TP \fB\-f pfsfile\fR Specifies file that holds identity/pass-phrase pairs .SH DESCRIPTION .B pfstore is used to create and manage files that hold identity/pass-phrase pairs. It is primarily used to manage the \fIowampd.pfs\fR file for \fBowampd\fR. .PP If the \fI\-d\fR option is not specified, then \fBpfstore\fR prompts the caller for a pass-phrase. The pass-phrase is hex-encoded and saved in the \fIpfsfile\fR with the associated \fIidentity\fR. If the given \fIidentity\fR already exists in the \fIpfsfile\fR, the previous pass-phrase is overwritten with the new one. .PP \fIpfsfiles\fR generated by \fBpfstore\fR are formatted for use with \fBOWAMP\fR. .SH PFSFILE FORMAT \fBpfstore\fR generates lines of the format: .LP test 54b0c58c7ce9f2a8b551351102ee0938 .PP An \fIidentity\fR, followed by whitespace, followed by a variable-length hex-encoded pass-phrase. .PP No other text is allowed on these lines; however, comment lines may be added. Comment lines are any line where the first non-white space character is '\fB#\fR'. .SH EXAMPLES \fBpfstore \-f /usr/local/etc/owampd.pfs testuser\fP .IP Adds a pass-phrase for the identity \fItestuser\fR. The user is prompted for a pass-phrase. If the file does not exist, an error message will be printed and no action will be taken. .LP \fBpfstore \-f /usr/local/etc/owampd.pfs \-n testuser\fP .IP Creates the file before doing the same as above. If the file already exists, an error message will be printed and no action will be taken. .LP \fBpfstore \-f /usr/local/etc/owampd.pfs \-d testuser\fP .IP Deletes the identity \fItestuser\fR from the pfsfile. If the file does not exist, an error message will be printed and no action will be taken. .LP .SH SECURITY CONSIDERATIONS The pass-phrases in the \fIpfsfile\fR are not encrypted in any way; they are simply hex-encoded. The security of these pass-phrases is completely dependent upon the security of the filesystem and the discretion of the system administrator. .SH RESTRICTIONS \fIidentity\fR names are restricted to 80 characters. .SH SEE ALSO owping(1), owampd(1), owampd(1) and the \%http://e2epi.internet2.edu/owamp web site. .SH ACKNOWLEDGMENTS This material is based, in part, on work supported by the National Science Foundation (NSF) under Grant No. ANI-0314723. Any opinions, findings, and conclusions or recommendations expressed in this material are those of the author(s) and do not necessarily reflect the views of the NSF. i2util-1.6/pfstore/000077500000000000000000000000001276605416600142675ustar00rootroot00000000000000i2util-1.6/pfstore/Makefile.am000066400000000000000000000021321276605416600163210ustar00rootroot00000000000000# # $Id$ # ######################################################################### # # # Copyright (C) 2006 # # Internet2 # # All Rights Reserved # # # ######################################################################### # # File: Makefile.am # # Author: Jeff Boote # Internet2 # # Date: Fri Oct 20 13:01:03 MDT 2006 # # Description: AM_CPPFLAGS = $(I2UTILINCS) bin_PROGRAMS = pfstore pfstore_SOURCES = pfstore.c pfstore_LDADD = $(I2UTILLIBS) $(MALLOCDEBUGLIBS) pfstore_DEPENDENCIES = $(I2UTILLIBDEPS) # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # i2util-1.6/pfstore/pfstore.c000066400000000000000000000156701276605416600161260ustar00rootroot00000000000000/* * ex: set tabstop=4 ai expandtab softtabstop=4 shiftwidth=4: * -*- mode: c-basic-indent: 4; tab-width: 4; indent-tabls-mode: nil -*- * $Id$ */ /************************************************************************ * * * Copyright (C) 2006 * * Internet2 * * All Rights Reserved * * * ************************************************************************/ /* * File: pfstore.c * * Author: Jeff W. Boote * Internet2 * * Date: Fri Oct 20 13:01:39 MDT 2006 * * Description: * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #include #include #include #include #include #include #include #include #include #include #include #include #if defined HAVE_DECL_OPTRESET && !HAVE_DECL_OPTRESET int optreset; #endif static void usage( const char *progname, const char *msg ) { if(msg) fprintf(stderr, "%s: %s\n", progname, msg); fprintf(stderr,"usage: %s %s\n", progname, "[arguments] identity" ); fprintf(stderr,"\n"); fprintf(stderr, " -f fname filename to edit [required option]\n" " -n create pffile\n" " -d delete given identity from file\n" ); return; } static int do_create = 0; static int do_delete = 0; static char *pffname; static char *idquery = NULL; static char *idname = NULL; static char *pf_bytes = NULL; static size_t pf_len = 0; int main( int argc, char **argv ) { char *progname; static char *copts = "hf:nd"; int ch; int lockfd; char lockfname[PATH_MAX]; char *dname; size_t len; struct flock flk; FILE *fromfp; FILE *tofp; char *passphrase = NULL; char *pbuf=NULL; size_t pbuf_max=0; char *lbuf=NULL; size_t lbuf_max=0; int rc; if((progname = strrchr(argv[0],'/'))){ progname++; }else{ progname = *argv; } opterr = 0; while((ch = getopt(argc,argv,copts)) != -1){ switch (ch) { case 'f': if(!(pffname = strdup(optarg))){ fprintf(stderr,"%s:%d: malloc(): %s\n", __FILE__,__LINE__, strerror(errno)); exit(errno); } break; case 'n': do_create++; break; case 'd': do_delete++; break; case 'h': case '?': default: usage(progname,""); exit(0); /* UNREACHED */ } } argc -= optind; argv += optind; if(!pffname){ usage(progname,"-f option is required"); exit(1); } if(argc != 1){ usage(progname,NULL); exit(1); } #define STR(val) #val #define STREXP(val) STR(val) if(!(idquery = strdup(argv[0]))){ fprintf(stderr,"%s:%s:%d: malloc(): %s\n", progname,__FILE__,__LINE__, strerror(errno)); exit(errno); } fromfp = fopen(pffname,"r+"); if(do_create && (fromfp != NULL)){ fprintf(stderr,"%s: -n option specified: %s exists\n\n", progname,pffname); usage(progname,NULL); exit(1); } if(!do_create && !fromfp){ fprintf(stderr,"%s: Can't open \'%s\': %s\nSee -n option?\n\n", progname,pffname,strerror(errno)); usage(progname,NULL); exit(1); } /* ensure string is nul terminated when strncpy is used */ memset(lockfname,'\0',sizeof(lockfname)); /* Don't let the last byte be written over */ len = sizeof(lockfname) - 1; /* * copy pffname to lockfname(used as tmp var here) before calling * dirname to ensure it doesn't modify pffname. */ strncpy(lockfname,pffname,len); if(!(dname = dirname(lockfname))){ fprintf(stderr,"%s: dirname(): %s\n",progname,strerror(errno)); exit(1); } /* * what directory are we putting the lockfile in. */ strncpy(lockfname,dname,len); /* * Concatinate lockfile name on. */ len = sizeof(lockfname) - strlen(lockfname) - 1; strncat(lockfname,"/.",len); len -= 2; /* strlen("/.") */ strncat(lockfname,progname,len); len -= strlen(progname); strncat(lockfname,".lock",len); /* * open the lock file (also used as the tempfile). */ lockfd = open(lockfname,O_RDWR|O_CREAT,S_IRUSR|S_IWUSR); if(lockfd < 0){ fprintf(stderr,"open(%s): %s\n",lockfname,strerror(errno)); exit(1); } /* * lock the file */ flk.l_start = 0; flk.l_len = 0; flk.l_type = F_WRLCK; flk.l_whence = SEEK_SET; if(fcntl(lockfd,F_SETLK,&flk) < 0){ fprintf(stderr,"%s: Unable to lock \'%s\': %s\n", progname,lockfname,strerror(errno)); exit(1); } /* * wrap a FILE* around the lockfile */ if(!(tofp = fdopen(lockfd,"r+"))){ fprintf(stderr,"%s: fdopen(): %s\n",progname,strerror(errno)); exit(1); } if(!do_delete){ char prompt[2048]; rc = snprintf(prompt,sizeof(prompt), "Enter passphrase for identity '%s': ", idquery); if((rc < 0) || ((size_t)rc > sizeof(prompt))){ fprintf(stderr,"%s: Identity '%s': Name too long\n", progname,idquery); exit(1); } if(!(passphrase = I2ReadPassPhraseAlloc(prompt,I2RPP_ECHO_OFF, &pbuf,&pbuf_max))){ fprintf(stderr,"%s: I2ReadPassPhrase(): %s\n", progname,strerror(errno)); exit(1); } } /* * All records that don't match idquery will be copied to tofp. */ rc = I2ParsePFFile(NULL,fromfp,tofp,0,idquery, &idname,&pf_bytes,&pf_len,&lbuf,&lbuf_max); if(rc < 0){ fprintf(stderr,"%s: I2ParseKeyFile('%s'): error line %d\n", progname,pffname,rc); exit(1); } if(do_delete){ /* * If we are deleting, the identity should have been found. */ if(!rc){ fprintf(stderr,"%s: Identity '%s' not found\n", progname,idquery); exit(1); } }else{ /* * Not deleting, add the new/changed pf line. */ if(I2WritePFLine(NULL,tofp,idquery, (uint8_t *)passphrase,strlen(passphrase), &lbuf,&lbuf_max) < 0){ fprintf(stderr,"%s:I2WritePFLine('%s'): %s\n", progname,pffname,strerror(errno)); exit(1); } } /* * Copy all remaining records. */ rc = I2ParsePFFile(NULL,fromfp,tofp,rc,idquery, &idname,&pf_bytes,&pf_len,&lbuf,&lbuf_max); if(rc != 0){ fprintf(stderr,"%s:I2ParsePFFile('%s'): error line %d\n", progname,pffname,rc); exit(1); } /* * Now close the pffile, and rename the lockfile to the pffile. */ if(fromfp) fclose(fromfp); rename(lockfname,pffname); fclose(tofp); exit(0); } i2util-1.6/support/000077500000000000000000000000001276605416600143215ustar00rootroot00000000000000i2util-1.6/support/man2html3.0.1/000077500000000000000000000000001276605416600164235ustar00rootroot00000000000000i2util-1.6/support/man2html3.0.1/CHANGES000066400000000000000000000113361276605416600174220ustar00rootroot00000000000000CHANGES for man2html: 97/08/12 13:18:14 MM/DD/YYYY =========================================================================== 08/12/1997 (3.0.1) o man2html now checks for EOF in page processing loop. This helps if page size (or margins) is set to an extremely large value to, in effect, specify no pagination exists in input. If EOF checks are not made, man2html will appear to hang until it counts off the specified page size. o Modified man.cgi so the cgi-bin location can be specified in the configuration variable section. =========================================================================== 08/11/1997 (3.0.0) o Updated man2html code for Perl 5. Program no longer executable by Perl 4 interpreters. o New command-line options: -belem : HTML Element for overstriked text (def: "B") -cgiurlexp : Perl expression URL for linking to other manpages -compress : Compress consective blank lines -uelem : HTML Element for underlined text (def: "I") o Slightly stricter check on keyword search parsing to avoid abnormal lines. o Manpage references will be put in bold even if no CGI URL expression is specified. This behavior will be restricted to the SEE ALSO section if the -seealso option is specified. o man2html modified so it can be required from Perl programs instead of using system(): - man2html code under package Man2Html - exit() not called - Input and output filehandles can be specified before being required o man2html documentation now done in troff so it can be be installed as a manpage. HTML, text, and postscript versions are created from the manpage version. o Changes to man.cgi: - Updated to run properly under Perl 5. - Requires man2html instead of using system(). - Uses implicit fork through open() to invoke man program for better security. - List variables are used for specifying command-line options instead of strings. - Cosmetic UI changes to HTML form. o Put man2html files under SCCS revision control. =========================================================================== 12/22/95 (2.1.0) o The -cgiurl option is no longer required with the -k option. if -k is specified, man2html will process input as keyword search results, regardless. o Added a -solaris option (for lack of a better word). Solaris systems have a different keyword search output compared to other systems. Example: zcmp zcmp (1) - compare compressed files zdiff zcmp (1) - compare compressed files The topic appears first. Then the actual manpage of the topic is listed second. If your keyword search results look like this, then use the -solaris option. This option is only effective with the -k option. o Fixed bug when -nohead and -seealso are both specified. o Fixed bug in detecting overstriking. man2html was try to be clever about non-alpha characters within overstriked text, but it screwed up in other cases. The "cleverness" has been removed. o '+' characters are mapped to '%2B' in cross-ref URLs. o If -seealso is specified, all xrefs are detected after the SEE ALSO heading. I.e. Sections after SEE ALSO may contain hyperlinked xrefs. o Speed increase. The amount of increase will vary depending on the input. =========================================================================== 09/02/94 (2.0.2) o Add the -bare option (for lack of a better name). This will keep man2html from inserting the HTML, HEAD, BODY tags from the output. This is useful if used in a CGI script that wants to include the output from man2html into an HTML document. =========================================================================== 08/19/94 (2.0.1) o Fixed bug in not recognizing manpage cross-refs that had a combination of bold-overstriking, underline-overstriking, and plain text. o Fixed bug in not detecting a <, >, or & to convert to an entity if the character right before it was a <, >, or &. o Speed increase. =========================================================================== 07/18/94 (2.0.0 beta) o Support for processing output from 'man -k', i.e. a keyord search. Links are created for all manpages listed, and the manpages are sorted by section. o Can now properly detect manpage references containing '_', '.', '+' characters. =========================================================================== 07/15/94 o man2html supports the ability to link to other manpages. =========================================================================== Earl Hood, ehood@medusa.acs.uci.edu i2util-1.6/support/man2html3.0.1/COPYING000066400000000000000000000433331276605416600174640ustar00rootroot00000000000000GNU General Public License ---------------------------------------------------------------------------- Table of Contents * GNU GENERAL PUBLIC LICENSE o Preamble o TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION o How to Apply These Terms to Your New Programs ---------------------------------------------------------------------------- GNU GENERAL PUBLIC LICENSE Version 2, June 1991 Copyright (C) 1989, 1991 Free Software Foundation, Inc. 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This General Public License applies to most of the Free Software Foundation's software and to any other program whose authors commit to using it. (Some other Free Software Foundation software is covered by the GNU Library General Public License instead.) You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs; and that you know you can do these things. To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it. For example, if you distribute copies of such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software. Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations. Finally, any free program is threatened constantly by software patents. We wish to avoid the danger that redistributors of a free program will individually obtain patent licenses, in effect making the program proprietary. To prevent this, we have made it clear that any patent must be licensed for everyone's free use or not licensed at all. The precise terms and conditions for copying, distribution and modification follow. TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The "Program", below, refers to any such program or work, and a "work based on the Program" means either the Program or any derivative work under copyright law: that is to say, a work containing the Program or a portion of it, either verbatim or with modifications and/or translated into another language. (Hereinafter, translation is included without limitation in the term "modification".) Each licensee is addressed as "you". Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running the Program is not restricted, and the output from the Program is covered only if its contents constitute a work based on the Program (independent of having been made by running the Program). Whether that is true depends on what the Program does. 1. You may copy and distribute verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and give any other recipients of the Program a copy of this License along with the Program. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. 2. You may modify your copy or copies of the Program or any portion of it, thus forming a work based on the Program, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: * a) You must cause the modified files to carry prominent notices stating that you changed the files and the date of any change. * b) You must cause any work that you distribute or publish, that in whole or in part contains or is derived from the Program or any part thereof, to be licensed as a whole at no charge to all third parties under the terms of this License. * c) If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the most ordinary way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this License. (Exception: if the Program itself is interactive but does not normally print such an announcement, your work based on the Program is not required to print an announcement.) These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Program, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Program, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Program. In addition, mere aggregation of another work not based on the Program with the Program (or with a work based on the Program) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 3. You may copy and distribute the Program (or a work based on it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you also do one of the following: * a) Accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, * b) Accompany it with a written offer, valid for at least three years, to give any third party, for a charge no more than your cost of physically performing source distribution, a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, * c) Accompany it with the information you received as to the offer to distribute corresponding source code. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form with such an offer, in accord with Subsection b above.) The source code for a work means the preferred form of the work for making modifications to it. For an executable work, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the executable. However, as a special exception, the source code distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. If distribution of executable or object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place counts as distribution of the source code, even though third parties are not compelled to copy the source along with the object code. 4. You may not copy, modify, sublicense, or distribute the Program except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense or distribute the Program is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. 5. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Program or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Program (or any work based on the Program), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Program or works based on it. 6. Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties to this License. 7. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Program at all. For example, if a patent license would not permit royalty-free redistribution of the Program by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Program. If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply and the section as a whole is intended to apply in other circumstances. It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system, which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. 8. If the distribution and/or use of the Program is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Program under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. 9. The Free Software Foundation may publish revised and/or new versions of the General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of this License, you may choose any version ever published by the Free Software Foundation. 10. If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. one line to give the program's name and an idea of what it does. Copyright (C) 19yy name of author This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program 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 General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. Also add information on how to contact you by electronic and paper mail. If the program is interactive, make it output a short notice like this when it starts in an interactive mode: Gnomovision version 69, Copyright (C) 19yy name of author Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, the commands you use may be called something other than `show w' and `show c'; they could even be mouse-clicks or menu items--whatever suits your program. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the program, if necessary. Here is a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the program `Gnomovision' (which makes passes at compilers) written by James Hacker. signature of Ty Coon, 1 April 1989 Ty Coon, President of Vice This General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Library General Public License instead of this License. i2util-1.6/support/man2html3.0.1/MANIFEST000066400000000000000000000000561276605416600175550ustar00rootroot00000000000000name:man2html man:doc/man2html.1 bin:man2html i2util-1.6/support/man2html3.0.1/README000066400000000000000000000073661276605416600173170ustar00rootroot00000000000000README for man2html 3.0.1 A Unix manpage-to-HTML converter. --------------------------------------------------------------------------- Copyright (C) 1995-1997 Earl Hood, ehood@medusa.acs.uci.edu This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program 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 General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA --------------------------------------------------------------------------- FILE LIST CHANGES History of changes MANIFEST List of files to install (used by install.me) README The file you are reading doc/ Documentation install.me Installation program man2html* Perl program man.cgi* A CGI program for viewing man pages. See source for usage and configuration information. --------------------------------------------------------------------------- RELEASE NOTES This is the v3 release. The reason for the increment of the major version number (from v2) is that man2html will run only under Perl 5. man2html is no longer compatible with Perl 4. Along with the change to Perl 5, several enhancments have been made. See the CHANGES file for a summary. --------------------------------------------------------------------------- INSTALLATION To install man2html, type the following command: % perl install.me The installation process will ask you a series of questions on where the Perl executable is and where to put man2html. Just hit to accept the default values listed in ()'s. Notes on installation process: o The '#!' line in the installed man2html program is set to point to the Perl executable specified in the installation process. o If you specify paths that do not exist, the install.me program will create the path. o man.cgi must be installed manually into you HTTP server's cgi-bin directory. Read the start of man.cgi for any site specific changes that may be required for proper execution. --------------------------------------------------------------------------- DOCUMENTATION A manpage for man2html gets installed as part of the installation process. The HTML, test, and PostScript versions of the documentation (dervied from the manpage) are also provided in the doc directory, but are not automatically installed by "install.me". --------------------------------------------------------------------------- BUGS/COMMENTS/SUGGESTIONS? If you have any bugs/comments/suggestions about man2html, feel free to drop me an e-mail message at ehood@medusa.acs.uci.edu. If it is a bug you are reporting, please include the following in your message: o Version of Perl (can be retrievied by "perl -v"). o Version of the program in question. o The exact command-line used to invoke the program. o Error/diagnostic message from the program. o Any other information that might prove useful. If you have questions on what man2html can, or cannot do, please read the documentation first. If the docs do not answer your question(s), feel free to e-mail me. --------------------------------------------------------------------------- Earl Hood, ehood@medusa.acs.uci.edu 97/08/12 13:18:15 i2util-1.6/support/man2html3.0.1/doc/000077500000000000000000000000001276605416600171705ustar00rootroot00000000000000i2util-1.6/support/man2html3.0.1/doc/man2html.1000066400000000000000000000443231276605416600210020ustar00rootroot00000000000000.\" sccsid = "@(#) man2html.1 1.2 08/12/97" .\" .\" ================================================ .\" ARGUMENT MACRO: .Ar "arg" [B] .de Ar .ie \\$2B \%\fB\\$1\fR .el \%\fI\\$1\fR .. .\" ================================================ .\" BRACKETED ARGUMENT MACRO: .Br "arg" [B] .de Br .ie \\$2B \%[\|\fB\\$1\fR\|] .el \%[\|\fI\\$1\fR\|] .. .\" ================================================ .\" OPTION FLAG MACRO .Of -x [arg] .de Of .ie \\n(.$==1 \%[\|\fB\\$1\fR\|] .el .if \\n(.$==2 \%[\|\fB\\$1\fR\0\fI\fI\\$2\fR\|] .. .\" ================================================ .\" SYNOPSIS START MACRO .de Ss .Ss name .na .nr aA \w\\$1\\0u .in +\\n(aAu 'ti -\\n(aAu .ta \\n(aAu \&\fB\\$1\fR\t\c .. .\" ================================================ .\" SYNOPSIS END MACRO .de Se .Se .ad .in .. .\" ================================================ .\" .\" .TH MAN2HTML 1 "97/08/12" .SH NAME .na man2html \- convert UNIX nroff(1) manual pages to HTML format .SH SYNOPSIS .na .Ss man2html .Of -bare .Of -belem name .Of -botm lines .Of -cgiurl string .Of -cgiurlexp expr .Of -compress .Of -headmap mapfile .Of -help .Of -k .Of -leftm chars .Of -nodepage .Of -noheads .Of -pgsize lines .Of -seealso .Of -solaris .Of -sun .Of -title string .Of -topm lines .Of -uelem name .Se .sp 2 Typical Usage: .sp .Ss man2html .Of -options .BI "\0<\0" infile .BI "\0\0>\0" outfile .Se .sp .B man .I topic .B | man2html .Of -options .BI "\0>\0" outfile .\" .SH DESCRIPTION .na The .B man2html filter reads formatted nroff text from standard input .RI ( stdin ) and writes a \s-1HTML\s+1 document to standard output .RI ( stdout ). .LP The formatted nroff output is surrounded with .B \s-1
\s+1
tags with the following exceptions/additions:
.RS 4n
.LP
.na
'ti -2n
'ta  2n
\(bu	Section heads are wrapped in \s-1HTML\s+1
.I header
tags.
See the
.B "\s-1SECTION\ HEAD\ MAP\ FILE\s+1"
section below for additional information.
The
.B \%-noheads
option can be used to disable this feature.
.ad
.LP
.na
'ti -2n
'ta  2n
\(bu	Bold words designated by a \%""
sequences are wrapped in
.B \s-1\s+1
tags (or the element specified via the
.B \%-belem
option).
.ad
.LP
.na
'ti -2n
'ta  2n
\(bu	Underlined words designated by a \%"_"
sequences are wrapped in
.B \s-1\s+1
tags (or the element specified via the
.B \%-uelem
option).
.ad
.RE
.SH OPTIONS
.na
.TP 0.5i
.B -bare
This option will eliminate \s-1HTML\s+1
.B \s-1\s+1
and
.B \s-1\s+1
tags from the output.
This is useful when you wish to incorporate the output into another
\s-1HTML\s+1 document.
.TP 0.5i 
.BI -belem\0 name
Use
.I name
as the name of the element to wrap overstriken characters.
The default is \fBB\fR.
.TP 0.5i 
.BI -botm\0 lines
The
.I lines
argument specifies the number of lines representing the bottom
margin of the formatted nroff input.
The line count includes any running footers.
The default value is 7.
.TP 0.5i
.BI -cgiurl\0 string
The
.I string
argument specifies a template \s-1URL\s+1 for creating links to other manpages.
See the
.B "\s-1LINKING\ TO\ OTHER\ MANPAGES\s+1"
section below for additional information.
.TP 0.5i
.BI -cgiurlexp\0 expr
The
.I expr
argument specifies a Perl expression evaluting to a \s-1URL\s+1 for
creating links to other manpages.
See the
.B "\s-1LINKING\ TO\ OTHER\ MANPAGES\s+1"
section below for additional information.
.TP 0.5i
.B -compress
Compress consecutive blank lines into a single line.
.TP 0.5i
.BI -headmap\0 mapfile
The
.I mapfile
argument is read to determine which \s-1HTML\s+1
header tags are to be used for various section heading in the manpage.
See the
.B "\s-1SECTION\ HEAD\ MAP\ FILE\s+1"
section below for information on the format of the map file.
.TP 0.5i
.B -help
Print out a short usage message and then exit immediately.
.TP 0.5i
.B -k
Process input resulting from a manpage keyword search
.RB ( "man\ -k" ).
See the
.B "\s-1KEYWORD\ SEARCH\s+1"
section below for additional information.
.TP 0.5i
.BI -leftm\0 chars
The
.I chars
argument specifies the width of the number of characters making
up the left margin of the formatted nroff input.
The default value is 0.
.TP 0.5i
.B -nodepage
By default,
.B man2html
merges multi-page formatted nroff into a single page.
This option may be used to disable depagination, causing
running headers and footers in the formatted nroff input
to be carried over into the \s-1HTML\s+1 output.
.TP 0.5i
.B -noheads
By default,
.B man2html
wraps section heads in \s-1HTML\s+1
header tags.
See the
.B "\s-1SECTION\ HEAD\ MAP\ FILE\s+1"
section below for additional information.
This option may be specified to disabled this feature.
.TP 0.5i
.BI -pgsize\0 lines
The
.I lines
argument specifies the number of lines making up the page size (length)
of the formatted nroff input.
The default value is 66.
.TP 0.5i
.B -seealso
If the
.B -cgiurl
option has been specified, then this option restricts the
creation of links to other manual pages to the
.B "\%\s-1SEE\ ALSO\s+1"
section only.
.TP 0.5i
.B -solaris
If the
.B -k
option has been specified, then this option modifies its operation
to process the alternate manual page keyword search format produced
by the
.BR man (1)
utility on systems running
.IR Solaris .
See the
.B "\s-1KEYWORD\ SEARCH\s+1"
section below for additional information.
.TP 0.5i
.B -sun
Do not require a section head to have bold overstriking in the
formatted nroff input.
The option is called
.B \%sun
because it was on a Sun workstation that section heads in
manpages were found to not be overstruck.
.TP 0.5i
.BI -title\0 string
By default,
.B man2html
does not generate a \s-1HTML\s+1 title
.RB ( \s-1\s+1 ).
This option sets the title of the \s-1HTML\s+1 output to the specified
.IR string .
.TP 0.5i
.BI -topm\0 lines
The
.I lines
argument specifies number number of lines representing the
top margin of the formatted nroff input.
The line count includes any running headers.
The default value is 7.
.TP 0.5i 
.BI -uelem\0 name
Use
.I name
as the name of the element to wrap underscored characters.
The default is \fBI\fR.
.\"
.SH "SECTION HEAD MAP FILE"
.na
.LP
The
.B \%-headmap
option may be used to customize which \s-1HTML\s+1 header tags,
.BR "\s-1<H1>\s+1 ... \s-1<H6>\s+1" ,
are used in manpage section headings.
Normally,
.B man2html
treats lines that are flush to the left margin
.RB ( -leftm ),
and contain overstriking (overstrike check is canceled with the
.B -sun
option), as section heads.
However, you can augment/override what \s-1HTML\s+1 header tags are used for
any given section head.
.LP
In order to write a section head map file, you will need to know about
.BR perl (1)
associative arrays.
You do not need to be an expert in
.B perl
to write a map file, however, having knowledge of
.B perl
allows you to be more clever.
.\"
.SS "Augmenting the Default Map" 
.LP
To add to the default mapping defined by
.BR man2html ,
your map file will contain lines with the following syntax:
.sp
.if t .RS 4n
.B "$SectionHead{'<section head text>'} = '<html header tag>';"
.if t .RE
.sp
where
.IP "\fB\%<section\ head\ text>\fR"
is the text of the manpage section head.
For example:
.B  \s-1SYNOPSIS\s+1
or
.BR \s-1DESCRIPTION\s+1 .
.IP "\fB\%<html\ header\ tag>\fR"
is the \s-1HTML\s+1 header tag to wrap the section head in.
Legal values are:
.BR \s-1<H1>\s+1 ,
.BR \s-1<H2>\s+1 ,
.BR \s-1<H3>\s+1 ,
.BR \s-1<H4>\s+1 ,
.BR \s-1<H5>\s+1 ,
.BR \s-1<H6>\s+1 .
.SS "Overriding the Default Map"
To override the default mapping with your own, then your map file will
have the following syntax:
.sp
.RS 4n
.ft B
.nf
.ne 6v
%SectionHead = (
         \&'<section head text>', '<html header tag>',
         \&'<section head text>', '<html header tag>',
         \&# ... More section head/tag pairs
         \&'<section head text>', '<html header tag>',
);
.fi
.ft
.RE
.SS "The Default Map"
.LP
As of this writing, this is the default map used by
.BR man2html :
.RS 4n
.sp
.ft C
.nf
.ne 29v
%SectionHead = (
.ps -1
    \&'\\S.*OPTIONS.*'             => '<H2>',
    \&'AUTHORS?'                  => '<H2>',
    \&'BUGS'                      => '<H2>',
    \&'COMPATIBILITY'             => '<H2>',
    \&'DEPENDENCIES'              => '<H2>',
    \&'DESCRIPTION'               => '<H2>',
    \&'DIAGNOSTICS'               => '<H2>',
    \&'ENVIRONMENT'               => '<H2>',
    \&'ERRORS'                    => '<H2>',
    \&'EXAMPLES'                  => '<H2>',
    \&'EXTERNAL INFLUENCES'       => '<H2>',
    \&'FILES'                     => '<H2>',
    \&'LIMITATIONS'               => '<H2>',
    \&'NAME'                      => '<H2>',
    \&'NOTES?'                    => '<H2>',
    \&'OPTIONS'                   => '<H2>',
    \&'REFERENCES'                => '<H2>',
    \&'RETURN VALUE'              => '<H2>',
    \&'SECTION.*:'                => '<H2>',
    \&'SEE ALSO'                  => '<H2>',
    \&'STANDARDS CONFORMANCE'     => '<H2>',
    \&'STYLE CONVENTION'          => '<H2>',
    \&'SYNOPSIS'                  => '<H2>',
    \&'SYNTAX'                    => '<H2>',
    \&'WARNINGS'                  => '<H2>',
    \&'\\s+Section.*:'             => '<H3>',
.ps +1
);
$HeadFallback = '\s-1<H2>\s+1';  # Fallback tag if above is not found.
.fi
.ft
.RE
.LP
Check the
.B perl
source code of
.B man2html
for the latest default mapping.
.LP 
You can reassign the
.B \%$HeadFallback
variable to a different value if you choose.
This value is used as the header tag of a section head if
no matches are found in the \%\fB%SectionHead\fR map.
.SS "Using Regular Expressions in the Map File"
.LP
You may have noticed unusual characters in the default map file, like
"\\s" or "*".
The
.B man2html
utility actual treats the
.B "\%<section\ head\ text>"
as a
.B perl
regular expression.
If you are comfortable with
.B perl
regular expressions, then you have their full power to use
in your map file.
.LP
.I Caution:
The
.B man2html
utility already anchors the regular expression to the beginning of the
line with left margin spacing specified by the
.B \%-leftm
option.
Therefore, do not use the `\fB\fR^' character to anchor your regular
expression to the beginning.
However, you may end your expression with a `\fB$\fR' to anchor it to
the end of the line.
.LP 
Since the
.B "\%<section\ head\ text>"
is actually a regular expression, you will have to be careful of
special characters if you want them to be treated literally.
Any of the characters
.RB ` "[ ] ( ) . ^ { } $ * ? + \\ |" '
should be escaped by prefixing them by the
\&`\fB\\\fR' character if you want
.B perl
to treat them "as is".
.LP
.I Caution:
One should use single quotes instead of double quotes to delimit
.BR "\%<section\ head\ text>" .
This will preserve any `\fB\\\fR' characters for character escaping
or when the `\fB\\\fR' is used for special
.B perl
character matching sequences (e.g.,  \fB\\s\fR, \fB\\w\fR, \fB\\S\fR).
.SS "Other Tid-bits on the Map File"
.LP
Comments can be inserted in the map file by using the '\fB#\fR'
character.
Anything after, and including, the '\fB#\fR' character is ignored,
up to the end of line.
.LP 
You might be thinking that the above is quite-a-bit-of-stuff just for
doing manpage section heads.
However, you will be surprised how much better the \s-1HTML\s+1 output looks
with header tags, even though, everything else is in a
.B \s-1<PRE>\s+1
tag.
.\"
.SH "LINKING TO OTHER MANPAGES"
.na
.LP 
The
.B man2html
utility allows the ability to link to other manpage references.
If the
.B \%-cgiurl
option is specified,
.B man2html
will create anchors that link to other manpages.
.LP 
The \s-1URL\s+1 entered with the
.B \%-cgiurl
option is actually a template that determines the actual \s-1URL\s+1 used to
link to other manpages.
The following variables are defined during run time that may be used in
the template string:
.sp
.RS 4n
.IP \fB$title\fR
The title of the manual page referenced.
.IP \fB$section\fR
The section number of the manual page referenced.
.IP \fB$subsection\fR
The subsection of the manual page referenced.
.RE
.LP
Any other text in the template is preserved "as is".
.LP
.I Caution:
The
.B man2html
utility evaluates the template string as a
.B perl
string expression.
Therefore, one might need to surround the variable names with
\&'\fB{\|}\fR' (e.g.,
.BR ${\|title\|}\| )
so that
.B man2html
properly recognizes the variable.
.LP
.I Note:
If a \s-1CGI\s+1 program calling
.B man2html
is actually a shell script or a
.B perl
program, make sure to properly escape the '\fB$\fR' character
in the \s-1URL\s+1 template to avoid variable interpolation by the \s-1CGI\s+1
program.
.LP
Normally, the \s-1URL\s+1 calls a \s-1CGI\s+1 program (hence the option name),
but the \s-1URL\s+1 can easily link to statically converted documents.
.SS "Example1:"
.LP 
The following template string is specified to call a \s-1CGI\s+1 program to
retrieve the appropriate manpage linked to:
.LP
.nf
.B "/cgi-bin/man.cgi?section=${section}${subsection}&topic=${title}"
.fi
.LP 
If the
.BR ls (1)
manpage is referenced in the
.B "SEE ALSO"
section, the above template will translate to the following \s-1URL\s+1:
.LP
.B "/cgi-bin/man.cgi?section=1&topic=ls"
.LP 
The actual \s-1HTML\s+1 markup will look like the following:
.LP
\fB<A\ HREF="/cgi-bin/man.cgi?section=1&topic=ls">ls(1)</A>\fR
.SS "Example2:"
.LP 
The following template string is specified to retrieve pre-converted
manpages:
.LP
.B "http://foo.org/man$section/$title.$section$subsection.html"
.LP 
If the
.BR mount (1M)
manpage is referenced, the above template will translate to the
following \s-1URL\s+1:
.LP
.B "http://foo.org/man1/mount.1M.html"
.LP 
The actual \s-1HTML\s+1 markup will look like the following:
.LP
\fB<A HREF="http://foo.org/man1/mount.1M.html">mount(1M)</A>\fR
.SS "-cgiurlexp"
The option
.B \%-cgiurlexp
is a more general form of the
.B \%-cgiurl
option.
.B \%-cgiurlexp
allows one to specify a general Perl expression.  For example:
.LP
\fB$title=~/^db_/i?"$title.html":"/cgi-bin/man?$title+$section"\fR
.LP
A
.B \%-cgiurl
.I string
can be expressed as follows with \fB-cgiurlexp\fR:
.LP
\fBreturn "\fIstring\fB"\fR
.\"
.SH "KEYWORD SEARCH"
.na
.LP
The
.B man2html
utility has the ability to process keyword search output generated
by the \%\fBman\ -k\fR or \%\fBapropos\fR commands, through the
use of the
.B -k
option.
The
.B man2html
utility will generate an \s-1HTML\s+1 document of the keyword search input
having the following format:
.RS 4n 
.LP
.na
'ti -2n
'ta  2n
\(bu	All manpage references are listed by section.
.ad
.LP
.na
'ti -2n
'ta  2n
\(bu	Within each section listing, the manpage references
are sorted alphabetically (case-sensitive) in a
.B \s-1<DL>\s+1
tag.
The manpage references are listed in the
.B \s-1<DT>\s+1
section, and the summary text is listed in the
.B \s-1<DD>\s+1
section.
.ad
.LP
.na
'ti -2n
'ta  2n
\(bu	Each manpage reference listed is a hyperlink to the
actual manpage as specified by the
.B \%-cgiurl
option.
.ad
.RE
.LP 
.na
This ability to process keyword searches gives nice added functionality
to a \s-1WWW\s+1 forms interface to
.BR man (1).
Even if you have statically converted manpages to \s-1HTML\s+1 via another
man->\s-1HTML\s+1 program, you can use
.B man2html
and "\fBman\ -k\fR" to provide keyword search capabilities easily for
your \s-1HTML\s+1 manpages.
.SS "Processing Keyword Search Results"
.na
.LP 
Unfortunately, there is no standard controlling the format of keyword
search results.
The
.B man2html
utility tries it best to handle all the variations.
However, the keyword search results generated by the
.I Solaris
operating system is different enough from other systems that a
special command-line option
.RB ( -solaris )
must be specified to handle its output.
.SS "Example of raw Solaris-type keyword search results:"
.LP
.ft C
.nf
.ne 10v
strcpy        strcpy (9f)  - copy a string from one location to another.
strcpy        string (3c)  - string operations
strncpy       strcpy (9f)  - copy a string from one location to another.
strncpy       string (3c)  - string operations
.fi
.ft
.LP 
If keyword search results on your systems appear in the following format:
.LP
.RS 4n
.B "<topic>  <actual_manpage> (#) - Description"
.RE
.LP
then you need to specify the
.B \%-solaris
option in addition to the
.B -k
option.
.SH "ADDITIONAL NOTES"
.na
.LP
Different systems format manpages differently.
Here is a list of recommended command-line options for certain systems:
.RS 4n
.LP
.ta 1i
.nf
.ne 3v
\fBConvex\fR:	<defaults should be okay>
\fBHP\fR:	\fB-leftm 1 -topm 8\fR
\fBSun\fR:	\fB-sun\fR (and \fB-solaris\fR when using \fB-k\fR)
.fi
.RE
.LP
Some line spacing gets lost in the formatted nroff since the
spacing would occur in the middle of a page break.
This can cause text to be merged that shouldn't be merged when
.B man2html
depaginates the text.
To avoid this problem,
.B man2html
keeps track of the margin indent right before and after a page break.
If the margin width of the line after the page break is less than the
line before the page break, then
.B man2html
inserts a blank line in the \s-1HTML\s+1 output.
.LP 
A manpage cross-reference is detected by the following pseudo expression:
\%\fB[A-z.-+_]+([0-9][A-z]?)\fR
.LP
The
.B man2html
utility only recognizes lines with "\fB - \fR" (the normal separator
between manpage references and summary text) while in keyword
search mode.
.LP 
The
.B man2html
utility can be hooked in a \s-1CGI\s+1 script/program to convert manpages
on the fly.
This is the reason for the
.B \%-cgiurl
option.
.SH LIMITATIONS
.na
.LP 
The order that section head mapping is searched is not defined.
Therefore, if two or more
.B "\%<section\ head\ text>"
can match a give manpage section, there is no way to determine
which map tag is chosen.
.LP 
If
.B \%-seealso
is specified, all xrefs are detected after the
.B "\%SEE\ ALSO"
heading.
In other words, sections after
.B "\%SEE\ ALSO"
may contain hyperlinked xrefs.
.SH BUGS
.na
.LP 
Text that is flush to the left margin, but is not actually a
section head, can be mistaken for a section head.
This mistake is more likely when the
.B \%-sun
option is in affect.
.SH VERSION
.na
This documentation describes
.B man2html
version 3.0.1
.SH "SEE ALSO"
.na
.BR man (1),
.BR nroff (1),
.BR perl (1)
.LP
.I http://www.oac.uci.edu/indiv/ehood/man2html.html
.SH AUTHOR
.LP
.B Earl Hood
.br
.I ehood@medusa.acs.uci.edu
.\"
.SH "ERRORS AND OMISSIONS"
.na
Troff version of this document initially created for version 2.1.0
by C. Jeffery Small
.RI ( jeff@cjsa.com )
by copying, reformatting, rearranging and partially rewriting
the contents of the ascii text file
.BR doc/man2html.txt .
�������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������i2util-1.6/support/man2html3.0.1/doc/man2html.html��������������������������������������������������0000664�0000000�0000000�00000051310�12766054166�0021600�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<HTML>
<BODY>
<PRE>
<!-- Manpage converted by man2html 3.0.1 -->

</PRE>
<H2>NAME</H2><PRE>
     man2html - convert UNIX <B>nroff(1)</B> manual pages to HTML format


</PRE>
<H2>SYNOPSIS</H2><PRE>
     <B>man2html</B> [<B>-bare</B>] [<B>-belem</B> <I>name</I>] [<B>-botm</B> <I>lines</I>]
              [<B>-cgiurl</B> <I>string</I>] [<B>-cgiurlexp</B> <I>expr</I>] [<B>-compress</B>]
              [<B>-headmap</B> <I>mapfile</I>] [<B>-help</B>] [<B>-k</B>] [<B>-leftm</B> <I>chars</I>]
              [<B>-nodepage</B>] [<B>-noheads</B>] [<B>-pgsize</B> <I>lines</I>] [<B>-seealso</B>]
              [<B>-solaris</B>] [<B>-sun</B>] [<B>-title</B> <I>string</I>] [<B>-topm</B> <I>lines</I>]
              [<B>-uelem</B> <I>name</I>]

     Typical Usage:

     <B>man2html</B> [<B>-options</B>]  <B><</B> <I>infile</I>   <B>></B> <I>outfile</I>

     <B>man</B> <I>topic</I> <B>|</B> <B>man2html</B> [<B>-options</B>]  <B>></B> <I>outfile</I>


</PRE>
<H2>DESCRIPTION</H2><PRE>
     The <B>man2html</B> filter reads formatted nroff text from standard
     input (<I>stdin</I>) and writes a HTML document to standard output
     (<I>stdout</I>).

     The formatted nroff output is surrounded with <B><PRE></B> tags
     with the following exceptions/additions:

       <B>o</B> Section heads are wrapped in HTML <I>header</I> tags.  See the
         <B>SECTION</B> <B>HEAD</B> <B>MAP</B> <B>FILE</B> section below for additional
         information.  The <B>-noheads</B> option can be used to disable
         this feature.

       <B>o</B> Bold words designated by a "<char><bs><char>" sequences
         are wrapped in <B><B></B> tags (or the element specified via
         the <B>-belem</B> option).

       <B>o</B> Underlined words designated by a "_<bs><char>" sequences
         are wrapped in <B><I></B> tags (or the element specified via
         the <B>-uelem</B> option).


</PRE>
<H2>OPTIONS</H2><PRE>
     <B>-bare</B>
          This option will eliminate HTML <B><HEAD></B> and <B><BODY></B> tags
          from the output.  This is useful when you wish to
          incorporate the output into another HTML document.

     <B>-belem</B> <I>name</I>
          Use <I>name</I> as the name of the element to wrap overstriken
          characters.  The default is <B>B</B>.

     <B>-botm</B> <I>lines</I>
          The <I>lines</I> argument specifies the number of lines repre-
          senting the bottom margin of the formatted nroff input.
          The line count includes any running footers.  The
          default value is 7.

     <B>-cgiurl</B> <I>string</I>
          The <I>string</I> argument specifies a template URL for creat-
          ing links to other manpages.  See the
          <B>LINKING</B> <B>TO</B> <B>OTHER</B> <B>MANPAGES</B> section below for additional
          information.

     <B>-cgiurlexp</B> <I>expr</I>
          The <I>expr</I> argument specifies a Perl expression evaluting
          to a URL for creating links to other manpages.  See the
          <B>LINKING</B> <B>TO</B> <B>OTHER</B> <B>MANPAGES</B> section below for additional
          information.

     <B>-compress</B>
          Compress consecutive blank lines into a single line.

     <B>-headmap</B> <I>mapfile</I>
          The <I>mapfile</I> argument is read to determine which HTML
          header tags are to be used for various section heading
          in the manpage.  See the <B>SECTION</B> <B>HEAD</B> <B>MAP</B> <B>FILE</B> section
          below for information on the format of the map file.

     <B>-help</B>
          Print out a short usage message and then exit immedi-
          ately.

     <B>-k</B>   Process input resulting from a manpage keyword search
          (<B>man</B> <B>-k</B>).  See the <B>KEYWORD</B> <B>SEARCH</B> section below for
          additional information.

     <B>-leftm</B> <I>chars</I>
          The <I>chars</I> argument specifies the width of the number of
          characters making up the left margin of the formatted
          nroff input.  The default value is 0.

     <B>-nodepage</B>
          By default, <B>man2html</B> merges multi-page formatted nroff
          into a single page.  This option may be used to disable
          depagination, causing running headers and footers in
          the formatted nroff input to be carried over into the
          HTML output.

     <B>-noheads</B>
          By default, <B>man2html</B> wraps section heads in HTML header
          tags.  See the <B>SECTION</B> <B>HEAD</B> <B>MAP</B> <B>FILE</B> section below for
          additional information.  This option may be specified
          to disabled this feature.

     <B>-pgsize</B> <I>lines</I>
          The <I>lines</I> argument specifies the number of lines making
          up the page size (length) of the formatted nroff input.
          The default value is 66.

     <B>-seealso</B>
          If the <B>-cgiurl</B> option has been specified, then this
          option restricts the creation of links to other manual
          pages to the <B>SEE</B> <B>ALSO</B> section only.

     <B>-solaris</B>
          If the <B>-k</B> option has been specified, then this option
          modifies its operation to process the alternate manual
          page keyword search format produced by the <B>man(1)</B> util-
          ity on systems running <I>Solaris</I>.  See the <B>KEYWORD</B> <B>SEARCH</B>
          section below for additional information.

     <B>-sun</B> Do not require a section head to have bold overstriking
          in the formatted nroff input.  The option is called <B>sun</B>
          because it was on a Sun workstation that section heads
          in manpages were found to not be overstruck.

     <B>-title</B> <I>string</I>
          By default, <B>man2html</B> does not generate a HTML title
          (<B><TITLE></B>).  This option sets the title of the HTML out-
          put to the specified <I>string</I>.

     <B>-topm</B> <I>lines</I>
          The <I>lines</I> argument specifies number number of lines
          representing the top margin of the formatted nroff
          input.  The line count includes any running headers.
          The default value is 7.

     <B>-uelem</B> <I>name</I>
          Use <I>name</I> as the name of the element to wrap underscored
          characters.  The default is <B>I</B>.


</PRE>
<H2>SECTION HEAD MAP FILE</H2><PRE>
     The <B>-headmap</B> option may be used to customize which HTML
     header tags, <B><H1></B> <B>...</B> <B><H6></B>, are used in manpage section
     headings.  Normally, <B>man2html</B> treats lines that are flush to
     the left margin (<B>-leftm</B>), and contain overstriking (over-
     strike check is canceled with the <B>-sun</B> option), as section
     heads.  However, you can augment/override what HTML header
     tags are used for any given section head.

     In order to write a section head map file, you will need to
     know about <B>perl(1)</B> associative arrays.  You do not need to
     be an expert in <B>perl</B> to write a map file, however, having
     knowledge of <B>perl</B> allows you to be more clever.

  <B>Augmenting</B> <B>the</B> <B>Default</B> <B>Map</B>
     To add to the default mapping defined by <B>man2html</B>, your map
     file will contain lines with the following syntax:
     <B>$SectionHead{'<section</B> <B>head</B> <B>text>'}</B> <B>=</B> <B>'<html</B> <B>header</B> <B>tag>';</B>

     where

     <B><section</B> <B>head</B> <B>text></B>
          is the text of the manpage section head.  For example:
          <B>SYNOPSIS</B> or <B>DESCRIPTION</B>.

     <B><html</B> <B>header</B> <B>tag></B>
          is the HTML header tag to wrap the section head in.
          Legal values are: <B><H1></B>, <B><H2></B>, <B><H3></B>, <B><H4></B>, <B><H5></B>, <B><H6></B>.

  <B>Overriding</B> <B>the</B> <B>Default</B> <B>Map</B>
     To override the default mapping with your own, then your map
     file will have the following syntax:

         <B>%SectionHead</B> <B>=</B> <B>(</B>
                  <B>'<section</B> <B>head</B> <B>text>',</B> <B>'<html</B> <B>header</B> <B>tag>',</B>
                  <B>'<section</B> <B>head</B> <B>text>',</B> <B>'<html</B> <B>header</B> <B>tag>',</B>
                  <B>#</B> <B>...</B> <B>More</B> <B>section</B> <B>head/tag</B> <B>pairs</B>
                  <B>'<section</B> <B>head</B> <B>text>',</B> <B>'<html</B> <B>header</B> <B>tag>',</B>
         <B>);</B>

  <B>The</B> <B>Default</B> <B>Map</B>
     As of this writing, this is the default map used by
     <B>man2html</B>:

         %SectionHead = (
             '\S.*OPTIONS.*'             => '<H2>',
             'AUTHORS?'                  => '<H2>',
             'BUGS'                      => '<H2>',
             'COMPATIBILITY'             => '<H2>',
             'DEPENDENCIES'              => '<H2>',
             'DESCRIPTION'               => '<H2>',
             'DIAGNOSTICS'               => '<H2>',
             'ENVIRONMENT'               => '<H2>',
             'ERRORS'                    => '<H2>',
             'EXAMPLES'                  => '<H2>',
             'EXTERNAL INFLUENCES'       => '<H2>',
             'FILES'                     => '<H2>',
             'LIMITATIONS'               => '<H2>',
             'NAME'                      => '<H2>',
             'NOTES?'                    => '<H2>',
             'OPTIONS'                   => '<H2>',
             'REFERENCES'                => '<H2>',
             'RETURN VALUE'              => '<H2>',
             'SECTION.*:'                => '<H2>',
             'SEE ALSO'                  => '<H2>',
             'STANDARDS CONFORMANCE'     => '<H2>',
             'STYLE CONVENTION'          => '<H2>',
             'SYNOPSIS'                  => '<H2>',
             'SYNTAX'                    => '<H2>',
             'WARNINGS'                  => '<H2>',
             '\s+Section.*:'             => '<H3>',
         );
         $HeadFallback = '<H2>';  # Fallback tag if above is not found.

     Check the <B>perl</B> source code of <B>man2html</B> for the latest
     default mapping.

     You can reassign the <B>$HeadFallback</B> variable to a different
     value if you choose.  This value is used as the header tag
     of a section head if no matches are found in the
     <B>%SectionHead</B> map.

  <B>Using</B> <B>Regular</B> <B>Expressions</B> <B>in</B> <B>the</B> <B>Map</B> <B>File</B>
     You may have noticed unusual characters in the default map
     file, like "\s" or "*".  The <B>man2html</B> utility actual treats
     the <B><section</B> <B>head</B> <B>text></B> as a <B>perl</B> regular expression.  If
     you are comfortable with <B>perl</B> regular expressions, then you
     have their full power to use in your map file.

     <I>Caution:</I> The <B>man2html</B> utility already anchors the regular
     expression to the beginning of the line with left margin
     spacing specified by the <B>-leftm</B> option.  Therefore, do not
     use the `^' character to anchor your regular expression to
     the beginning.  However, you may end your expression with a
     `<B>$</B>' to anchor it to the end of the line.

     Since the <B><section</B> <B>head</B> <B>text></B> is actually a regular expres-
     sion, you will have to be careful of special characters if
     you want them to be treated literally.  Any of the charac-
     ters `<B>[</B> <B>]</B> <B>(</B> <B>)</B> <B>.</B> <B>^</B> <B>{</B> <B>}</B> <B>$</B> <B>*</B> <B>?</B> <B>+</B>  <B>|</B>' should be escaped by pre-
     fixing them by the `<B>\</B>' character if you want <B>perl</B> to treat
     them "as is".

     <I>Caution:</I> One should use single quotes instead of double
     quotes to delimit <B><section</B> <B>head</B> <B>text></B>.  This will preserve
     any `<B>\</B>' characters for character escaping or when the `<B>\</B>' is
     used for special <B>perl</B> character matching sequences (e.g.,
     <B>\s</B>, <B>\w</B>, <B>\S</B>).

  <B>Other</B> <B>Tid-bits</B> <B>on</B> <B>the</B> <B>Map</B> <B>File</B>
     Comments can be inserted in the map file by using the '<B>#</B>'
     character.  Anything after, and including, the '<B>#</B>' character
     is ignored, up to the end of line.

     You might be thinking that the above is quite-a-bit-of-stuff
     just for doing manpage section heads.  However, you will be
     surprised how much better the HTML output looks with header
     tags, even though, everything else is in a <B><PRE></B> tag.


</PRE>
<H2>LINKING TO OTHER MANPAGES</H2><PRE>
     The <B>man2html</B> utility allows the ability to link to other
     manpage references.  If the <B>-cgiurl</B> option is specified,
     <B>man2html</B> will create anchors that link to other manpages.

     The URL entered with the <B>-cgiurl</B> option is actually a tem-
     plate that determines the actual URL used to link to other
     manpages.  The following variables are defined during run
     time that may be used in the template string:

         <B>$title</B>
              The title of the manual page referenced.

         <B>$section</B>
              The section number of the manual page referenced.

         <B>$subsection</B>
              The subsection of the manual page referenced.

     Any other text in the template is preserved "as is".

     <I>Caution:</I> The <B>man2html</B> utility evaluates the template string
     as a <B>perl</B> string expression.  Therefore, one might need to
     surround the variable names with '<B>{}</B>' (e.g., <B>${title}</B>) so
     that <B>man2html</B> properly recognizes the variable.

     <I>Note:</I> If a CGI program calling <B>man2html</B> is actually a shell
     script or a <B>perl</B> program, make sure to properly escape the
     '<B>$</B>' character in the URL template to avoid variable interpo-
     lation by the CGI program.

     Normally, the URL calls a CGI program (hence the option
     name), but the URL can easily link to statically converted
     documents.

  <B>Example1:</B>
     The following template string is specified to call a CGI
     program to retrieve the appropriate manpage linked to:

     <B>/cgi-bin/man.cgi?section=${section}${subsection}&topic=${title}</B>

     If the <B>ls(1)</B> manpage is referenced in the <B>SEE</B> <B>ALSO</B> section,
     the above template will translate to the following URL:

     <B>/cgi-bin/man.cgi?section=1&topic=ls</B>

     The actual HTML markup will look like the following:

     <B><A</B> <B>HREF="/cgi-bin/man.cgi?section=1&topic=ls">ls(1)</A></B>

  <B>Example2:</B>
     The following template string is specified to retrieve pre-
     converted manpages:

     <B>http://foo.org/man$section/$title.$section$subsection.html</B>

     If the <B>mount(1M)</B> manpage is referenced, the above template
     will translate to the following URL:

     <B>http://foo.org/man1/mount.1M.html</B>

     The actual HTML markup will look like the following:

     <B><A</B> <B>HREF="http://foo.org/man1/mount.1M.html">mount(1M)</A></B>

  <B>-cgiurlexp</B>
     The option <B>-cgiurlexp</B> is a more general form of the <B>-cgiurl</B>
     option.  <B>-cgiurlexp</B> allows one to specify a general Perl
     expression.  For example:

     <B>$title=~/^db_/i?"$title.html":"/cgi-bin/man?$title+$section"</B>

     A <B>-cgiurl</B> <I>string</I> can be expressed as follows with <B>-cgiurl-</B>
     <B>exp</B>:

     <B>return</B> <B>"</B><I>string</I><B>"</B>


</PRE>
<H2>KEYWORD SEARCH</H2><PRE>
     The <B>man2html</B> utility has the ability to process keyword
     search output generated by the <B>man</B> <B>-k</B> or <B>apropos</B> commands,
     through the use of the <B>-k</B> option.  The <B>man2html</B> utility will
     generate an HTML document of the keyword search input having
     the following format:

       <B>o</B> All manpage references are listed by section.

       <B>o</B> Within each section listing, the manpage references are
         sorted alphabetically (case-sensitive) in a <B><DL></B> tag.
         The manpage references are listed in the <B><DT></B> section,
         and the summary text is listed in the <B><DD></B> section.

       <B>o</B> Each manpage reference listed is a hyperlink to the
         actual manpage as specified by the <B>-cgiurl</B> option.

     This ability to process keyword searches gives nice added
     functionality to a WWW forms interface to <B>man(1)</B>.  Even if
     you have statically converted manpages to HTML via another
     man->HTML program, you can use <B>man2html</B> and "<B>man</B> <B>-k</B>" to pro-
     vide keyword search capabilities easily for your HTML man-
     pages.

  <B>Processing</B> <B>Keyword</B> <B>Search</B> <B>Results</B>
     Unfortunately, there is no standard controlling the format
     of keyword search results.  The <B>man2html</B> utility tries it
     best to handle all the variations.  However, the keyword
     search results generated by the <I>Solaris</I> operating system is
     different enough from other systems that a special command-
     line option (<B>-solaris</B>) must be specified to handle its out-
     put.

  <B>Example</B> <B>of</B> <B>raw</B> <B>Solaris-type</B> <B>keyword</B> <B>search</B> <B>results:</B>
     strcpy        strcpy (9f)  - copy a string from one location to another.
     strcpy        string (3c)  - string operations
     strncpy       strcpy (9f)  - copy a string from one location to another.
     strncpy       string (3c)  - string operations

     If keyword search results on your systems appear in the fol-
     lowing format:

         <B><topic></B>  <B><actual_manpage></B> <B>(#)</B> <B>-</B> <B>Description</B>

     then you need to specify the <B>-solaris</B> option in addition to
     the <B>-k</B> option.


</PRE>
<H2>ADDITIONAL NOTES</H2><PRE>
     Different systems format manpages differently.  Here is a
     list of recommended command-line options for certain sys-
     tems:

         <B>Convex</B>:   <defaults should be okay>
         <B>HP</B>:       <B>-leftm</B> <B>1</B> <B>-topm</B> <B>8</B>
         <B>Sun</B>:      <B>-sun</B> (and <B>-solaris</B> when using <B>-k</B>)

     Some line spacing gets lost in the formatted nroff since the
     spacing would occur in the middle of a page break.  This can
     cause text to be merged that shouldn't be merged when
     <B>man2html</B> depaginates the text.  To avoid this problem,
     <B>man2html</B> keeps track of the margin indent right before and
     after a page break.  If the margin width of the line after
     the page break is less than the line before the page break,
     then <B>man2html</B> inserts a blank line in the HTML output.

     A manpage cross-reference is detected by the following
     pseudo expression: <B>[A-z.-+_]+([0-9][A-z]?)</B>

     The <B>man2html</B> utility only recognizes lines with " <B>-</B> " (the
     normal separator between manpage references and summary
     text) while in keyword search mode.

     The <B>man2html</B> utility can be hooked in a CGI script/program
     to convert manpages on the fly.  This is the reason for the
     <B>-cgiurl</B> option.


</PRE>
<H2>LIMITATIONS</H2><PRE>
     The order that section head mapping is searched is not
     defined.  Therefore, if two or more <B><section</B> <B>head</B> <B>text></B> can
     match a give manpage section, there is no way to determine
     which map tag is chosen.

     If <B>-seealso</B> is specified, all xrefs are detected after the
     <B>SEE</B> <B>ALSO</B> heading.  In other words, sections after <B>SEE</B> <B>ALSO</B>
     may contain hyperlinked xrefs.


</PRE>
<H2>BUGS</H2><PRE>
     Text that is flush to the left margin, but is not actually a
     section head, can be mistaken for a section head.  This mis-
     take is more likely when the <B>-sun</B> option is in affect.


</PRE>
<H2>VERSION</H2><PRE>
     This documentation describes <B>man2html</B> version 3.0.1


</PRE>
<H2>SEE ALSO</H2><PRE>
     <B>man(1)</B>, <B>nroff(1)</B>, <B>perl(1)</B>

     <I>http://www.oac.uci.edu/indiv/ehood/man2html.html</I>


</PRE>
<H2>AUTHOR</H2><PRE>
     <B>Earl</B> <B>Hood</B>
     <I>ehood@medusa.acs.uci.edu</I>


</PRE>
<H2>ERRORS AND OMISSIONS</H2><PRE>
     Troff version of this document initially created for version
     2.1.0 by C. Jeffery Small (<I>jeff@cjsa.com</I>) by copying, refor-
     matting, rearranging and partially rewriting the contents of
     the ascii text file <B>doc/man2html.txt</B>.
</PRE>
<HR>
<ADDRESS>
Man(1) output converted with
<a href="http://www.oac.uci.edu/indiv/ehood/man2html.html">man2html</a>
</ADDRESS>
</BODY>
</HTML>
������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������i2util-1.6/support/man2html3.0.1/doc/man2html.ps����������������������������������������������������0000664�0000000�0000000�00000103563�12766054166�0021266�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������%!PS-Adobe-3.0
%%Creator: groff version 1.10
%%CreationDate: Tue Aug 12 13:19:38 1997
%%DocumentNeededResources: font Times-Roman
%%+ font Times-Bold
%%+ font Times-Italic
%%+ font Courier
%%+ font Symbol
%%DocumentSuppliedResources: procset grops 1.10 0
%%Pages: 6
%%PageOrder: Ascend
%%Orientation: Portrait
%%EndComments
%%BeginProlog
%%BeginResource: procset grops 1.10 0
/setpacking where{
pop
currentpacking
true setpacking
}if
/grops 120 dict dup begin
/SC 32 def
/A/show load def
/B{0 SC 3 -1 roll widthshow}bind def
/C{0 exch ashow}bind def
/D{0 exch 0 SC 5 2 roll awidthshow}bind def
/E{0 rmoveto show}bind def
/F{0 rmoveto 0 SC 3 -1 roll widthshow}bind def
/G{0 rmoveto 0 exch ashow}bind def
/H{0 rmoveto 0 exch 0 SC 5 2 roll awidthshow}bind def
/I{0 exch rmoveto show}bind def
/J{0 exch rmoveto 0 SC 3 -1 roll widthshow}bind def
/K{0 exch rmoveto 0 exch ashow}bind def
/L{0 exch rmoveto 0 exch 0 SC 5 2 roll awidthshow}bind def
/M{rmoveto show}bind def
/N{rmoveto 0 SC 3 -1 roll widthshow}bind def
/O{rmoveto 0 exch ashow}bind def
/P{rmoveto 0 exch 0 SC 5 2 roll awidthshow}bind def
/Q{moveto show}bind def
/R{moveto 0 SC 3 -1 roll widthshow}bind def
/S{moveto 0 exch ashow}bind def
/T{moveto 0 exch 0 SC 5 2 roll awidthshow}bind def
/SF{
findfont exch
[exch dup 0 exch 0 exch neg 0 0]makefont
dup setfont
[exch/setfont cvx]cvx bind def
}bind def
/MF{
findfont
[5 2 roll
0 3 1 roll
neg 0 0]makefont
dup setfont
[exch/setfont cvx]cvx bind def
}bind def
/level0 0 def
/RES 0 def
/PL 0 def
/LS 0 def
/MANUAL{
statusdict begin/manualfeed true store end
}bind def
/PLG{
gsave newpath clippath pathbbox grestore
exch pop add exch pop
}bind def
/BP{
/level0 save def
1 setlinecap
1 setlinejoin
72 RES div dup scale
LS{
90 rotate
}{
0 PL translate
}ifelse
1 -1 scale
}bind def
/EP{
level0 restore
showpage
}bind def
/DA{
newpath arcn stroke
}bind def
/SN{
transform
.25 sub exch .25 sub exch
round .25 add exch round .25 add exch
itransform
}bind def
/DL{
SN
moveto
SN
lineto stroke
}bind def
/DC{
newpath 0 360 arc closepath
}bind def
/TM matrix def
/DE{
TM currentmatrix pop
translate scale newpath 0 0 .5 0 360 arc closepath
TM setmatrix
}bind def
/RC/rcurveto load def
/RL/rlineto load def
/ST/stroke load def
/MT/moveto load def
/CL/closepath load def
/FL{
currentgray exch setgray fill setgray
}bind def
/BL/fill load def
/LW/setlinewidth load def
/RE{
findfont
dup maxlength 1 index/FontName known not{1 add}if dict begin
{
1 index/FID ne{def}{pop pop}ifelse
}forall
/Encoding exch def
dup/FontName exch def
currentdict end definefont pop
}bind def
/DEFS 0 def
/EBEGIN{
moveto
DEFS begin
}bind def
/EEND/end load def
/CNT 0 def
/level1 0 def
/PBEGIN{
/level1 save def
translate
div 3 1 roll div exch scale
neg exch neg exch translate
0 setgray
0 setlinecap
1 setlinewidth
0 setlinejoin
10 setmiterlimit
[]0 setdash
/setstrokeadjust where{
pop
false setstrokeadjust
}if
/setoverprint where{
pop
false setoverprint
}if
newpath
/CNT countdictstack def
userdict begin
/showpage{}def
}bind def
/PEND{
clear
countdictstack CNT sub{end}repeat
level1 restore
}bind def
end def
/setpacking where{
pop
setpacking
}if
%%EndResource
%%IncludeResource: font Times-Roman
%%IncludeResource: font Times-Bold
%%IncludeResource: font Times-Italic
%%IncludeResource: font Courier
%%IncludeResource: font Symbol
grops begin/DEFS 1 dict def DEFS begin/u{.001 mul}bind def end/RES 72
def/PL 792 def/LS false def/ENC0[/asciicircum/asciitilde/Scaron/Zcaron
/scaron/zcaron/Ydieresis/trademark/quotesingle/.notdef/.notdef/.notdef
/.notdef/.notdef/.notdef/.notdef/.notdef/.notdef/.notdef/.notdef/.notdef
/.notdef/.notdef/.notdef/.notdef/.notdef/.notdef/.notdef/.notdef/.notdef
/.notdef/.notdef/space/exclam/quotedbl/numbersign/dollar/percent
/ampersand/quoteright/parenleft/parenright/asterisk/plus/comma/hyphen
/period/slash/zero/one/two/three/four/five/six/seven/eight/nine/colon
/semicolon/less/equal/greater/question/at/A/B/C/D/E/F/G/H/I/J/K/L/M/N/O
/P/Q/R/S/T/U/V/W/X/Y/Z/bracketleft/backslash/bracketright/circumflex
/underscore/quoteleft/a/b/c/d/e/f/g/h/i/j/k/l/m/n/o/p/q/r/s/t/u/v/w/x/y
/z/braceleft/bar/braceright/tilde/.notdef/quotesinglbase/guillemotleft
/guillemotright/bullet/florin/fraction/perthousand/dagger/daggerdbl
/endash/emdash/ff/fi/fl/ffi/ffl/dotlessi/dotlessj/grave/hungarumlaut
/dotaccent/breve/caron/ring/ogonek/quotedblleft/quotedblright/oe/lslash
/quotedblbase/OE/Lslash/.notdef/exclamdown/cent/sterling/currency/yen
/brokenbar/section/dieresis/copyright/ordfeminine/guilsinglleft
/logicalnot/minus/registered/macron/degree/plusminus/twosuperior
/threesuperior/acute/mu/paragraph/periodcentered/cedilla/onesuperior
/ordmasculine/guilsinglright/onequarter/onehalf/threequarters
/questiondown/Agrave/Aacute/Acircumflex/Atilde/Adieresis/Aring/AE
/Ccedilla/Egrave/Eacute/Ecircumflex/Edieresis/Igrave/Iacute/Icircumflex
/Idieresis/Eth/Ntilde/Ograve/Oacute/Ocircumflex/Otilde/Odieresis
/multiply/Oslash/Ugrave/Uacute/Ucircumflex/Udieresis/Yacute/Thorn
/germandbls/agrave/aacute/acircumflex/atilde/adieresis/aring/ae/ccedilla
/egrave/eacute/ecircumflex/edieresis/igrave/iacute/icircumflex/idieresis
/eth/ntilde/ograve/oacute/ocircumflex/otilde/odieresis/divide/oslash
/ugrave/uacute/ucircumflex/udieresis/yacute/thorn/ydieresis]def
/Courier@0 ENC0/Courier RE/Times-Italic@0 ENC0/Times-Italic RE
/Times-Bold@0 ENC0/Times-Bold RE/Times-Roman@0 ENC0/Times-Roman RE
%%EndProlog
%%Page: 1 1
%%BeginPageSetup
BP
%%EndPageSetup
/F0 10/Times-Roman@0 SF -.834(MAN2HTML \( 1 \))72 48 R(User Commands)
127.212 E -.834(MAN2HTML \( 1 \))127.212 F/F1 9/Times-Bold@0 SF -.18(NA)
72 96 S(ME).18 E F0(man2html \255 con)108 108 Q -.15(ve)-.4 G
(rt UNIX nrof).15 E(f\(1\) manual pages to HTML format)-.25 E F1
(SYNOPSIS)72 124.8 Q/F2 10/Times-Bold@0 SF(man2html)108 136.8 Q F0([)
1.67 E F2(-bar)1.666 E(e)-.18 E F0 2.5(][)1.666 G F2(-belem)-.834 E/F3
10/Times-Italic@0 SF(name)5 E F0 2.5(][)1.666 G F2(-botm)-.834 E F3
(lines)5 E F0 2.5(][)1.666 G F2(-cgiurl)-.834 E F3(string)5 E F0 2.5(][)
1.666 G F2(-cgiurlexp)-.834 E F3 -.2(ex)5 G(pr).2 E F0 2.5(][)1.666 G F2
(-compr)-.834 E(ess)-.18 E F0(])1.666 E([)153.56 148.8 Q F2(-headmap)
1.666 E F3(map\214le)5 E F0 2.5(][)1.666 G F2(-help)-.834 E F0 2.5(][)
1.666 G F2(-k)-.834 E F0 2.5(][)1.666 G F2(-leftm)-.834 E F3 -.15(ch)5 G
(ar).15 E(s)-.1 E F0 2.5(][)1.666 G F2(-nodepage)-.834 E F0 2.5(][)1.666
G F2(-noheads)-.834 E F0 2.5(][)1.666 G F2(-pgsize)-.834 E F3(lines)5 E
F0(])1.666 E([)153.56 160.8 Q F2(-seealso)1.666 E F0 2.5(][)1.666 G F2
(-solaris)-.834 E F0 2.5(][)1.666 G F2(-sun)-.834 E F0 2.5(][)1.666 G F2
(-title)-.834 E F3(string)5 E F0 2.5(][)1.666 G F2(-topm)-.834 E F3
(lines)5 E F0 2.5(][)1.666 G F2(-uelem)-.834 E F3(name)5 E F0(])1.666 E
-.8(Ty)108 196.8 S(pical Usage:).8 E F2(man2html)108 220.8 Q F0([)1.67 E
F2(-options)1.666 E F0(])1.666 E F2(<)7.5 E F3(in\214le)5 E F2(>)12.5 E
F3(out\214le)5 E F2(man)108 244.8 Q F3(topic)2.5 E F2 2.5(|m)2.5 G
(an2html)-2.5 E F0([)2.5 E F2(-options)1.666 E F0(])1.666 E F2(>)7.5 E
F3(out\214le)5 E F1(DESCRIPTION)72 261.6 Q F0(The)108 273.6 Q F2
(man2html)2.5 E F0(\214lter reads formatted nrof)2.5 E 2.5(ft)-.25 G
-.15(ex)-2.5 G 2.5(tf).15 G(rom standard input \()-2.5 E F3(stdin)A F0
2.5(\)a).833 G(nd writes a)-2.5 E/F4 9/Times-Roman@0 SF(HTML)2.5 E F0
(document to)2.5 E(standard output \()108 285.6 Q F3(stdout)A F0(\).)
.833 E(The formatted nrof)108 302.4 Q 2.5(fo)-.25 G
(utput is surrounded with)-2.5 E F1(<PRE>)2.5 E F0(tags with the follo)
2.5 E(wing e)-.25 E(xceptions/additions:)-.15 E 6.5<8353>118 319.2 S
(ection heads are wrapped in)-6.5 E F4(HTML)2.5 E F3(header)2.5 E F0 2.5
(tags. See)2.5 F(the)2.5 E F1(SECTION HEAD MAP FILE)2.5 E F0
(section belo)2.5 E(w)-.25 E(for additional information.)128 331.2 Q
(The)5 E F2(-noheads)2.5 E F0
(option can be used to disable this feature.)2.5 E 6.5<8342>118 348 S
(old w)-6.5 E
(ords designated by a "<char><bs><char>" sequences are wrapped in)-.1 E
F1(<B>)2.5 E F0(tags \(or the element)2.5 E(speci\214ed via the)128 360
Q F2(-belem)2.5 E F0(option\).)2.5 E 6.5<8355>118 376.8 S(nderlined w)
-6.5 E(ords designated by a "_<bs><char>" sequences are wrapped in)-.1 E
F1(<I>)2.5 E F0(tags \(or the element)2.5 E(speci\214ed via the)128
388.8 Q F2(-uelem)2.5 E F0(option\).)2.5 E F1(OPTIONS)72 405.6 Q F2
(-bar)108 417.6 Q(e)-.18 E F0(This option will eliminate)13.41 E F4
(HTML)2.5 E F1(<HEAD>)2.5 E F0(and)2.5 E F1(<BOD)2.5 E(Y>)-.36 E F0
(tags from the output.)2.5 E(This is useful when)5 E
(you wish to incorporate the output into another)144 429.6 Q F4(HTML)2.5
E F0(document.)2.5 E F2(-belem)108 446.4 Q F3(name)5 E F0(Use)144 458.4
Q F3(name)2.5 E F0(as the name of the element to wrap o)2.5 E -.15(ve)
-.15 G(rstrik).15 E(en characters.)-.1 E(The def)5 E(ault is)-.1 E F2(B)
2.5 E F0(.)A F2(-botm)108 475.2 Q F3(lines)5 E F0(The)144 487.2 Q F3
(lines)2.5 E F0(ar)2.5 E
(gument speci\214es the number of lines representing the bottom mar)-.18
E(gin of the formatted)-.18 E(nrof)144 499.2 Q 2.5(fi)-.25 G 2.5
(nput. The)-2.5 F(line count includes an)2.5 E 2.5(yr)-.15 G
(unning footers.)-2.5 E(The def)5 E(ault v)-.1 E(alue is 7.)-.25 E F2
(-cgiurl)108 516 Q F3(string)5 E F0(The)144 528 Q F3(string)2.5 E F0(ar)
2.5 E(gument speci\214es a template)-.18 E F4(URL)2.5 E F0
(for creating links to other manpages.)2.5 E(See the)5 E F1(LINKING T)
144 540 Q 2.25(OO)-.162 G(THER MANP)-2.61 E -.495(AG)-.666 G(ES).495 E
F0(section belo)2.5 E 2.5(wf)-.25 G(or additional information.)-2.5 E F2
(-cgiurlexp)108 556.8 Q F3 -.2(ex)5 G(pr).2 E F0(The)144 568.8 Q F3 -.2
(ex)2.5 G(pr).2 E F0(ar)2.5 E(gument speci\214es a Perl e)-.18 E
(xpression e)-.15 E -.25(va)-.25 G(luting to a).25 E F4(URL)2.5 E F0
(for creating links to other man-)2.5 E 2.5(pages. See)144 580.8 R(the)
2.5 E F1(LINKING T)2.5 E 2.25(OO)-.162 G(THER MANP)-2.61 E -.495(AG)
-.666 G(ES).495 E F0(section belo)2.5 E 2.5(wf)-.25 G
(or additional information.)-2.5 E F2(-compr)108 597.6 Q(ess)-.18 E F0
(Compress consecuti)144 609.6 Q .3 -.15(ve b)-.25 H
(lank lines into a single line.).15 E F2(-headmap)108 626.4 Q F3
(map\214le)5 E F0(The)144 638.4 Q F3(map\214le)2.5 E F0(ar)2.5 E
(gument is read to determine which)-.18 E F4(HTML)2.5 E F0
(header tags are to be used for v)2.5 E(arious sec-)-.25 E
(tion heading in the manpage.)144 650.4 Q(See the)5 E F1
(SECTION HEAD MAP FILE)2.5 E F0(section belo)2.5 E 2.5(wf)-.25 G
(or information)-2.5 E(on the format of the map \214le.)144 662.4 Q F2
(-help)108 679.2 Q F0(Print out a short usage message and then e)14.33 E
(xit immediately)-.15 E(.)-.65 E F2(-k)108 696 Q F0
(Process input resulting from a manpage k)27.11 E -.15(ey)-.1 G -.1(wo)
.15 G(rd search \().1 E F2(man -k)A F0 2.5(\). See)B(the)2.5 E F1(KEYW)
2.5 E(ORD SEARCH)-.09 E F0(section belo)144 708 Q 2.5(wf)-.25 G
(or additional information.)-2.5 E F2(-leftm)108 724.8 Q F3 -.15(ch)5 G
(ar).15 E(s)-.1 E F0(SunOS 5.5.1)72 772.8 Q(Last change: 97/08/12)138.72
E(1)184.56 E EP
%%Page: 2 2
%%BeginPageSetup
BP
%%EndPageSetup
/F0 10/Times-Roman@0 SF -.834(MAN2HTML \( 1 \))72 48 R(User Commands)
127.212 E -.834(MAN2HTML \( 1 \))127.212 F(The)144 96 Q/F1 10
/Times-Italic@0 SF -.15(ch)2.5 G(ar).15 E(s)-.1 E F0(ar)2.5 E(gument sp\
eci\214es the width of the number of characters making up the left mar)
-.18 E(gin of)-.18 E(the formatted nrof)144 108 Q 2.5(fi)-.25 G 2.5
(nput. The)-2.5 F(def)2.5 E(ault v)-.1 E(alue is 0.)-.25 E/F2 10
/Times-Bold@0 SF(-nodepage)108 124.8 Q F0(By def)144 136.8 Q(ault,)-.1 E
F2(man2html)2.5 E F0(mer)2.5 E(ges multi-page formatted nrof)-.18 E 2.5
(fi)-.25 G(nto a single page.)-2.5 E(This option may be)5 E(used to dis\
able depagination, causing running headers and footers in the formatted\
 nrof)144 148.8 Q 2.5(fi)-.25 G(nput to)-2.5 E(be carried o)144 160.8 Q
-.15(ve)-.15 G 2.5(ri).15 G(nto the)-2.5 E/F3 9/Times-Roman@0 SF(HTML)
2.5 E F0(output.)2.5 E F2(-noheads)108 177.6 Q F0(By def)144 189.6 Q
(ault,)-.1 E F2(man2html)2.5 E F0(wraps section heads in)2.5 E F3(HTML)
2.5 E F0(header tags.)2.5 E(See the)5 E/F4 9/Times-Bold@0 SF
(SECTION HEAD MAP FILE)144 201.6 Q F0(section belo)2.5 E 2.5(wf)-.25 G
(or additional information.)-2.5 E(This option may be speci-)5 E
(\214ed to disabled this feature.)144 213.6 Q F2(-pgsize)108 230.4 Q F1
(lines)5 E F0(The)144 242.4 Q F1(lines)2.5 E F0(ar)2.5 E(gument speci\
\214es the number of lines making up the page size \(length\) of the fo\
rmatted)-.18 E(nrof)144 254.4 Q 2.5(fi)-.25 G 2.5(nput. The)-2.5 F(def)
2.5 E(ault v)-.1 E(alue is 66.)-.25 E F2(-seealso)108 271.2 Q F0(If the)
3.23 E F2(-cgiurl)2.5 E F0(option has been speci\214ed, then this optio\
n restricts the creation of links to other man-)2.5 E(ual pages to the)
144 283.2 Q F4(SEE ALSO)2.5 E F0(section only)2.5 E(.)-.65 E F2
(-solaris)108 300 Q F0(If the)4.89 E F2(-k)2.5 E F0(option has been spe\
ci\214ed, then this option modi\214es its operation to process the alte\
rnate)2.5 E(manual page k)144 312 Q -.15(ey)-.1 G -.1(wo).15 G
(rd search format produced by the).1 E F2(man)2.5 E F0
(\(1\) utility on systems running)A F1(Solaris)2.5 E F0(.).833 E
(See the)144 324 Q F4(KEYW)2.5 E(ORD SEARCH)-.09 E F0(section belo)2.5 E
2.5(wf)-.25 G(or additional information.)-2.5 E F2(-sun)108 340.8 Q F0
(Do not require a section head to ha)17.66 E .3 -.15(ve b)-.2 H(old o)
.15 E -.15(ve)-.15 G(rstriking in the formatted nrof).15 E 2.5(fi)-.25 G
2.5(nput. The)-2.5 F(option is)2.5 E(called)144 352.8 Q F2(sun)2.5 E F0
(because it w)2.5 E(as on a Sun w)-.1 E
(orkstation that section heads in manpages were found to not)-.1 E(be o)
144 364.8 Q -.15(ve)-.15 G(rstruck.).15 E F2(-title)108 381.6 Q F1
(string)5 E F0(By def)144 393.6 Q(ault,)-.1 E F2(man2html)2.5 E F0
(does not generate a)2.5 E F3(HTML)2.5 E F0(title \()2.5 E F4(<TITLE>)A
F0 2.5(\). This)B(option sets the title of the)2.5 E F3(HTML)144 405.6 Q
F0(output to the speci\214ed)2.5 E F1(string)2.5 E F0(.).833 E F2(-topm)
108 422.4 Q F1(lines)5 E F0(The)144 434.4 Q F1(lines)2.5 E F0(ar)2.5 E
(gument speci\214es number number of lines representing the top mar)-.18
E(gin of the formatted)-.18 E(nrof)144 446.4 Q 2.5(fi)-.25 G 2.5
(nput. The)-2.5 F(line count includes an)2.5 E 2.5(yr)-.15 G
(unning headers.)-2.5 E(The def)5 E(ault v)-.1 E(alue is 7.)-.25 E F2
(-uelem)108 463.2 Q F1(name)5 E F0(Use)144 475.2 Q F1(name)2.5 E F0
(as the name of the element to wrap underscored characters.)2.5 E
(The def)5 E(ault is)-.1 E F2(I)2.5 E F0(.)A F4(SECTION HEAD MAP FILE)72
492 Q F0(The)108 504 Q F2(-headmap)2.5 E F0
(option may be used to customize which)2.5 E F3(HTML)2.5 E F0
(header tags,)2.5 E F4(<H1>)2.5 E F2(...)2.5 E F4(<H6>)2.5 E F0 2.5(,a)C
(re used in man-)-2.5 E(page section headings.)108 516 Q(Normally)5 E(,)
-.65 E F2(man2html)2.5 E F0
(treats lines that are \215ush to the left mar)2.5 E(gin \()-.18 E F2
(-leftm)A F0(\), and con-)A(tain o)108 528 Q -.15(ve)-.15 G
(rstriking \(o).15 E -.15(ve)-.15 G(rstrik).15 E 2.5(ec)-.1 G
(heck is canceled with the)-2.5 E F2(-sun)2.5 E F0
(option\), as section heads.)2.5 E(Ho)5 E(we)-.25 E -.15(ve)-.25 G .8
-.4(r, y).15 H(ou can).4 E(augment/o)108 540 Q -.15(ve)-.15 G
(rride what).15 E F3(HTML)2.5 E F0(header tags are used for an)2.5 E 2.5
(yg)-.15 G -2.15 -.25(iv e)-2.5 H 2.5(ns).25 G(ection head.)-2.5 E
(In order to write a section head map \214le, you will need to kno)108
556.8 Q 2.5(wa)-.25 G(bout)-2.5 E F2(perl)2.5 E F0(\(1\) associati)A .3
-.15(ve a)-.25 H 2.5(rrays. Y).15 F(ou do)-1.1 E(not need to be an e)108
568.8 Q(xpert in)-.15 E F2(perl)2.5 E F0(to write a map \214le, ho)2.5 E
(we)-.25 E -.15(ve)-.25 G .8 -.4(r, h).15 H -.2(av).4 G(ing kno).2 E
(wledge of)-.25 E F2(perl)2.5 E F0(allo)2.5 E(ws you to be)-.25 E
(more cle)108 580.8 Q -.15(ve)-.25 G -.55(r.).15 G F4 -.45(Au)90 597.6 S
(gmenting the Default Map).45 E F0 1.6 -.8(To a)108 609.6 T
(dd to the def).8 E(ault mapping de\214ned by)-.1 E F2(man2html)2.5 E F0
2.5(,y)C(our map \214le will contain lines with the follo)-2.5 E(wing)
-.25 E(syntax:)108 621.6 Q F2
($SectionHead{'<section head text>'} = '<html header tag>';)128 645.6 Q
F0(where)108 669.6 Q F2(<section head text>)108 686.4 Q F0(is the te)144
698.4 Q(xt of the manpage section head.)-.15 E -.15(Fo)5 G 2.5(re).15 G
(xample:)-2.65 E F4(SYNOPSIS)2.5 E F0(or)2.5 E F4(DESCRIPTION)2.5 E F0
(.)A F2(<html header tag>)108 715.2 Q F0(is the)144 727.2 Q F3(HTML)2.5
E F0(header tag to wrap the section head in.)2.5 E(Le)5 E -.05(ga)-.15 G
2.5(lv).05 G(alues are:)-2.75 E F4(<H1>)2.5 E F0(,)A F4(<H2>)2.5 E F0(,)
A F4(<H3>)2.5 E F0(,)A F4(<H4>)2.5 E F0(,)A(SunOS 5.5.1)72 775.2 Q
(Last change: 97/08/12)138.72 E(2)184.56 E EP
%%Page: 3 3
%%BeginPageSetup
BP
%%EndPageSetup
/F0 10/Times-Roman@0 SF -.834(MAN2HTML \( 1 \))72 48 R(User Commands)
127.212 E -.834(MAN2HTML \( 1 \))127.212 F/F1 9/Times-Bold@0 SF(<H5>)144
96 Q F0(,)A F1(<H6>)2.5 E F0(.)A F1(Ov)90 112.8 Q
(erriding the Default Map)-.09 E F0 1.6 -.8(To o)108 124.8 T -.15(ve).65
G(rride the def).15 E(ault mapping with your o)-.1 E
(wn, then your map \214le will ha)-.25 E .3 -.15(ve t)-.2 H(he follo).15
E(wing syntax:)-.25 E/F2 10/Times-Bold@0 SF(%SectionHead = \()128 148.8
Q('<section head text>', '<html header tag>',)150.5 160.8 Q
('<section head text>', '<html header tag>',)150.5 172.8 Q 2.5(#.)150.5
184.8 S(.. Mor)-2.5 E 2.5(es)-.18 G(ection head/tag pairs)-2.5 E
('<section head text>', '<html header tag>',)150.5 196.8 Q(\);)128 208.8
Q F1(The Default Map)90 225.6 Q F0(As of this writing, this is the def)
108 237.6 Q(ault map used by)-.1 E F2(man2html)2.5 E F0(:)A/F3 10
/Courier@0 SF(%SectionHead = \()128 261.6 Q/F4 9/Courier@0 SF('\\S.)
149.6 273.6 Q/F5 9/Symbol SF(*)A F4(OPTIONS.)A F5(*)A F4 70.2('=)C 5.4
(>')-70.2 G(<H2>',)-5.4 E 91.8('AUTHORS?' =>)149.6 285.6 R('<H2>',)5.4 E
113.4('BUGS' =>)149.6 297.6 R('<H2>',)5.4 E 64.8('COMPATIBILITY' =>)
149.6 309.6 R('<H2>',)5.4 E 70.2('DEPENDENCIES' =>)149.6 321.6 R
('<H2>',)5.4 E 75.6('DESCRIPTION' =>)149.6 333.6 R('<H2>',)5.4 E 75.6
('DIAGNOSTICS' =>)149.6 345.6 R('<H2>',)5.4 E 75.6('ENVIRONMENT' =>)
149.6 357.6 R('<H2>',)5.4 E 102.6('ERRORS' =>)149.6 369.6 R('<H2>',)5.4
E 91.8('EXAMPLES' =>)149.6 381.6 R('<H2>',)5.4 E('EXTERNAL INFLUENCES')
149.6 393.6 Q(=> '<H2>',)37.8 E 108('FILES' =>)149.6 405.6 R('<H2>',)5.4
E 75.6('LIMITATIONS' =>)149.6 417.6 R('<H2>',)5.4 E 113.4('NAME' =>)
149.6 429.6 R('<H2>',)5.4 E 102.6('NOTES?' =>)149.6 441.6 R('<H2>',)5.4
E 97.2('OPTIONS' =>)149.6 453.6 R('<H2>',)5.4 E 81('REFERENCES' =>)149.6
465.6 R('<H2>',)5.4 E('RETURN VALUE')149.6 477.6 Q(=> '<H2>',)75.6 E
('SECTION.)149.6 489.6 Q F5(*)A F4 81(:' =>)B('<H2>',)5.4 E('SEE ALSO')
149.6 501.6 Q(=> '<H2>',)97.2 E('STANDARDS CONFORMANCE')149.6 513.6 Q
(=> '<H2>',)27 E('STYLE CONVENTION')149.6 525.6 Q(=> '<H2>',)54 E 91.8
('SYNOPSIS' =>)149.6 537.6 R('<H2>',)5.4 E 102.6('SYNTAX' =>)149.6 549.6
R('<H2>',)5.4 E 91.8('WARNINGS' =>)149.6 561.6 R('<H2>',)5.4 E
('\\s+Section.)149.6 573.6 Q F5(*)A F4 64.8(:' =>)B('<H3>',)5.4 E F3
(\);)128 585.6 Q($HeadFallback = ')128 597.6 Q F4(<H2>)A F3 6('; #)B
(Fallback tag if above is not found.)6 E F0(Check the)108 614.4 Q F2
(perl)2.5 E F0(source code of)2.5 E F2(man2html)2.5 E F0
(for the latest def)2.5 E(ault mapping.)-.1 E -1.1(Yo)108 631.2 S 2.5
(uc)1.1 G(an reassign the)-2.5 E F2($HeadF)2.5 E(allback)-.25 E F0 -.25
(va)2.5 G(riable to a dif).25 E(ferent v)-.25 E(alue if you choose.)-.25
E(This v)5 E(alue is used as the)-.25 E
(header tag of a section head if no matches are found in the)108 643.2 Q
F2(%SectionHead)2.5 E F0(map.)2.5 E F1(Using Regular Expr)90 660 Q
(essions in the Map File)-.162 E F0 -1.1(Yo)108 672 S 2.5(um)1.1 G
(ay ha)-2.5 E .3 -.15(ve n)-.2 H(oticed unusual characters in the def)
.15 E(ault map \214le, lik)-.1 E 2.5(e")-.1 G(\\s" or ")-2.5 E/F6 10
/Symbol SF(*)A F0 2.5(". The)B F2(man2html)2.5 E F0(utility)2.5 E
(actual treats the)108 684 Q F2(<section head text>)2.5 E F0(as a)2.5 E
F2(perl)2.5 E F0(re)2.5 E(gular e)-.15 E 2.5(xpression. If)-.15 F
(you are comfortable with)2.5 E F2(perl)2.5 E F0(re)2.5 E(gular)-.15 E
-.15(ex)108 696 S(pressions, then you ha).15 E .3 -.15(ve t)-.2 H
(heir full po).15 E(wer to use in your map \214le.)-.25 E(SunOS 5.5.1)72
768 Q(Last change: 97/08/12)138.72 E(3)184.56 E EP
%%Page: 4 4
%%BeginPageSetup
BP
%%EndPageSetup
/F0 10/Times-Roman@0 SF -.834(MAN2HTML \( 1 \))72 48 R(User Commands)
127.212 E -.834(MAN2HTML \( 1 \))127.212 F/F1 10/Times-Italic@0 SF
(Caution:)108 96 Q F0(The)2.5 E/F2 10/Times-Bold@0 SF(man2html)2.5 E F0
(utility already anchors the re)2.5 E(gular e)-.15 E
(xpression to the be)-.15 E(ginning of the line with left)-.15 E(mar)108
108 Q(gin spacing speci\214ed by the)-.18 E F2(-leftm)2.5 E F0 2.5
(option. Therefore,)2.5 F
(do not use the `^' character to anchor your re)2.5 E(gu-)-.15 E(lar e)
108 120 Q(xpression to the be)-.15 E 2.5(ginning. Ho)-.15 F(we)-.25 E
-.15(ve)-.25 G .8 -.4(r, y).15 H(ou may end your e).4 E
(xpression with a `)-.15 E F2($)A F0 2.5('t)C 2.5(oa)-2.5 G
(nchor it to the end of)-2.5 E(the line.)108 132 Q(Since the)108 148.8 Q
F2(<section head text>)2.5 E F0(is actually a re)2.5 E(gular e)-.15 E
(xpression, you will ha)-.15 E .3 -.15(ve t)-.2 H 2.5(ob).15 G 2.5(ec)
-2.5 G(areful of special char)-2.5 E(-)-.2 E(acters if you w)108 160.8 Q
(ant them to be treated literally)-.1 E 5(.A)-.65 G .3 -.15(ny o)-5 H
2.5(ft).15 G(he characters `)-2.5 E F2 2.5([]\(\).^{}$)C/F3 10/Symbol SF
(*)A F2 -2.5 2.5(?+ |)2.5 H F0 2.5('s)-2.5 G(hould be)-2.5 E
(escaped by pre\214xing them by the `)108 172.8 Q F2(\\)A F0 2.5('c)C
(haracter if you w)-2.5 E(ant)-.1 E F2(perl)2.5 E F0
(to treat them "as is".)2.5 E F1(Caution:)108 189.6 Q F0
(One should use single quotes instead of double quotes to delimit)2.5 E
F2(<section head text>)2.5 E F0 5(.T)C(his will)-5 E(preserv)108 201.6 Q
2.5(ea)-.15 G .3 -.15(ny `)-2.5 H F2(\\).15 E F0 2.5('c)C
(haracters for character escaping or when the `)-2.5 E F2(\\)A F0 2.5
('i)C 2.5(su)-2.5 G(sed for special)-2.5 E F2(perl)2.5 E F0
(character matching)2.5 E(sequences \(e.g.,)108 213.6 Q F2(\\s)5 E F0(,)
A F2(\\w)2.5 E F0(,)A F2(\\S)2.5 E F0(\).)A/F4 9/Times-Bold@0 SF
(Other T)90 230.4 Q(id-bits on the Map File)-.162 E F0
(Comments can be inserted in the map \214le by using the ')108 242.4 Q
F2(#)A F0 2.5('c)C(haracter)-2.5 E 5(.A)-.55 G -.15(ny)-5 G(thing after)
.15 E 2.5(,a)-.4 G(nd including, the ')-2.5 E F2(#)A F0(')A
(character is ignored, up to the end of line.)108 254.4 Q -1.1(Yo)108
271.2 S 2.5(um)1.1 G(ight be thinking that the abo)-2.5 E .3 -.15(ve i)
-.15 H 2.5(sq).15 G(uite-a-bit-of-stuf)-2.5 E 2.5(fj)-.25 G
(ust for doing manpage section heads.)-2.5 E(Ho)5 E(we)-.25 E -.15(ve)
-.25 G -.4(r,).15 G(you will be surprised ho)108 283.2 Q 2.5(wm)-.25 G
(uch better the)-2.5 E/F5 9/Times-Roman@0 SF(HTML)2.5 E F0
(output looks with header tags, e)2.5 E -.15(ve)-.25 G 2.5(nt).15 G
(hough, e)-2.5 E -.15(ve)-.25 G(rything).15 E(else is in a)108 295.2 Q
F4(<PRE>)2.5 E F0(tag.)2.5 E F4(LINKING T)72 312 Q 2.25(OO)-.162 G
(THER MANP)-2.61 E -.495(AG)-.666 G(ES).495 E F0(The)108 324 Q F2
(man2html)2.5 E F0(utility allo)2.5 E
(ws the ability to link to other manpage references.)-.25 E(If the)5 E
F2(-cgiurl)2.5 E F0(option is speci-)2.5 E(\214ed,)108 336 Q F2
(man2html)2.5 E F0(will create anchors that link to other manpages.)2.5
E(The)108 352.8 Q F5(URL)2.5 E F0(entered with the)2.5 E F2(-cgiurl)2.5
E F0(option is actually a template that determines the actual)2.5 E F5
(URL)2.5 E F0(used to link)2.5 E(to other manpages.)108 364.8 Q
(The follo)5 E(wing v)-.25 E(ariables are de\214ned during run time tha\
t may be used in the template)-.25 E(string:)108 376.8 Q F2($title)128
405.6 Q F0(The title of the manual page referenced.)14.34 E F2($section)
128 422.4 Q F0(The section number of the manual page referenced.)164
434.4 Q F2($subsection)128 451.2 Q F0
(The subsection of the manual page referenced.)164 463.2 Q(An)108 480 Q
2.5(yo)-.15 G(ther te)-2.5 E(xt in the template is preserv)-.15 E
(ed "as is".)-.15 E F1(Caution:)108 496.8 Q F0(The)2.5 E F2(man2html)2.5
E F0(utility e)2.5 E -.25(va)-.25 G(luates the template string as a).25
E F2(perl)2.5 E F0(string e)2.5 E 2.5(xpression. Therefore,)-.15 F(one)
2.5 E(might need to surround the v)108 508.8 Q(ariable names with ')-.25
E F2 1.666({})C F0 2.5('\()-1.666 G(e.g.,)-2.5 E F2 -.834(${ title })2.5
F F0 2.5(\)s)1.666 G 2.5(ot)-2.5 G(hat)-2.5 E F2(man2html)2.5 E F0
(properly recognizes)2.5 E(the v)108 520.8 Q(ariable.)-.25 E F1(Note:)
108 537.6 Q F0(If a)2.5 E F5(CGI)2.5 E F0(program calling)2.5 E F2
(man2html)2.5 E F0(is actually a shell script or a)2.5 E F2(perl)2.5 E
F0(program, mak)2.5 E 2.5(es)-.1 G(ure to properly)-2.5 E(escape the ')
108 549.6 Q F2($)A F0 2.5('c)C(haracter in the)-2.5 E F5(URL)2.5 E F0
(template to a)2.5 E -.2(vo)-.2 G(id v).2 E
(ariable interpolation by the)-.25 E F5(CGI)2.5 E F0(program.)2.5 E
(Normally)108 566.4 Q 2.5(,t)-.65 G(he)-2.5 E F5(URL)2.5 E F0(calls a)
2.5 E F5(CGI)2.5 E F0(program \(hence the option name\), b)2.5 E(ut the)
-.2 E F5(URL)2.5 E F0(can easily link to statically)2.5 E(con)108 578.4
Q -.15(ve)-.4 G(rted documents.).15 E F4(Example1:)90 595.2 Q F0
(The follo)108 607.2 Q(wing template string is speci\214ed to call a)
-.25 E F5(CGI)2.5 E F0(program to retrie)2.5 E .3 -.15(ve t)-.25 H
(he appropriate manpage link).15 E(ed)-.1 E(to:)108 619.2 Q F2
(/cgi-bin/man.cgi?section=${section}${subsection}&topic=${title})108 636
Q F0(If the)108 652.8 Q F2(ls)2.5 E F0
(\(1\) manpage is referenced in the)A F2(SEE ALSO)2.5 E F0
(section, the abo)2.5 E .3 -.15(ve t)-.15 H
(emplate will translate to the fol-).15 E(lo)108 664.8 Q(wing)-.25 E F5
(URL)2.5 E F0(:)A F2(/cgi-bin/man.cgi?section=1&topic=ls)108 681.6 Q F0
(The actual)108 698.4 Q F5(HTML)2.5 E F0(markup will look lik)2.5 E 2.5
(et)-.1 G(he follo)-2.5 E(wing:)-.25 E(SunOS 5.5.1)72 768 Q
(Last change: 97/08/12)138.72 E(4)184.56 E EP
%%Page: 5 5
%%BeginPageSetup
BP
%%EndPageSetup
/F0 10/Times-Roman@0 SF -.834(MAN2HTML \( 1 \))72 48 R(User Commands)
127.212 E -.834(MAN2HTML \( 1 \))127.212 F/F1 10/Times-Bold@0 SF
(<A HREF="/cgi-bin/man.cgi?section=1&topic=ls">ls\(1\)</A>)108 96 Q/F2 9
/Times-Bold@0 SF(Example2:)90 112.8 Q F0(The follo)108 124.8 Q
(wing template string is speci\214ed to retrie)-.25 E .3 -.15(ve p)-.25
H(re-con).15 E -.15(ve)-.4 G(rted manpages:).15 E F1(http://f)108 141.6
Q(oo.or)-.25 E(g/man$section/$title.$section$subsection.html)-.1 E F0
(If the)108 158.4 Q F1(mount)2.5 E F0
(\(1M\) manpage is referenced, the abo)A .3 -.15(ve t)-.15 H
(emplate will translate to the follo).15 E(wing)-.25 E/F3 9
/Times-Roman@0 SF(URL)2.5 E F0(:)A F1(http://f)108 175.2 Q(oo.or)-.25 E
(g/man1/mount.1M.html)-.1 E F0(The actual)108 192 Q F3(HTML)2.5 E F0
(markup will look lik)2.5 E 2.5(et)-.1 G(he follo)-2.5 E(wing:)-.25 E F1
(<A HREF="http://f)108 208.8 Q(oo.or)-.25 E
(g/man1/mount.1M.html">mount\(1M\)</A>)-.1 E F2(-cgiurlexp)90 225.6 Q F0
(The option)108 237.6 Q F1(-cgiurlexp)2.5 E F0
(is a more general form of the)2.5 E F1(-cgiurl)2.5 E F0(option.)2.5 E
F1(-cgiurlexp)5 E F0(allo)2.5 E(ws one to specify a gen-)-.25 E
(eral Perl e)108 249.6 Q 2.5(xpression. F)-.15 F(or e)-.15 E(xample:)
-.15 E F1($title=~/^db_/i?"$title.html":"/cgi-bin/man?$title+$section")
108 266.4 Q F0(A)108 283.2 Q F1(-cgiurl)2.5 E/F4 10/Times-Italic@0 SF
(string)2.5 E F0(can be e)2.5 E(xpressed as follo)-.15 E(ws with)-.25 E
F1(-cgiurlexp)2.5 E F0(:)A F1 -.18(re)108 300 S(tur).18 E 2.5(n")-.15 G
F4(string)-2.5 E F1(")A F2(KEYW)72 316.8 Q(ORD SEARCH)-.09 E F0(The)108
328.8 Q F1(man2html)2.5 E F0(utility has the ability to process k)2.5 E
-.15(ey)-.1 G -.1(wo).15 G(rd search output generated by the).1 E F1
(man -k)2.5 E F0(or)2.5 E F1(apr)2.5 E(opos)-.18 E F0
(commands, through the use of the)108 340.8 Q F1(-k)2.5 E F0 2.5
(option. The)2.5 F F1(man2html)2.5 E F0(utility will generate an)2.5 E
F3(HTML)2.5 E F0(document of)2.5 E(the k)108 352.8 Q -.15(ey)-.1 G -.1
(wo).15 G(rd search input ha).1 E(ving the follo)-.2 E(wing format:)-.25
E 6.5<8341>118 369.6 S(ll manpage references are listed by section.)-6.5
E 6.5<8357>118 386.4 S(ithin each section listing, the manpage referenc\
es are sorted alphabetically \(case-sensiti)-6.9 E -.15(ve)-.25 G 2.5
(\)i).15 G 2.5(na)-2.5 G F2(<DL>)128 398.4 Q F0 2.5(tag. The)2.5 F
(manpage references are listed in the)2.5 E F2(<DT>)2.5 E F0
(section, and the summary te)2.5 E(xt is listed in)-.15 E(the)128 410.4
Q F2(<DD>)2.5 E F0(section.)2.5 E 6.5<8345>118 427.2 S
(ach manpage reference listed is a h)-6.5 E
(yperlink to the actual manpage as speci\214ed by the)-.05 E F1(-cgiurl)
2.5 E F0(option.)2.5 E(This ability to process k)108 444 Q -.15(ey)-.1 G
-.1(wo).15 G(rd searches gi).1 E -.15(ve)-.25 G 2.5(sn).15 G
(ice added functionality to a)-2.5 E F3(WWW)2.5 E F0(forms interf)2.5 E
(ace to)-.1 E F1(man)108 456 Q F0 2.5(\(1\). Ev)B(en if you ha)-.15 E .3
-.15(ve s)-.2 H(tatically con).15 E -.15(ve)-.4 G(rted manpages to).15 E
F3(HTML)2.5 E F0(via another man->)2.5 E F3(HTML)A F0(program, you)2.5 E
(can use)108 468 Q F1(man2html)2.5 E F0(and ")2.5 E F1(man -k)A F0 2.5
("t)C 2.5(op)-2.5 G(ro)-2.5 E(vide k)-.15 E -.15(ey)-.1 G -.1(wo).15 G
(rd search capabilities easily for your).1 E F3(HTML)2.5 E F0(manpages.)
2.5 E F2(Pr)90 484.8 Q(ocessing K)-.162 E(eyw)-.225 E(ord Sear)-.09 E
(ch Results)-.162 E F0(Unfortunately)108 496.8 Q 2.5(,t)-.65 G
(here is no standard controlling the format of k)-2.5 E -.15(ey)-.1 G
-.1(wo).15 G(rd search results.).1 E(The)5 E F1(man2html)2.5 E F0
(utility)2.5 E(tries it best to handle all the v)108 508.8 Q 2.5
(ariations. Ho)-.25 F(we)-.25 E -.15(ve)-.25 G .8 -.4(r, t).15 H(he k).4
E -.15(ey)-.1 G -.1(wo).15 G(rd search results generated by the).1 E F4
(Solaris)2.5 E F0(oper)2.5 E(-)-.2 E(ating system is dif)108 520.8 Q
(ferent enough from other systems that a special command-line option \()
-.25 E F1(-solaris)A F0 2.5(\)m)C(ust be)-2.5 E
(speci\214ed to handle its output.)108 532.8 Q F2
(Example of raw Solaris-type k)90 549.6 Q(eyw)-.09 E(ord sear)-.09 E
(ch r)-.162 E(esults:)-.162 E/F5 10/Courier@0 SF 42(strcpy strcpy)108
561.6 R 6(\(9f\) -)6 F(copy a string from one location to another.)6 E
42(strcpy string)108 573.6 R 6(\(3c\) -)6 F(string operations)6 E 36
(strncpy strcpy)108 585.6 R 6(\(9f\) -)6 F
(copy a string from one location to another.)6 E 36(strncpy string)108
597.6 R 6(\(3c\) -)6 F(string operations)6 E F0(If k)108 614.4 Q -.15
(ey)-.1 G -.1(wo).15 G
(rd search results on your systems appear in the follo).1 E
(wing format:)-.25 E F1 2.5(<topic> <actual_manpage>)128 631.2 R
(\(#\) - Description)2.5 E F0(then you need to specify the)108 648 Q F1
(-solaris)2.5 E F0(option in addition to the)2.5 E F1(-k)2.5 E F0
(option.)2.5 E F2(ADDITION)72 664.8 Q(AL NO)-.18 E(TES)-.36 E F0(Dif)108
676.8 Q(ferent systems format manpages dif)-.25 E(ferently)-.25 E 5(.H)
-.65 G(ere is a list of recommended command-line options for)-5 E
(certain systems:)108 688.8 Q(SunOS 5.5.1)72 768 Q
(Last change: 97/08/12)138.72 E(5)184.56 E EP
%%Page: 6 6
%%BeginPageSetup
BP
%%EndPageSetup
/F0 10/Times-Roman@0 SF -.834(MAN2HTML \( 1 \))72 48 R(User Commands)
127.212 E -.834(MAN2HTML \( 1 \))127.212 F/F1 10/Times-Bold@0 SF(Con)128
96 Q -.1(ve)-.4 G(x).1 E F0 37.5(:<)C(def)-37.5 E(aults should be okay>)
-.1 E F1(HP)128 108 Q F0(:)A F1(-leftm 1 -topm 8)55.33 E(Sun)128 120 Q
F0(:)A F1(-sun)52.54 E F0(\(and)2.5 E F1(-solaris)2.5 E F0(when using)
2.5 E F1(-k)2.5 E F0(\))A
(Some line spacing gets lost in the formatted nrof)108 136.8 Q 2.5(fs)
-.25 G(ince the spacing w)-2.5 E(ould occur in the middle of a page)-.1
E 2.5(break. This)108 148.8 R(can cause te)2.5 E(xt to be mer)-.15 E
(ged that shouldn')-.18 E 2.5(tb)-.18 G 2.5(em)-2.5 G(er)-2.5 E
(ged when)-.18 E F1(man2html)2.5 E F0(depaginates the te)2.5 E(xt.)-.15
E 1.6 -.8(To a)108 160.8 T -.2(vo).6 G(id this problem,).2 E F1
(man2html)2.5 E F0 -.1(ke)2.5 G(eps track of the mar).1 E
(gin indent right before and after a page break.)-.18 E(If)5 E(the mar)
108 172.8 Q(gin width of the line after the page break is less than the\
 line before the page break, then)-.18 E F1(man2html)2.5 E F0
(inserts a blank line in the)108 184.8 Q/F2 9/Times-Roman@0 SF(HTML)2.5
E F0(output.)2.5 E 2.5(Am)108 201.6 S
(anpage cross-reference is detected by the follo)-2.5 E(wing pseudo e)
-.25 E(xpression:)-.15 E F1([A-z.-+_]+\([0-9][A-z]?\))2.5 E F0(The)108
218.4 Q F1(man2html)2.5 E F0(utility only recognizes lines with ")2.5 E
F1(-)2.5 E F0 2.5("\()2.5 G
(the normal separator between manpage references)-2.5 E(and summary te)
108 230.4 Q(xt\) while in k)-.15 E -.15(ey)-.1 G -.1(wo).15 G
(rd search mode.).1 E(The)108 247.2 Q F1(man2html)2.5 E F0
(utility can be hook)2.5 E(ed in a)-.1 E F2(CGI)2.5 E F0
(script/program to con)2.5 E -.15(ve)-.4 G(rt manpages on the \215y).15
E 5(.T)-.65 G(his is the)-5 E(reason for the)108 259.2 Q F1(-cgiurl)2.5
E F0(option.)2.5 E/F3 9/Times-Bold@0 SF(LIMIT)72 276 Q -.855(AT)-.81 G
(IONS).855 E F0
(The order that section head mapping is searched is not de\214ned.)108
288 Q(Therefore, if tw)5 E 2.5(oo)-.1 G 2.5(rm)-2.5 G(ore)-2.5 E F1
(<section head text>)108 300 Q F0(can match a gi)2.5 E .3 -.15(ve m)-.25
H(anpage section, there is no w).15 E
(ay to determine which map tag is cho-)-.1 E(sen.)108 312 Q(If)108 328.8
Q F1(-seealso)2.5 E F0(is speci\214ed, all xrefs are detected after the)
2.5 E F1(SEE ALSO)2.5 E F0 2.5(heading. In)2.5 F(other w)2.5 E
(ords, sections after)-.1 E F1(SEE ALSO)108 340.8 Q F0(may contain h)2.5
E(yperlink)-.05 E(ed xrefs.)-.1 E F3 -.09(BU)72 357.6 S(GS).09 E F0
-1.25 -.7(Te x)108 369.6 T 2.5(tt).7 G(hat is \215ush to the left mar)
-2.5 E(gin, b)-.18 E(ut is not actually a section head, can be mistak)
-.2 E(en for a section head.)-.1 E(This mistak)108 381.6 Q 2.5(ei)-.1 G
2.5(sm)-2.5 G(ore lik)-2.5 E(ely when the)-.1 E F1(-sun)2.5 E F0
(option is in af)2.5 E(fect.)-.25 E F3(VERSION)72 398.4 Q F0
(This documentation describes)108 410.4 Q F1(man2html)2.5 E F0 -.15(ve)
2.5 G(rsion 3.0.1).15 E F3(SEE ALSO)72 427.2 Q F1(man)108 439.2 Q F0
(\(1\),)A F1(nr)2.5 E(off)-.18 E F0(\(1\),)A F1(perl)2.5 E F0(\(1\))A/F4
10/Times-Italic@0 SF(http://www)108 456 Q
(.oac.uci.edu/indiv/ehood/man2html.html)-.74 E F3 -.45(AU)72 472.8 S
(THOR).45 E F1(Earl Hood)108 484.8 Q F4(ehood@medusa.acs.uci.edu)108
496.8 Q F3(ERR)72 513.6 Q(ORS AND OMISSIONS)-.27 E F0 -.35(Tr)108 525.6
S(of).35 E 2.5(fv)-.25 G
(ersion of this document initially created for v)-2.65 E
(ersion 2.1.0 by C. Jef)-.15 E(fery Small \()-.25 E F4(jef)A(f@cjsa.com)
-.18 E F0 2.5(\)b).833 G(y)-2.5 E(cop)108 537.6 Q
(ying, reformatting, rearranging and partially re)-.1 E
(writing the contents of the ascii te)-.25 E(xt \214le)-.15 E F1
(doc/man2html.txt)108 549.6 Q F0(.)A(SunOS 5.5.1)72 768 Q
(Last change: 97/08/12)138.72 E(6)184.56 E EP
%%Trailer
end
%%EOF
���������������������������������������������������������������������������������������������������������������������������������������������i2util-1.6/support/man2html3.0.1/doc/man2html.txt���������������������������������������������������0000664�0000000�0000000�00000042266�12766054166�0021465�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������


NAME

     man2html - convert UNIX nroff(1) manual pages to HTML format


SYNOPSIS

     man2html [-bare] [-belem name] [-botm lines]
              [-cgiurl string] [-cgiurlexp expr] [-compress]
              [-headmap mapfile] [-help] [-k] [-leftm chars]
              [-nodepage] [-noheads] [-pgsize lines] [-seealso]
              [-solaris] [-sun] [-title string] [-topm lines]
              [-uelem name]

     Typical Usage:

     man2html [-options]  < infile   > outfile

     man topic | man2html [-options]  > outfile


DESCRIPTION

     The man2html filter reads formatted nroff text from standard
     input (stdin) and writes a HTML document to standard output
     (stdout).

     The formatted nroff output is surrounded with <PRE> tags
     with the following exceptions/additions:

       o Section heads are wrapped in HTML header tags.  See the
         SECTION HEAD MAP FILE section below for additional
         information.  The -noheads option can be used to disable
         this feature.

       o Bold words designated by a "<char><bs><char>" sequences
         are wrapped in <B> tags (or the element specified via
         the -belem option).

       o Underlined words designated by a "_<bs><char>" sequences
         are wrapped in <I> tags (or the element specified via
         the -uelem option).


OPTIONS

     -bare
          This option will eliminate HTML <HEAD> and <BODY> tags
          from the output.  This is useful when you wish to
          incorporate the output into another HTML document.

     -belem name
          Use name as the name of the element to wrap overstriken
          characters.  The default is B.

     -botm lines
          The lines argument specifies the number of lines repre-
          senting the bottom margin of the formatted nroff input.
          The line count includes any running footers.  The
          default value is 7.

     -cgiurl string
          The string argument specifies a template URL for creat-
          ing links to other manpages.  See the
          LINKING TO OTHER MANPAGES section below for additional
          information.

     -cgiurlexp expr
          The expr argument specifies a Perl expression evaluting
          to a URL for creating links to other manpages.  See the
          LINKING TO OTHER MANPAGES section below for additional
          information.

     -compress
          Compress consecutive blank lines into a single line.

     -headmap mapfile
          The mapfile argument is read to determine which HTML
          header tags are to be used for various section heading
          in the manpage.  See the SECTION HEAD MAP FILE section
          below for information on the format of the map file.

     -help
          Print out a short usage message and then exit immedi-
          ately.

     -k   Process input resulting from a manpage keyword search
          (man -k).  See the KEYWORD SEARCH section below for
          additional information.

     -leftm chars
          The chars argument specifies the width of the number of
          characters making up the left margin of the formatted
          nroff input.  The default value is 0.

     -nodepage
          By default, man2html merges multi-page formatted nroff
          into a single page.  This option may be used to disable
          depagination, causing running headers and footers in
          the formatted nroff input to be carried over into the
          HTML output.

     -noheads
          By default, man2html wraps section heads in HTML header
          tags.  See the SECTION HEAD MAP FILE section below for
          additional information.  This option may be specified
          to disabled this feature.

     -pgsize lines
          The lines argument specifies the number of lines making
          up the page size (length) of the formatted nroff input.
          The default value is 66.

     -seealso
          If the -cgiurl option has been specified, then this
          option restricts the creation of links to other manual
          pages to the SEE ALSO section only.

     -solaris
          If the -k option has been specified, then this option
          modifies its operation to process the alternate manual
          page keyword search format produced by the man(1) util-
          ity on systems running Solaris.  See the KEYWORD SEARCH
          section below for additional information.

     -sun Do not require a section head to have bold overstriking
          in the formatted nroff input.  The option is called sun
          because it was on a Sun workstation that section heads
          in manpages were found to not be overstruck.

     -title string
          By default, man2html does not generate a HTML title
          (<TITLE>).  This option sets the title of the HTML out-
          put to the specified string.

     -topm lines
          The lines argument specifies number number of lines
          representing the top margin of the formatted nroff
          input.  The line count includes any running headers.
          The default value is 7.

     -uelem name
          Use name as the name of the element to wrap underscored
          characters.  The default is I.


SECTION HEAD MAP FILE

     The -headmap option may be used to customize which HTML
     header tags, <H1> ... <H6>, are used in manpage section
     headings.  Normally, man2html treats lines that are flush to
     the left margin (-leftm), and contain overstriking (over-
     strike check is canceled with the -sun option), as section
     heads.  However, you can augment/override what HTML header
     tags are used for any given section head.

     In order to write a section head map file, you will need to
     know about perl(1) associative arrays.  You do not need to
     be an expert in perl to write a map file, however, having
     knowledge of perl allows you to be more clever.

  Augmenting the Default Map
     To add to the default mapping defined by man2html, your map
     file will contain lines with the following syntax:
     $SectionHead{'<section head text>'} = '<html header tag>';

     where

     <section head text>
          is the text of the manpage section head.  For example:
          SYNOPSIS or DESCRIPTION.

     <html header tag>
          is the HTML header tag to wrap the section head in.
          Legal values are: <H1>, <H2>, <H3>, <H4>, <H5>, <H6>.

  Overriding the Default Map
     To override the default mapping with your own, then your map
     file will have the following syntax:

         %SectionHead = (
                  '<section head text>', '<html header tag>',
                  '<section head text>', '<html header tag>',
                  # ... More section head/tag pairs
                  '<section head text>', '<html header tag>',
         );

  The Default Map
     As of this writing, this is the default map used by
     man2html:

         %SectionHead = (
             '\S.*OPTIONS.*'             => '<H2>',
             'AUTHORS?'                  => '<H2>',
             'BUGS'                      => '<H2>',
             'COMPATIBILITY'             => '<H2>',
             'DEPENDENCIES'              => '<H2>',
             'DESCRIPTION'               => '<H2>',
             'DIAGNOSTICS'               => '<H2>',
             'ENVIRONMENT'               => '<H2>',
             'ERRORS'                    => '<H2>',
             'EXAMPLES'                  => '<H2>',
             'EXTERNAL INFLUENCES'       => '<H2>',
             'FILES'                     => '<H2>',
             'LIMITATIONS'               => '<H2>',
             'NAME'                      => '<H2>',
             'NOTES?'                    => '<H2>',
             'OPTIONS'                   => '<H2>',
             'REFERENCES'                => '<H2>',
             'RETURN VALUE'              => '<H2>',
             'SECTION.*:'                => '<H2>',
             'SEE ALSO'                  => '<H2>',
             'STANDARDS CONFORMANCE'     => '<H2>',
             'STYLE CONVENTION'          => '<H2>',
             'SYNOPSIS'                  => '<H2>',
             'SYNTAX'                    => '<H2>',
             'WARNINGS'                  => '<H2>',
             '\s+Section.*:'             => '<H3>',
         );
         $HeadFallback = '<H2>';  # Fallback tag if above is not found.

     Check the perl source code of man2html for the latest
     default mapping.

     You can reassign the $HeadFallback variable to a different
     value if you choose.  This value is used as the header tag
     of a section head if no matches are found in the
     %SectionHead map.

  Using Regular Expressions in the Map File
     You may have noticed unusual characters in the default map
     file, like "\s" or "*".  The man2html utility actual treats
     the <section head text> as a perl regular expression.  If
     you are comfortable with perl regular expressions, then you
     have their full power to use in your map file.

     Caution: The man2html utility already anchors the regular
     expression to the beginning of the line with left margin
     spacing specified by the -leftm option.  Therefore, do not
     use the `^' character to anchor your regular expression to
     the beginning.  However, you may end your expression with a
     `$' to anchor it to the end of the line.

     Since the <section head text> is actually a regular expres-
     sion, you will have to be careful of special characters if
     you want them to be treated literally.  Any of the charac-
     ters `[ ] ( ) . ^ { } $ * ? +  |' should be escaped by pre-
     fixing them by the `\' character if you want perl to treat
     them "as is".

     Caution: One should use single quotes instead of double
     quotes to delimit <section head text>.  This will preserve
     any `\' characters for character escaping or when the `\' is
     used for special perl character matching sequences (e.g.,
     \s, \w, \S).

  Other Tid-bits on the Map File
     Comments can be inserted in the map file by using the '#'
     character.  Anything after, and including, the '#' character
     is ignored, up to the end of line.

     You might be thinking that the above is quite-a-bit-of-stuff
     just for doing manpage section heads.  However, you will be
     surprised how much better the HTML output looks with header
     tags, even though, everything else is in a <PRE> tag.


LINKING TO OTHER MANPAGES

     The man2html utility allows the ability to link to other
     manpage references.  If the -cgiurl option is specified,
     man2html will create anchors that link to other manpages.

     The URL entered with the -cgiurl option is actually a tem-
     plate that determines the actual URL used to link to other
     manpages.  The following variables are defined during run
     time that may be used in the template string:

         $title
              The title of the manual page referenced.

         $section
              The section number of the manual page referenced.

         $subsection
              The subsection of the manual page referenced.

     Any other text in the template is preserved "as is".

     Caution: The man2html utility evaluates the template string
     as a perl string expression.  Therefore, one might need to
     surround the variable names with '{}' (e.g., ${title}) so
     that man2html properly recognizes the variable.

     Note: If a CGI program calling man2html is actually a shell
     script or a perl program, make sure to properly escape the
     '$' character in the URL template to avoid variable interpo-
     lation by the CGI program.

     Normally, the URL calls a CGI program (hence the option
     name), but the URL can easily link to statically converted
     documents.

  Example1:
     The following template string is specified to call a CGI
     program to retrieve the appropriate manpage linked to:

     /cgi-bin/man.cgi?section=${section}${subsection}&topic=${title}

     If the ls(1) manpage is referenced in the SEE ALSO section,
     the above template will translate to the following URL:

     /cgi-bin/man.cgi?section=1&topic=ls

     The actual HTML markup will look like the following:

     <A HREF="/cgi-bin/man.cgi?section=1&topic=ls">ls(1)</A>

  Example2:
     The following template string is specified to retrieve pre-
     converted manpages:

     http://foo.org/man$section/$title.$section$subsection.html

     If the mount(1M) manpage is referenced, the above template
     will translate to the following URL:

     http://foo.org/man1/mount.1M.html

     The actual HTML markup will look like the following:

     <A HREF="http://foo.org/man1/mount.1M.html">mount(1M)</A>

  -cgiurlexp
     The option -cgiurlexp is a more general form of the -cgiurl
     option.  -cgiurlexp allows one to specify a general Perl
     expression.  For example:

     $title=~/^db_/i?"$title.html":"/cgi-bin/man?$title+$section"

     A -cgiurl string can be expressed as follows with -cgiurl-
     exp:

     return "string"


KEYWORD SEARCH

     The man2html utility has the ability to process keyword
     search output generated by the man -k or apropos commands,
     through the use of the -k option.  The man2html utility will
     generate an HTML document of the keyword search input having
     the following format:

       o All manpage references are listed by section.

       o Within each section listing, the manpage references are
         sorted alphabetically (case-sensitive) in a <DL> tag.
         The manpage references are listed in the <DT> section,
         and the summary text is listed in the <DD> section.

       o Each manpage reference listed is a hyperlink to the
         actual manpage as specified by the -cgiurl option.

     This ability to process keyword searches gives nice added
     functionality to a WWW forms interface to man(1).  Even if
     you have statically converted manpages to HTML via another
     man->HTML program, you can use man2html and "man -k" to pro-
     vide keyword search capabilities easily for your HTML man-
     pages.

  Processing Keyword Search Results
     Unfortunately, there is no standard controlling the format
     of keyword search results.  The man2html utility tries it
     best to handle all the variations.  However, the keyword
     search results generated by the Solaris operating system is
     different enough from other systems that a special command-
     line option (-solaris) must be specified to handle its out-
     put.

  Example of raw Solaris-type keyword search results:
     strcpy        strcpy (9f)  - copy a string from one location to another.
     strcpy        string (3c)  - string operations
     strncpy       strcpy (9f)  - copy a string from one location to another.
     strncpy       string (3c)  - string operations

     If keyword search results on your systems appear in the fol-
     lowing format:

         <topic>  <actual_manpage> (#) - Description

     then you need to specify the -solaris option in addition to
     the -k option.


ADDITIONAL NOTES

     Different systems format manpages differently.  Here is a
     list of recommended command-line options for certain sys-
     tems:

         Convex:   <defaults should be okay>
         HP:       -leftm 1 -topm 8
         Sun:      -sun (and -solaris when using -k)

     Some line spacing gets lost in the formatted nroff since the
     spacing would occur in the middle of a page break.  This can
     cause text to be merged that shouldn't be merged when
     man2html depaginates the text.  To avoid this problem,
     man2html keeps track of the margin indent right before and
     after a page break.  If the margin width of the line after
     the page break is less than the line before the page break,
     then man2html inserts a blank line in the HTML output.

     A manpage cross-reference is detected by the following
     pseudo expression: [A-z.-+_]+([0-9][A-z]?)

     The man2html utility only recognizes lines with " - " (the
     normal separator between manpage references and summary
     text) while in keyword search mode.

     The man2html utility can be hooked in a CGI script/program
     to convert manpages on the fly.  This is the reason for the
     -cgiurl option.


LIMITATIONS

     The order that section head mapping is searched is not
     defined.  Therefore, if two or more <section head text> can
     match a give manpage section, there is no way to determine
     which map tag is chosen.

     If -seealso is specified, all xrefs are detected after the
     SEE ALSO heading.  In other words, sections after SEE ALSO
     may contain hyperlinked xrefs.


BUGS

     Text that is flush to the left margin, but is not actually a
     section head, can be mistaken for a section head.  This mis-
     take is more likely when the -sun option is in affect.


VERSION

     This documentation describes man2html version 3.0.1


SEE ALSO

     man(1), nroff(1), perl(1)

     http://www.oac.uci.edu/indiv/ehood/man2html.html


AUTHOR

     Earl Hood
     ehood@medusa.acs.uci.edu


ERRORS AND OMISSIONS

     Troff version of this document initially created for version
     2.1.0 by C. Jeffery Small (jeff@cjsa.com) by copying, refor-
     matting, rearranging and partially rewriting the contents of
     the ascii text file doc/man2html.txt.
     _________________________________________________________________
   
   
    Man(1) output converted with man2html
������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������i2util-1.6/support/man2html3.0.1/install.me���������������������������������������������������������0000775�0000000�0000000�00000044053�12766054166�0020425�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������#!/opt/perl/bin/perl
##---------------------------------------------------------------------------##
##  File:
##	@(#) install.me 1.5 97/08/12 13:08:50 @(#)
##  Author:
##      Earl Hood, ehood@medusa.acs.uci.edu
##  Summary:
##	Installation program for Perl applications.
##---------------------------------------------------------------------------##
##    Copyright (C) 1997	Earl Hood, ehood@medusa.acs.uci.edu
##
##    This program is free software; you can redistribute it and/or modify
##    it under the terms of the GNU General Public License as published by
##    the Free Software Foundation; either version 2 of the License, or
##    (at your option) any later version.
##
##    This program 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 General Public License for more details.
##
##    You should have received a copy of the GNU General Public License
##    along with this program; if not, write to the Free Software
##    Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
##    02111-1307, USA
##---------------------------------------------------------------------------##

package InstallMe;

use vars qw(  
    $MSDOS $MACOS $UNIX $VMS $WINDOWS
    $DIRSEP $DIRSEPRX $CURDIR
    $PROG $PATHSEP
    $OSType
);
use Config;
use FileHandle;
use Getopt::Long;

###############################################################################
##	OS Configuration Code
###############################################################################
##---------------------------------------------------------------------------##
##	BEGIN block.
##
##	Variables set:
##
##	    $MSDOS	=> Set to 1 if running under MS-DOS/Windows
##	    $MACOS	=> Set to 1 if running under Mac
##	    $UNIX	=> Set to 1 if running under Unix
##	    $VMS 	=> Set to 1 if running under VMS
##	    $WINDOWS	=> Set to 1 if running under Windows
##	    $DIRSEP	=> Directory separator character
##	    $DIRSEPRX	=> Directory separator character for use in
##			   regular expressions.
##	    $CURDIR	=> Value representing current directory
##	    $PROG	=> Program name with leading pathname component
##			   stripped off.
##	    $PATHSEP	=> Recommend separator for a list of paths.
##
##	Notes:
##	    Do not know what to do about VMS.  Currently treat it
##	    like Unix.  Mac stuff may be incorrect.
##
BEGIN {
    %DirSep = (
	macos	=> ':',
	msdos	=> '\\',
	unix	=> '/',
	vms	=> '/',	# ??
	windows	=> '\\',
    );
    %CurDir = (
	macos	=> ':',	# ??
	msdos	=> '.',
	unix	=> '.',
	vms	=> '.',	# ??
	windows	=> '.',
    );
    %PathSep = (
	macos	=> ';',	# ??
	msdos	=> ';',
	unix	=> ':',
	vms	=> ':',	# ??
	windows	=> ';',
    );

    my $dontknow = 0;

    ## Init variables
    $MACOS	= 0;	$MSDOS	= 0;
    $UNIX	= 0;	$VMS	= 0;
    $WINDOWS	= 0;
    $DIRSEP	= '/';	$CURDIR = '.';
    $PATHSEP	= ':';

    ## See if ostype can be determined from osname in Config
    $_ = $Config{'osname'};
    if (/mac/i) {
	$MACOS = 1;
	$OSType = 'macos';
    } elsif (/vms/i) {
	$VMS = 1;
	$OSType = 'vms';
    } elsif (/msdos/i) {
	$MSDOS = 1;
	$OSType = 'msdos';
    } elsif (/mswin/i) {
	$WINDOWS = 1;  $MSDOS = 1;
	$OSType = 'windows';
    } elsif (/unix/i or
	     /aix/i or
	     /dynix/i or
	     /hpux/i or
	     /solaris/i or
	     /sunos/i or
	     /ultrix/i or
	     /linux/i) {
	$UNIX = 1;
	$OSType = 'unix';
    } else {
	$dontknow = 1;
    }

    ## If we do not know now what the ostype is, make a guess.
    if ($dontknow) {
	my($tmp);

	## MSDOG/Windoze
	if (($tmp = $ENV{'COMSPEC'}) and
	    ($tmp =~ /[a-zA-Z]:\\/) and
	    (-e $tmp)) {

	    $MSDOS = 1;
	    if ($tmp =~ /win/i) {
		$WINDOWS = 1;
		$OSType = 'windows';
	    } else {
		$OSType = 'msdos';
	    }

	## MacOS
	} elsif (defined($MacPerl::Version)) {
	    $MACOS = 1;
	    $OSType = 'macos';

	## Unix (fallback case)
	} else {
	    $UNIX = 1;
	    $OSType = 'unix';
	}
    }

    ## Set other variables
    $DIRSEP 	= $DirSep{$OSType};
    $CURDIR 	= $CurDir{$OSType};
    $PATHSEP 	= $PathSep{$OSType};
    ($DIRSEPRX 	= $DIRSEP) =~ s/(\W)/\\$1/g;

    ##	Store name of program
    ($PROG = $0) =~ s%.*[$DIRSEPRX]%%o;

    ##	Flag to prompt for command-line options on a Mac
    $MacCLPrompt = 1;
}

###############################################################################
##	Initialize Globals
###############################################################################

my %Files	= ();
my %DefValues	= (
    binpath	=> $Config{'installbin'},
    docpath	=> $Config{'prefix'} . $DIRSEP . 'doc',
    libpath	=> $Config{'installsitelib'},
    manifest	=> 'MANIFEST',
    manpath	=> $Config{'installman1dir'},
    perlpath	=> $Config{'perlpath'},
);
$DefValues{'manpath'} =~ s|(${DIRSEPRX}man)${DIRSEPRX}.*|$1|;
my %OptValues	= ();

###############################################################################
##	Parse Command-line
###############################################################################

{
    CLinit();
    my $ret =
    GetOptions(\%OptValues,
	       qw(
		   batch
		   binpath=s
		   libpath=s
		   manpath=s
		   perlpath=s
		   manifest=s
		   nobin
		   nodoc
		   nolib
		   noman

		   help));

    if (!$ret or $OptValues{"help"}) {
	usage();
	exit !$ret;
    }
}

###############################################################################
##	Do It
###############################################################################

{
    my($dobin, $dolib, $dodoc, $doman);

    ## Get isntallation files
    ## ----------------------
    read_manifest($OptValues{'manifest'} || $DefValues{'manifest'},
		  \%Files);

    $DefValues{'docpath'} .= $DISRSEP . $Files{'name'}[0]
	if $Files{'name'}[0];
    $dobin = scalar(@{$Files{'bin'}}) && !$OptValues{'nobin'};
    $dolib = scalar(@{$Files{'lib'}}) && !$OptValues{'nolib'};
    $dodoc = scalar(@{$Files{'doc'}}) && !$OptValues{'nodoc'};
    $doman = scalar(@{$Files{'man'}}) && !$OptValues{'noman'};
    die "Nothing to install!\n"
	unless $dobin or $dolib or $dodoc or $doman;

    ## Get path stuff
    ## --------------
    if ($OptValues{'batch'}) {
	$OptValues{'perlpath'} = $DefValues{'perlpath'}
	    unless $OptValues{'perlpath'};
	$OptValues{'binpath'}  = $DefValues{'binpath'}
	    unless $OptValues{'binpath'};
	$OptValues{'libpath'}  = $DefValues{'libpath'}
	    unless $OptValues{'libpath'};
	$OptValues{'docpath'}  = $DefValues{'docpath'}
	    unless $OptValues{'docpath'};
	$OptValues{'manpath'}  = $DefValues{'manpath'}
	    unless $OptValues{'manpath'};
    } else {
	while (1) {
	    $OptValues{'perlpath'} =
		get_perl_from_user($OptValues{'perlpath'},
				   $DefValues{'perlpath'},
				   "Pathname of perl executable:");
	    $OptValues{'binpath'} =
		get_path_from_user($OptValues{'binpath'},
				   $DefValues{'binpath'},
				   "Directory to install executables:")
				   if $dobin;
	    $OptValues{'libpath'} =
		get_path_from_user($OptValues{'libpath'},
				   $DefValues{'libpath'},
				   "Directory to install library files:")
				   if $dolib;
	    $OptValues{'docpath'} =
		get_path_from_user($OptValues{'docpath'},
				   $DefValues{'docpath'},
				   "Directory to install documentation:")
				   if $dodoc;
	    $OptValues{'manpath'} =
		get_path_from_user($OptValues{'manpath'},
				   $DefValues{'manpath'},
				   "Directory to install manpages:")
				   if $doman;

	    print STDOUT "You have specified the following:\n";
	    print STDOUT "\tPerl path: $OptValues{'perlpath'}\n";
	    print STDOUT "\tBin directory: $OptValues{'binpath'}\n"
		if $dobin;
	    print STDOUT "\tLib directory: $OptValues{'libpath'}\n"
		if $dolib;
	    print STDOUT "\tDoc directory: $OptValues{'docpath'}\n"
		if $dodoc;
	    print STDOUT "\tMan directory: $OptValues{'manpath'}\n"
		if $doman;

	    last  if prompt_user_yn("Is this correct?", 1);

	    $DefValues{'perlpath'} = $OptValues{'perlpath'};
	    $DefValues{'binpath'}  = $OptValues{'binpath'};
	    $DefValues{'libpath'}  = $OptValues{'libpath'};
	    $DefValues{'docpath'}  = $OptValues{'docpath'};
	    $DefValues{'manpath'}  = $OptValues{'manpath'};
	    $OptValues{'perlpath'} = '';
	    $OptValues{'binpath'}  = '';
	    $OptValues{'libpath'}  = '';
	    $OptValues{'docpath'}  = '';
	    $OptValues{'manpath'}  = '';
	}
    }

    ## Install files
    ## -------------
    print STDERR "($OptValues{'perlpath'})\n";
    my $plprefix  = "#!$OptValues{'perlpath'}\n";
       $plprefix .= "use lib qw($OptValues{'libpath'});\n"
		    if $OptValues{'libpath'};
    my($file, $destfile);
    if ($dobin) {
	print STDOUT qq(Installing programs to "$OptValues{'binpath'}":\n);
	foreach (@{$Files{'bin'}}) {
	    print STDOUT "    $_ => ";
	    ($file = $_) =~ s%.*/%%o;
	    $destfile = join('', $OptValues{'binpath'}, $DIRSEP, $file);
	    print STDOUT $destfile, "\n";
	    cp($_, $destfile, $plprefix);
	    eval q{chmod 0755, $destfile;};
	}
    }
    if ($dolib) {
	print STDOUT qq(Installing lib files to "$OptValues{'libpath'}":\n);
	foreach (@{$Files{'lib'}}) {
	    print STDOUT "    $_ => ";
	    ($file = $_) =~ s%.*/%%o;
	    $destfile = join('', $OptValues{'libpath'}, $DIRSEP, $file);
	    print STDOUT $destfile, "\n";
	    cp($_, $destfile);
	}
    }
    if ($dodoc) {
	print STDOUT qq(Installing docs to "$OptValues{'docpath'}":\n);
	foreach (@{$Files{'doc'}}) {
	    print STDOUT "    $_ => ";
	    ($file = $_) =~ s%.*/%%o;
	    $destfile = join('', $OptValues{'docpath'}, $DIRSEP, $file);
	    print STDOUT $destfile, "\n";
	    cp($_, $destfile);
	}
    }
    if ($doman) {
	my $sect;
	print STDOUT qq(Installing manpages to "$OptValues{'manpath'}":\n);
	foreach (@{$Files{'man'}}) {
	    print STDOUT "    $_ => ";
	    ($file = $_)    =~ s%.*/%%o;
	    ($sect = $file) =~ s%.*\.%%o;
	    $destfile = join('', $OptValues{'manpath'},
			     $DIRSEP, "man", $sect, $DIRSEP, $file);
	    print STDOUT $destfile, "\n";
	    cp($_, $destfile);
	}
    }
}

###############################################################################
##	Subroutines
###############################################################################

##------------------------------------------------------------------------
##	read_manifest() reads file giving list of all files to
##	install.
##
sub read_manifest {
    my $file	= shift;
    my $href	= shift;
    my($key, $pathname);

    open FILE, $file or die qq(Unable to open "$file"\n);
    while (<FILE>) {
	next  if /^#/;
	next  unless /\S/;
	chomp;
	($key, $pathname) = split(/:/, $_, 2);
	push @{$href->{$key}}, $pathname;
    }
    close FILE;
}

##------------------------------------------------------------------------
##	perl_exe() returns true if pathname argument is a perl
##	interpreter.
##
sub perl_exe {
    my $pathname = shift;

    return 0  unless open PERL, "perl -v |";
    while (<PERL>) {
	if (/\bperl\b/) {
	    close PERL;
	    return 1;
	}
    }
    close PERL;
    0;
}

##------------------------------------------------------------------------
##	get_perl_from_user() gets the pathname of the perl executable.
##
sub get_perl_from_user {
    my $value	= shift;	# Current value (if set, batch mode)
    my $default	= shift;	# Default value
    my $prompt	= shift;	# User prompt

    if ($value =~ /\S/) {
	die qq(ERROR: "$value" is not perl.\n)
	    unless perl_exe($value);
    } else {
	while (1) {
	    $value = interpolate_path(prompt_user($prompt, $default));
	    last  if perl_exe($value);
	    warn qq(Warning: "$value" is not perl.\n);
	}
    }
    $value;
}

##------------------------------------------------------------------------
##	get_path_from_user() gets a path from the user.  The function
##	insures the path exists.
##
sub get_path_from_user {
    my $value	= shift;	# Current value (if set, batch mode)
    my $default	= shift;	# Default value
    my $prompt	= shift;	# User prompt

    if ($value =~ /\S/) {
	die qq(ERROR: Unable to create "$value".\n)
	    unless create_dir($value, 1);
    } else {
	while (1) {
	    $value = interpolate_path(prompt_user($prompt, $default));
	    last  if create_dir($value);
	    warn qq(Warning: Unable to create "$value".\n);
	}
    }
    $value;
}

##------------------------------------------------------------------------
##	create_dir() creates a directory path
##
sub create_dir {
    my $d	= shift;	# Directory path
    my $noask	= shift;	# Don't ask to create flag

    return 1  if -e $d;

    my(@a) = grep($_ ne '', split(/$'DIRSEPrxp/o, $d));
    my($path, $dir, $curpath);

    if (!$noask) {
        return 0  unless prompt_user_yn(qq{"$d" does not exist.  Create}, 1);
    }
    if ($MSDOS) {
	if ($d =~ m%^\s*([a-zA-Z]:)?[/\\]%) {
	    $path = shift @a;
	} else {
	    $path = $CURDIR;
	}
    } else {
	if ($d =~ /^\s*\//) {
	    $path = '';
	} else {
	    $path = $CURDIR;
	}
    }
    foreach $dir (@a) {
	$curpath = "$path$DIRSEP$dir";
	if (! -e $curpath) {
	    if (!mkdir($curpath, 0777)) {
		warn "Unable to create $curpath: $!\n";
		return 0;
	    }
	} elsif (! -d $curpath) {
	    warn "$curpath is not a directory\n";
	    return 0;
	}
	$path .= $DIRSEP . $dir;
    }
    if (! -w $d) {
	warn "$d not writable\n";
	return 0;
    }
    1;
}

##------------------------------------------------------------------------
##	interpolate_path() expands any special characters in a
##	pathname.
##
sub interpolate_path {
    my($path) = shift;

    $path =~ s/^~/$ENV{'HOME'}/;
    $path =~ s/\$(\w+)/$ENV{$1}/ge;
    $path =~ s/\$\{(\w+)\}/$ENV{$1}/ge;
    $path;
}

##------------------------------------------------------------------------
##	cp() copies a file, or directory.
##
sub cp {
    my($src, $dst, $prepend) = @_;

    if (-d $src) {
	if (! -e $dst) {
	    mkdir($dst,0777) or die "Unable to create $dst: $!\n";
	}
	opendir(DIR, $src) or die "Unable to open $src: $!\n";
	my @files = grep(!/^(sccs|\.|\..)$/i, readdir(DIR));
	closedir(DIR);
	my($file, $srcpn, $dstpn);
	foreach $file (@files) {
	    $srcpn = "$src$DIRSEP$file";
	    $dstpn = "$dst$DIRSEP$file";
	    if (-d $srcpn) {
		cp($srcpn, $dstpn, $prepend);
	    } else {
		cpfile($srcpn, $dstpn, $prepend);
	    }
	}


    } else {
	cpfile($src, $dst, $prepend);
    }
}

##------------------------------------------------------------------------
##	cpfile() copies a file.  Any text in $prepend will be prepending
##	to the destination file.
##
sub cpfile {
    my($src, $dst, $prepend) = @_;

    if (-d $dst) {
	my $tmp;
	($tmp = $src) =~ s%.*[$DIRSEPRX]%%o;
	$dst .= $DIRSEP . $tmp;
    }
    open(SRC, $src) 	or die "Unable to open $src: $!\n";
    open(DST, "> $dst") or die "Unable to create $dst: $!\n";
    if (-B $src) { binmode( SRC ); binmode( DST ); }
    if ($prepend) {
	print DST $prepend;
    }
    print DST <SRC>;
    close(SRC);
    close(DST);
}

##------------------------------------------------------------------------
##      prompt_user() prompts the user for some input.  The first
##      argument is the prompt string, the second is the default
##      value is the user specifies nothing.
##
sub prompt_user {
    my $prompt = shift;
    my $default = shift;
 
    my($answer);
 
    print STDOUT $prompt;
    print STDOUT qq{ ("$default")}  if defined($default);
    print STDOUT " ";
    $answer = <STDIN>;
    chomp $answer;
    $answer = $default  if $answer !~ /\S/;
    $answer;
}
 
##------------------------------------------------------------------------
##      prompt_user_yn() prompts the user for a yes or no question.
##
sub prompt_user_yn {
    my $prompt = shift;
    my $default = shift;
 
    my($answer);
 
    print STDOUT $prompt, " ";
    print STDOUT $default ? "['y']" : "['n']"; 
    print STDOUT " ";
    $answer = <STDIN>;
    chomp $answer;
    if ($answer !~ /\S/) {
        $answer = $default;
    } elsif ($answer =~ /y/i or $answer =~ /yes/i) {
        $answer = 1;
    } else {
        $answer = 0;
    }
    $answer;
}

##---------------------------------------------------------------------------##
##	CLinit() initializes @ARGV.  Currently, it does nothing under
##	MSDOS and Unix.
##
##	If running under a Mac and the script is a droplet, command-line
##	options will be prompted for if $MacCLPrompt is set to a
##	non-zero value.
##
sub CLinit {

    ##	Ask for command-line options if script is a Mac droplet
    ##		Code taken from the MacPerl FAQ
    ##
    if ($MacCLPrompt && ( $MacPerl::Version =~ /Application$/ )) {

	# we're running from the app
	my( $cmdLine, @args );
	$cmdLine = &MacPerl::Ask( "Enter command line options:" );
	require "shellwords.pl";
	@args = &shellwords( $cmdLine );
	unshift( @::ARGV, @args );
    }
}

##---------------------------------------------------------------------------##
##	path_join takes an array of path components and returns a string
##	with components joined together by the directoy separator.
##
sub path_join {
    join($DIRSEP, @_);
}

##---------------------------------------------------------------------------##
##	path_split takes a string representing a pathname and splits
##	it into an array of components.  The pathname is interpreted
##	with respect to the OS we are running under.
##
sub path_split {
    split(/$DIRSEPRX/o, $_[0]);
}

##---------------------------------------------------------------------------##
##	is_absolute_path() returns true if a string is an absolute path
##
sub is_absolute_path {

    if ($MSDOS or $WINDOWS) {	## Path starts with a drive letter
	return $_[0] =~ /^[a-z]:/i;
    }
    if ($MACOS) {		## Not sure about Mac
	return $_[0] =~ /^$DIRSEPRX/o;
    }
    if ($VMS) {			## Not sure about VMS
	return $_[0] =~ /^\w+:/i;
    }
    $_[0] =~ /^$DIRSEPRX/o;	## Unix
}

##---------------------------------------------------------------------------##
##
sub usage {
    print STDOUT <<EOF;
Usage: $PROG [options]
Options:
  -batch                : Run in batch mode
  -binpath <path>       : Path to bin directory
  -help                 : This message
  -libpath <path>       : Path to lib directory
  -manifest <file>      : List of files to install (def="MANIFEST")
  -manpath <path>       : Path to man directory
  -nobin                : Do not install programs
  -nodoc                : Do not install documentation
  -nolib                : Do not install library files
  -noman                : Do not install manpages
  -perlpath <pathname>  : Pathname of perl interpreter
EOF
}

##---------------------------------------------------------------------------##
�������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������i2util-1.6/support/man2html3.0.1/man.cgi������������������������������������������������������������0000775�0000000�0000000�00000026337�12766054166�0017700�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������#!/usr/local/bin/perl
##---------------------------------------------------------------------------##
##  File:
##      @(#) man.cgi 1.2 97/08/12 12:58:26 @(#)
##  Author:
##      Earl Hood       ehood@medusa.acs.uci.edu
##  Description:
##	man.cgi is a CGI program for viewing Unix manpages.  The
##	program man2html,
##	<URL:http://www.oac.uci.edu/indiv/ehood/man2html.html>,
##	is used to convert the output from man(1) to html.
##
##	If man.cgi is invoked with no input data, it will output a
##	form for the user to select a manpage to view.
##	man.cgi can handle POST and GET methods.
##
##	The code section "Configureable Globals" is designed to
##	allow you to modify man.cgi to work with your particular
##	system configuration.
##---------------------------------------------------------------------------##
##  Copyright (C) 1995-1997,  Earl Hood, ehood@medusa.acs.uci.edu
##
##  This program is free software; you can redistribute it and/or modify
##  it under the terms of the GNU General Public License as published by
##  the Free Software Foundation; either version 2 of the License, or
##  (at your option) any later version.
##  
##  This program 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 General Public License for more details.
##  
##  You should have received a copy of the GNU General Public License
##  along with this program; if not, write to the Free Software
##  Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
##  02111-1307, USA
##---------------------------------------------------------------------------##

########################################################################
##	Configureable Globals
########################################################################
##	Change the value of these variables to reflect your
##	system configuration.
########################################################################

##  "English" name for program

$ProgName	= "Manpage Viewer";

##  cgi-bin directory as accessed by a URL.

$CgiBin  	= "/cgi-bin";

##  man program (should be a full pathname)

$ManPrg		= '/usr/bin/man';

##  man(1) option to specify a section.  "-s" is used for Solaris
##  systems.  If using Tom Christiansen's Perl man program, than
##  define use "".

#$SectOpt	= "";
$SectOpt	= "-s";

##  man2html program (needs to be a full pathname)

$ManConvPrg	= '/usr/local/bin/man2html';

##  Flag if the -cgiurl option should be used

$DoCgiurl	= 1;

##  System specific arguments to man2html:
##	HP  => ("-leftm", "1", "-topm", "8")
##	Sun => ("-sun")
##  See man2html documentation for more information.

#@ConvArgs	= ("-compress");
#@ConvArgs	= ("-compress", "-leftm", "1", "-topm", "8");
@ConvArgs	= ("-compress", "-sun");

##  Keyword search processing arguments for man2html.  Normally,
##  '-k' is adequate.  However, if on a Solaris system, the
##  '-solaris' option should be specified with '-k'.  See
##  man2html documentation on information about the '-solaris' option.

#@KeyWArgs	= ("-k");			# Normal
@KeyWArgs	= ("-k", "-solaris");		# For Solaris

##  Possible manual sections.  This array is used to determine the
##  the choices available in an option menu.

@Sections	= (
    '1', '1F', '1M',
    '2',
    '3', '3C', '3F', '3G', '3I', '3N', '3S', '3X',
    '4',
    '5',
    '6',
    '7',
    '8',
    '9', '9F',
);

##  Form method.  The value is either 'GET' or 'POST'.  'GET' is
##  recommended since the URL sent by the client also contains
##  the argument information.  This allows a client's "Reload" function
##  to reprocess a currently viewed manpage.

$FormMethod	= 'GET';

##  Argument separator for CGI URL links.  As clients become more
##  SGML conformant, the simple use of '&' conflicts with
##  SGML syntax.  You can set this variable to control what is
##  used as the separator.  Possibilities:
##	&
##	&
##	;
##

$ArgSep		= '&';

##  Man directories.  Add paths to the list you want man(1) to
##  know about

@ManPath	= qw(
    /usr/local/man
    /usr/openwin/man
    /usr/man
);

##  PATH setting.  Modify as see fit.  Once useful modification
##  is to have groff utils first in path since its nroff would
##  be invoked over the systems nroff when man formats a manpage.

@Path   	= qw(
    /opt/FSFgroff/bin
    /bin
    /usr/bin
);

########################################################################
##	END!!!! Configureable Globals section
########################################################################

########################################################################
##	Globals
########################################################################

($PROG = $0)	=~ s/.*\///;		# Name of program
$VERSION	= '2.0.1';		# Version
%FORM		= ();			# Hash to hold form contents
$Error		= '';			# Error string
$ENV{'MANPATH'}	= join(":", @ManPath);
$ENV{'PATH'}	= join(":", @Path);

########################################################################
##	Main block
{
    #	Set unbuffered I/O.  Prevents buffering problems with
    #	"system()" calls.
    select((select(STDOUT), $| = 1)[0]);

    #	Print content-type header
    printouttype("text/html");

    #	Print man form if called w/no arguments
    printform() if noarg();

    #	If reached here, there is input to process
    error("CGI input error") unless parseinput();
    printform() unless $FORM{'topic'};
    doit();
    exit 0;
}
########################################################################
##	Subroutines
########################################################################

#-----------------------------------------------------------------------
#	printform outputs the man selection form to the client.
#
sub printform {
    printhead($ProgName);
    print STDOUT <<EndOfForm;
<p>The following form allows you to view a manpage on this system.
Please fill out the following fields and select <strong>Submit</strong>
to view a manpage.
</p>
<form method="$FormMethod" action="$CgiBin/man.cgi">
<table border=0>
<tr>
<td align=right>Section:</td>
<td><select name=section>
<option value="all">All Sections</option>
<option value="keyword">Keyword Search</option>
EndOfForm

    #	Print out possible section choices
    local($section);
    foreach $section (@Sections) {
	print STDOUT qq|<option value="$section">Section $section</option>\n|;
    }

print STDOUT <<EndOfForm;
</select>
</td>
</tr>
<tr>
<td align=right>Topic:</td>
<td><input type="TEXT" name="topic"></td>
</tr>
<tr>
<td></td><td><input type="SUBMIT" value="Submit"><td>
</tr>
</table>
</form>
EndOfForm
    printend();
    exit 0;
}

#-----------------------------------------------------------------------
#	doit does the conversion
#
sub doit {
    my($section, $topic, $manexec, $manout, $tmp);
    $manout = '';

    # Get section and topic from input
    #---------------------------------
    $section = $FORM{'section'};
    $topic = $FORM{'topic'};
    error("Questionable characters in topic")  if isquestionable($topic);

    # Determine command arguments for man and man2html
    #-------------------------------------------------
    @ARGV = ();
    @manargs = ();
    $manexec = $ManPrg;
    if ($section =~ /keyword/) {
	$manexec .= " -k $topic";
	push(@manargs, "-k", $topic);
	push(@ARGV, @KeyWArgs,
		    "-title", qq{Keyword search: "$topic"});
    } else {
	error("No topic entered")  unless $topic;
	if ($section !~ /all/) {
	    push(@manargs, $SectOpt)  if $SectOpt;
	    push(@manargs, $section);
	}
	push(@manargs, $topic);
	$manexec .= " $section"  if $section !~ /all/;
	$manexec .= " $topic";
	$tmp  = $topic;
	$tmp .= "($section)"  if $section !~ /all/;
	push(@ARGV, @ConvArgs,
		    "-title", $tmp);
    }

    # Check if doing man xref detection
    #----------------------------------
    if ($DoCgiurl) {
	push(@ARGV, "-cgiurl",
		    join('', $CgiBin, '/man.cgi?',
			     'section=${section}${subsection}',
			     $ArgSep,
			     'topic=${title}'));
    }

    # Convert output from man to html
    #--------------------------------
    close(STDERR);
    open(MANPRG, "-|") or exec($ManPrg, @manargs);
    $Man2Html::InFH = \*MANPRG;		# set input filehandle
    require $ManConvPrg or
	error("Problem executing man->HTML converter");
}

########################################################################
##	Generic subroutines for CGI use
########################################################################

#-----------------------------------------------------------------------
#	noarg returns true if no arguments were passed to script.
#
sub noarg {
    $ENV{"REQUEST_METHOD"} eq "GET" && $ENV{"QUERY_STRING"} =~ /^\s*$/;
}

#-----------------------------------------------------------------------
#	parseinput converts the input data into the %FORM array
#
sub parseinput {
    my($method) = ($ENV{"REQUEST_METHOD"});
    my($data);
    if ($method eq "GET") {
	$data = $ENV{"QUERY_STRING"};
    } elsif ($method eq "POST") {
	read(STDIN, $data, $ENV{"CONTENT_LENGTH"});
    } else {
	$Error = "Unrecgonized request method : $method";
	return 0;
    }
    my(@pairs, $name, $value);
    if ($data ne '') {
	@pairs = split(/&/, $data);
	foreach (@pairs) {
	    ($name, $value) = split(/=/);
	    $name = expandstr($name);
	    $value = expandstr($value);
	    $FORM{$name} = $value;
	}
    }
    1;
}

#-----------------------------------------------------------------------
#	printouttype prints out specified content-type header back
#	to client
#
sub printouttype {
    my($type) = shift;
    print STDOUT "Content-type: $type\r\n\r\n";
}

#-----------------------------------------------------------------------
#	printhead outputs html prematter
#
sub printhead {
    my($title, $h1) = @_;
    $h1 = $title  unless $h1;

    print STDOUT <<ENDOFHEAD;
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML//EN">
<HTML>
<HEAD>
<TITLE>$title


$h1

ENDOFHEAD } #----------------------------------------------------------------------- # printend outputs html postmatter # sub printend { print STDOUT <
Manpage viewer available with the man2html package.
ENDOFEND } #----------------------------------------------------------------------- # error prints an error out to the client. # sub error { my($str) = htmlize(shift); printhead("$ProgName Error"); $str .= ":" if $Error && $str; $str .= " $Error"; print STDOUT "

$str

"; printend(); exit 0; } #----------------------------------------------------------------------- # htmlize translates special characters to enitity refs. # sub htmlize { my($str) = shift; $str =~ s/&/\&/g; $str =~ s//\>/g; $str; } #----------------------------------------------------------------------- # expandstr translates hex codes to characters # sub expandstr { my($str) = shift; $str =~ tr/+/ /; $str =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C", hex($1))/ge; $str; } #----------------------------------------------------------------------- # isquestionable determines if $str contains questionable # characters if $str is used in a subshell invocation. # sub isquestionable { my($str) = shift; $str !~ /^[a-zA-Z0-9_\-+ \t\/@%\.]+$/; } ######################################################################## i2util-1.6/support/man2html3.0.1/man2html000077500000000000000000000460771276605416600201110ustar00rootroot00000000000000#!/usr/bin/perl ##---------------------------------------------------------------------------## ## File: ## @(#) man2html 1.2 97/08/12 12:57:30 @(#) ## Author: ## Earl Hood, ehood@medusa.acs.uci.edu ## Description: ## man2html is a Perl program to convert formatted nroff output ## to HTML. ## ## Recommend command-line options based on platform: ## ## Platform Options ## --------------------------------------------------------------------- ## c2mp ## hp9000s700/800 -leftm 1 -topm 8 ## sun4 -sun ## --------------------------------------------------------------------- ## ##---------------------------------------------------------------------------## ## Copyright (C) 1995-1997 Earl Hood, ehood@medusa.acs.uci.edu ## ## This program is free software; you can redistribute it and/or modify ## it under the terms of the GNU General Public License as published by ## the Free Software Foundation; either version 2 of the License, or ## (at your option) any later version. ## ## This program 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 General Public License for more details. ## ## You should have received a copy of the GNU General Public License ## along with this program; if not, write to the Free Software ## Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA ## 02111-1307, USA ##---------------------------------------------------------------------------## package Man2Html; use Getopt::Long; ($PROG = $0) =~ s/.*\///; $VERSION = "3.0.1"; ## Input and outputs filehandles $InFH = \*STDIN unless $InFH; $OutFH = \*STDOUT unless $OutFH; ## Backspace character: Used in overstriking detection *bs = \"\b"; ## Hash of section titles and their HTML tag wrapper. ## This list allows customization of what HTML tag is used for ## a given section head. ## ## The section title can be a regular expression. Therefore, one must ## be careful about quoting special characters. ## %SectionHead = ( '\S.*OPTIONS.*' => '

', 'AUTHORS?' => '

', 'BUGS' => '

', 'COMPATIBILITY' => '

', 'DEPENDENCIES' => '

', 'DESCRIPTION' => '

', 'DIAGNOSTICS' => '

', 'ENVIRONMENT' => '

', 'ERRORS' => '

', 'EXAMPLES' => '

', 'EXTERNAL INFLUENCES' => '

', 'FILES' => '

', 'LIMITATIONS' => '

', 'NAME' => '

', 'NOTES?' => '

', 'OPTIONS' => '

', 'REFERENCES' => '

', 'RETURN VALUE' => '

', 'SECTION.*:' => '

', 'SEE ALSO' => '

', 'STANDARDS CONFORMANCE' => '

', 'STYLE CONVENTION' => '

', 'SYNOPSIS' => '

', 'SYNTAX' => '

', 'WARNINGS' => '

', '\s+Section.*:' => '

', ); ## Fallback tag if above is not found $HeadFallback = '

'; ## Other gobals $Bare = 0; # Skip printing HTML head/foot flag $BTag = 'B'; # Overstrike tag $CgiUrl = ''; # CGI URL expression $Compress = 0; # Do blank line compression flag $K = 0; # Do keyword search processing flag $NoDepage = 0; # Do not strip page information $NoHeads = 0; # Do no header detection flag $SeeAlso = 0; # Do only SEE ALSO xrefs flag $Solaris = 0; # Solaris keyword search processing flag $Sun = 0; # Headers not overstriken flag $Title = ''; # Title $UTag = 'I'; # Underline tag $ftsz = 0; # Bottome margin size $hdsz = 0; # Top margin size #$ftsz = 7; # Bottome margin size #$hdsz = 7; # Top margin size $leftm = ''; # Left margin pad $leftmsz = 0; # Left margin size $pgsz = 66; # Size of page size $txsz = 52; # Text body length size ############################################################################# ## Main Block ############################################################################# { if (get_cli_opts()) { if ($K) { man_k(); } else { do_it(); } } else { usage(); } } ############################################################################# ## Subroutines ############################################################################# sub do_it { ## Define while loop and then eval it when used. The reason ## is to avoid the regular expression reevaulation in the ## section head detection code. $doitcode =<<'EndOfDoItCode'; my($line, $tmp, $i, $head, $preindent, $see_also, $do); $see_also = !$SeeAlso; print $OutFH "\n"; LOOP: while(!eof($InFH)) { $blank = 0; for ($i=0; $i < $hdsz; $i++) { last LOOP unless defined($_ = <$InFH>); } for ($i=0; $i < $txsz; $i++) { last LOOP unless defined($_ = <$InFH>); ## Check if compress consecutive blank lines if ($Compress and !/\S/) { if ($blank) { next; } else { $blank = 1; } } else { $blank = 0; } ## Try to check if line space is needed at page boundaries ## if (!$NoDepage && ($i==0 || $i==($txsz-1)) && !/^\s*$/) { /^(\s*)/; $tmp = length($1); if ($do) { if ($tmp < $preindent) { print $OutFH "\n"; } } else { $do = 1; } $preindent = $tmp; } else { $do = 0; $preindent = 0; } ## Interpret line $line = $_; entitize(\$_); # Convert [$<>] to entity references ## Check for 'SEE ALSO' link only if (!$see_also && $CgiUrl && $SeeAlso) { ($tmp = $line) =~ s/.\010//go; if ($tmp =~ /^\s*SEE\s+ALSO\s*$/o) { $see_also = 1; } else { $see_also = 0; } } ## Create anchor links for manpage references s/((((.\010)+)?[\+_\.\w-])+\(((.\010)+)? \d((.\010)+)?\w?\)) /make_xref($1) /geox if $see_also; ## Create anchor links for http refs. s#(http\://\S*)#make_urlref($1)#gieo; ## Emphasize underlined words # s/((_\010[^_])+[\.\(\)_]?(_\010[^_])+\)?)/emphasize($1)/oge; # s/((_\010[^_])+([\.\(\)_]?(_\010[^_])+)?)/emphasize($1)/oge; # # The previous expressions were trying to be clever about # detecting underlined text which contain non-alphanumeric # characters. nroff will not underline non-alphanumeric # characters in an underlined phrase, and the above was trying # to detect that. It does not work all the time, and it # screws up other text, so a simplified expression is used. s/((_\010[^_])+)/emphasize($1)/oge; $secth = 0; ## Check for strong text and headings if ($Sun || /.\010./o) { if (!$NoHeads) { $line =~ s/.\010//go; $tmp = $HeadFallback; EndOfDoItCode ## Create switch statement for detecting a heading ## $doitcode .= "HEADSW: {\n"; foreach $head (keys %SectionHead) { $doitcode .= join("", "\$tmp = '$SectionHead{$head}', ", "\$secth = 1, last HEADSW ", "if \$line =~ /^$leftm$head/o;\n"); } $doitcode .= "}\n"; ## Rest of routine ## $doitcode .=<<'EndOfDoItCode'; if ($secth || $line =~ /^$leftm\S/o) { chop $line; $_ = $tmp . $line . $tmp; s%<([^>]*)>$%%; $_ = "\n

\n" . $_ . "
\n";
		    } else {
			s/(((.\010)+.)+)/strongize($1)/oge;
		    }
		} else {
		    s/(((.\010)+.)+)/strongize($1)/oge;
		}
	    }
	    print $OutFH $_;
	}

	for ($i=0; $i < $ftsz; $i++) {
	    last LOOP  unless defined($_ = <$InFH>);
	}
    }
EndOfDoItCode


    ##	Perform processing.

    printhead()  unless $Bare;
    print $OutFH "
\n";
    eval $doitcode;			# $doitcode defined above
    print $OutFH "
\n"; printtail() unless $Bare; } ##--------------------------------------------------------------------------- ## sub get_cli_opts { return 0 unless GetOptions( "bare", # Leave out HTML, HEAD, BODY tags. "belem=s", # HTML Element for overstriked text (def: "B") "botm=i", # Number of lines for bottom margin (def: 7) "cgiurl=s", # CGI URL for linking to other manpages "cgiurlexp=s", # CGI URL Perl expr for linking to other manpages "compress", # Compress consecutive blank lines "headmap=s", # Filename of user section head map file "k", # Process input from 'man -k' output. "leftm=i", # Character width of left margin (def: 0) "nodepage", # Do not remove pagination lines "noheads", # Do not detect for section heads "pgsize=i", # Number of lines in a page (def: 66) "seealso", # Link to other manpages only in the SEE ALSO section "solaris", # Parse 'man -k' output from a solaris system "sun", # Section heads are not overstriked in input "title=s", # Title of manpage (def: Not defined) "topm=i", # Number of lines for top margin (def: 7) "uelem=s", # HTML Element for underlined text (def: "I") "help" # Short usage message ); return 0 if defined($opt_help); $pgsz = $opt_pgsize || $pgsz; if (defined($opt_nodepage)) { $hdsz = 0; $ftsz = 0; } else { $hdsz = $opt_topm if defined($opt_topm); $ftsz = $opt_botm if defined($opt_botm); } $txsz = $pgsz - ($hdsz + $ftsz); $leftmsz = $opt_leftm if defined($opt_leftm); $leftm = ' ' x $leftmsz; $Bare = defined($opt_bare); $Compress = defined($opt_compress); $K = defined($opt_k); $NoDepage = defined($opt_nodepage); $NoHeads = defined($opt_noheads); $SeeAlso = defined($opt_seealso); $Solaris = defined($opt_solaris); $Sun = defined($opt_sun); $Title = $opt_title || $Title; $CgiUrl = $opt_cgiurlexp || ($opt_cgiurl ? qq{return "$opt_cgiurl"} : ''); $BTag = $opt_belem || $BTag; $UTag = $opt_uelem || $UTag; $BTag =~ s/[<>]//g; $UTag =~ s/[<>]//g; if (defined($opt_headmap)) { require $opt_headmap or warn "Unable to read $opt_headmap\n"; } 1; } ##--------------------------------------------------------------------------- sub printhead { print $OutFH "\n"; print $OutFH "\n", "$Title\n", "\n" if $Title; print $OutFH "\n"; print $OutFH "

$Title

\n", "
\n" if $Title; } ##--------------------------------------------------------------------------- sub printtail { print $OutFH <
Man(1) output converted with man2html
EndOfRef } ##--------------------------------------------------------------------------- sub emphasize { my($txt) = shift; $txt =~ s/.\010//go; $txt = "<$UTag>$txt"; $txt; } ##--------------------------------------------------------------------------- sub strongize { my($txt) = shift; $txt =~ s/.\010//go; $txt = "<$BTag>$txt"; $txt; } ##--------------------------------------------------------------------------- sub entitize { my($txt) = shift; ## Check for special characters in overstrike text ## $$txt =~ s/_\010\&/strike('_', '&')/geo; $$txt =~ s/_\010/strike('_', '>')/geo; $$txt =~ s/(\&\010)+\&/strike('&', '&')/geo; $$txt =~ s/(<\010)+\010)+>/strike('>', '>')/geo; ## Check for special characters in regular text. Must be careful ## to check before/after character in expression because it might be ## a special character. $$txt =~ s/([^\010]\&[^\010])/htmlize2($1)/geo; $$txt =~ s/([^\010]<[^\010])/htmlize2($1)/geo; $$txt =~ s/([^\010]>[^\010])/htmlize2($1)/geo; } ##--------------------------------------------------------------------------- ## escape special characters in a string, in-place ## sub htmlize { my($str) = shift; $$str =~ s/&/\&/g; $$str =~ s//\>/g; $$str; } ##--------------------------------------------------------------------------- ## htmlize2() is used by entitize. ## sub htmlize2 { my($str) = shift; $str =~ s/&/\&/g; $str =~ s//\>/g; $str; } ##--------------------------------------------------------------------------- ## strike converts HTML special characters in overstriked text ## into entity references. The entities are overstriked so ## strongize() and emphasize() will recognize the entity to be ## wrapped in tags. ## sub strike { my($w, $char) = @_; my($ret); if ($w eq '_') { if ($char eq '&') { $ret = "_$bs\&_${bs}a_${bs}m_${bs}p_${bs};"; } elsif ($char eq '<') { $ret = "_$bs\&_${bs}l_${bs}t_${bs};"; } elsif ($char eq '>') { $ret = "_$bs\&_${bs}g_${bs}t_${bs};"; } else { warn qq|Unrecognized character, "$char", passed to strike()\n|; } } else { if ($char eq '&') { $ret = "\&$bs\&a${bs}am${bs}mp${bs}p;${bs};"; } elsif ($char eq '<') { $ret = "\&$bs\&l${bs}lt${bs}t;${bs};"; } elsif ($char eq '>') { $ret = "\&$bs\&g${bs}gt${bs}t;${bs};"; } else { warn qq|Unrecognized character, "$char", passed to strike()\n|; } } $ret; } ##--------------------------------------------------------------------------- ## make_xref() converts a manpage crossreference into a hyperlink. ## sub make_xref { my $str = shift; $str =~ s/.\010//go; # Remove overstriking if ($CgiUrl) { my($title,$section,$subsection) = ($str =~ /([\+_\.\w-]+)\((\d)(\w?)\)/); $title =~ s/\+/%2B/g; my($href) = (eval $CgiUrl); qq|$str|; } else { qq|$str|; } } # ##--------------------------------------------------------------------------- ## make_urlref() converts an http crossreference into a hyperlink. ## sub make_urlref { my $str = shift; $str =~ s/.\010//go; # Remove overstriking qq|$str|; } ##--------------------------------------------------------------------------- ## man_k() process a keyword search. The problem we have is there ## is no standard for keyword search results from man. Solaris ## systems have a different enough format to warrent dealing ## with it as a special case. For other cases, we try our best. ## Unfortunately, there are some lines of results that may be ## skipped. ## sub man_k { my($line,$refs,$section,$subsection,$desc,$i, %Sec1, %Sec1sub, %Sec2, %Sec2sub, %Sec3, %Sec3sub, %Sec4, %Sec4sub, %Sec5, %Sec5sub, %Sec6, %Sec6sub, %Sec7, %Sec7sub, %Sec8, %Sec8sub, %Sec9, %Sec9sub, %SecN, %SecNsub, %SecNsec); printhead() unless $Bare; print $OutFH "\n"; while ($line = <$InFH>) { next if $line !~ /\(\d\w?\)\s+-\s/; # check if line can be handled ($refs,$section,$subsection,$desc) = $line =~ /^\s*(.*)\((\d)(\w?)\)\s*-\s*(.*)$/; if ($Solaris) { $refs =~ s/^\s*([\+_\.\w-]+)\s+([\+_\.\w-]+)\s*$/$1/; # } else { $refs =~ s/\s(and|or)\s/,/gi; # Convert and/or to commas $refs =~ s/^[^:\s]:\s*//; # Remove prefixed whatis path } $refs =~ s/\s//g; # Remove all whitespace $refs =~ s/,/, /g; # Put space after comma htmlize(\$desc); # Check for special chars in desc $desc =~ s/^(.)/\U$1/; # Uppercase first letter in desc if ($section eq '1') { $Sec1{$refs} = $desc; $Sec1sub{$refs} = $subsection; } elsif ($section eq '2') { $Sec2{$refs} = $desc; $Sec2sub{$refs} = $subsection; } elsif ($section eq '3') { $Sec3{$refs} = $desc; $Sec3sub{$refs} = $subsection; } elsif ($section eq '4') { $Sec4{$refs} = $desc; $Sec4sub{$refs} = $subsection; } elsif ($section eq '5') { $Sec5{$refs} = $desc; $Sec5sub{$refs} = $subsection; } elsif ($section eq '6') { $Sec6{$refs} = $desc; $Sec6sub{$refs} = $subsection; } elsif ($section eq '7') { $Sec7{$refs} = $desc; $Sec7sub{$refs} = $subsection; } elsif ($section eq '8') { $Sec8{$refs} = $desc; $Sec8sub{$refs} = $subsection; } elsif ($section eq '9') { $Sec9{$refs} = $desc; $Sec9sub{$refs} = $subsection; } else { # Catch all $SecN{$refs} = $desc; $SecNsec{$refs} = $section; $SecNsub{$refs} = $subsection; } } print_mank_sec(\%Sec1, 1, \%Sec1sub); print_mank_sec(\%Sec2, 2, \%Sec2sub); print_mank_sec(\%Sec3, 3, \%Sec3sub); print_mank_sec(\%Sec4, 4, \%Sec4sub); print_mank_sec(\%Sec5, 5, \%Sec5sub); print_mank_sec(\%Sec6, 6, \%Sec6sub); print_mank_sec(\%Sec7, 7, \%Sec7sub); print_mank_sec(\%Sec8, 8, \%Sec8sub); print_mank_sec(\%Sec9, 9, \%Sec9sub); print_mank_sec(\%SecN, 'N', \%SecNsub, \%SecNsec); printtail() unless $Bare; } ##--------------------------------------------------------------------------- ## print_mank_sec() prints out manpage cross-refs of a specific section. ## sub print_mank_sec { my($sec, $sect, $secsub, $secsec) = @_; my(@array, @refs, $href, $item, $title, $subsection, $i, $section, $xref); $section = $sect; @array = sort keys %$sec; if ($#array >= 0) { print $OutFH "

Section $section

\n", "
\n"; foreach $item (@array) { @refs = split(/,/, $item); $section = $secsec->{$item} if $sect eq 'N'; $subsection = $secsub->{$item}; if ($CgiUrl) { ($title = $refs[0]) =~ s/\(\)//g; # watch out for extra ()'s $xref = eval $CgiUrl; } print $OutFH "
\n"; $i = 0; foreach (@refs) { if ($CgiUrl) { print $OutFH qq|$_|; } else { print $OutFH $_; } print $OutFH ", " if $i < $#refs; $i++; } print $OutFH " ($section$subsection)\n", "
\n", $sec->{$item}, "
\n"; } print $OutFH "
\n"; } } ##--------------------------------------------------------------------------- ## sub usage { print $OutFH < outfile Options: -bare : Do not put in HTML, HEAD, BODY tags -belem : HTML Element for overstriked text (def: "B") -botm <#> : Number of lines for bottom margin (def: 7) -cgiurl : URL for linking to other manpages -cgiurlexp : Perl expression URL for linking to other manpages -compress : Compress consective blank lines -headmap : Filename of user section head map file -help : This message -k : Process a keyword search result -leftm <#> : Character width of left margin (def: 0) -nodepage : Do not remove pagination lines -noheads : Turn off section head detection -pgsize <#> : Number of lines in a page (def: 66) -seealso : Link to other manpages only in the SEE ALSO section -solaris : Process keyword search result in Solaris format -sun : Section heads are not overstriked in input -title : Title of manpage (def: Not defined) -topm <#> : Number of lines for top margin (def: 7) -uelem : HTML Element for underlined text (def: "I") Description: $PROG takes formatted manpages from STDIN and converts it to HTML sent to STDOUT. The -topm and -botm arguments are the number of lines to the main body text and NOT to the running headers/footers. Version: $VERSION Copyright (C) 1995-1997 Earl Hood, ehood\@medusa.acs.uci.edu $PROG comes with ABSOLUTELY NO WARRANTY and $PROG may be copied only under the terms of the GNU General Public License, which may be found in the $PROG distribution. EndOfUsage exit 0; } i2util-1.6/support/mandoc.cgi000077500000000000000000000057051276605416600162600ustar00rootroot00000000000000#!/usr/bin/perl # # $Id$ # ######################################################################### # # # Copyright (C) 2004 # # Internet2 # # All Rights Reserved # # # ######################################################################### # # File: mandoc.cgi # # Author: Jeff Boote # Internet2 # # Date: Fri Feb 20 16:36:35 MST 2004 # # Description: # # Usage: # # Environment: # # Files: # # Options: use CGI; use CGI::Carp 'fatalsToBrowser'; use File::Basename; $CGI::POST_MAX=1024 * 100; # max 100K posts $CGI::DISABLE_UPLOADS = 1; # no uploads # Add the directory this script lives in to the INC list. unshift(@INC,substr($0,$[,rindex($0,'/',length($0)))."/."); # Turn off buffered I/O. $|=0; ############################################################ # CONFIGURE HERE # use constant InstallAsAction => 1; # True or False # man program (must take a filename as an arg.) my $ManExe = '/usr/bin/man'; my $ManConv = 'man2html'; # args to man2html my @m2hargs = ("-compress", -cgiurl => '${title}.man.html', -botm => 0, -topm => 0, ); # End configure ############################################################ $q = new CGI; # # Determine which "root" # setup ARGV to "require" right into man2html @ARGV = @m2hargs; print $q->header( -type=>'text/html', -expires=>'+1d'); if(InstallAsAction && !defined($ENV{'REDIRECT_URL'})){ print $q->start_html( -title=>'Invalid use of mandoc.cgi', -author=>'boote@internet2.edu'); print $q->h1("Invalid use of mandoc.cgi!"); print $q->p("mandoc.cgi is intended to be used as the target of ", "an Apache \"Action\" directive. It is invalid in other", "context."); print $q->p("Please report problems to", $q->a({href=>'mailto:'.$ENV{'SERVER_ADMIN'}}, $ENV{'SERVER_ADMIN'}), "."); print $q->end_html; exit(1); } if(!-r $q->path_translated){ print $q->start_html( -title=>'Error', -author=>'boote@internet2.edu'); print $q->h1("Unable to read: ",$q->path_info); print $q->p("Unable to read: ",$q->path_info); print $q->p("Please report problems to", $q->a({href=>'mailto:'.$ENV{'SERVER_ADMIN'}}, $ENV{'SERVER_ADMIN'}), "."); print $q->end_html; exit(1); } # chdir so man '.so' includes will work. my $path = dirname($q->path_translated); chdir($path) || die "Can't cd to $path: $!\n"; # use open to fork and exec man(1) open(MAN,"-|") or exec($ManExe, $q->path_translated); # If open succeeded, then we are the read end of the pipe and continue # on to read the output of man(1) and send it out to the client. $Man2Html::InFH = \*MAN; require $ManConv or die("Unable to run man2html: $!"); i2util-1.6/test/000077500000000000000000000000001276605416600135645ustar00rootroot00000000000000i2util-1.6/test/Makefile.am000066400000000000000000000026401276605416600156220ustar00rootroot00000000000000# # $Id$ # ######################################################################### # # # Copyright (C) 2003 # # Internet2 # # All Rights Reserved # # # ######################################################################### # # File: Makefile.am # # Author: Jeff Boote # Internet2 # # Date: Thu Dec 18 14:28:42 MST 2003 # # Description: AM_CPPFLAGS = $(I2UTILINCS) TESTS = sha1test hmac-sha1test pbkdf2test check_PROGRAMS = $(TESTS) sha1test_SOURCES = sha1test.c sha1test_LDADD = $(I2UTILLIBS) $(MALLOCDEBUGLIBS) sha1test_DEPENDENCIES = $(I2UTILLIBDEPS) hmac_sha1test_SOURCES = hmac-sha1test.c hmac_sha1test_LDADD = $(I2UTILLIBS) $(MALLOCDEBUGLIBS) hmac_sha1test_DEPENDENCIES = $(I2UTILLIBDEPS) pbkdf2test_SOURCES = pbkdf2test.c pbkdf2test_LDADD = $(I2UTILLIBS) $(MALLOCDEBUGLIBS) pbkdf2test_DEPENDENCIES = $(I2UTILLIBDEPS) # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # i2util-1.6/test/hmac-sha1test.c000066400000000000000000000144661276605416600164050ustar00rootroot00000000000000/* * ex: set tabstop=4 ai expandtab softtabstop=4 shiftwidth=4: * -*- mode: c-basic-indent: 4; tab-width: 4; indent-tabls-mode: nil -*- * $Id$ */ /************************************************************************ * * * Copyright (C) 2006 * * Internet2 * * All Rights Reserved * * * ************************************************************************/ /* * File: hmac-sha1test.c * * Author: Jeff W. Boote * Internet2 * * Date: Fri Sep 29 18:48:51 MDT 2006 * * Description: * Use the test vectors from RFC2202 to test the * sha-1 implementation: * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #include #include #include #include #include #include int status = 0; static void DoTestCase( int test_case, uint8_t *key, uint32_t keylen, uint8_t *txt, uint32_t txtlen, char *dtxt, char *datadesc) { uint8_t digest[I2SHA1_DIGEST_SIZE]; uint8_t result[I2SHA1_DIGEST_SIZE]; char hd[(2*I2SHA1_DIGEST_SIZE)+1]; char *ststr; I2HMACSha1(key,keylen,txt,txtlen,result); I2HexDecode(dtxt,digest,I2SHA1_DIGEST_SIZE); if(memcmp(digest,result,I2SHA1_DIGEST_SIZE)){ status = 1; ststr = "FAILED"; } else{ ststr = "SUCCESS"; } hd[2*I2SHA1_DIGEST_SIZE] = '\0'; I2HexEncode(hd,result,I2SHA1_DIGEST_SIZE); fprintf(stdout,"%d: %s: hmac-sha1(\"%s\") = %s\n",test_case,ststr, ((datadesc)? datadesc: (char*)txt),hd); return; } int main( int argc __attribute__((unused)), char **argv ) { char *progname; I2LogImmediateAttr ia; I2ErrHandle eh; uint8_t key[80]; uint8_t txt[74]; ia.line_info = (I2NAME | I2MSG); #ifndef NDEBUG ia.line_info |= (I2LINE | I2FILE); #endif ia.fp = stderr; progname = (progname = strrchr(argv[0], '/')) ? progname+1 : *argv; /* * Start an error logging session for reporing errors to the * standard error */ eh = I2ErrOpen(progname, I2ErrLogImmediate, &ia, NULL, NULL); if(! eh) { fprintf(stderr, "%s : Couldn't init error module\n", progname); exit(1); } /* * * 3. Test Cases for HMAC-SHA-1 * */ /* * test_case = 1 * key = 0x0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b * key_len = 20 * data = "Hi There" * data_len = 8 * digest = 0xb617318655057264e28bc0b6fb378c8ef146be00 */ memset(key,0x0b,20); strcpy((char*)txt,"Hi There"); DoTestCase(1,key,20,txt,8, "b617318655057264e28bc0b6fb378c8ef146be00",NULL); /* * test_case = 2 * key = "Jefe" * key_len = 4 * data = "what do ya want for nothing?" * data_len = 28 * digest = 0xeffcdf6ae5eb2fa2d27416d5f184df9c259a7c79 */ strcpy((char*)key,"Jefe"); strcpy((char*)txt,"what do ya want for nothing?"); DoTestCase(2,key,4,txt,28,"effcdf6ae5eb2fa2d27416d5f184df9c259a7c79",NULL); /* * test_case = 3 * key = 0xaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa * key_len = 20 * data = 0xdd repeated 50 times * data_len = 50 * digest = 0x125d7342b9ac11cd91a39af48aa17b4f63f175d3 */ memset(key,0xaa,20); memset(txt,0xdd,50); DoTestCase(3,key,20,txt,50, "125d7342b9ac11cd91a39af48aa17b4f63f175d3","0xdd * 50"); /* * test_case = 4 * key = 0x0102030405060708090a0b0c0d0e0f10111213141516171819 * key_len = 25 * data = 0xcd repeated 50 times * data_len = 50 * digest = 0x4c9007f4026250c6bc8414f9bf50c86c2d7235da */ I2HexDecode("0102030405060708090a0b0c0d0e0f10111213141516171819",key,25); memset(txt,0xcd,50); DoTestCase(4,key,25,txt,50,"4c9007f4026250c6bc8414f9bf50c86c2d7235da", "0xcd * 50"); /* * test_case = 5 * key = 0x0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c * key_len = 20 * data = "Test With Truncation" * data_len = 20 * digest = 0x4c1a03424b55e07fe7f27be1d58bb9324a9a5a04 * digest-96 = 0x4c1a03424b55e07fe7f27be1 */ memset(key,0x0c,20); strcpy((char *)txt,"Test With Truncation"); DoTestCase(5,key,20,txt,20,"4c1a03424b55e07fe7f27be1d58bb9324a9a5a04",NULL); /* * * test_case = 6 * key = 0xaa repeated 80 times * key_len = 80 * data = "Test Using Larger Than Block-Size Key - Hash Key First" * data_len = 54 * digest = 0xaa4ae5e15272d00e95705637ce8a3b55ed402112 */ memset(key,0xaa,80); strcpy((char *)txt,"Test Using Larger Than Block-Size Key - Hash Key First"); DoTestCase(6,key,80,txt,54,"aa4ae5e15272d00e95705637ce8a3b55ed402112",NULL); /* * * test_case = 7 * key = 0xaa repeated 80 times * key_len = 80 * data = "Test Using Larger Than Block-Size Key and Larger * Than One Block-Size Data" * data_len = 73 * digest = 0xe8e99d0f45237d786d6bbaa7965c7808bbff1a91 */ memset(key,0xaa,80); strcpy((char *)txt, "Test Using Larger Than Block-Size Key and Larger Than One Block-Size Data"); DoTestCase(7,key,80,txt,73,"e8e99d0f45237d786d6bbaa7965c7808bbff1a91",NULL); exit(status); } i2util-1.6/test/pbkdf2test.c000066400000000000000000000257661276605416600160200ustar00rootroot00000000000000/* * ex: set tabstop=4 ai expandtab softtabstop=4 shiftwidth=4: * -*- mode: c-basic-indent: 4; tab-width: 4; indent-tabls-mode: nil -*- * $Id$ */ /************************************************************************ * * * Copyright (C) 2006 * * Internet2 * * All Rights Reserved * * * ************************************************************************/ /* * File: pbkdftest.c * * Author: Jeff W. Boote * Internet2 * * Date: Fri Oct 13 19:53:35 MDT 2006 * * Description: * Current test vectors are bogus. I created them - but they will * at least let me test on multiple hosts architectures to make * sure things are consistent. * Test vectors from RFC 3962. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #include #include #include #include #include #include #include #include int status = 0; #ifndef tvalsub #define tvalsub(a, b) \ do { \ (a)->tv_sec -= (b)->tv_sec; \ (a)->tv_usec -= (b)->tv_usec; \ if((a)->tv_usec < 0){ \ (a)->tv_sec--; \ (a)->tv_usec += 1000000; \ } \ } while(0) #endif static void DoTestCase( int test_case, char *pw, uint32_t pwlen, char *salt, uint32_t saltlen, uint32_t count, char *dk, uint32_t dklen, char *pwbuff /* "nice" printable pw */ ) { /* * Largest dk supported currently is 256-bits (32 bytes) */ uint8_t verify[32]; uint8_t result[32]; char hd[(2*32)+1]; char *ststr; struct timeval start; struct timeval end; double exectime; assert(dklen <= 32); memset(&start,0,sizeof(start)); memset(&end,0,sizeof(end)); /* * First test vector */ gettimeofday(&start,NULL); if( (I2pbkdf2(I2HMACSha1,(uint32_t)I2SHA1_DIGEST_SIZE,(uint8_t *)pw,pwlen, (uint8_t *)salt,saltlen,count,dklen,result))){ perror("I2pbkdf2: "); exit(1); } gettimeofday(&end,NULL); tvalsub(&end,&start); exectime = end.tv_usec / 1000000.0; exectime += end.tv_sec; if(dk){ I2HexDecode(dk,verify,dklen); if(memcmp(verify,result,dklen)){ status = 1; ststr = "FAILED"; } else{ ststr = "SUCCESS"; } hd[2*dklen] = '\0'; I2HexEncode(hd,result,dklen); } else{ ststr = "UNCHECKED"; strcpy(hd,"\'N/A\'"); } fprintf(stdout, "%d: %s: pbkdf2(pw=\"%s\",s=\"%s\",c=%d,dklen=%d) = %s (%g sec)\n", test_case,ststr,pwbuff?pwbuff:pw,salt,count,dklen,hd,exectime); return; } int main( int argc __attribute__((unused)), char **argv __attribute__((unused)) ) { int i=1; char saltbuff[8]; char passbuff[65]; /* * Use test vectors from RFC 3962 to test pbkdf2 impl. */ /* * Iteration count = 1 * Pass phrase = "password" * Salt = "ATHENA.MIT.EDUraeburn" * 128-bit PBKDF2 output: * cd ed b5 28 1b b2 f8 01 56 5a 11 22 b2 56 35 15 * 128-bit AES key: * 42 26 3c 6e 89 f4 fc 28 b8 df 68 ee 09 79 9f 15 * 256-bit PBKDF2 output: * cd ed b5 28 1b b2 f8 01 56 5a 11 22 b2 56 35 15 * 0a d1 f7 a0 4b b9 f3 a3 33 ec c0 e2 e1 f7 08 37 * 256-bit AES key: * fe 69 7b 52 bc 0d 3c e1 44 32 ba 03 6a 92 e6 5b * bb 52 28 09 90 a2 fa 27 88 39 98 d7 2a f3 01 61 */ DoTestCase(i++,"password",8,"ATHENA.MIT.EDUraeburn",21,1, "cdedb5281bb2f801565a1122b2563515",16,NULL); DoTestCase(i++,"password",8,"ATHENA.MIT.EDUraeburn",21,1, "cdedb5281bb2f801565a1122b25635150ad1f7a04bb9f3a333ecc0e2e1f70837", 32,NULL); /* * * Iteration count = 2 * Pass phrase = "password" * Salt="ATHENA.MIT.EDUraeburn" * 128-bit PBKDF2 output: * 01 db ee 7f 4a 9e 24 3e 98 8b 62 c7 3c da 93 5d * 128-bit AES key: * c6 51 bf 29 e2 30 0a c2 7f a4 69 d6 93 bd da 13 * 256-bit PBKDF2 output: * 01 db ee 7f 4a 9e 24 3e 98 8b 62 c7 3c da 93 5d * a0 53 78 b9 32 44 ec 8f 48 a9 9e 61 ad 79 9d 86 * 256-bit AES key: * a2 e1 6d 16 b3 60 69 c1 35 d5 e9 d2 e2 5f 89 61 * 02 68 56 18 b9 59 14 b4 67 c6 76 22 22 58 24 ff */ DoTestCase(i++,"password",8,"ATHENA.MIT.EDUraeburn",21,2, "01dbee7f4a9e243e988b62c73cda935d",16,NULL); DoTestCase(i++,"password",8,"ATHENA.MIT.EDUraeburn",21,2, "01dbee7f4a9e243e988b62c73cda935da05378b93244ec8f48a99e61ad799d86", 32,NULL); /* * Iteration count = 1200 * Pass phrase = "password" * Salt = "ATHENA.MIT.EDUraeburn" * 128-bit PBKDF2 output: * 5c 08 eb 61 fd f7 1e 4e 4e c3 cf 6b a1 f5 51 2b * 128-bit AES key: * 4c 01 cd 46 d6 32 d0 1e 6d be 23 0a 01 ed 64 2a * 256-bit PBKDF2 output: * 5c 08 eb 61 fd f7 1e 4e 4e c3 cf 6b a1 f5 51 2b * a7 e5 2d db c5 e5 14 2f 70 8a 31 e2 e6 2b 1e 13 * 256-bit AES key: * 55 a6 ac 74 0a d1 7b 48 46 94 10 51 e1 e8 b0 a7 * 54 8d 93 b0 ab 30 a8 bc 3f f1 62 80 38 2b 8c 2a */ DoTestCase(i++,"password",8,"ATHENA.MIT.EDUraeburn",21,1200, "5c08eb61fdf71e4e4ec3cf6ba1f5512b", 16,NULL); DoTestCase(i++,"password",8,"ATHENA.MIT.EDUraeburn",21,1200, "5c08eb61fdf71e4e4ec3cf6ba1f5512ba7e52ddbc5e5142f708a31e2e62b1e13", 32,NULL); /* * Iteration count = 5 * Pass phrase = "password" * Salt=0x1234567878563412 * 128-bit PBKDF2 output: * d1 da a7 86 15 f2 87 e6 a1 c8 b1 20 d7 06 2a 49 * 128-bit AES key: * e9 b2 3d 52 27 37 47 dd 5c 35 cb 55 be 61 9d 8e * 256-bit PBKDF2 output: * d1 da a7 86 15 f2 87 e6 a1 c8 b1 20 d7 06 2a 49 * 3f 98 d2 03 e6 be 49 a6 ad f4 fa 57 4b 6e 64 ee * 256-bit AES key: * 97 a4 e7 86 be 20 d8 1a 38 2d 5e bc 96 d5 90 9c * ab cd ad c8 7c a4 8f 57 45 04 15 9f 16 c3 6e 31 * (This test is based on values given in [PECMS].) */ I2HexDecode("1234567878563412",(uint8_t *)saltbuff,8); DoTestCase(i++,"password",8,saltbuff,8,5, "d1daa78615f287e6a1c8b120d7062a49", 16,NULL); DoTestCase(i++,"password",8,saltbuff,8,5, "d1daa78615f287e6a1c8b120d7062a493f98d203e6be49a6adf4fa574b6e64ee", 32,NULL); /* * Iteration count = 1200 * Pass phrase = (64 characters) * "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" * Salt="pass phrase equals block size" * 128-bit PBKDF2 output: * 13 9c 30 c0 96 6b c3 2b a5 5f db f2 12 53 0a c9 * 128-bit AES key: * 59 d1 bb 78 9a 82 8b 1a a5 4e f9 c2 88 3f 69 ed * 256-bit PBKDF2 output: * 13 9c 30 c0 96 6b c3 2b a5 5f db f2 12 53 0a c9 * c5 ec 59 f1 a4 52 f5 cc 9a d9 40 fe a0 59 8e d1 * 256-bit AES key: * 89 ad ee 36 08 db 8b c7 1f 1b fb fe 45 94 86 b0 * 56 18 b7 0c ba e2 20 92 53 4e 56 c5 53 ba 4b 34 */ memset(passbuff,'X',64); DoTestCase(i++,passbuff,64,"pass phrase equals block size",29,1200, "139c30c0966bc32ba55fdbf212530ac9", 16,"\'X\' (64 times)"); DoTestCase(i++,passbuff,64,"pass phrase equals block size",29,1200, "139c30c0966bc32ba55fdbf212530ac9c5ec59f1a452f5cc9ad940fea0598ed1", 32,"\'X\' (64 times)"); /* * Iteration count = 1200 * Pass phrase = (65 characters) * "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" * Salt = "pass phrase exceeds block size" * 128-bit PBKDF2 output: * 9c ca d6 d4 68 77 0c d5 1b 10 e6 a6 87 21 be 61 * 128-bit AES key: * cb 80 05 dc 5f 90 17 9a 7f 02 10 4c 00 18 75 1d * 256-bit PBKDF2 output: * 9c ca d6 d4 68 77 0c d5 1b 10 e6 a6 87 21 be 61 * 1a 8b 4d 28 26 01 db 3b 36 be 92 46 91 5e c8 2a * 256-bit AES key: * d7 8c 5c 9c b8 72 a8 c9 da d4 69 7f 0b b5 b2 d2 * 14 96 c8 2b eb 2c ae da 21 12 fc ee a0 57 40 1b */ memset(passbuff,'X',65); DoTestCase(i++,passbuff,65,"pass phrase exceeds block size",30,1200, "9ccad6d468770cd51b10e6a68721be61", 16,"\'X\' (65 times)"); DoTestCase(i++,passbuff,65,"pass phrase exceeds block size",30,1200, "9ccad6d468770cd51b10e6a68721be611a8b4d282601db3b36be9246915ec82a", 32,"\'X\' (65 times)"); /* * Iteration count = 50 * Pass phrase = g-clef (0xf09d849e) * Salt = "EXAMPLE.COMpianist" * 128-bit PBKDF2 output: * 6b 9c f2 6d 45 45 5a 43 a5 b8 bb 27 6a 40 3b 39 * 128-bit AES key: * f1 49 c1 f2 e1 54 a7 34 52 d4 3e 7f e6 2a 56 e5 * 256-bit PBKDF2 output: * 6b 9c f2 6d 45 45 5a 43 a5 b8 bb 27 6a 40 3b 39 * e7 fe 37 a0 c4 1e 02 c2 81 ff 30 69 e1 e9 4f 52 * 256-bit AES key: * 4b 6d 98 39 f8 44 06 df 1f 09 cc 16 6d b4 b8 3c * 57 18 48 b7 84 a3 d6 bd c3 46 58 9a 3e 39 3f 9e */ I2HexDecode("f09d849e",(uint8_t *)passbuff,4); passbuff[4]='\0'; DoTestCase(i++,passbuff,4,"EXAMPLE.COMpianist",18,50, "6b9cf26d45455a43a5b8bb276a403b39", 16,"g-clef (0xf09d849e)"); DoTestCase(i++,passbuff,4,"EXAMPLE.COMpianist",18,50, "6b9cf26d45455a43a5b8bb276a403b39e7fe37a0c41e02c281ff3069e1e94f52", 32,"g-clef (0xf09d849e)"); /* * Remaining test cases are not part of RFC 3962. They were put in place * simply to test how long it would take for some larger values * of count. */ /* * Iteration count = 2048 * Pass phrase = "how long?" * Salt = "garlic" */ memset(passbuff,'X',64); DoTestCase(i++,passbuff,64,"pass phrase equals block size",29,2048, NULL, 16,"\'X\' (64 times)"); exit(status); } i2util-1.6/test/sha1test.c000066400000000000000000000106201276605416600154630ustar00rootroot00000000000000/* * ex: set tabstop=4 ai expandtab softtabstop=4 shiftwidth=4: * -*- mode: c-basic-indent: 4; tab-width: 4; indent-tabls-mode: nil -*- * $Id$ */ /************************************************************************ * * * Copyright (C) 2006 * * Internet2 * * All Rights Reserved * * * ************************************************************************/ /* * File: sha1test.c * * Author: Jeff W. Boote * Internet2 * * Date: Fri Sep 29 18:48:51 MDT 2006 * * Description: * Use the test vectors from fips 180-1 to test the * sha-1 implementation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #include #include #include #include #include #include int main( int argc __attribute__((unused)), char **argv ) { char *progname; I2LogImmediateAttr ia; I2ErrHandle eh; int status = 0; char *in[] = {"abc", "abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq", NULL, NULL}; char *out[] = {"A9993E364706816ABA3E25717850C26C9CD0D89D", "84983E441C3BD26EBAAE4AA1F95129E5E54670F1", "34AA973CD4C4DAA4F61EEB2BDBAD27316534016F", NULL}; char *ststr; uint8_t digest[I2SHA1_DIGEST_SIZE]; uint8_t result[I2SHA1_DIGEST_SIZE]; char hd[(2*I2SHA1_DIGEST_SIZE)+1]; ia.line_info = (I2NAME | I2MSG); #ifndef NDEBUG ia.line_info |= (I2LINE | I2FILE); #endif ia.fp = stderr; progname = (progname = strrchr(argv[0], '/')) ? progname+1 : *argv; /* * Start an error logging session for reporing errors to the * standard error */ eh = I2ErrOpen(progname, I2ErrLogImmediate, &ia, NULL, NULL); if(! eh) { fprintf(stderr, "%s : Couldn't init error module\n", progname); exit(1); } /* * First test vector */ I2Sha1((uint8_t*)in[0],strlen(in[0]),result); I2HexDecode(out[0],digest,I2SHA1_DIGEST_SIZE); if(memcmp(digest,result,I2SHA1_DIGEST_SIZE)){ status = 1; ststr = "FAILED"; } else{ ststr = "SUCCESS"; } hd[2*I2SHA1_DIGEST_SIZE] = '\0'; I2HexEncode(hd,result,I2SHA1_DIGEST_SIZE); fprintf(stdout,"%s: sha1(\"%s\") = %s\n",ststr,in[0],hd); /* * Second test vector */ I2Sha1((uint8_t*)in[1],strlen(in[1]),result); I2HexDecode(out[1],digest,I2SHA1_DIGEST_SIZE); if(memcmp(digest,result,I2SHA1_DIGEST_SIZE)){ status = 1; ststr = "FAILED"; } else{ ststr = "SUCCESS"; } hd[2*I2SHA1_DIGEST_SIZE] = '\0'; I2HexEncode(hd,result,I2SHA1_DIGEST_SIZE); fprintf(stdout,"%s: sha1(\"%s\") = %s\n",ststr,in[1],hd); /* * Third test vector * (1,000,000 "a"'s) */ in[2] = malloc(1000000*sizeof(char)); if(!in[2]){ perror("Unable to malloc 1000000 char's for 3rd test vector"); exit(1); } memset(in[2],'a',1000000); I2Sha1((uint8_t*)in[2],1000000,result); I2HexDecode(out[2],digest,I2SHA1_DIGEST_SIZE); if(memcmp(digest,result,I2SHA1_DIGEST_SIZE)){ status = 1; ststr = "FAILED"; } else{ ststr = "SUCCESS"; } hd[2*I2SHA1_DIGEST_SIZE] = '\0'; I2HexEncode(hd,result,I2SHA1_DIGEST_SIZE); fprintf(stdout,"%s: sha1(\"%s\") = %s\n",ststr,"1000000 a\'s",hd); exit(status); }