diff options
author | Aaron M. Ucko <ucko@debian.org> | 2005-10-29 16:25:15 +0000 |
---|---|---|
committer | Aaron M. Ucko <ucko@debian.org> | 2005-10-29 16:25:15 +0000 |
commit | dcaa9ec463eeeee591b9fa68d771984107b76834 (patch) | |
tree | 96d37c77fd095fd74d808871bb676587a836203d /network | |
parent | d76c50353c9e74f6915ca6352afb29ae53d45777 (diff) |
Load /tmp/.../ncbi-tools6-6.1.20050828 into
branches/upstream/current.
Diffstat (limited to 'network')
77 files changed, 167 insertions, 23433 deletions
diff --git a/network/blast3/client/netblap3.c b/network/blast3/client/netblap3.c index 0748f819..2179f439 100644 --- a/network/blast3/client/netblap3.c +++ b/network/blast3/client/netblap3.c @@ -34,6 +34,12 @@ * * RCS Modification History: * $Log: netblap3.c,v $ +* Revision 1.107 2005/08/04 15:54:41 kans +* local variable defined before ASSERT in s_addTweakToOtherOptions for strict C compliance (CodeWarrior Carbon complained) +* +* Revision 1.106 2005/08/04 15:40:33 madden +* Add static functions s_parseOtherOptions and s_addTweakToOtherOptions to allow composition-based info to be passed +* * Revision 1.105 2004/01/27 20:53:12 dondosha * Value of no_traceback megablast option is now Uint1 instead of Boolean * @@ -728,6 +734,34 @@ BlastFini (BlastNet3Hptr bl3hptr) return retval; } +void static +s_addTweakToOtherOptions(Uint1 tweak_parameters, BlastParametersPtr parameters) +{ + const Int4 kBuffSize=128; + ASSERT(parameters); + + if (tweak_parameters > 0) + { + char* other_options = NULL; + Int4 len = 0; + if (parameters->other_options && StringLen(parameters->other_options) > 0) + { + len = 1 + StringLen(parameters->other_options); + other_options = MemNew((len+kBuffSize)*sizeof(char)); + StrCpy(other_options, parameters->other_options); + MemFree(parameters->other_options); + } + else + { + other_options = MemNew((kBuffSize)*sizeof(char)); + } + sprintf(other_options+len, "t=%ld", (long) tweak_parameters); + parameters->other_options = other_options; + } + + return; +} + NLM_EXTERN BlastParametersPtr LIBCALL BlastOptionsToParameters (BLAST_OptionsBlkPtr options) @@ -799,7 +833,11 @@ BlastOptionsToParameters (BLAST_OptionsBlkPtr options) parameters->required_end = options->required_end; parameters->is_rps_blast = options->is_rps_blast; + parameters->tweak_parameters = options->tweak_parameters; + if (options->tweak_parameters > 0) + s_addTweakToOtherOptions(options->tweak_parameters, parameters); + parameters->smith_waterman = options->smith_waterman; parameters->is_megablast = options->is_megablast_search; parameters->query_lcase_mask = (ValNodePtr) options->query_lcase_mask; @@ -1420,7 +1458,6 @@ SeedBioseq (BlastNet3BlockPtr blnet3blkptr, ValNodePtr *error_returns, BlastSearchPtr search = NULL; BlastResponsePtr response = NULL; ValNodePtr node, vnp = NULL; - SeqAlignPtr seqalign=NULL; /* Uint1 err_id; */ BlastPhialignPtr bphp = NULL; @@ -1489,7 +1526,6 @@ SeedBioseqNetCore(BlastNet3Hptr bl3hp, BioseqPtr bsp, CharPtr program, Boolean options_allocated = FALSE; CharPtr params_buffer; Int2 status; - SeqAlignPtr seqalign = NULL; TxDfDbInfoPtr txdbinfo; ValNodePtr descr, mask; @@ -2659,6 +2695,33 @@ TraditionalBlastReportLocExtra(SeqLocPtr slp, BLAST_OptionsBlkPtr options, Blast return TraditionalBlastReportEngine(slp, NULL, options, bl3hp, program, database, html, outfp, verbose, print_options, align_options, number_of_descriptions, number_of_alignments, number_of_hits, overview); } +/* Fills in other options based upon "other_options" string in BlastParametersPtr. */ + +static void +s_parseOtherOptions(char* other_options, BLAST_OptionsBlkPtr options) +{ + + char* opt_str = "t"; + char* *values; + Int4 index; + + ASSERT(options); + + if (other_options == NULL) + return; + + if(!BlastParseInputString(other_options, opt_str, &values, NULL)) + return; + + index = BlastGetLetterIndex(opt_str, 't'); + + if(values[index] != NULL) { + options->tweak_parameters = atoi(values[index]); + } + + return; +} + /* Converst the BlastParametersPtr (used by network service) to @@ -2766,7 +2829,10 @@ parametersToOptions (BlastParametersPtr parameters, CharPtr program, ValNodePtr options->required_end = parameters->required_end; options->is_rps_blast = parameters->is_rps_blast; - options->tweak_parameters = parameters->tweak_parameters; + /* this value may be overwritten by the call to s_parseOtherOptions + if different information is contained there. */ + options->tweak_parameters = parameters->tweak_parameters; + options->smith_waterman = parameters->smith_waterman; options->is_megablast_search = parameters->is_megablast; options->query_lcase_mask = @@ -2785,6 +2851,9 @@ parametersToOptions (BlastParametersPtr parameters, CharPtr program, ValNodePtr (options->gap_open > 0 || options->gap_extend > 0)) { options->mb_use_dyn_prog = TRUE; } + + /* Parses out tweak_parameters. */ + s_parseOtherOptions(parameters->other_options, options); } if ((status = BLASTOptionValidateEx(options, program, error_return))) { diff --git a/network/entrez/client/netentr.c b/network/entrez/client/netentr.c index b5a9a019..e3fc08e0 100644 --- a/network/entrez/client/netentr.c +++ b/network/entrez/client/netentr.c @@ -29,7 +29,7 @@ * * Version Creation Date: 06/02/92 * -* $Revision: 6.7 $ +* $Revision: 6.8 $ * * File Description: * entrez index access library for Network Entrez @@ -51,6 +51,9 @@ * * RCS Modification History: * $Log: netentr.c,v $ +* Revision 6.8 2005/07/25 18:06:48 lavr +* Remove deprecated ni_ API references +* * Revision 6.7 1999/05/28 15:39:31 kans * missing # on else and endif * @@ -260,7 +263,7 @@ extern EntrezInfoPtr LIBCALL EntrezInfoAsnRead PROTO((AsnIoPtr aip, AsnTypePtr a EntrezInfoPtr NetEntrezGetInfo PROTO((void)); static void RemoveNonPrintingCharacters(CharPtr str); -extern void MsgSetReadTimeout PROTO((MHandPtr mh, int t)); +/*extern void MsgSetReadTimeout PROTO((MHandPtr mh, int t));*/ static void NEAR FindAsnType (AsnTypePtr PNTR atp, AsnModulePtr amp, CharPtr str) @@ -752,9 +755,9 @@ NLM_EXTERN ByteStorePtr CDECL NetEntTLEvalX (ValNodePtr elst) ErrGetOpts(&erract, NULL); ErrSetOpts(ERR_CONTINUE, 0); ErrFetch(&err); - MsgSetReadTimeout(Entrez_ni, 1200); + /*MsgSetReadTimeout(Entrez_ni, 1200);*/ retval = s_NetEntTLEvalX(elst); - MsgSetReadTimeout(Entrez_ni, 60); + /*MsgSetReadTimeout(Entrez_ni, 60);*/ ErrSetOpts(erract, 0); if (! ErrFetch(&err)) return retval; /* success */ @@ -789,10 +792,10 @@ static Int4 NEAR s_NetEntTLEvalCount (ValNodePtr elst) AsnEndStruct(Entrez_asnout, ENTREZ_REQUEST_eval_count); AsnIoReset(Entrez_asnout); - MsgSetReadTimeout(Entrez_ni, 1200); + /*MsgSetReadTimeout(Entrez_ni, 1200);*. if ((atp = NetEntReadAsn()) == NULL) return 0; - MsgSetReadTimeout(Entrez_ni, 60); + /*MsgSetReadTimeout(Entrez_ni, 60);*/ if (atp == ENTREZ_BACK_eval_count) { @@ -2675,10 +2678,10 @@ NetEntBlastBioseq(BioseqPtr bsp, DocType db, CharPtr program, CharPtr database, ErrGetOpts(&erract, NULL); ErrSetOpts(ERR_CONTINUE, 0); ErrFetch(&err); - MsgSetReadTimeout(Entrez_ni, 1200); + /*MsgSetReadTimeout(Entrez_ni, 1200);*/ noMoreTries = FALSE; lsp = s_NetEntBlastBioseq(bsp, db, program, database, options, usemonitor, &noMoreTries); - MsgSetReadTimeout(Entrez_ni, 60); + /*MsgSetReadTimeout(Entrez_ni, 60);*/ ErrSetOpts(erract, 0); if (noMoreTries || ! ErrFetch(&err)) return lsp; @@ -2738,7 +2741,7 @@ NLM_EXTERN Int4 LIBCALL NetEntClusterAnalysis(DocUidPtr uids, Int4 numuids, DocF Int4 retval; short erract; ErrDesc err; - extern void MsgSetReadTimeout PROTO((MHandPtr mh, int t)); + /*extern void MsgSetReadTimeout PROTO((MHandPtr mh, int t));*/ for (i = 0; i < ENT_SERV_RETRIES; i++) { @@ -2751,9 +2754,9 @@ NLM_EXTERN Int4 LIBCALL NetEntClusterAnalysis(DocUidPtr uids, Int4 numuids, DocF ErrGetOpts(&erract, NULL); ErrSetOpts(ERR_CONTINUE, 0); ErrFetch(&err); - MsgSetReadTimeout(Entrez_ni, 1200); + /*MsgSetReadTimeout(Entrez_ni, 1200);*/ retval = s_NetEntClusterAnalysis(uids, numuids, fld, minCluster, maxCluster, maxTerms, terms, termTotals); - MsgSetReadTimeout(Entrez_ni, 60); + /*MsgSetReadTimeout(Entrez_ni, 60);*/ ErrSetOpts(erract, 0); if (! ErrFetch(&err)) { diff --git a/network/entrez/client/netlib.c b/network/entrez/client/netlib.c index d4224e6c..b7898570 100644 --- a/network/entrez/client/netlib.c +++ b/network/entrez/client/netlib.c @@ -29,7 +29,7 @@ * * Version Creation Date: 06/05/92 * -* $Revision: 6.1 $ +* $Revision: 6.2 $ * * File Description: * miscellaneous library for network Entrez @@ -44,6 +44,9 @@ * * RCS Modification History: * $Log: netlib.c,v $ +* Revision 6.2 2005/07/25 18:06:48 lavr +* Remove deprecated ni_ API references +* * Revision 6.1 1998/08/24 21:00:51 kans * fixed -v -fd warnings * @@ -543,6 +546,7 @@ NLM_EXTERN void GetClientInfo (CharPtr buf) StrCat(buf, "\n Entrez service currently connected to "); StrCat(buf, lastEntrezServ->hostname); StrCat(buf, " server\n"); + /* if (NI_EncrAvailable()) { if (lastEntrezServ->encryption != NULL) @@ -552,6 +556,7 @@ NLM_EXTERN void GetClientInfo (CharPtr buf) StrCat (buf, " Encryption available, but not in use\n"); } } + */ statsPtr = &buf[StringLen(buf)]; DumpNetStats(SUBSYS_CLI_ENTREZ, appendStats); } diff --git a/network/nsclilib/ncbinet.h b/network/nsclilib/ncbinet.h index 9c1a23ce..2552fbfd 100644 --- a/network/nsclilib/ncbinet.h +++ b/network/nsclilib/ncbinet.h @@ -1,4 +1,4 @@ -/* $Id: ncbinet.h,v 6.6 2001/04/05 04:02:21 juran Exp $ +/* $Id: ncbinet.h,v 6.7 2005/07/25 18:06:48 lavr Exp $ * =========================================================================== * * PUBLIC DOMAIN NOTICE @@ -29,7 +29,7 @@ * * Version Creation Date: 1/1/92 * -* $Revision: 6.6 $ +* $Revision: 6.7 $ * * File Description: * @@ -37,6 +37,9 @@ * Modifications: * -------------------------------------------------------------------------- * $Log: ncbinet.h,v $ +* Revision 6.7 2005/07/25 18:06:48 lavr +* Remove deprecated ni_ API references +* * Revision 6.6 2001/04/05 04:02:21 juran * Removed MacTCP-enabling preprocessor hacks. * @@ -78,7 +81,6 @@ #include "ni_types.h" /* include <ncbi.h> */ #include "ni_defin.h" #include "ni_error.h" -#include "ni_encr.h" #include <ni_lib_.h> #ifdef NETP_INET_MACTCP diff --git a/network/nsclilib/ni_disp.c b/network/nsclilib/ni_disp.c deleted file mode 100644 index 4871a619..00000000 --- a/network/nsclilib/ni_disp.c +++ /dev/null @@ -1,3905 +0,0 @@ -/* -* =========================================================================== -* -* PUBLIC DOMAIN NOTICE -* National Center for Biotechnology Information -* -* This software/database is a "United States Government Work" under the -* terms of the United States Copyright Act. It was written as part of -* the author's official duties as a United States Government employee and -* thus cannot be copyrighted. This software/database is freely available -* to the public for use. The National Library of Medicine and the U.S. -* Government have not placed any restriction on its use or reproduction. -* -* Although all reasonable efforts have been taken to ensure the accuracy -* and reliability of the software and data, the NLM and the U.S. -* Government do not and cannot warrant the performance or results that -* may be obtained by using this software or data. The NLM and the U.S. -* Government disclaim all warranties, express or implied, including -* warranties of performance, merchantability or fitness for any particular -* purpose. -* -* Please cite the author in any work or product based on this material. -* -* =========================================================================== -* -* File Name: ni_disp.c (originally -- "ni_lib.c") -* -* Author: Beatty, Gish, Epstein, Vakatov -* -* Version Creation Date: 1/1/92 -* -* $Revision: 4.15 $ -* -* File Description: -* This file is a library of functions to be used by server application -* and client software, using the NCBI "network services" paradigm. -* It was slightly redesigned in order to fit the new "multiple NCBI -* protocols" paradigm -* -* -* Modifications: -* -------------------------------------------------------------------------- -* Date Name Description of modification -* ------- ---------- ----------------------------------------------------- -* 4/27/92 Epstein Added extensive in-line commentary, and removed all tabs. -* 5/11/92 Epstein Removed unused function NI_SVCRequestGet(); added support -* for the connection ID to be written to a CONID file each -* time that the value of conid is updated; in practice, -* only dispatcher will update a CONID file. -* 6/22/92 Epstein For UNIX signals, catch the SIGPIPE error which can -* occur when writing to a socket which is no longer -* connected. -* 7/06/92 Epstein Changed sokselectw() to examine the SO_ERROR socket option -* after select()-ing a socket to which we were attempting a -* connection. This eliminates "false connects", i.e., -* unsuccessful connection attempts which look successful -* because the select() call returns 1. -* 7/14/92 Epstein Changed NI_SetDispatcher() and NI_InitServices() to use -* a configurable timeout parameter, and in the process -* also changed sokselectw() to have a timeout parameter, -* 1/21/93 Epstein Add dispatcher-list support, and add dispatcher-list -* parameter to NI_InitServices(). -* 2/12/93 Epstein Use new boolean parameter to MsgMakeHandle(), indicating -* whether or not it should create a socket. This was -* an attempted fix for a Mac problem ... it later -* turned out to be an incorrect problem-fix, but also -* does no harm. -* 2/24/93 Epstein Fix long-standing Mac bug, by correctly destroying -* services handle and hence closing an open socket. -* 3/02/93 Epstein Add functions to write dispatcher-configuration info -* to a config file. This provides a standardized -* mechanisms which applications may use for net services -* configuration. Also added platform functions, so -* that dispatcher/server complex can know what type -* of platform a client is running on, assuming that the -* client is telling the truth. -* 3/03/93 Epstein Cleanup variable initialization. -* 3/08/93 Epstein Improve error messages & cleanup to NI_InitServices, -* include reason in login failure message, and add -* client platform to service request. -* 3/09/93 Epstein Add HaltServices() function to simplify cleanup. -* 3/22/93 Epstein Fix typecast for getsockopt(), and, more importantly, -* remember to return the computed value in NI_GetPlatform. -* 3/23/93 Epstein Support VMS/TGV, and add NETP_INET_ prefixes to -* conditional-compilation symbols. -* 3/24/93 Epstein Clear the caller's pointer in NI_SetDispConfig(). -* 3/31/93 Epstein Add dispatcher pointer as context for all network -* services operations; this allows an application -* to use more than one dispatcher at a time, at the -* expense of slightly greater complexity. Also add -* a "Generic Init" function, which can be used by -* an application to obtain network-services in a -* simplified, standardized manner. -* 3/31/93 Epstein Move debug and module variables to their correct home. -* 4/02/93 Epstein Add WinSock support. -* 4/12/93 Schuler Add MAKEWORD macro. -* 4/21/93 Schuler Removed function prototypes for NI_AsnRead, NI_AsnWrite -* 5/07/93 Epstein Move WSAStartup() code to a better place, add workaround -* for connection attempt on a non-blocking socket in PC-NFS -* 4.0, add more platform definitions. -* 5/24/93 Epstein Add separate error codes for TCP/IP initialization -* failure and inability to resolve local host name. -* 5/25/93 Epstein Add configuration-file workaround for PC-NFS 5.0 bug, -* where NIS sometimes fails on the PC's own host name. -* 5/27/93 Epstein Incorporate pragmatic "Gestalt" code for Vibrant -* scrolling workaround for WinSock under Windows 3.1, -* add add SOCK_INDEX_ERRNO macro to workaround another -* WinSock pecularity. -* 6/02/93 Schuler Change "Handle" to "MonitorPtr" for Monitors. -* 6/07/93 Epstein Added generic timer functions. -* Also add missing revision history, derived from -* RCS file. -* 6/09/93 Epstein Added activity hook to report network activity back -* to an application. -* 6/14/93 Epstein Changed "Generic" logic to cause UNIX/VMS loginname -* to override loginname, rather than vice versa. Also -* setup DispatchConnect() logic to set client's declared -* IP address to 0.0.0.0, rather than causing an error, -* in the case where the client cannot resolve its own -* host name. In this case, the dispatcher will set its -* own opinion of the client address based upon -* getpeername(). -* 6/15/93 Epstein Eliminate "Gestalt" code for Vibrant scrolling -* workaround for WinSock under Windows 3.1, since the -* solution for this problem does not require its use. -* 6/25/93 Epstein Fix activity-hook action for service disconnection (had -* erroneously announced dispatcher-disconnection), and -* add logic to try to avoid getservbyname() by looking -* up dispatcher port # and (loport,hiport) in NCBI -* configuration file instead of in NIS. As a last resort, -* look up the name in NIS if the entry in the NCBI -* config. file is non-numeric. Also, change the client -* port lookup mechanism for Macintoshes to add a configured -* "delta" value to the low port number. This results in -* allowing several Network Services applications to run -* concurrently on a Mac without port conflicts. -* 7/08/93 Epstein Fix list traversal error in NI_ProcessTimers() -* 7/08/93 Epstein Added a counter as a failsafe mechanism in -* NI_ProcessTimers(), since previous fix attempt failed. -* 7/09/93 Epstein Changed a few #define names to avoid Alpha compilation -* warnings, and added reference count to dispatcher data -* structure. -* 8/09/93 Epstein Improve diagnostics when a listen() call fails -* 8/23/93 Epstein Add currentDisp variable so that the currently-attached -* dispatcher is used when the parameter to NI_SetDispatcher -* is NULL. -* 8/31/93 Epstein Fix host vs. network order when comparing port numbers. -* 9/08/93 Epstein Added new stackDescription variable, to be able to -* report to the dispatcher the identity of the vendor -* of the WinSock stack -* 9/09/93 Epstein Fix use of currentDisp variable to correctly compare -* new dispatcher request again current dispatcher. -*11/24/93 Epstein Added code to support standalone servers and clients -* which communicate with standalone servers or "service -* brokers", which listen on a specific port (to be -* augmented later). -*11/30/93 Epstein Made standalone server code UNIX-only, to avoid -* possible compilation errors on other platforms. However, -* it should be possible in principle to run and test a -* standalone server on a non-UNIX host. Also, added -* limited security to standalone servers. -*12/08/93 Epstein Fixed service connection activity hook, per discussion -* with Kyle Hart. -*01/19/94 Schuler Post error (SEV_INFO) on WinSock initialization -* failure showing WinSock's error code. -*01/28/94 Schuler Replace "NETP_INET_MACTCP" with "NETP_INET_MACTCP" -*01/28/94 Schuler Defined THIS_MODULE and THIS_FILE -*02/14/94 Epstein Add preliminary RSAREF encryption support -*02/22/94 Epstein Add DISP_RECONN_ACTION logic to allow users to breakout -* or quit if unable to contact primary dispatcher. -*02/24/94 Epstein Make use of new NI_DupPubKey function, and insert -* newlines in macros to make editing easier. -*03/03/94 Epstein Reduce memory leaks, suppress non-printing characters -* in winsock.dll. -*04/22/94 Epstein Change error handling to use SEV_ERROR and SEV_WARNING -* (ErrPostEx). Also do a better job of detecting -* inability to connect to dispatcher in DispatchConnect(), -* because under Solaris getsockopt() doesn't correctly -* detect an error. -*04/25/94 Epstein Cosmetic change for error when NACK received from -* Dispatcher. -*05/04/94 Epstein Add logic to allow a mixture of encrypted and -* unencrypted services, determined by ENCRYPTION=FALSE -* fields in the appropriate sections in the config. -* files. -*06/08/94 Epstein Add SOCKS support (probably not correct yet) by -* asking Dispatcher to provide a SVC_PRE_RESPONSE message -* which contains the server's IP address. -*06/10/94 Epstein More SOCKS refinement, plus added tracing for SOCKS -*06/15/94 Epstein Produce working SOCKS version, by changing the protocol -* so that a SOCKSified client uses two service request -* messages; one to learn the IP address of the server -* to which it will be assigned, and the second "real" -* service request after it has bound the 'listen' port -* on the SOCKS daemon. -*07/01/94 Epstein Determine at runtime whether or not to use SOCKS, -* methodology, based upon presence or absence of -* SOCKS_CONF file. -*07/07/94 Epstein Updated commentary. -*09/22/94 Epstein Improved standalone server code by using SO_REUSEADDR -* option, making it possible for identical servers to -* run consecutively without waiting for sockets to -* shutdown. -*12/02/94 Epstein Changed NI_GenericGetService() to have environment -* variables override configuration file for SERVICE_NAME -* and RESOURCE_TYPE. This is mostly just a convenience -* for internal NCBI use, allowing the use of a single -* config. file while using scripts to force the use -* of a different service. -*12/06/94 Epstein Added connectDelay, adminInfo and motd fields. -* The client reports the time which it took to -* establish a connection in their connectDelay field. -* The Dispatcher provides the name of the Network -* administrator and a secondary message-of-the-day in -* the other two fields. -*12/21/94 Epstein Added instrumentation for socket management -*01/11/95 Epstein Change socket instrumentation to suppress some -* errors for WinSock 1.1. -*01/13/95 Epstein Add new GetLAPType() function to report Mac clients' -* TCP/IP implementation ("Ethernet", "PPP", etc.) to -* the Dispatcher. -*03/20/95 Epstein Fix InitServices/EndServices logic to correctly only -* establish a single Dispatcher connection for multiple -* services. -*03/29/95 Epstein Reduce calls to Message() in favor of ErrPostEx(). -*06/02/95 Epstein Fix bindPort() to address host/network byte ordering; -* this should correct a byte-ordering problem on little- -* endian hosts which use SOCKS. -*06/06/95 Epstein For UNIX, try to get the user's name from the USER -* environment variable before inquiring getlogin(); -* this can save CPU time and contention on some systems, -* since access to utmp can be slow. -*06/12/95 Epstein Another byte-ordering fix for SOCKS for the SOCKS -* proxy's port number. -*10/19/95 Epstein Bug fix to accomodate logic correct in Nlm_StringCmp() -* -*11/15/95 Shavirin Added new ability of clients to get direct connection -* to the server. -* Created new function: NI_DirectServiceRequest to connect - to the server directly and to send SVC_REQUEST -* Added new parameter in configuration file - DIRECT_SVC_CON -* This parameter updates new field in dispatcher stucture: -* disp->useOutServ. If this parameter set to FALSE - old style -* communication will be used. TRUE is set for direct -* connection. -* To handle direct connection protocol of the service request -* function was changed. In the case of old style everything -* remained the same (except reconnect switch option - to -* try direct connection if old style failed - currently disabled) -* In the case when disp->useOutServ is set client sends -* service request with field svcreq->want_ticket = TRUE. -* Dispatcher will sent back SVC_REQUEST with the prepared ticket -* or NACK in the case of error. Client will send SVC_REQUEST -* directly to the server and will wait until SVC_RESPONCE or -* NACK will be received from the dispatcher. After SVC_RESPONCE -* received communication transfers to the upper layers. -*01/17/96 Epstein Add protection for DIRECT_SVC_CON mode; this comes into -* play with Mac OpenTransport (OT) -*02/02/96 Epstein Add PROXY_SERV_OVERRIDE GetAppParam() flag for -* DIRECT_SVC_CON mode. This makes it easier for a -* machine behind a firewall to get through the firewall, -* although it assumes a priori knowledge of the IP -* address of the server, and the port numbers on the -* server. -*02/21/96 Epstein Fix brokered-services for little-endian clients -* ========================================================================== -* -* -* RCS Modification History: -* $Log: ni_disp.c,v $ -* Revision 4.15 2003/09/17 15:38:06 rsmith -* include unistd.h for Windows (yes MS-Windows) when compiling with Codewarrior only. -* -* Revision 4.14 2003/09/17 13:38:48 ivanov -* Include unistd.h only for OS_UNIX -* -* Revision 4.13 2003/09/15 18:45:55 rsmith -* add unistd.h include for write and dup. -* -* Revision 4.12 2002/11/06 21:30:08 ucko -* Don't assume MIPS is IRIX, or HPPA is HP/UX; allow Linux too, for both. -* -* Revision 4.11 2002/06/17 15:14:32 ivanov -* Added fix for BeOS platform to sokselectw() -* -* Revision 4.10 2001/09/17 20:09:38 lavr -* Added conditional compilation for config parameter HAVE_SOCKLEN_T -* -* Revision 4.9 2001/04/13 14:59:40 kans -* header for dup on Mac -* -* Revision 4.8 2001/01/04 22:42:50 vakatov -* NI_ServerACK(), NI_ServerNACK() -- to do nothing, always return 0. -* -* Revision 4.7 2000/10/30 18:12:01 beloslyu -* FreeBSD was added -* -* Revision 4.6 1999/07/30 19:11:06 vakatov -* Use "strerror()" instead of "sys_errlist[]" -* -* Revision 4.5 1999/06/07 18:28:26 beloslyu -* NetBSD port -* -* Revision 4.4 1998/03/30 17:50:15 vakatov -* Ingrafted to the main NCBI CVS tree -* -* Revision 4.3 1998/03/30 17:17:03 vakatov -* Renamed from "ni_lib.c" to "ni_disp.c" -* -* Revision 4.2 1998/03/25 17:41:02 vakatov -* Fix for the "gethostname()" proto under Solaris -* -* Revision 6.6 1998/03/17 18:55:42 shavirin -* Rolling back to version 6.3 -* -* Revision 6.3 1997/11/18 21:14:42 epstein -* identify Linux Alpha client -* -* Revision 6.2 1997/10/06 21:21:50 shavirin -* Fixed memory leak and uninitiolized memory read errors -* -* Revision 6.1 1997/09/11 18:08:24 epstein -* add output of uname -a to Unix clients' self-identifying string -* -* Revision 5.5 1997/07/01 19:12:49 vakatov -* [WIN32] DLL'd "netcli.lib" -* -* Revision 5.4 1997/06/17 18:52:17 epstein -* fix numerous memory problems associated with timers -* -* Revision 5.3 1997/04/24 12:53:33 ostell -* fixed typo in call to AsnTypeStringToHex -* -* Revision 5.2 1997/04/24 12:44:36 ostell -* changed calls to AsnTypeStringToHex to match new arguments and returns -* -* Revision 5.1 1996/10/02 18:18:20 epstein -* add function NI_FqdnToIpaddr() to simplify layering of netcnfg.c -* -* Revision 4.15 1996/05/22 15:12:54 epstein -* adopt more reasonable semantics for brokered services: by default, only first service is brokered -* -* Revision 4.14 1996/04/29 15:29:19 epstein -* add disp to NI_HandPtr so that service-handle can encapsulate greater context -* -* Revision 4.13 1996/02/21 15:50:07 epstein -* Fix brokered-services for little-endian clients -* -* Revision 4.12 1996/02/02 14:53:41 epstein -* add PROXY_SERV_OVERRIDE setting for DIRECT_SVC_CON mode -* -* Revision 4.11 1996/01/17 20:33:09 epstein -* Add protection for DIRECT_SVC_CON mode; this comes into play with Mac OpenTransport -* -* Revision 4.10 1995/12/21 19:55:47 epstein -* make socket non-blocking for brokered services -* -* Revision 4.9 1995/11/30 19:58:08 epstein -* make NI_DirectServiceRequest() function static -* -* Revision 4.8 1995/11/29 17:50:24 epstein -* fix byte-ordering for direct-service connection -* -* Revision 4.7 1995/11/28 21:39:06 epstein -* remove unneeded sleep() call from non-UNIX platforms -* -* Revision 4.6 1995/11/28 20:18:41 epstein -* fix leaky-socket problem for non-direct-connection services -* -* Revision 4.5 1995/11/27 20:59:17 epstein -* add client support for direct-connection services -* -* Revision 4.2 95/10/19 20:29:06 epstein -* Bug fix to accomodate logic correct in Nlm_StringCmp() -* -* Revision 4.1 1995/08/01 13:48:33 epstein -* remember to initialize someBrokered -* -* Revision 1.74 1995/07/12 14:53:28 epstein -* Another byte-ordering fix for SOCKS -* -* Revision 1.73 1995/06/06 10:04:52 epstein -* use USER environment variable in lieu of getlogin() -* -* Revision 1.72 95/06/02 16:58:43 epstein -* fix bindPort() using htonl() to correct byte-ordering problem on little-endian clients which use SOCKS -*/ - -#define _NCBINET_LOCAL_VARS -#define THIS_MODULE g_nsclient_module -#define THIS_FILE _this_file -#define __NI_LIB__ -#include "ncbinet.h" -#include "ni_lib.h" -#include "ni_msg.h" -#if defined(OS_MSWIN) && defined(COMP_METRO) -# include <unistd.h> /* for write and dup with MW compiler. */ -#endif - -/* missing prototypes */ -#ifdef __cplusplus -extern "C" { -#endif - -/* patch to old SunOS/Solaris proto(cut&paste from Solaris 2.6 "unistd.h") */ -#if defined(OS_UNIX_SOL) || defined(OS_UNIX_SUN) -#if defined(_XPG4_2) - extern int gethostname(char *, size_t); -#elif defined(__EXTENSIONS__) || \ - (!defined(_POSIX_C_SOURCE) && !defined(_XOPEN_SOURCE)) - extern int gethostname(char *, int); -#endif -#endif - -#ifdef OS_UNIX - extern char *getlogin(void); -#endif - -#ifdef OS_MAC - extern int dup(int fildes); -#endif - -#ifdef __cplusplus -} -#endif - - - -char * g_nsclient_module = "nsclient"; -static char *_this_file = __FILE__; - - -#define ERR_KEY_MISMATCH "The public encryption key received from the dispatcher does\n\ -not match what is on file. There is a slight security risk\n\ -that this key is being presented by a \"spoofer\" rather than\n\ -the real dispatcher. You may wish to contact the NCBI by\n\ -other means to determine whether this new key is valid. Do\n\ -you wish to accept this as the new key and continue?" -#define ERR_KEY_NOPREVKEY "A public encryption key was just received from the dispatcher,\n\ -but no key is currently on file. There is a slight security\n\ -risk that this key is being presented by a \"spoofer\" rather\n\ -than the real dispatcher. You may wish to contact the NCBI by\n\ -other means to determine whether this new key is valid. Do\n\ -you wish to accept this as the new key and continue?" - -#ifdef NETP_INET_NEWT - -#define SIN_ADDR sin_addr.S_un.S_addr -#define H_ADDR_TYPE Uint4Ptr -#else -#define SIN_ADDR sin_addr -#define H_ADDR_TYPE struct in_addr * -#endif - -#ifdef WIN16 -#ifndef MAKEWORD -#define MAKEWORD(a,b) ((WORD)(((BYTE)(a)) | ((WORD)((BYTE)(b))) <<8)) -#endif -#endif - -#define NULL_TIMER 0 - - -typedef struct NI_Timer { - time_t timeout; - NI_TimeoutHook hook; - Pointer hookParam; -} NI_Timer, PNTR NI_TimerPtr; - - -/* GLOBALS */ -static FILE *conid_fp = NULL; /* File pointer for CONID */ -static NodePtr timerHead = NULL; /* list of timers */ -static NI_NetServHook activityHook = NULL; -static NI_DispatcherPtr currentDisp = NULL; -static CharPtr stackDescription = NULL; -static fd_set openfds; - - -#ifdef NETP_INET_WSOCK -static Int4 wsaStartupCount = 0; -#endif - -NILoginPtr NI_MakeMsgLogin PROTO((void)); - -static Int2 s_EndServices(NI_DispatcherPtr disp); -static Int2 SetIdentity PROTO((NI_DispatcherPtr disp, CharPtr user, CharPtr group, CharPtr domain)); -static void HaltServices PROTO((NI_DispatcherPtr disp)); -static NI_HandPtr DispatchConnect PROTO((NI_DispatcherPtr disp, CharPtr host, CharPtr name, int timeout)); -static Uint2 bindPort PROTO((int sok, struct sockaddr_in PNTR sokadr, Int2 loport, Int2 hiport, Uint4 remoteHost)); -static Int2 CopyIdentity PROTO((NI_DispatcherPtr disp, NI_UidPtr uid)); -static NI_HandPtr NI_DirectServiceRequest PROTO((NIMsgPtr imp, NI_HandPtr sconnhp)); - - -int sokselectr PROTO((int fd)); -int sokselectw PROTO((int fd, int timeout)); - -int getAsnError PROTO((char * str)); -void SetConFilePtr PROTO((FILE *fp)); -void CloseConFile PROTO((void)); - - - -/* - * Purpose: Specify which dispatcher a client should try to connect to - * - * Parameters: - * disp Usually NULL, the pointer to a pre-existing Dispatcher - * structure - * host Name of the host (Fully Qualified Domain Name) to use - * svc Name of the "service" to try to use on that host - * dispserialnum Serial number of dispatcher-list. Use -1 if no response - * list is desired, or 0 if the serial number is not known. - * - * - * Description: - * Set up the dispatcher name which should be used, and the - * name of the service on that dispatcher. If other parameters - * have been specified previously, free the memory associated - * with those names. - * - * Note: - * There are useful defaults for "svc". When in doubt, call - * this function with a second arguement of NULL. - */ - -static NI_DispatcherPtr s_SetDispatcher -(NI_DispatcherPtr disp, CharPtr host, CharPtr svc, int timeout, - Int4 dispserialnum, ValNodePtr encryption, Boolean useOutServ) -{ - if (disp == NULL) { - if (currentDisp != NULL && !currentDisp->someBrokered) - { /* use current dispatcher if it matches what the caller wants */ - if ((svc == NULL || - StringCmp(svc, currentDisp->dispServiceName) == 0 ) && - StringCmp(host, currentDisp->dispHostName) == 0) { - return currentDisp; - } - } - - disp = (NI_DispatcherPtr) MemNew(sizeof(NI_Dispatcher)); - if (disp == NULL) - return NULL; - disp->useOutServ = useOutServ; /* value from configfile */ - disp->reqResponse = NULL; - disp->dispHostName = NULL; - disp->dispServiceName = NULL; - disp->dispSerialNo = 0; - disp->localHostAddr[0] = '\0'; - disp->dispHP = NULL; - disp->svcsHP = NULL; - disp->clientPort = 0; - disp->identity = NULL; - disp->dispTimeout = 0; - disp->referenceCount = 0; - disp->someBrokered = FALSE; - disp->brokeredDummy = FALSE; - disp->encryptInfo = encryption; - disp->useSocks = FALSE; -#ifdef SOCKS_CONF - { - FILE *fp; - - if ((fp = FileOpen(SOCKS_CONF, "r")) != NULL) - { - disp->useSocks = TRUE; - FileClose(fp); - } - } -#endif /* SOCKS_CONF */ - } - if (disp->dispHostName != NULL) { - MemFree(disp->dispHostName); - disp->dispHostName = NULL; - } - if (disp->dispServiceName != NULL) { - MemFree(disp->dispServiceName); - disp->dispServiceName = NULL; - } - if (host != NULL) - disp->dispHostName = StringSave(host); - if (svc != NULL) - disp->dispServiceName = StringSave(svc); - - disp->dispSerialNo = dispserialnum; - disp->dispTimeout = timeout; - - return disp; -} /* NI_SetDispatcher */ - - -/* - * Purpose: Try to establish a connection to the dispatcher - * - * Parameters: - * disp A pointer to the dispatcher structure - * user User name to try on the dispatcher - * group Group name to try on the dispatcher - * password Password for this user name - * dip A pointer to the caller's list of dispatchers; this should - * be used by the caller to update its information - * regarding which dispatchers to try in the future - * (if dip == NULL, then no retries will be made to get - * alternate dispatchers) - * - * Returns: - * -1, if something failed (ni_errno indicates the nature of - * the problem) - * 0, if everything was successful - * 1, if we are connected to the dispatcher which we requested, - * but the list of current dispatchers has changed - * 2, if we are connected to a dispatcher, but not the one - * which we requested - * - * - * Description: - * Perform any WinSock and/or SOCKS initialization as necessary - * Connect to the dispatcher - * Set-up a socket for an incoming connection from a server - * application process (non-SOCKS clients only) - * Send a LOGIN message to the dispatcher - * Wait for an ACK or NACK response from the dispatcher (or for - * a timeout to occur) - * If the response was a NACK due to the dispatcher being a - * backup dispatcher, then try the dispatcher which it - * directs us to - */ - -NLM_EXTERN Int2 NI_InitServices(NI_DispatcherPtr disp, CharPtr user, CharPtr group, CharPtr password, NI_DispInfoPtr PNTR dip) -{ - NIMsgPtr mp, imp; - NILoginPtr loginp; - struct sockaddr_in svcsAddr; - struct timeval timeout; - int ready; - NIDispInfoPtr dispinfo = NULL; - Boolean newDispToTry; - Int2 altDispTries = 0; - Int2 retval = 0; - int status; - fd_set readfds; - NI_PubKeyPtr pubKey = NULL; - Boolean failed; -#ifdef NETP_INET_WSOCK - WSADATA wsaData; -#endif /* NETP_INET_WSOCK */ -#if defined(OS_MAC) && defined(NETP_INET_MACTCP) - extern char * GetLAPType(void); - char *lapType = GetLAPType(); -#endif /* OS_MAC && NETP_INET_MACTCP */ - - if (disp == NULL) - { - ni_errno = NIE_MISC; - return -1; - } - - if (disp->referenceCount > 0 && disp->dispHP != NULL) - { /* already connected */ - disp->referenceCount++; - return 0; - } - -#ifdef NETP_INET_WSOCK - status = WSAStartup(MAKEWORD(1,1),&wsaData); - if (status != 0) - ErrPostEx(SEV_ERROR,0,0,"WinSock 1.1 initialization failure, code %d", status-WSABASEERR); - /* Try WinSock 1.1 and 1.0 in that order of preference */ - if (status != 0 && (status = WSAStartup(MAKEWORD(1,0),&wsaData)) != 0) - { - ErrPostEx(SEV_ERROR,0,0,"WinSock 1.0 initialization failure, code %d", status-WSABASEERR); - ni_errno = NIE_TCPINITFAIL; - return -1; - } - TRACE("%s\n", wsaData.szDescription); - if (stackDescription != NULL) - { - MemFree(stackDescription); - } - stackDescription = StringSave(wsaData.szDescription); - for (status = StrLen(stackDescription) - 1; status >= 0; status--) - { - /* convert characters which are incompatible with VisibleString */ - if (stackDescription[status] < ' ' || stackDescription[status] > '~') - stackDescription[status] = '#'; - } - wsaStartupCount++; - -#endif -#if defined(OS_MAC) && defined(NETP_INET_MACTCP) - if (lapType != NULL) - { - stackDescription = StringSave(lapType); - } -#endif /* OS_MAC && NETP_INET_MACTCP */ -#ifdef OS_UNIX - { - FILE *fp; - char buffer[128]; - int status; - - MemSet(&buffer, 0, sizeof(buffer)); - - if ((fp = popen("uname -a","r")) != NULL) - { - FileRead (buffer, 1, sizeof (buffer), fp); - stackDescription = StringSave(buffer); - pclose(fp); - for (status = StrLen(stackDescription) - 1; status >= 0; status--) - { - /* convert characters which are incompatible with VisibleString */ - if (stackDescription[status] < ' ' || stackDescription[status] > '~') - stackDescription[status] = '#'; - } - - } - } -#endif /* OS_UNIX */ -#ifdef NETP_SOCKS - if (disp->useSocks) - { - char path[128]; - - Nlm_ProgramPath(path, sizeof path); - - SOCKSinit(path); - TRACE("Performed SOCKSinit(%s)\n", path); - } -#endif /* NETP_SOCKS */ - - if (disp->dispHostName == NULL) - disp->dispHostName = StringSave(NI_DEFAULT_HOST); - if (disp->dispServiceName == NULL) - disp->dispServiceName = StringSave(NI_DEFAULT_SERVICE); - - do { - newDispToTry = FALSE; - disp->svcsHP = NULL; - if ((disp->dispHP = DispatchConnect(disp, disp->dispHostName, disp->dispServiceName, disp->dispTimeout)) - == NULL) { - NI_DestroyDispInfo(dispinfo); - HaltServices (disp); - ErrPostEx(SEV_WARNING,0,0, "NI_InitServices: Unable to connect to host <%s>, error <%s>", disp->dispHostName, ni_errlist[ni_errno]); - return -1; /* ni_errno remains set */ - } - - if ((disp->svcsHP = MsgMakeHandle(TRUE)) == NULL) { - NI_DestroyDispInfo(dispinfo); - HaltServices (disp); - ErrPostEx (SEV_ERROR, CTX_NCBICORE, CORE_UNKNOWN, "NI_InitServices: Unable to allocate resources to communicate with %s", disp->dispHostName); - return -1; - } - - if (disp->dispTimeout > 0) - { - MsgSetReadTimeout(disp->svcsHP, disp->dispTimeout); - } - - if (!disp->useOutServ) - { /* we need no listening if we are using direct connection */ - if ((disp->clientPort = bindPort(disp->svcsHP->sok, &svcsAddr, disp->loport, disp->hiport, 0)) == 0) { - MsgDestroyHandle(disp->svcsHP); - disp->svcsHP = NULL; - ni_errno = NIE_NOBIND; /* can't bind a free application socket */ - NI_DestroyDispInfo(dispinfo); - HaltServices (disp); - ErrPostEx (SEV_ERROR, CTX_NCBICORE, CORE_UNKNOWN, "NI_InitServices: <%s>", ni_errlist[ni_errno]); - return -1; - } - if ((status = NI_LISTEN(disp->svcsHP->sok, 5)) < 0) { -#ifdef NETP_INET_NEWT - SOCK_ERRNO = ABS(status); -#endif - StringCpy(ni_errtext, strerror(SOCK_INDEX_ERRNO)); - ni_errno = NIE_NOLISTEN; - NI_DestroyDispInfo(dispinfo); - HaltServices (disp); - ErrPostEx (SEV_ERROR, CTX_NCBICORE, CORE_UNKNOWN, "NI_InitServices: <%s> <port %d, errno %d>", ni_errlist[ni_errno], (int) disp->clientPort, (int) SOCK_ERRNO); - return -1; - } - } - - SetIdentity(disp, user, group, NI_DEFAULT_DOMAIN); - - loginp = NI_MakeMsgLogin(); - NI_DestroyUid(loginp->uid); - loginp->uid = NI_MakeUid(); - loginp->seqno = disp->dispHP->seqno++; - loginp->dispserialno = disp->dispSerialNo; - loginp->connectDelay = disp->dispHP->connectDelay; - if (disp->encryptInfo != NULL && NI_EncrAvailable()) - { - loginp->encryptionDesired = TRUE; - if (disp->encryptInfo->data.ptrvalue != NULL) - { - pubKey = (NI_PubKeyPtr) disp->encryptInfo->data.ptrvalue; - loginp->pubKey = (NIPubKeyPtr) NI_PubKeyDup(pubKey); - } - } - CopyIdentity(disp, loginp->uid); - if (password != NULL) - loginp->password = StringSave(password); - mp = MsgBuild(NI_LOGIN, disp->dispHP->conid, (VoidPtr) loginp); - - if (MsgWrite(disp->dispHP, mp, FALSE) < 0) { - if (getAsnError(ni_errtext) == ECONNRESET) - ni_errno = NIE_MAXCONNS; - else - ni_errno = NIE_MSGWRITE; - MsgDestroyHandle(disp->svcsHP); - disp->svcsHP = NULL; - NI_DestroyDispInfo(dispinfo); - HaltServices (disp); - ErrPostEx (SEV_ERROR, CTX_NCBICORE, CORE_UNKNOWN, "NI_InitServices: <%s>", ni_errlist[ni_errno]); - return -1; - } - - /* blocks until ACK or ERROR from dispatcher or TIMEOUT */ - - timeout.tv_sec = (Uint4) NI_TIMEOUT_SECS; - timeout.tv_usec = 0; - FD_ZERO(&readfds); - FD_SET(disp->dispHP->sok, &readfds); - while ((ready = NI_select(FD_SETSIZE, &readfds, NULL, NULL, &timeout)) < 0) { - if (SOCK_ERRNO == EINTR) - ; /* repeat while interrupted */ - else { - MsgDestroyHandle(disp->svcsHP); - disp->svcsHP = NULL; - ni_errno = NIE_SELECT; /* select error */ - NI_DestroyDispInfo(dispinfo); - ErrPostEx (SEV_ERROR, CTX_NCBICORE, CORE_UNKNOWN, "NI_InitServices: <%s>", ni_errlist[ni_errno]); - return -1; - } - } - - if (FD_ISSET(disp->dispHP->sok, &readfds) != 0) { - if ((imp = MsgRead(disp->dispHP, FALSE)) == NULL) { - if (getAsnError(ni_errtext) == ECONNRESET) - ni_errno = NIE_MAXCONNS; - else - ni_errno = NIE_MSGREAD; - - MsgDestroyHandle(disp->svcsHP); - disp->svcsHP = NULL; - NI_DestroyDispInfo(dispinfo); - HaltServices (disp); - ErrPostEx (SEV_ERROR, CTX_NCBICORE, CORE_UNKNOWN, "NI_InitServices: <%s>", ni_errlist[ni_errno]); - return -1; - } - switch (imp->type) { - case NI_ACK: - /************************************************************/ - /* even though we connected successfully to the dispatcher, */ - /* it may have given us more up-to-date information on the */ - /* latest list of dispatchers which should be tried; if so, */ - /* pass the updated list back to the caller */ - /************************************************************/ - if (imp->msun.ack->dispinfo != NULL) { - if (dispinfo != NULL) - { - NI_DestroyDispInfo(dispinfo); - dispinfo = NULL; - } - dispinfo = imp->msun.ack->dispinfo; - imp->msun.ack->dispinfo = NULL; /* for clean free */ - } - if (disp->encryptInfo != NULL && NI_EncrAvailable()) - { - if (dispinfo != NULL && dispinfo->pubKey != NULL) - { - failed = FALSE; - if (pubKey == NULL) - { - failed = (Boolean) - (Message(MSG_YN, ERR_KEY_NOPREVKEY) == ANS_NO); - ni_errno = NIE_NEWKEYNOTACCPT; - } else { - if (! NI_PubKeysEqual(pubKey, (NI_PubKeyPtr) dispinfo->pubKey)) - { - failed = (Boolean) - (Message(MSG_YN, ERR_KEY_MISMATCH) == ANS_NO); - ni_errno = NIE_NEWKEYMISMATCH; - } - } - if (failed) - { - HaltServices(disp); - MsgDestroy(imp); - return -1; - } else { - /* replace the key */ - NI_DestroyPubKey((NIPubKeyPtr) pubKey); - pubKey = (NI_PubKeyPtr) dispinfo->pubKey; - dispinfo->pubKey = NULL; - disp->encryptInfo->data.ptrvalue = (Pointer) pubKey; - } - } - } - if (dispinfo != NULL && dip != NULL) { - if (*dip != NULL) - NI_DestroyDispInfo((NIDispInfoPtr) *dip); - *dip = (NI_DispInfoPtr) dispinfo; - dispinfo = NULL; - retval = 1; - } - else { - NI_DestroyDispInfo(dispinfo); - } - if (imp->msun.ack->motd != NULL && - imp->msun.ack->motd[0] != NULLB) - { - disp->motd = imp->msun.ack->motd; - imp->msun.ack->motd = NULL; /* for clean free */ - } - if (imp->msun.ack->adminInfo != NULL && - imp->msun.ack->adminInfo[0] != NULLB) - { - disp->adminInfo = imp->msun.ack->adminInfo; - imp->msun.ack->adminInfo = NULL; /* for clean free */ - } -#ifdef OS_UNIX - signal(SIGPIPE, SIG_IGN); /* catch socket errors */ -#endif /* OS_UNIX */ - MsgDestroy(imp); - disp->referenceCount++; - if (currentDisp == NULL) - { - currentDisp = disp; - } - return retval; /* only good return */ - - case NI_NACK: - ni_errno = (enum ni_error) imp->msun.nack->code; - if (imp->msun.nack->reason != NULL) - { - StringCpy(ni_errtext, imp->msun.nack->reason); - } else { - ni_errtext[0] = '\0'; - } - if (dispinfo != NULL) - { - NI_DestroyDispInfo(dispinfo); - dispinfo = NULL; - } - dispinfo = imp->msun.nack->dispinfo; - imp->msun.nack->dispinfo = NULL; /* for clean free */ - if (ni_errno == NIE_BACKUPDISP && dispinfo != NULL && - dispinfo->numdispatchers > 0 && dip != NULL && - ++altDispTries < MAX_ALT_DISP_TRIES) - { - MsgDestroy(imp); - HaltServices (disp); - s_SetDispatcher(disp, dispinfo->displist[0], disp->dispServiceName, - disp->dispTimeout, dispinfo->serialno, disp->encryptInfo, - disp->useOutServ); - newDispToTry = TRUE; - retval = 2; - break; - } - MsgDestroy(imp); - MsgDestroyHandle(disp->svcsHP); - disp->svcsHP = NULL; - NI_DestroyDispInfo(dispinfo); - HaltServices (disp); - ErrPostEx (SEV_ERROR, CTX_NCBICORE, CORE_UNKNOWN, "NI_InitServices: <%s>\n%s", ni_errlist[ni_errno], ni_errtext); - return -1; - - default: - MsgDestroy(imp); - ni_errno = NIE_MSGUNK; - MsgDestroyHandle(disp->svcsHP); - disp->svcsHP = NULL; - NI_DestroyDispInfo(dispinfo); - HaltServices (disp); - ErrPostEx (SEV_ERROR, CTX_NCBICORE, CORE_UNKNOWN, "NI_InitServices: <%s>", ni_errlist[ni_errno]); - return -1; - } - } - } while (newDispToTry); - - MsgDestroyHandle(disp->svcsHP); - disp->svcsHP = NULL; - ni_errno = NIE_LOGTIMEOUT; /* TIMEOUT */ - NI_DestroyDispInfo(dispinfo); - HaltServices (disp); - ErrPostEx (SEV_ERROR, CTX_NCBICORE, CORE_UNKNOWN, "NI_InitServices: <%s>", ni_errlist[ni_errno]); - return -1; -} /* NI_InitServices */ - - -/* - * Purpose: Init network services based on information in config file - * - * Parameters: - * configFile Name of NCBI-style configuration file. If NULL, defaults - * to "NCBI" - * configSection Section with NCBI-style configuration file. If NULL, - * defaults to "NET_SERV" - * showMonitor Boolean; if TRUE, display a monitor while re-trying - * for an alternate dispatcher - * lastDispatcher Pointer to where this function should store the name - * of the dispatcher which was actually used (may be NULL - * if the caller does not care about this value) - * lastDispLen Maximum length of lastDispatcher - * - * Returns: - * NULL, if unable to contact dispatcher - * a pointer to the Dispatcher structure, otherwise - * - * - * Description: - * Extracts a dispatcher name and a user name from a configuration - * file. If necessary, tries other dispatchers, in order, as - * listed in configuration file. Also sets up encryption, if - * the client is encryption-capable and encryption is requested - * in the configuration file. - * - * - * Note: - * This function is provided as a convenience to developers who - * wish to use Network Services. Use of this function is not - * integral to the use of Network Services ... it is merely a - * convenience. - */ - -static NI_DispatcherPtr s_GenericInit -(CharPtr configFile, CharPtr configSection, Boolean showMonitor, -CharPtr lastDispatcher, Int2 lastDispLen) -{ - char *def_user; - char username[64]; - char groupname[20]; - char password[20]; - char dispname[60]; - char disp_config[10]; - char disp_msg[110]; - char buf[60]; - Boolean more_disps; - int alternate = 1; - int disp_timeout; - Int4 disp_serialno; - Monitor *mon = NULL; - NI_DispInfoPtr dip = NULL; - NI_DispatcherPtr disp = NULL; - Boolean someBrokered; - Boolean useOutServ; - ValNodePtr encryptInfo = NULL; - NI_PubKeyPtr keyCopy = NULL; - Boolean doEncr = FALSE; - Boolean quitOnDispConnFailure = FALSE; - Boolean showMessage = FALSE; - Int4 numBrokeredServices; - - /******************* open the network connnection *********/ -#define NI_DISP_NAME "dispatch1.nlm.nih.gov" -#define NI_USER_NAME "anonymous" -#define NI_GROUP_NAME "GUEST" - - def_user = NI_USER_NAME; - - if (configFile == NULL) - configFile = "NCBI"; - if (configSection == NULL) - configSection = "NET_SERV"; - - GetAppParam(configFile, configSection, "DISP_USERNAME", NI_USER_NAME, username, - sizeof username); - /* the user's login name overrides the config file */ - /* for UNIX or VMS systems (or, for the future, any system where the */ - /* user name can be determined), use the user's login name as the default */ - def_user = NULL; -#ifdef OS_UNIX - if ((def_user = getenv("USER")) == NULL) - { - def_user = getlogin(); - } -#endif -#ifdef OS_VMS - def_user = getenv("USER"); -#endif - if (def_user != NULL) - { - StrNCpy(username, def_user, sizeof username); - } - - GetAppParam(configFile, configSection, "DISP_GROUPNAME", NI_GROUP_NAME, groupname, - sizeof groupname); - GetAppParam(configFile, configSection, "DISP_PASSWORD", "", password, - sizeof password); /* default = NONE */ - - GetAppParam(configFile, configSection, "DISP_TIMEOUT", "0", buf, sizeof buf); - disp_timeout = atoi(buf); - - GetAppParam(configFile, configSection, "DISPSERIALNO", "0", buf, sizeof buf); - disp_serialno = atoi(buf); - - GetAppParam(configFile, configSection, "DISPATCHER", NI_DISP_NAME, dispname, - sizeof dispname); - - GetAppParam(configFile, configSection, "DIRECT_SVC_CON", "FALSE", buf, - sizeof(buf)); - useOutServ = (Boolean)(StrICmp(buf, "TRUE") == 0); - - GetAppParam(configFile, configSection, "SOME_BROKERED", "FALSE", buf, sizeof buf); - someBrokered = (Boolean)(StrICmp(buf, "TRUE") == 0); - if (someBrokered) { - GetAppParam(configFile, configSection, "BROKERED_COUNT", "1", buf, sizeof buf); - numBrokeredServices = atoi(buf); - if (numBrokeredServices <= 0) { - someBrokered = FALSE; - } else { - sprintf (buf, "%ld", (long) numBrokeredServices - 1); - TransientSetAppParam(configFile, configSection, "BROKERED_COUNT", buf); - } - } - - GetAppParam(configFile, configSection, "DISP_RECONN_ACTION", "CONT", buf, sizeof buf); - showMessage = (Boolean)(StrICmp(buf, "ASK") == 0); - quitOnDispConnFailure = (Boolean)(StrICmp(buf, "QUIT") == 0); - - GetAppParam(configFile, configSection, "ENCRYPTION_DESIRED", "FALSE", buf, sizeof buf); - if (StrICmp(buf, "TRUE") == 0 && NI_EncrAvailable()) - { - doEncr = TRUE; - encryptInfo = ValNodeNew(NULL); - encryptInfo->data.ptrvalue = (Pointer) NI_ReadPubKeyFromConfig(); - keyCopy = NI_PubKeyDup((NI_PubKeyPtr) encryptInfo->data.ptrvalue); - } - - do { - if (alternate == 2 && showMonitor) - { - mon = MonitorStrNew("Unable to contact primary dispatcher", 35); - } - if (alternate >= 2) - { - if (showMessage) - { - sprintf (disp_msg, "Unable to contact primary dispatcher. Ready to try\ndispatcher #%d <", alternate); - StrCat(disp_msg, dispname); - StrCat(disp_msg, ">. Continue?"); - if (Message(MSG_YN, disp_msg) == ANS_NO) - break; - } else { - sprintf(disp_msg, "Trying dispatcher #%d <", alternate); - StrCat(disp_msg, dispname); - StrCat(disp_msg, ">"); - if (showMonitor) { - MonitorStrValue(mon, disp_msg); - } - } - } - - if (lastDispatcher != NULL) { - StrNCpy(lastDispatcher, dispname, lastDispLen); - } - - disp = s_SetDispatcher (NULL, dispname, NULL, disp_timeout, disp_serialno, encryptInfo, useOutServ); - - if (someBrokered) { - disp->brokeredDummy = TRUE; - disp->someBrokered = TRUE; - disp->referenceCount++; - ValNodeFree (encryptInfo); - return disp; - } - - if (NI_InitServices(disp, username, - groupname[0] == '\0' ? 0 : groupname, - password [0] == '\0' ? 0 : password, &dip) >= 0) - { - if (dip != NULL && dip->serialno != disp_serialno) { - NI_SetDispConfig (&dip, dispname, sizeof dispname); - } - if (mon != NULL) - MonitorFree(mon); - if (disp->encryptInfo != NULL && - disp->encryptInfo->data.ptrvalue != NULL && - ! NI_PubKeysEqual(keyCopy, - (NI_PubKeyPtr) disp->encryptInfo->data.ptrvalue)) - { - NI_WritePubKeyToConfig ((NI_PubKeyPtr) disp->encryptInfo->data.ptrvalue); - } - NI_DestroyPubKey ((NIPubKeyPtr) keyCopy); - return disp; - } - ErrShow (); - s_EndServices (disp); - sprintf(disp_config, "DISP_ALT_%d", alternate++); - more_disps = (Nlm_Boolean)GetAppParam - (configFile, configSection, disp_config, "", - dispname, sizeof(dispname)); - if (doEncr) - { - encryptInfo = ValNodeNew(NULL); - encryptInfo->data.ptrvalue = (Pointer) - NI_PubKeyDup((NI_PubKeyPtr) keyCopy); - } - } while (more_disps && ! quitOnDispConnFailure); - - if (mon != NULL) - MonitorFree(mon); - - ValNodeFree (encryptInfo); - NI_DestroyPubKey ((NIPubKeyPtr) keyCopy); - ErrPostEx(SEV_ERROR,0,0, "NI_InitServices: Unable to connect to any dispatcher"); - return NULL; -} - - -/* - * Purpose: Get a network service based on information in config file - * - * Parameters: - * disp Pointer to the dispatcher structure obtained from a - * previous call to NI_SetDispatcher or NI_GenericInit - * configFile Name of NCBI-style configuration file. If NULL, defaults - * to "NCBI" - * defService The default service/resource/resource-type name, if - * not specified otherwise in configuration file. - * hasResource Boolean; if TRUE, ask for a resource when requesting - * service - * - * Returns: - * NULL, if unable to obtain service - * a pointer to the service-structure, otherwise - * - * - * Description: - * Extracts a service name and other service data from a - * configuration file, and attempts to obtain that service. - * As a special case, handle communication with a "brokered - * server" (a server which is already listening on a port, where - * no communication needs to be performed with the dispatcher). - * Also disable data encryption for this service request, if - * explicitly specified in the configuration file. - * - * - * Note: - * This function is provided as a convenience to developers who - * wish to use Network Services. Use of this function is not - * integral to the use of Network Services ... it is merely a - * convenience. - * - * For UNIX systems, environment variables can be used to - * override the config. file's values for SERVICE_NAME and - * RESOURCE_TYPE. - */ - -static NI_HandPtr s_GenericGetService -(NI_DispatcherPtr disp, CharPtr configFile, CharPtr configSection, - CharPtr defService, Boolean hasResource) -{ - char buf[40]; - char service[40]; - char resource[40]; - char res_type[40]; - Uint2 serv_min, serv_max; - Uint2 res_min, res_max; - char brokeredIpaddr[40]; - Uint2 port; - NI_HandPtr result; - ValNodePtr savEncrypt; -#ifdef OS_UNIX - CharPtr envName = (CharPtr)MemNew(StrLen(configSection) + 20); - CharPtr envValue; -#endif - - if (configFile == NULL) - configFile = "NCBI"; - - GetAppParam(configFile, configSection, "SERVICE_NAME", defService, - service, sizeof service); -#ifdef OS_UNIX - /* environment variable overrides config. file */ - sprintf (envName, "NI_SERVICE_NAME_%s", configSection); - if ((envValue = getenv(envName)) != NULL) - { - StrCpy (service, envValue); - } -#endif /* OS_UNIX */ - GetAppParam(configFile, configSection, "SERV_VERS_MIN", "1", - buf, sizeof buf); - serv_min = (Uint2)atoi(buf); - GetAppParam(configFile, configSection, "SERV_VERS_MAX", "0", - buf, sizeof buf); - serv_max = (Uint2)atoi(buf); - - res_min = 1; - res_max = 0; - - if (hasResource) { - GetAppParam(configFile, configSection, "RESOURCE_NAME", defService, - resource, sizeof resource); - GetAppParam(configFile, configSection, "RESOURCE_TYPE", defService, - res_type, sizeof res_type); -#ifdef OS_UNIX - /* environment variable overrides config. file */ - sprintf (envName, "NI_RESOURCE_TYPE_%s", configSection); - if ((envValue = getenv(envName)) != NULL) - { - StrCpy (res_type, envValue); - } -#endif /* OS_UNIX */ - GetAppParam(configFile, configSection, "RES_VERS_MIN", "1", - buf, sizeof buf); - res_min = (Uint2)atoi(buf); - GetAppParam(configFile, configSection, "RES_VERS_MAX", "0", - buf, sizeof buf); - res_max = (Uint2)atoi(buf); - } - -#ifdef OS_UNIX - MemFree (envName); -#endif /* OS_UNIX */ - - if (disp->someBrokered) - { - GetAppParam(configFile, configSection, "BROKERED_PORT", "0", - buf, sizeof buf); - port = htons((unsigned short)atoi(buf)); - GetAppParam(configFile, configSection, "BROKERED_IPADDR", "", - brokeredIpaddr, sizeof brokeredIpaddr); - if (port != 0 && brokeredIpaddr[0] != '\0') - { /* simulate service request by connecting to that port */ - struct sockaddr_in serv_addr; - NI_HandPtr sHP; - int timeout = 30; - int status; - - MemFill((VoidPtr) &serv_addr, '\0', sizeof(serv_addr)); - serv_addr.sin_family = AF_INET; - serv_addr.sin_addr.s_addr = inet_addr(brokeredIpaddr); - serv_addr.sin_port = port; - - if ((sHP = MsgMakeHandle(TRUE)) == NULL) - return NULL; - MsgSetLJError(sHP); - sHP->hostname = StringSave(brokeredIpaddr); - - if (activityHook != NULL) - { - activityHook(sHP, NetServHook_svcreq, 0); - } - - RETRY: -#ifndef NETP_INET_NEWT - if ((status = NI_CONNECT(sHP->sok, (struct sockaddr PNTR) &serv_addr, sizeof(serv_addr))) < 0) { /* } */ -#else - if ((status = NI_CONNECT(sHP->sok, &serv_addr, sizeof(serv_addr))) < 0) { - SOCK_ERRNO = ABS(status); -#endif - switch (SOCK_ERRNO) { - case EINTR: - goto RETRY; - -#ifdef NETP_INET_PCNFS - /* This is apparently a bug in PC-NFS 4.0 ... a connection attempt */ - /* on a non-blocking socket yields errno == 0 */ - case 0: -#endif /* NETP_INET_PCNFS */ - case EWOULDBLOCK: - case EINPROGRESS: - /* if the connect()ion is not established immediately, a */ - /* select() can be performed where the corresponding "write" */ - /* file descriptor will be enabled once the connect()ion has been*/ - /* established */ - if (sokselectw(sHP->sok, timeout) == 0) { - return sHP; - } - break; - - default: - break; - } - MsgDestroyHandle(sHP); - ni_errno = NIE_BROKSVCCONN; /* can't connect to brokered service */ - return NULL; - } - { - Char buf[16]; - Char key[8]; - Int2 len; - - if ((len = GetAppParam("NCBI", "NET_SERV", "DESKEY", "", buf, sizeof buf)) > 0 && - (AsnTypeStringToHex(buf, len, key, NULL) == 0)) - - { - NI_SetupDESEncryption(sHP, (UcharPtr) key); - } - } - return sHP; - } else { - if (disp->brokeredDummy) - { /* JAE ... establish a true dispatcher connection here */ - } - } - } - - savEncrypt = disp->encryptInfo; - if (GetAppParam(configFile, configSection, "ENCRYPTION", "TRUE", - buf, sizeof buf) > 0 && StrICmp(buf, "FALSE") == 0) - { - /* temporarily disable encryption */ - disp->encryptInfo = NULL; - } - result = NI_ServiceGet(disp, service, serv_min, serv_max, - hasResource ? resource : 0, res_type, res_min, - res_max); - disp->encryptInfo = savEncrypt; - - return result; -} - - -/* - * Purpose: Write dispatcher-configuration information to a config file - * - * Parameters: - * dipp A pointer to the caller's list of dispatchers, obtained - * from NI_InitServices() - * dispatcher The caller's dispatcher string - * dispLen Length of the caller's dispatcher string - * - * Returns: - * 0, if bad parameters were provided - * the dispatcher-list serial number, otherwise - * - * - * Description: - * Sets up the "NCBI" configuration file with the following - * entries in the "NET_SERV" section: - * * DISPATCHER is the primary dispatcher name - * * DISP_ALT_n for every alternate dispatcher, 1 <= n, a smaller - * n indicates a higher priority alternate dispatcher - * * DISPSERIALNO is the serial number of the dispatcher list - * obtained from a remote dispatcher. This serial number should - * be unique for all time ... the dispatcher's serial number - * must be changed whenever the master list is modified. - * - * Note: - * This configuration mechanism is only _one_ recommended - * mechanism for network services dispatcher configuration. The - * application may perform this configuration in any manner - * deemed appropriate by the application programmer. - * - * The value returned by this function is the recommended value - * for the dispserialno parameter in a subsequent call to - * NI_InitDispatcher(). - */ - -NLM_EXTERN Int4 NI_SetDispConfig(NI_DispInfoPtr PNTR dipp, CharPtr dispatcher, Int2 dispLen) -{ - int num; - Char dispConfig[20]; - char buf[10]; - Int4 retval; - NI_DispInfoPtr dip; - - if (dipp == NULL || (dip = *dipp) == NULL) - { - if (dispatcher != NULL) - { - dispatcher[0] = '\0'; - } - return 0; - } - - if (dip->numdispatchers > 0 && dip->displist != NULL) - { - StringNCpy (dispatcher, dip->displist[0], dispLen); - SetAppParam ("NCBI", "NET_SERV", "DISPATCHER", dip->displist[0]); - } - - for (num = 1; num < dip->numdispatchers; num++) - { - sprintf (dispConfig, "DISP_ALT_%d", num); - SetAppParam ("NCBI", "NET_SERV", dispConfig, dip->displist[num]); - } - - /* wipe out any extraneous old configuration */ - for (num = dip->numdispatchers; num < 100; num++) - { - sprintf (dispConfig, "DISP_ALT_%d", num); - if (GetAppParam("NCBI", "NET_SERV", dispConfig, "", buf, sizeof buf) <= 0) - { - break; - } - SetAppParam ("NCBI", "NET_SERV", dispConfig, NULL); - } - - retval = dip->serialno; - sprintf (buf, "%ld", (long) dip->serialno); - SetAppParam ("NCBI", "NET_SERV", "DISPSERIALNO", buf); - - NI_DestroyDispInfo ((NIDispInfoPtr) dip); - *dipp = NULL; - - return retval; -} - - -/* - * Purpose: End use of network services - * - * Parameters: - * disp A pointer to the dispatcher structure - * - * Returns: - * 0 (always) - * - * - * Description: - * Tear down the sockets and data structures associated with - * the dispatcher and a server, and free all memory associated - * with data structures. - */ - -static Int2 s_EndServices(NI_DispatcherPtr disp) -{ - Int2 openSockets; - - if (disp == NULL) - return 0; - - if (disp->referenceCount > 0) - disp->referenceCount--; - - if (disp->referenceCount <= 0) - { - if (disp == currentDisp) - { - currentDisp = NULL; - } - - HaltServices (disp); - s_SetDispatcher(disp, NULL, NULL, 0, 0, NULL, FALSE); /* free mem */ - - if (stackDescription != NULL) - { - MemFree(stackDescription); - stackDescription = NULL; - } - MemFree(disp->adminInfo); - MemFree(disp->motd); - MemFree(disp); - - /* For historical reasons pertaining to Network Entrez, a single open - socket does not constitute an error in this context. However, at - program exit time, a single open socket does constitute a serious - problem. */ - if ((openSockets = NI_SocketsOpen()) > 1) - { - ErrPostEx(SEV_WARNING,0,0, "At end-services time, %d sockets are still open", openSockets); - } - } - - return 0; -} /* NI_EndServices */ - - - -/* - * Purpose: Request a catalog from the dispatcher - * - * Parameters: - * disp A pointer to the dispatcher structure - * - * Returns: - * NULL, if unable to obtain the catalog - * a pointer to the received catalog data structure, otherwise - * - * - * Description: - * Send a request to the dispatcher, requesting a catalog, and - * wait (up to some timeout) for a response. The dispatcher's - * response should either be that catalog, or a NACK. - */ - -NLM_EXTERN NICatalogPtr NI_GetCatalog(NI_DispatcherPtr disp) -{ - NICatalogPtr catp; - NIMsgPtr mp, imp; - NICmdPtr cmdp; - struct timeval timeout; - int ready; - fd_set readfds; - - if (disp == NULL) - return NULL; - - cmdp = (NICmdPtr) NI_MakeMsgCmd(); - cmdp->seqno = disp->dispHP->seqno++; - cmdp->code = NI_SEND_CATALOG; - if ((mp = MsgBuild(NI_COMMAND, disp->dispHP->conid, (VoidPtr) cmdp)) == NULL) { - ni_errno = NIE_MISC; /* unable to alloc mem for Msg */ - return NULL; - } - if (MsgWrite(disp->dispHP, mp, FALSE) < 0) { - ni_errno = NIE_MSGWRITE; - return NULL; - } - - /* blocks until response from dispatcher or TIMEOUT */ - - timeout.tv_sec = (Uint4) NI_TIMEOUT_SECS; - timeout.tv_usec = 0; - FD_ZERO(&readfds); - FD_SET(disp->dispHP->sok, &readfds); - while ((ready = NI_select(FD_SETSIZE, &readfds, NULL, NULL, &timeout)) < 0) { - if (SOCK_ERRNO == EINTR) - ; /* repeat while interrupted */ - else { - ni_errno = NIE_SELECT; /* select error */ - return NULL; - } - } - - if (FD_ISSET(disp->dispHP->sok, &readfds) != 0) { - if ((imp = MsgRead(disp->dispHP, FALSE)) == NULL) { - LOG_SOCKET(disp->dispHP->sok, FALSE); - NI_CLOSESOCKET(disp->dispHP->sok); - ni_errno = NIE_MSGREAD; - return NULL; - } - switch (imp->type) { - case NI_CATALOG: - catp = imp->msun.catalog; - imp->msun.catalog = NULL; - ni_errno = NIE_NO_ERROR; - MsgDestroy(imp); - return catp; - break; - - case NI_NACK: - ni_errno = (enum ni_error) imp->msun.nack->code; - if (imp->msun.nack->reason != NULL) - StringCpy(ni_errtext, imp->msun.nack->reason); - else - ni_errtext[0] = '\0'; - MsgDestroy(imp); - return NULL; - - default: - MsgDestroy(imp); - ni_errno = NIE_MSGUNK; /* Unknown MSG type */ - return NULL; - } - } - ni_errno = NIE_CMDTIMEOUT; /* TIMEOUT */ - return NULL; -} /* NI_GetCatalog */ - - - -/* - * Purpose: Create the data structure for a service request - * - * Parameters: - * disp A pointer to the dispatcher structure - * - * Returns: - * a pointer to the newly created data structure - * - * - * Description: - * Allocate the memory for a service request data structure, - * and fill in some of the fields. - * Note: - * There are two ways for a program to issue a service request: - * (1) Multi-step, general method (like IRS form 1040) - * * Build a request with NI_SVCRequestBuild() - * * Populate the request with a specific service request using - * NI_RequestSetService() - * * Populate the request with zero or more resource requests - * calling NI_RequestAddResource() once for every resource - * * Send the request with NI_ServiceRequest(), and (hopefully) - * obtain a connection to a service provider - * * At some later time, delete the request (to save memory) - * (2) One-stop shopping, for simple requirement (like form 1040EZ) - * * Do everything for a service and up to one resource using - * NI_ServiceGet() - */ - -NLM_EXTERN NI_ReqPtr NI_SVCRequestBuild(NI_DispatcherPtr disp) -{ - NI_ReqPtr reqp; - - if (disp == NULL) - return NULL; - - reqp = (NI_ReqPtr) NI_MakeRequest(); - reqp->clientPort = (Uint2) disp->clientPort; - if (disp->useSocks) - { - /* tell the Dispatcher that it should use getpeername() to determine */ - /* the IP address of the SOCKS daemon */ - reqp->clientAddr = StringSave("0.0.0.0"); - } else { - reqp->clientAddr = StringSave(disp->localHostAddr); - } - reqp->dispatcher = disp; /* should not be freed when destroying Req */ - - return reqp; -} /* NI_SVCRequestBuild */ - - - -/* - * Purpose: Destroy a service request data structure - * - * Parameters: - * reqp A pointer to the data structure to be destroyed - * - * - * Description: - * Free all the resources associated with a service request - */ - -NLM_EXTERN void NI_SVCRequestDestroy(NI_ReqPtr reqp) -{ - NI_DestroyRequest(reqp); -} /* NI_SVCRequestDestroy */ - - - -/* - * Purpose: Make a service request for a service and up to one resource - * - * Parameters: - * disp A pointer to the dispatcher structure - * svc Name of requested service - * svcvermin Minimum version number requested for this service - * svcvermax Maximum version number requested for this service - * res Name of requested resource (possibly NULL) - * resvermin Minimum version number requested for this resource - * resvermax Maximum version number requested for this resource - * - * Returns: - * The result of the service request - * - * - * Description: - * Create and issue a service request for the specified - * parameters. - */ - -NLM_EXTERN NI_HandPtr NI_ServiceGet(NI_DispatcherPtr disp, CharPtr svc, Uint2 svcvermin, Uint2 svcvermax, CharPtr res, CharPtr restype, Uint2 resvermin, Uint2 resvermax) -{ - NI_ReqPtr reqp; - - if (disp == NULL) - return NULL; - - reqp = NI_SVCRequestBuild(disp); - NI_RequestSetService(reqp, svc, svcvermin, svcvermax); - if (res != NULL) - NI_RequestAddResource(reqp, res, restype, resvermin, resvermax); - - return NI_ServiceRequest(reqp); -} /* NI_ServiceGet */ - - - -/* - * Purpose: Issue the specified service request - * - * Parameters: - * req The pre-formatted service request - * - * Returns: - * A message handle to the server which is servicing our request, - * if successful - * NULL, otherwise (ni_errno will indicate a more precise cause) - * - * - * Description: - * Create and issue a service request for the specified - * service request, as follows: - * - * * Create a data structure to which the resulting service - * connection can be attached - * * Send the service request to the dispatcher - * - * old - style connection: - * - * * Wait for the following two events, in either order: - * (1) A response from the dispatcher, which is either a - * SVC_RESPONSE (good), or a NACK (bad) {or a timeout} - * (2) A connection request from the server, which we then - * accept() - * * If both of the two events occur successfully, return with - * success, else, return with failure. - * - * old-style / direct connection switch - * (currently disabled) - * - * * After NACK was received in old - style connection we don't - * worry, set disp->useOutServ to TRUE and return to the beginning - * of the function. All service request will be repeated with - * direct connection. - * - * direct connection: - * - * * Wait for the following events: - * (1) A response from the dispatcher, which is either a - * SVC_REQUEST (good), or a NACK (bad) {or a timeout} - * * In the case of SVC_REQUEST we send this request directly - * to the server and wait for next event: - * (2) A response from the dispatcher, which is either a - * SVC_RESPONSE (good), or a NACK (bad) {or a timeout} - * * If both of the two events occur successfully, return with - * success, else, return with failure. - * - * Note: - * If the caller's Dispatcher data structure indicates that - * encryption should be performed, then a DES key is - * pseudorandomly generated prior to issuing the service request, - * and is encrypted using public-key encryption. Following - * successful establishment of the client<->server session, the - * DES key is used to encrypt the ensuing session using - * cypher-block-chaining. - * - * For SOCKSified clients, a different protocol is used where - * the client first sends a "pre-service-request", asking the - * IP address of the computer to which the Dispatcher will assign - * the request. Upon receipt of a NI_SVC_PRE_RESPONSE message - * containing that IP address, the client performs a SOCKSified - * bind()ing indicating that the specified IP address will - * "call back". Having determine the port number which has - * been bound on the SOCKS proxy, the client sends the "real" - * service request containing the SOCKS proxy's port number - * and a reminder as to which IP address the Dispatcher - * "promised" would be assigned. After that, processing - * proceeds normally, with the server connecting-back (via - * the SOCKS proxy) and the Dispatcher sending a SVC_RESPONSE - * acknowledgement. - * - * Note that SOCKS and encryption are completely orthogonal - * with respect to each other, and a client may use either, both, - * or neither. - */ - -NLM_EXTERN NI_HandPtr NI_ServiceRequest(NI_ReqPtr req) -{ - NI_HandPtr sconnhp; -#ifdef HAVE_SOCKLEN_T - socklen_t sconnlen; -#else -# ifdef NETP_INET_MACTCP - Int4 sconnlen; -# else - int sconnlen; -# endif -#endif - struct sockaddr_in sconnaddr; - NIMsgPtr mp, imp; - NISvcReqPtr svcreqp; - struct timeval timeout; - Monitor *mon = NULL; - int ready; - Boolean disp_contact = FALSE, serv_contact = FALSE; - Uint4 this_req; - fd_set readfds; - NI_DispatcherPtr disp = req->dispatcher; - Uchar desKey[8]; -#ifdef NETP_SOCKS - struct sockaddr_in svcsAddr; - Int2 status; -#endif - -NEXTTRY: - ni_errtext[0] = '\0'; - if (disp->useOutServ) { - if ((sconnhp = MsgMakeHandle(TRUE)) == NULL) { - ni_errno = NIE_MAKEHAND; - return NULL; - } - } else { - if ((sconnhp = MsgMakeHandle(FALSE)) == NULL) { - ni_errno = NIE_MAKEHAND; - return NULL; - } - } - - svcreqp = NI_MakeMsgSvcreq(); - svcreqp->seqno = disp->dispHP->seqno++; - svcreqp->platform = (Uint4) NI_GetPlatform(); - if (stackDescription != NULL) - { - svcreqp->applId = StringSave(stackDescription); - } - if (disp->encryptInfo != NULL && NI_EncrAvailable()) - { - UcharPtr encryptedDesKey; - Int2 encryptedLen; - - NI_GenerateDESKey (desKey); - encryptedLen = NI_PubKeyEncrypt((NI_PubKeyPtr) disp->encryptInfo->data.ptrvalue, - desKey, sizeof desKey, &encryptedDesKey); - if (encryptedLen <= 0) - { - NI_DestroyRequest(req); - MsgDestroyHandle(sconnhp); - ni_errno = NIE_PUBKEYENCRFAIL; - return NULL; - } - /* convert the DES key into a ByteStore */ - svcreqp->desKey = BSNew(encryptedLen); - BSWrite (svcreqp->desKey, (VoidPtr) encryptedDesKey, encryptedLen); - MemFree (encryptedDesKey); - } - this_req = svcreqp->seqno; - CopyIdentity(disp, svcreqp->uid); - NI_DestroyRequest(svcreqp->request); - svcreqp->request = req; - - if (disp->useSocks) - { - svcreqp->wantPreResponse = TRUE; - } - /* we want to get a ticket for the direct connection */ - if (disp->useOutServ) { - svcreqp->want_ticket = TRUE; - } - - if ((mp = MsgBuild(NI_SVC_REQUEST, disp->dispHP->conid, (VoidPtr) svcreqp)) == NULL) { - NI_DestroyRequest(req); - MsgDestroyHandle(sconnhp); - ni_errno = NIE_MISC; /* unable to alloc mem for Msg */ - return NULL; - } - - if (MsgWrite(disp->dispHP, mp, disp->useSocks) < 0) { - MsgDestroyHandle(sconnhp); - ni_errno = NIE_MSGWRITE; - return NULL; - } - - /* blocks until SVC_RESPONSE from dispatcher and service or NACK or TIMEOUT */ - while ( !disp_contact || !serv_contact) { - timeout.tv_sec = (Uint4) NI_TIMEOUT_SECS; - timeout.tv_usec = 0; - FD_ZERO(&readfds); - FD_SET(disp->dispHP->sok, &readfds); - if (! disp->useOutServ) - FD_SET(disp->svcsHP->sok, &readfds); - while ((ready = NI_select(FD_SETSIZE, &readfds, NULL, NULL, &timeout)) < 0) { - if (SOCK_ERRNO == EINTR) - ; /* repeat while interrupted */ - else { - MsgDestroyHandle(sconnhp); - ni_errno = NIE_SELECT; /* select error */ - return NULL; - } - } - if (ready == 0) { - MsgDestroyHandle(sconnhp); - ni_errno = NIE_DSPTIMEOUT; /* TIMEOUT */ - return NULL; - } - if (FD_ISSET(disp->dispHP->sok, &readfds) != 0) { - if ((imp = MsgRead(disp->dispHP, FALSE)) == NULL) { - LOG_SOCKET(disp->dispHP->sok, FALSE); - NI_CLOSESOCKET(disp->dispHP->sok); - MsgDestroyHandle(sconnhp); - ni_errno = NIE_MSGREAD; - return NULL; - } - disp_contact = TRUE; - switch (imp->type) { - case NI_SVC_PRE_RESPONSE: -#ifdef NETP_SOCKS - if (disp->useSocks) - { - /* must defer binding and listening for SOCKS connection */ - /* until server's IP address is known */ - - TRACE("Processing SOCKS SVC_PRE_RESPONSE\n"); - /* SOCKS can't deal well with non-blocking connections */ - NI_SETBLOCKING(disp->svcsHP->sok); - - if ((disp->clientPort = bindPort(disp->svcsHP->sok, &svcsAddr, disp->loport, disp->hiport, imp->msun.preresp->server_ip)) == 0) { - TRACE("bindPort failed\n"); - MsgDestroyHandle(sconnhp); - disp->svcsHP = NULL; - ni_errno = NIE_NOBIND; /* can't bind a free application socket */ - ErrPost (CTX_NCBICORE, CORE_UNKNOWN, "NI_ServiceRequest: <%s>", ni_errlist[ni_errno]); - return NULL; - } - TRACE("bindPort succeeded, port = %d\n", disp->clientPort); - if (NI_GETSOCKNAME(disp->svcsHP->sok, &svcsAddr, &sconnlen) >= 0) - disp->clientPort = ntohs(svcsAddr.sin_port); - req->clientPort = disp->clientPort; - svcreqp->server_ip = imp->msun.preresp->server_ip; - svcreqp->wantPreResponse = FALSE; - if (MsgWrite(disp->dispHP, mp, FALSE) < 0) { - MsgDestroyHandle(sconnhp); - ni_errno = NIE_MSGWRITE; - return NULL; - } - disp_contact = FALSE; /* now waiting to hear one more msg */ - - TRACE("After GETSOCKNAME, port = %d\n", disp->clientPort); - if ((status = NI_LISTEN(disp->svcsHP->sok, 5)) < 0) { -#ifdef NETP_INET_NEWT - SOCK_ERRNO = ABS(status); -#endif - TRACE("Listen failed, errno = %d\n", SOCK_ERRNO); - MsgDestroyHandle(sconnhp); - StringCpy(ni_errtext, strerror(SOCK_INDEX_ERRNO)); - ni_errno = NIE_NOLISTEN; - ErrPost (CTX_NCBICORE, CORE_UNKNOWN, "NI_ServiceRequest: <%s> <port %d, errno %d>", ni_errlist[ni_errno], (int) disp->clientPort, (int) SOCK_ERRNO); - return NULL; - } - } -#endif - /* non-SOCKS clients ignore this message, and should never receive it */ - TRACE("Listen succeeded\n"); - MsgDestroy(imp); - break; - - case NI_SVC_RESPONSE: - if (disp->useSocks) - { - TRACE("Got SOCKS service response from Dispatcher\n"); - } - ni_errno = NIE_NO_ERROR; - NI_DestroyRequest(disp->reqResponse); - disp->reqResponse = imp->msun.svcresp->request; - sconnhp->hostname = StringSave(disp->reqResponse->clientAddr); - imp->msun.svcresp->request = NULL; - MsgDestroy(imp); - if (mon != NULL) { - MonitorStrValue(mon, "Direct connection established"); -#ifdef OS_UNIX - sleep(1); -#endif /* OS_UNIX */ - MonitorFree(mon); - } - break; - - case NI_NACK: - if (disp->useSocks) - { - TRACE("Got SOCKS NACK from Dispatcher\n"); - } - ni_errno = (enum ni_error) imp->msun.nack->code; - if (imp->msun.nack->reason != NULL) - StringCpy(ni_errtext, imp->msun.nack->reason); - else - ni_errtext[0] = '\0'; - MsgDestroy(imp); - - /* retry in the case when old style connection failed now is disabled */ - - if (FALSE && !disp->useOutServ) { - disp->useOutServ = TRUE; - mon = MonitorStrNew("Old type of connection failed", 40); - MonitorStrValue(mon, "Trying to establish direct connection"); - serv_contact = FALSE; - disp_contact = FALSE; - goto NEXTTRY; - } - else { - MsgDestroyHandle(sconnhp); - return NULL; - } - /* Message with direct connection ticket was received */ - case NI_SVC_REQUEST: - if ((sconnhp = NI_DirectServiceRequest(imp, sconnhp)) == NULL) { - TRACE("Unable to establish direct connection\n"); - return NULL; - } - if (mon != NULL) - MonitorStrValue(mon, "Received ticket for direct connection"); - - serv_contact = TRUE; - disp_contact = FALSE; /* we are looking for SVC_RESPONCE */ - break; - - - default: - if (disp->useSocks) - { - TRACE("Got SOCKS unknown message type from Dispatcher\n"); - } - MsgDestroy(imp); - MsgDestroyHandle(sconnhp); - ni_errno = NIE_MSGUNK; /* Unknown MSG type */ - sprintf(ni_errtext, "%d", imp->type); - return NULL; - } - } - if (!disp->useOutServ && (FD_ISSET(disp->svcsHP->sok, &readfds) != 0) && !serv_contact) { - sconnlen = sizeof(sconnaddr); -#ifdef NETP_INET_NEWT - sconnhp->sok = NI_ACCEPT(disp->svcsHP->sok, &sconnaddr, &sconnlen); -#else - sconnhp->sok = NI_ACCEPT(disp->svcsHP->sok, (struct sockaddr PNTR) &sconnaddr, &sconnlen); -#endif /* NETP_INET_NEWT */ - LOG_SOCKET(sconnhp->sok, TRUE); -#ifdef NETP_SOCKS - if (disp->useSocks) - { - TRACE("Got connection from server, socket %d\n", sconnhp->sok); - MsgDestroyHandle(disp->svcsHP); - disp->svcsHP = MsgMakeHandle(TRUE); /* for next time */ - } -#endif /* NETP_SOCKS */ - if (sconnhp->sok < 0) { -#ifdef NETP_INET_NEWT - SOCK_ERRNO = ABS(sconnhp->sok); -#endif - MsgDestroyHandle(sconnhp); - StringCpy(ni_errtext, strerror(SOCK_INDEX_ERRNO)); - ni_errno = NIE_NOACCEPT; /* application accept error */ - return NULL; - } - serv_contact = TRUE; - } - } - - if (activityHook != NULL) - { - (*activityHook)(sconnhp, NetServHook_svcreq, 0); - } - - if (disp->encryptInfo != NULL && NI_EncrAvailable()) - { - NI_SetupDESEncryption(sconnhp, desKey); - } - - if (sconnhp != NULL) - { - sconnhp->disp = disp; - } - - return sconnhp; -} /* NI_ServiceRequest */ - - - -/* - * Purpose: Issue the specified direct service request - * - * Parameters: - * - * imp The pre-formatted service request - * sconnhp server handle to connect to - * - * Returns: - * - * sconnhp A message handle to the server which is servicing our request, - * if successful - * - * Description: This function connects directly to server specified by sconnhp - * and sends SVC_REQUEST message imp, formated and completed by - * dispatcher and received by NI_ServiceRequest function of the client - * - * - */ -static NI_HandPtr -NI_DirectServiceRequest(NIMsgPtr imp, NI_HandPtr sconnhp) -{ - int timeout = 30; - int status; - struct sockaddr_in sconnaddr; - char buf[20]; - - MemFill((VoidPtr) &sconnaddr, '\0', sizeof(sconnaddr)); - sconnaddr.sin_family = AF_INET; - sconnaddr.sin_addr.s_addr = htonl(imp->msun.svcreq->server_ip); - if (GetAppParam("NCBI", "NET_SERV", "PROXY_SERV_OVERRIDE", "", buf, sizeof buf) > 0) - { - sconnaddr.sin_addr.s_addr = inet_addr(buf); - } - sconnaddr.sin_port = htons(imp->msun.svcreq->server_port); - -RETRY1: - - -#ifndef NETP_INET_NEWT - status = NI_CONNECT(sconnhp->sok, (struct sockaddr PNTR) &sconnaddr, - sizeof(sconnaddr)); -#else - status = NI_CONNECT(sconnhp->sok, &sconnaddr, sizeof(sconnaddr)); -#endif - if (status < 0) { -#ifdef NETP_INET_NEWT - SOCK_ERRNO = ABS(status); -#endif - switch (SOCK_ERRNO) { - case EINTR: - goto RETRY1; - -#ifdef NETP_INET_PCNFS - case 0: -#endif /* NETP_INET_PCNFS */ - case EWOULDBLOCK: - case EINPROGRESS: - /* if the connect()ion is not established immediately, a */ - /* select() can be performed where the corresponding "write" */ - /* file descriptor will be enabled once the connect()ion has been*/ - /* established */ - - if (sokselectw(sconnhp->sok, timeout) != 0) { - MsgDestroyHandle(sconnhp); - return NULL; - } - break; - - default: - MsgDestroyHandle(sconnhp); - ni_errno = NIE_DIRUNCONNECT; /* cannot establish direct connection */ - return NULL; - } - } - - /* Now we are sending service request directly to the server */ - - if (MsgWrite(sconnhp, imp, TRUE) < 0) { - MsgDestroyHandle(sconnhp); - ni_errno = NIE_DIRUNCONNECT; - return NULL; - } - return sconnhp; -} - - - -/* - * Purpose: Disconnect from a service provider - * - * Parameters: - * mhp Message handle for the server - * - * Returns: - * 0, always - * - * - * Description: - * Disconnect from a service provider, essentially by just - * closing the communication socket to that service provider. - */ - -static Int2 s_ServiceDisconnect(NI_HandPtr mhp) -{ - if (activityHook != NULL) - { - activityHook(mhp, NetServHook_svcdisconn, 0); - } - - MsgDestroyHandle(mhp); - return 0; -} /* NI_ServiceDisconnect */ - - - -/* - * Purpose: Obtain the read file descriptor from a "message handle" - * - * Parameters: - * handp Message handle - * - * Returns: - * Socket associated with message handle - * - * - * Description: - * Get the read file desciptor from a message handle. This - * might be useful, for example, when wishing to perform - * "direct" I/O to the socket after a connection has been - * established with a server/client. - */ - -NLM_EXTERN int NI_ServiceGetReadFd(NI_HandPtr handp) -{ - return handp->sok; -} /* NI_ServiceGetReadFd */ - - - -/* - * Purpose: Obtain the write file descriptor from a "message handle" - * - * Parameters: - * handp Message handle - * - * Returns: - * Socket associated with message handle - * - * - * Description: - * Get the write file desciptor from a message handle. This - * might be useful, for example, when wishing to perform - * "direct" I/O to the socket after a connection has been - * established with a server/client. - */ - -NLM_EXTERN int NI_ServiceGetWriteFd(NI_HandPtr handp) -{ - return handp->sok; -} /* NI_ServiceGetWriteFd */ - - - -/* - * Purpose: Populate a service request with a service name and version #s - * - * Parameters: - * req Service request - * name Service name - * vermin Minimum version number for this service - * vermax Maximum version number for this service - * - * Returns: - * -1, if the name is a NULL pointer - * 0, otherwise - * - * - * Description: - * Populate the service request with the specified service name - * and version numbers, dynamically allocating space for the - * service name. - */ - -NLM_EXTERN Int2 NI_RequestSetService(NI_ReqPtr req, CharPtr name, Uint2 vermin, Uint2 vermax) -{ - if (name == NULL) { - ni_errno = NIE_INVAL; - return -1; - } - req->service->name = StringSave(name); - req->service->minVersion = vermin; - req->service->maxVersion = vermax; - req->service->typeL = NULL; - return 0; -} /* NI_RequestSetService */ - - - -/* - * Purpose: Populate a service request with an additional resource - * - * Parameters: - * req Service request - * name Resource name - * type Service type - * vermin Minimum version number for this resource - * vermax Maximum version number for this resource - * - * Returns: - * -1, if the name is a NULL pointer - * 0, otherwise - * - * - * Description: - * Insert the information for this resource into a list of - * resources associated with this service request. This - * function may be called one or more times (or, not at all) to - * populate a service request with one or more resources. - */ - -NLM_EXTERN Int2 NI_RequestAddResource(NI_ReqPtr req, CharPtr name, CharPtr type, Uint2 vermin, Uint2 vermax) - -{ - NIResPtr resp; - - if (name == NULL) { - ni_errno = NIE_INVAL; - return -1; - } - resp = NI_MakeResource(); - resp->name = StringSave(name); - if (type != NULL) - resp->type = StringSave(type); - resp->minVersion = vermin; - resp->maxVersion = vermax; - req->resourceL = ListInsertPrev((VoidPtr) resp, req->resourceL); /* add to end of list */ - return 0; -} /* NI_RequestAddResource */ - - - -/* THESE FUNCTIONS NOT VISIBLE TO API USER */ - -/* - * Purpose: Partially halt Network Services - * - * Parameters: - * disp A pointer to the dispatcher structure - * - * Description: - * Halt network services, except refrain from freeing the - * parameters which are set by NI_SetDispatcher(). - */ - -static void -HaltServices (NI_DispatcherPtr disp) -{ - if (disp == NULL) - return; - - if (disp->referenceCount > 0) - return; - - if (activityHook != NULL) - { - activityHook((NI_HandPtr) disp, NetServHook_dispdisconn, 0); - } - - MsgDestroyHandle(disp->dispHP); - MsgDestroyHandle(disp->svcsHP); - NI_DestroyRequest(disp->reqResponse); - if (disp->identity != NULL) { - MemFree (disp->identity->username); - MemFree (disp->identity->group); - MemFree (disp->identity->domain); - MemFree (disp->identity); - disp->identity = NULL; - } - disp->dispHP = NULL; - disp->svcsHP = NULL; - disp->reqResponse = NULL; - if (disp->encryptInfo != NULL) - { - if (disp->encryptInfo != NULL) - NI_DestroyPubKey((NIPubKeyPtr) disp->encryptInfo->data.ptrvalue); - ValNodeFree(disp->encryptInfo); - } - -#ifdef NETP_INET_WSOCK - /* we have an obligation to perform one cleanup call for every Startup */ - while (wsaStartupCount-- > 0) - { - WSACleanup(); - } -#endif -} - - -/* - * Purpose: Lookup a port # in config file and possible NIS - * - * Parameters: - * service Name of config. file entry - * networkOrder Boolean, indicates whether value should be returned in host - * order or network order. - * - * Description: - * Look up the specified entry in the NCBI config. file, and - * lookup in NIS the name obtained from the config file if it's - * non-numeric. - * - * Note: - * The intent of this function is that, in most cases, the - * GetAppParam() entry will not be present, and a default value - * will be used instead. The getservbyname() call is intended - * to be a last resort, because this may be slow on some systems. - */ - -static Uint2 -GetByConfigOrServ(CharPtr service, Boolean networkOrder) -{ - struct servent PNTR portEntry; - Char buf[50]; - Uint2 port; - - if (GetAppParam("NCBI", "NET_SERV", service, "", buf, sizeof buf) <= 0) - { - port = 0; - } else { - if (StrSpn(buf, "0123456789") == StrLen(buf)) - { /* all numeric */ - port = (Uint2)atoi(buf); - if (networkOrder) - port = htons(port); - } else { - /* entry from configuration file is name to use in getservbyname */ - if ((portEntry = getservbyname(buf, "tcp")) == NULL) - { - port = 0; - } else { - port = portEntry->s_port; - if (! networkOrder) - port = ntohs(port); - } - } - } - - return port; -} - - -/* - * Purpose: Connect to the dispatcher - * - * Parameters: - * disp A pointer to the dispatcher structure - * host Name of the host on which dispatcher resides - * service Name of the "service" (i.e., port) to which we should connect - * timeout How long to wait for dispatcher to respond, 0 ==> use default - * - * Returns: - * NULL, if the attempt to connect failed - * a pointer to the "Msg" structure for the dispatcher, otherwise - * - * - * Description: - * Connect to the dispatcher on the specified hostname on the - * specified service (where a service maps to a port number). - * This is done by establishing a socket to the dispatcher, - * and then connect()ing to that socket; the dispatcher should - * be listen()ing on that socket, and should subsequently accept() - * the connection request. - * - * While doing this, also obtain other useful information; - * namely, the dotted IP address of the local host, and the - * high and low port numbers to be used when attempting - * dispatcher connections. This global information is used - * elsewhere. - */ - -#ifndef INADDR_NONE -#define INADDR_NONE -1 -#endif /* INADDR_NONE */ - -static NI_HandPtr -DispatchConnect(NI_DispatcherPtr disp, CharPtr host, CharPtr service, int timeout) -{ - struct hostent PNTR dispHost, PNTR localHost; - struct sockaddr_in serv_addr; - NI_HandPtr dHP; - Uint2 disp_port; - Uint4 srvadd; - Char servInetAddr[INETADDR_SIZ], localHostName[SVC_HOST_SIZ]; - Char t_service[64]; - int status; - Int4 connectStartTime; -#ifdef HAVE_SOCKLEN_T - socklen_t socklen; -#else - int socklen; -#endif - - if (disp == NULL) - return NULL; - - - serv_addr.sin_family = AF_INET; - - srvadd = inet_addr(host); - if ((Int4)srvadd != INADDR_NONE) /* malformed request */ - MemCopy((VoidPtr) &serv_addr.sin_addr, (VoidPtr) &srvadd, sizeof(srvadd)); - else { - if ((dispHost = gethostbyname(host)) == NULL) { - ni_errno = NIE_NOHOSTENT; - return NULL; - } -/* MemCopy((VoidPtr)&serv_addr.sin_addr, (VoidPtr)(dispHost->h_addr), dispHost->h_length);*/ - MemCopy(&serv_addr.sin_addr, dispHost->h_addr, dispHost->h_length); - } - StringCpy(servInetAddr, inet_ntoa(serv_addr.SIN_ADDR)); - - if ((disp_port = GetByConfigOrServ(service, TRUE)) == 0) - { - if (service) - StringCpy(t_service, service); /* because Windows barfs on the pointer */ - else - t_service[0] = 0; - if ((disp_port = htons((unsigned short)atoi(t_service))) == 0) - disp_port = htons(NI_DFLT_SVC_PORT); - } - if (ntohs(disp_port) <= NI_LAST_RESERVED_PORT) { - ni_errno = NIE_NOSERVENT; - return NULL; - } - - /* get the Internet address of the "local host" */ -#ifdef NETP_INET_MACTCP - /* simpler solution to avoid the hazards of gethostname() */ - { - unsigned long localHostId; - - localHostId = gethostid(); - StringCpy(disp->localHostAddr, inet_ntoa(* (H_ADDR_TYPE) &localHostId)); - } -#else - gethostname(localHostName, SVC_HOST_SIZ); - if ((localHost = gethostbyname(localHostName)) == NULL) { - /* GetAppParam() workaround for PC-NFS 5.0 bug */ - if (GetAppParam("NCBI", "NET_SERV", "HOST_ADDRESS", "", - disp->localHostAddr, sizeof(disp->localHostAddr)) <= 0) - { /* use a bogus address which the dispatcher will try to fix */ - StringCpy(disp->localHostAddr, "0.0.0.0"); - - } - } else { - StringCpy(disp->localHostAddr, inet_ntoa(* (H_ADDR_TYPE) localHost->h_addr)); - } -#endif /* NETP_INET_MACTCP */ - - if ((disp->loport = GetByConfigOrServ(NI_CLIENT_PORT_LO_NAME, FALSE)) == 0) - { - if ((disp->loport = (Int2)atoi(NI_CLIENT_PORT_LO_NAME)) == 0) - disp->loport = NI_DFLT_CLILO_PORT; - } - if (disp->loport <= NI_LAST_RESERVED_PORT) { - ni_errno = NIE_BADPORT; /* bad low client port */ - return NULL; - } - - if ((disp->hiport = GetByConfigOrServ(NI_CLIENT_PORT_HI_NAME, FALSE)) == 0) - { - if ((disp->hiport = (Int2)atoi(NI_CLIENT_PORT_HI_NAME)) == 0) - disp->hiport = NI_DFLT_CLIHI_PORT; - } - if (disp->hiport <= NI_LAST_RESERVED_PORT) { - ni_errno = NIE_BADPORT; /* bad high client port */ - return NULL; - } - - MemFill((VoidPtr) &serv_addr, '\0', sizeof(serv_addr)); - serv_addr.sin_family = AF_INET; - serv_addr.sin_addr.s_addr = inet_addr(servInetAddr); - serv_addr.sin_port = disp_port; - - if ((dHP = MsgMakeHandle(TRUE)) == NULL) - return NULL; - MsgSetLJError(dHP); - if (timeout > 0) - MsgSetReadTimeout(dHP, timeout); - - if (activityHook != NULL) - { - activityHook((NI_HandPtr) disp, NetServHook_dispconn, 0); - } - -#ifdef NETP_SOCKS - if (disp->useSocks) - { /* SOCKS can't deal well with blocking connections */ - NI_SETBLOCKING(dHP->sok); - } -#endif - - connectStartTime = Nlm_GetSecs(); - - RETRY: -#ifndef NETP_INET_NEWT - if ((status = NI_CONNECT(dHP->sok, (struct sockaddr PNTR) &serv_addr, sizeof(serv_addr))) < 0) { /* } */ -#else - if ((status = NI_CONNECT(dHP->sok, &serv_addr, sizeof(serv_addr))) < 0) { - SOCK_ERRNO = ABS(status); -#endif - switch (SOCK_ERRNO) { - case EINTR: - goto RETRY; - -#ifdef NETP_INET_PCNFS - /* This is apparently a bug in PC-NFS 4.0 ... a connection attempt */ - /* on a non-blocking socket yields errno == 0 */ - case 0: -#endif /* NETP_INET_PCNFS */ - case EWOULDBLOCK: - case EINPROGRESS: - /* if the connect()ion is not established immediately, a */ - /* select() can be performed where the corresponding "write" */ - /* file descriptor will be enabled once the connect()ion has been*/ - /* established */ - socklen = sizeof(serv_addr); - if (sokselectw(dHP->sok, timeout) == 0 -#ifdef OS_UNIX - && getpeername(dHP->sok,(struct sockaddr *) &serv_addr, &socklen) == 0 -#endif - ) { - dHP->state = NI_CONNECTED; - dHP->connectDelay = (Uint2)(Nlm_GetSecs() - connectStartTime); - return dHP; - } - break; - - default: - break; - } - MsgDestroyHandle(dHP); - ni_errno = NIE_DISPCONN; /* can't connect to dispatcher */ - return NULL; - } - dHP->state = NI_CONNECTED; - dHP->connectDelay = (Uint2)(Nlm_GetSecs() - connectStartTime); - return dHP; -} /* DispatchConnect */ - - -/* - * Purpose: Convert an FQDN to an IP address - * - * Parameters: - * fqdn A fully-qualified domain name, like "dispatch1.nlm.nih.gov" - * ipbuf An output buffer for the dotted-decimal IP address - * ipbuflen The length of ipbuf - * - * Returns: - * TRUE, if the address was resolved successfully, FALSE otherwise - */ - -NLM_EXTERN Boolean NI_FqdnToIpaddr(CharPtr fqdn, CharPtr ipbuf, Int2 ipbuflen) -{ - struct hostent PNTR dispHost; - struct sockaddr_in serv_addr; - - serv_addr.sin_family = AF_INET; - if ((dispHost = gethostbyname(fqdn)) != NULL) - { - MemCopy (&serv_addr.sin_addr, dispHost->h_addr, dispHost->h_length); - StringNCpy (ipbuf, inet_ntoa (serv_addr.SIN_ADDR), ipbuflen-1); - return TRUE; - } else { - return FALSE; - } -} - - - - -/* - * Purpose: Get the platform on which this client is running - * - * Parameters: - * none - * - * Returns: - * the client's platform, or NI_PLATFORM_UNKNOWN - * - * - * Description: - * Calculate what platform this client is running on. - * - * - * Note: - * Although the initial implementation of this function - * calculates the platform-type at compile-time, it is - * legitimate to perform some computation at run time, e.g., - * to determine whether this client is using a particular - * low-level driver. - * - * The dispatcher and servers should not rely on the - * information which is received for platform-type, because - * the client may be lying, either because of a coding error - * or malice on the part of a client developer. - */ - -NLM_EXTERN Int2 NI_GetPlatform (void) -{ - static Boolean alreadyInited = FALSE; - static Int2 retval; - - if (alreadyInited) - { - return retval; - } - - alreadyInited = TRUE; - - retval = NI_PLATFORM_UNKNOWN; - -#ifdef NETP_INET_MACTCP - retval = NI_PLATFORM_MAC; -#endif - -#ifdef OS_VMS -#ifdef NETP_INET_TGV - retval = NI_PLATFORM_VMS_TGV; -#endif -#ifdef NETP_INET_TWG - retval = NI_PLATFORM_VMS_TWG; -#endif -#ifdef NETP_INET_WPW - retval = NI_PLATFORM_VMS_WPW; -#endif -#ifdef NETP_INET_UCX - retval = NI_PLATFORM_VMS_UCX; -#endif -#ifdef OS_AXP_VMS - retval = NI_PLATFORM_AXP_OPENVMS; -#endif -#endif /* OS_VMS */ - -#ifdef OS_UNIX - retval = NI_PLATFORM_GENERIC_UNIX; -#ifdef PROC_IBM370 - retval = NI_PLATFORM_IBM370AIX; -#endif -#ifdef OS_UNIX_SUN - retval = NI_PLATFORM_SUN; -#endif -#if defined(OS_UNIX_OSF1) && defined(PROC_ALPHA) - retval = NI_PLATFORM_ALPHA_OSF1; -#endif -#ifdef COMP_AUX - retval = NI_PLATFORM_AUX; -#endif -#if defined(COMP_CRAY) && defined(PROC_YMP) - retval = NI_PLATFORM_CRAY; -#endif -#ifdef PROC_CONVEX - retval = NI_PLATFORM_CONVEX; -#endif -#if defined(PROC_HPPA) && !defined(OS_UNIX_LINUX) - retval = NI_PLATFORM_HPUX; -#endif -#ifdef OS_UNIX_NEXT - retval = NI_PLATFORM_NEXT; -#endif -#if defined(PROC_MIPS) && !defined(OS_UNIX_LINUX) - retval = NI_PLATFORM_SGI; -#endif -#ifdef OS_UNIX_ULTRIX - retval = NI_PLATFORM_ULTRIX; -#endif -#if defined(OS_UNIX_SYSV) && defined(PROC_SPARC) - retval = NI_PLATFORM_SYSV_ON_SPARC; -#endif -#ifdef OS_UNIX_AIX - retval = NI_PLATFORM_AIX; -#endif -#ifdef OS_UNIX_LINUX -#ifdef PROC_ALPHA - retval = NI_PLATFORM_LINUX_ALPHA; -#else - retval = NI_PLATFORM_LINUX; -#endif -#endif -#ifdef OS_UNIX_NETBSD - retval = NI_PLATFORM_NETBSD; -#endif -#ifdef OS_UNIX_FREEBSD - retval = NI_PLATFORM_FREEBSD; -#endif -#endif /* OS_UNIX */ - -#ifdef OS_DOS - retval = NI_PLATFORM_DOS; -#ifdef WIN16 - retval = NI_PLATFORM_WIN16; -#endif -#ifdef NETP_INET_NEWT - retval = NI_PLATFORM_WIN_NEWT; -#endif -#ifdef NETP_INET_PCNFS - retval = NI_PLATFORM_WIN_PCNFS; -#endif -#ifdef WINSOCK - retval = NI_PLATFORM_WIN_WINSOCK; -#endif -#endif /* OS_DOS */ - -#ifdef OS_WINNT - retval = NI_PLATFORM_WINNT; -#endif - - return retval; -} - - -/* - * Purpose: Set the "identity" of this client - * - * Parameters: - * disp A pointer to the dispatcher structure - * user New Username - * group New Groupname - * domain New DomainName - * - * Returns: - * 0, always - * - * - * Description: - * Allocate the space for the "UID" structure, if not already - * allocated, and populate it with the user name, group name, - * and domain name. - */ - -static Int2 -SetIdentity(NI_DispatcherPtr disp, CharPtr user, CharPtr group, CharPtr domain) -{ - if (disp == NULL) - return 0; - - if (disp->identity == NULL) - disp->identity = NI_MakeUid(); - - if (disp->identity->username != NULL) - MemFree(disp->identity->username); - disp->identity->username = StringSave(user); - if (disp->identity->group != NULL) - MemFree(disp->identity->group); - if (group != NULL) - disp->identity->group = StringSave(group); - else - disp->identity->group = NULL; - if (disp->identity->domain != NULL) - MemFree(disp->identity->domain); - disp->identity->domain = StringSave(domain); - return 0; -} /* SetIdentity */ - - - -/* - * Purpose: Copy from the "identity" UID to the specified UID data struct - * - * Parameters: - * disp A pointer to the dispatcher structure - * uid UID structure to be copied into - * - * Returns: - * -1, if invalid arguments - * 0, otherwise - * - * - * Description: - * Copy fields from the "identity" UID data structure into the - * UID data structure provided by the caller. - */ - -static Int2 -CopyIdentity(NI_DispatcherPtr disp, NI_UidPtr uid) -{ - if (disp == NULL || disp->identity == NULL || uid == NULL) - return -1; - if (uid->username != NULL) - MemFree(uid->username); - uid->username = StringSave(disp->identity->username); - if (uid->group != NULL) - MemFree(uid->group); - uid->group = StringSave(disp->identity->group); - if (uid->domain != NULL) - MemFree(uid->domain); - uid->domain = StringSave(disp->identity->domain); - return 0; -} /* CopyIdentity */ - - - -/* - * Purpose: Select the next available port within the given range, - * and bind a socket to it. - * - * Parameters: - * sok Socket to be bound to a port (INPUT) - * sokadr Socket data structure to be populated (OUTPUT) - * loport Minimum acceptable port number - * hiport Maximum acceptable port number - * - * Returns: - * 0, if unable to bind to a port - * the selected ("bound") port number, otherwise - * - * - * Description: - * Iterate through the range of acceptable port numbers, until - * an unused port number can be selected to which the socket - * can be bound. - */ - -static Uint2 -bindPort(int sok, struct sockaddr_in PNTR sokadr, Int2 loport, Int2 hiport, Uint4 remoteHost) -{ - int status; -#ifdef NETP_INET_MACTCP - int delta = 0; - Char buf[20]; -#endif - - if (hiport == 0) - hiport = loport; - if (loport > hiport) - return 0; - -#ifdef NETP_INET_MACTCP - /* use a hint from the configuration file to avoid port # conflicts */ - if (hiport > loport && GetAppParam("NCBI", "NET_SERV", "PORT_DELTA", "0", - buf, sizeof buf) > 0) - { - delta = atoi(buf); - loport += delta % (hiport - loport); - sprintf (buf, "%d", delta + 1); - SetAppParam("NCBI", "NET_SERV", "PORT_DELTA", buf); - } -#endif - - MemFill((VoidPtr) sokadr, '\0', sizeof(struct sockaddr_in)); - sokadr->sin_family = AF_INET; - sokadr->sin_addr.s_addr = INADDR_ANY; - - while (loport <= hiport) { - sokadr->sin_port = htons(loport); -#ifdef NETP_INET_NEWT - if ((status = NI_BIND(sok, sokadr, sizeof(struct sockaddr_in), htonl(remoteHost))) == 0) -#else - if ((status = NI_BIND(sok, (struct sockaddr PNTR) sokadr, sizeof(struct sockaddr_in), htonl(remoteHost))) == 0) -#endif /* NETP_INET_NEWT */ - return (Uint2) ntohs(sokadr->sin_port); - else { -#ifdef NETP_INET_NEWT - SOCK_ERRNO = ABS(status); -#endif - loport++; - } - } - return 0; -} /* bindPort */ - - - -/* SERVER FUNCTIONS */ - -static int writepipe PROTO((int fd, char *buf, int len)); - -/* - * Purpose: Write a message on the pipe from a child server application - * process to its parent NCBID. - * - * Parameters: - * fd Pipe file descriptor - * buf Buffer to be written - * len Length of buffer - * - * Returns: - * 0, if unable to write because the pipe is full - * number of bytes written, otherwise - * - * - * Description: - * Write the specified number of bytes to a pipe, and handle - * multiple write attempts if necessary, to handle the case where - * a write() may be interrupted by a signal. - * - * Note: - * This routine is only used by a child process after it has been - * forked and before it has been execed. - */ - -static int -writepipe(int fd, char *buf, int len) -{ - int byteswrit; - - WriteAgain: - if ((byteswrit = write(fd, buf, len)) < 0) { - switch (errno) { - case EINTR: - goto WriteAgain; - - case EWOULDBLOCK: - default: - return 0; - } - } - - return byteswrit; -} /* writepipe */ - -static Int2 StandAlonePort(void) -{ -#ifdef OS_UNIX - CharPtr env; - if ((env = getenv("NI_STANDALONE_SERVER")) != NULL) - return (Int2)atoi(env); -#endif - return 0; -} - - -/* - * Purpose: Send an "ACK" from a child server application process to its - * parent NCBID. - * - * Returns: - * 0, if the ACK was sent successfully - * -1, otherwise - * - * - * Description: - * Write an "ACK" from a child server application process to its - * parent NCBID, on the pipe connecting the two processes. - * - * Note: - * This routine should be called by a child process after it has - * determined that it has started successfully. At most one - * of NI_ServerACK() and NI_ServerNACK() may be called. - */ - -#define TEMP_BUF_SIZ 256 - -NLM_EXTERN int NI_ServerACK(void) -{ -#if 0 - int wstat; - Char temp_buf[TEMP_BUF_SIZ]; - Int2 port; - - if ((port = StandAlonePort()) == 0) - { /* not stand-alone */ - sprintf(temp_buf, PIPE_MSG_FMT, NIE_SERVACK, "OK"); - if ((wstat = writepipe(STDPIPE, temp_buf, strlen(temp_buf))) <= 0) { - ni_errno = NIE_PIPEIO; - strcpy(ni_errtext, (wstat == 0) ? "EWOULDBLOCK" : strerror(errno)); - return -1; - } - } else { /* stand-alone */ -#ifdef OS_UNIX - /* non-UNIX platforms currently experience compilation errors */ - struct sockaddr_in soktAddr; - NI_HandPtr hp; - int sok; - int status; - struct sockaddr_in sockaddr; - int soktLen; - CharPtr security; - int one = 1; /* for SO_REUSEADDR */ - - hp = MsgMakeHandle(TRUE); - NI_SETBLOCKING(hp->sok); - - MemFill(&sockaddr, '\0', sizeof(struct sockaddr_in)); - sockaddr.sin_family = AF_INET; - sockaddr.sin_addr.s_addr = INADDR_ANY; - sockaddr.sin_port = htons(port); - - if (setsockopt(hp->sok, SOL_SOCKET, SO_REUSEADDR, (char *) &one, - sizeof(one)) < 0) - { - Message (MSG_ERROR, "Unable to set socket re-usability, errno = %d", errno); - } - -#ifdef NETP_INET_NEWT - if ((status = bind(hp->sok, &sockaddr, sizeof(struct sockaddr_in))) == 0) -#else - if ((status = bind(hp->sok, (struct sockaddr PNTR) &sockaddr, sizeof(struct sockaddr_in))) != 0) -#endif /* NETP_INET_NEWT */ - { /* error */ - ErrPostEx(SEV_FATAL,0,0, - "Bind failed on socket %d, status = %d, errno = %d", - hp->sok, status, errno); - return -1; - } - - NI_LISTEN(hp->sok, 1); - close(0); /* so that accept() will return 0 */ - soktLen = sizeof(soktAddr); - - /* accept the connection */ - if ((sok = NI_ACCEPT(hp->sok, (struct sockaddr *) &soktAddr, &soktLen)) < 0) - { /* error */ - ErrPostEx(SEV_FATAL,0,0, "Accept returned bad file descriptor %d, errno = %d", - sok, errno); - return -1; - } - LOG_SOCKET(sok, TRUE); - NI_SETNONBLOCKING(sok); - MsgDestroyHandle(hp); - if ((security = getenv("NI_STANDALONE_SECURITY")) != NULL) - { /* security must be substring of client address */ - if (StrNCmp(inet_ntoa(soktAddr.SIN_ADDR), security, StrLen(security)) != 0) - { - close(sok); - ErrPostEx(SEV_FATAL,0,0, "Security violation from IP address %s, security = %s\n", - inet_ntoa(soktAddr.SIN_ADDR), security); - return -1; - } - } -#endif /* OS_UNIX */ - } -#endif /* 0 */ - - return 0; -} /* NI_ServerACK */ - - - -/* - * Purpose: Send an "NACK" from a child server application process to its - * parent NCBID. - * - * Returns: - * 0, if the NACK was sent successfully - * -1, otherwise - * - * - * Description: - * Write an "NACK" from a child server application process to its - * parent NCBID, on the pipe connecting the two processes. - * - * Note: - * This routine should be called by a child process after it has - * determined that it will be unable to start successfully. In - * the event that this routine is not called (or is unable to - * perform its function), a timeout mechanism must be relied - * upon for the NCBID to realize that a child has started - * unsuccessfully. - * - * At most one of NI_ServerACK() and NI_ServerNACK() may be called. - */ - -NLM_EXTERN int NI_ServerNACK(CharPtr err_text) -{ -#if 0 - int wstat; - Char temp_buf[TEMP_BUF_SIZ]; - - sprintf(temp_buf, PIPE_MSG_FMT, NIE_SERVNACK, err_text); - if (StandAlonePort() == 0) - { /* not stand-alone */ - if ((wstat = writepipe(STDPIPE, temp_buf, strlen(temp_buf))) <= 0) { - ni_errno = NIE_PIPEIO; - strcpy(ni_errtext, (wstat == 0) ? "EWOULDBLOCK" : strerror(errno)); - return -1; - } - } else { /* stand-alone */ - ErrPostEx(SEV_FATAL,0,0, "Stand-alone server failed startup {%s}", temp_buf); - return -1; - } -#endif /* 0 */ - - return 0; -} /* NI_ServerNACK */ - -static Int2 LIBCALLBACK NI_AsnWriteSTDOUT(Pointer p,CharPtr buf,Uint2 len) -{ - int bytes = write(STDOUT, buf, len); - - return (Int2)(bytes > 0 ? bytes : 0); -} - - -/* - * Purpose: Open the stream to be used for ASN I/O between a server - * application process and its client. - * - * Returns: - * NULL, if something went wrong - * a pointer to the Msg structure, otherwise - * - * - * Description: - * Create a "Msg" structure for ASN I/O, and associate the Msg's - * socket with the standard input file descriptor (STDIN), which is - * the communication socket between the server application process - * and its client. - * - * Note: - * This routine should only be called by a child application - * process (not by a client). - */ - -NLM_EXTERN NI_HandPtr NI_OpenASNIO(void) -{ - NI_HandPtr hp; - CharPtr agent; - - if ((hp = MsgMakeHandle(FALSE)) == NULL) - return NULL; - - MsgSetReadTimeout(hp, NI_SERV_LISTEN_TIMEOUT); /* set default for servers to listen */ - - if ((hp->sok = dup(STDIN)) == -1) { - MsgDestroyHandle(hp); - return NULL; - } - - agent = getenv("HTTP_USER_AGENT"); - if(agent){ - hp->waip->writefunc=NI_AsnWriteSTDOUT; - } - - LOG_SOCKET(hp->sok, TRUE); - { - CharPtr buf; - Char key[8]; - - if ((buf = getenv("NI_DESKEY")) != NULL && - (AsnTypeStringToHex(buf, StrLen(buf), key, NULL) == 0)) - { - NI_SetupDESEncryption(hp, (UcharPtr) key); - } - } - return hp; -} /* NI_OpenASNIO */ - - - -/* - * Purpose: Close the ASN stream between a server application process and - * its client. - * - * Returns: - * -1 if something went wrong - * 0, otherwise - * - * - * Description: - * Close the stream by closing the socket and deleting the - * associated data structures. - * - * Note: - * This routine should only be called by a child application - * process (not by a client). - */ - -NLM_EXTERN Int2 NI_CloseASNIO(NI_HandPtr hp) -{ - return MsgDestroyHandle(hp); -} /* NI_CloseANSIO */ - - - -/* MISC FUNCTIONS */ - -/* sokselectr and sokselectw are not prototyped in ni_lib.h */ - -/* - * Purpose: Wait for a "read" socket to become ready to read, or for - * a timeout to occur. - * - * Returns: - * -1 if something went wrong - * 0, otherwise - * - * - * Description: - * Wait for the indicated "read" socket to be marked as - * "selected" by a socket() call. - * - * Note: - * This routine is presently unused. - * - * The timeout mechanism is not exactly enforced, because - * received signals could result in a longer timeout period. - */ - -int sokselectr(int fd) -{ - fd_set rfds; - int ready; - struct timeval timeout; - - FD_ZERO(&rfds); - FD_SET(fd, &rfds); - timeout.tv_sec = NI_SELECT_TIMEOUT; - timeout.tv_usec = 0; - while ((ready = select(fd+1, &rfds, NULL, NULL, &timeout)) == -1) { - switch (SOCK_ERRNO) { - case EINTR: - continue; - - default: - ni_errno = NIE_MISC; - sprintf(ni_errtext, "%s", strerror(SOCK_INDEX_ERRNO)); - return -1; - } - } - if (ready == 0) { - strcpy(ni_errtext, ni_errlist[ni_errno]); - ni_errno = NIE_TIMEOUT; - return -1; - } - if (FD_ISSET(fd, &rfds)) - return 0; - else - return -1; -} /* sokselectr */ - - - -/* - * Purpose: Wait for a "write" socket to become ready to write, or for - * a timeout to occur. - * - * Returns: - * -1 if something went wrong - * 0, otherwise - * - * - * Description: - * Wait for the indicated "write" socket to be marked as - * "selected" by a socket() call. - * - * Note: - * This routine can be used when waiting for a connect() to go - * through successfully. - * - * The timeout mechanism is not exactly enforced, because - * received signals could result in a longer timeout period. - */ - -int sokselectw(int fd, int seconds) -{ - fd_set wfds; - int ready; - struct timeval timeout; - - FD_ZERO(&wfds); - FD_SET(fd, &wfds); - timeout.tv_sec = NI_SELECT_TIMEOUT; - if (seconds > 0) /* override default */ - timeout.tv_sec = seconds; - timeout.tv_usec = 0; - while ((ready = select(fd+1, NULL, &wfds, NULL, &timeout)) == -1) { - switch (SOCK_ERRNO) { - case EINTR: - continue; - - default: - ni_errno = NIE_MISC; - sprintf(ni_errtext, "%s", strerror(SOCK_INDEX_ERRNO)); - return -1; - } - } - if (ready == 0) { - strcpy(ni_errtext, ni_errlist[ni_errno]); - ni_errno = NIE_TIMEOUT; - return -1; - } - if (FD_ISSET(fd, &wfds)) - { -#ifdef OS_UNIX -#ifndef OS_UNIX_BEOS - int err; -# ifdef HAVE_SOCKLEN_T - socklen_t optlen; -# else - int optlen; -# endif - - optlen = sizeof(int); - if (getsockopt(fd, SOL_SOCKET, SO_ERROR, (char *) &err, &optlen) >= 0 && - err != 0) /* check for an error */ - return -1; /* got some error */ -#endif -#endif /* OS_UNIX */ - return 0; - } - else - return -1; -} /* sokselectw */ - - - -/* - * Purpose: Parse the error number from an ASN error string which was - * formatted at a low level. - * - * Returns: - * -1, if unable to parse the string - * the parsed error number, otherwise - * - * - * Description: - * Parse the error number from an ASN error string which was - * prepared by the ASN tools, and formatted at a low level. - * - * Note: - * The parsing mechanism is dependent upon any future format - * changes which may occur in the ASN tools. - */ - -int getAsnError(char *str) -{ - int errnum; - - if (sscanf(str, "%*s %*s %*s [-%d]", &errnum) < 1) - errnum = -1; - return errnum; -} /* getAsnError */ - - -/* - * Purpose: Set the Connection ID file pointer - * - * Parameters: - * fp The new value for the file descriptor - * - * - * Description: - * Set the Connection ID file pointer. This is used to update - * the connection ID each time it is updated, to keep the - * value current. - * - * Note: - * In reality, this should only be called by the dispatcher. - */ - -void SetConFilePtr (FILE *fp) -{ - conid_fp = fp; -} - - -/* - * Purpose: Update the connection ID file - * - * Parameters: - * conid The new connection ID value - * - * - * Description: - * Update the connection ID file, and be sure to flush the stream, - * to try to ensure that output really occurs. - * - * Note: - * Should be called every time the "next" connection ID is - * modified. - */ - -NLM_EXTERN void WriteConFile (Uint4 conid) -{ - if (conid_fp != NULL) { - (void) fseek(conid_fp, 0L, SEEK_SET); - (void) FileWrite((CharPtr) &conid, 1, sizeof(conid), conid_fp); - (void) fflush (conid_fp); - } -} - - -/* - * Purpose: Close the connection ID file - * - * - * Description: - * Close the connection ID file. - * to try to ensure that output really occurs. - * - * Note: - * In reality, this should only be called by the dispatcher. - */ - -void CloseConFile (void) -{ - if (conid_fp != NULL) { - fclose (conid_fp); - conid_fp = NULL; - } -} - - - -/* - * Purpose: Check for expired timers - * - * - * Description: - * For every expired timer, call the specified timer - * callback function, which is in turn responsible for cancelling - * the timer. - * - * Note: - * Timer checks only take place when this function is called. - * Therefore, it is the responsibility of an application to - * intermitently call this function. This could be done, e.g. - * using the UNIX alarm clock mechanism, or inside of an event - * loop. - * - * The order of operations is significant here, because the - * hook function must cancel the timer. To perform the linked - * list traversal in a less careful manner could result in - * illegal memory accesses. - * - * The timer list in managed in a very unsophisticated manner; - * if lots of timers were anticipated, the list would be - * maintained sorted by time, and all of the timer functions - * would need to maintain and traverse the timer list based - * upon this criterion. - * - * A count is used as a failsafe mechanism against infinite loops. - */ - -#define NI_MAX_TIMERS 1000 - -NLM_EXTERN void NI_ProcessTimers(void) -{ - NodePtr t; - NodePtr tnew; - NI_TimerPtr timer; - NodePtr timersToBeFired = NULL; - time_t curtime; - int count = NI_MAX_TIMERS; - - if ((t = timerHead) == NULL) - { - return; - } - - curtime = GetSecs(); - - do { - timer = (NI_TimerPtr) t->elem; - tnew = ListGetNext(t); - if (timer != NULL && timer->timeout != NULL_TIMER && - timer->timeout <= curtime) - { /* note the timer to be fired */ - timersToBeFired = ListInsert(timer, timersToBeFired); - } - if (t == tnew) - { /* data structure error, time to bail out */ - break; - } - t = tnew; - } while (t != timerHead && t != NULL && --count > 0); - - if ((t = timersToBeFired) == NULL) - return; - - count = NI_MAX_TIMERS; - - do { - timer = (NI_TimerPtr) t->elem; - tnew = ListGetNext(t); - - /* mark the timer so it won't fire again */ - timer->timeout = NULL_TIMER; - if (timer->hook != NULL) - { - timer->hook(timer->hookParam); - } - t = tnew; - } while (t != timersToBeFired && t != NULL && --count > 0); - - ListDelete(timersToBeFired); -} - - -/* - * Purpose: Return the time when the next timeout will occur - * - * Returns: The time, in seconds, when the next scheduled timeout will - * occur, or NULL_TIMER, if there are no timers set. - * - * Description: - * Return the time when the next timer timeout will occur. - * This information is typically used with the select() - * system call, to ensure that a timeout parameter is passed - * to select() which is sufficiently short to ensure that - * the application will call NI_ProcessTimers() at an - * appropriate time. - * - * Note: - * The timer list in managed in a very unsophisticated manner; - * if lots of timers were anticipated, the list would be - * maintained sorted by time, and all of the timer functions - * would need to maintain and traverse the timer list based - * upon this criterion. - */ - -NLM_EXTERN time_t NI_GetNextWakeup(void) -{ - time_t next_wakeup = NULL_TIMER; - NodePtr t; - NI_TimerPtr timer; - - NI_ProcessTimers(); - - if ((t = timerHead) == NULL) - { - return NULL_TIMER; - } - - do { - t = ListGetNext(t); - timer = (NI_TimerPtr) t->elem; - if (next_wakeup == NULL_TIMER || (timer->timeout != NULL_TIMER && - timer->timeout < next_wakeup)) - { - next_wakeup = timer->timeout; - } - } while (t != timerHead && t != NULL); - - return next_wakeup; -} - - -/* - * Purpose: Set a timer - * - * Parameters: - * timeout The time in seconds when the timer should expire - * hook Callback to be called when (if) the timer expires - * hookParam Parameter to be passed to caller's hook when the timer expires - * - * - * Returns: The "timer ID", really a pointer to the timer data structure - * - * - * Description: - * Sets a timer with the appropriate parameters. - * - * Note: - * The timer list in managed in a very unsophisticated manner; - * if lots of timers were anticipated, the list would be - * maintained sorted by time, and all of the timer functions - * would need to maintain and traverse the timer list based - * upon this criterion. - * - * It is the responsibility of the application (usually the - * hook function) to cancel the timer. - */ - -NodePtr -NI_SetTimer(time_t timeout, NI_TimeoutHook hook, Pointer hookParam) -{ - NodePtr t; - NI_TimerPtr timer; - - timer = (NI_TimerPtr) MemNew(sizeof(NI_Timer)); - timer->timeout = timeout; - timer->hook = hook; - timer->hookParam = hookParam; - t = ListInsert(timer, timerHead); - timerHead = t; - - return t; -} - - -/* - * Purpose: Cancel a timer - * - * Parameters: - * timerID The ID of the timer - * - * - * Description: - * Cancel the specified timer by deleting the entry and its - * associated data structure. - * - * Note: - * The timer list in managed in a very unsophisticated manner; - * if lots of timers were anticipated, the list would be - * maintained sorted by time, and all of the timer functions - * would need to maintain and traverse the timer list based - * upon this criterion. - */ - -NLM_EXTERN void NI_CancelTimer(NodePtr timerId) -{ - if (timerId != NULL) - { - MemFree (timerId->elem); - timerHead = ListDelete(timerId); - } -} - - -/* - * Purpose: Set an activity hook, to inform the application of key events - * - * Parameters: - * hook The hook (callback function) - * - * - * Description: - * Setup a hook function which will subsequently be used to - * inform the application of various events; these currently - * include: - * * Connection to dispatcher - * * Disconnection from dispatcher - * * Service connection - * * Service disconnection - * * Bytes written - * * Bytes read - * - * Note: - * This hook is global for the running application. - */ - -NLM_EXTERN void NI_SetActivityHook (NI_NetServHook hook) -{ - activityHook = hook; -} - - -/* - * Purpose: Return the current activity hook - * - * - * Description: - * Return the current activity hook. This is only intended - * to be used internally by the Network Services library. - * This function is used to avoid making activityHook into a - * global variable. - */ - -NLM_EXTERN NI_NetServHook NI_ActivityHook (void) -{ - return activityHook; -} - - -/* - * Purpose: Initialize socket management - * - * Description: - * If not already initialized, initialize the socket management - * data structures - */ - -static void -InitLogSocket() -{ - static Boolean inited = FALSE; - - if (! inited) - { - FD_ZERO(&openfds); - inited = TRUE; - } -} - - -/* - * Purpose: Count the number of open sockets - */ - -NLM_EXTERN Int2 NI_SocketsOpen(void) -{ - int sok; - Int2 count = 0; - - InitLogSocket(); - for (sok = 0; sok < FD_SETSIZE; sok++) - { - if (FD_ISSET(sok, &openfds)) - count++; - } - return count; -} - -/* - * Purpose: Log each socket transaction - */ - -NLM_EXTERN void NI_LogSocket(int sok, Boolean opening, CharPtr filename, int lineno) -{ - InitLogSocket(); - - if (sok == INVALID_SOCKET || sok < 0 || sok >= FD_SETSIZE) - { -#ifndef NETP_INET_WSOCK - /* FD_SETSIZE doesn't accurately describe the socket range for - WinSock applications, so don't generate misleading error msgs */ - ErrPostEx(SEV_WARNING,0,0, "Bad %s operation on socket %d at %s:%d", - opening ? "opening" : "closing", sok, filename, lineno); -#endif /* NETP_INET_WSOCK */ - return; - } - - if (opening) - { - TRACE("Just opened socket %d at %s:%d\n", sok, filename, lineno); - if (FD_ISSET(sok, &openfds)) - { - ErrPostEx(SEV_ERROR,0,0, "Duplicate open of socket %d at %s:%d", - sok, filename, lineno); - } else { - FD_SET(sok, &openfds); - } - } else { - TRACE("Trying to close socket %d at %s:%d\n", sok, filename, lineno); - if (FD_ISSET(sok, &openfds)) - { - FD_CLR(sok, &openfds); - } else { - ErrPostEx(SEV_ERROR,0,0, "Duplicate close of socket %d at %s:%d", - sok, filename, lineno); - } - } - -#ifdef _DEBUG - {{ - int localsok; - for (localsok = 0; localsok < FD_SETSIZE; localsok++) { - if (FD_ISSET(localsok, &openfds)) { - TRACE("Socket %d is currently open\n", localsok); - } - } - }} -#endif /* _DEBUG */ -} - - -/* Exported table of interface functions - */ -static const NIInterface s_NII_Dispatcher = { - s_GenericInit, - s_SetDispatcher, - s_GenericGetService, - s_ServiceDisconnect, - s_EndServices -}; -const NIInterface *g_NII_Dispatcher = &s_NII_Dispatcher; - diff --git a/network/nsclilib/ni_encr.c b/network/nsclilib/ni_encr.c deleted file mode 100644 index 332670a0..00000000 --- a/network/nsclilib/ni_encr.c +++ /dev/null @@ -1,1005 +0,0 @@ -/* -* =========================================================================== -* -* PUBLIC DOMAIN NOTICE -* National Center for Biotechnology Information -* -* This software/database is a "United States Government Work" under the -* terms of the United States Copyright Act. It was written as part of -* the author's official duties as a United States Government employee and -* thus cannot be copyrighted. This software/database is freely available -* to the public for use. The National Library of Medicine and the U.S. -* Government have not placed any restriction on its use or reproduction. -* -* Although all reasonable efforts have been taken to ensure the accuracy -* and reliability of the software and data, the NLM and the U.S. -* Government do not and cannot warrant the performance or results that -* may be obtained by using this software or data. The NLM and the U.S. -* Government disclaim all warranties, express or implied, including -* warranties of performance, merchantability or fitness for any particular -* purpose. -* -* Please cite the author in any work or product based on this material. -* -* =========================================================================== -* -* File Name: ni_encr.c -* -* Author: Epstein -* -* Version Creation Date: 2/14/94 -* -* $Revision: 6.2 $ -* -* File Description: -* Supports RSAREF-based encryption for NCBI Network Services client-server -* architecture -* -* -* Modifications: -* -------------------------------------------------------------------------- -* 02/22/94 Epstein Fix reading of public keys from config. file, and -* initialization of random data structure for RSA -* encryption. -* 03/04/94 Epstein Reduce memory leakage, avoid ErrPost error if unable -* to open public-key file. -* 03/09/94 Epstein Add length parameter to NI_LoadPrivKey(), add code -* which allows {Transient}SetAppParam() to provide -* some help in providing an unbreakable key. Also -* use high-granularity timing in generating random -* key, where available. -* 07/14/94 Epstein Pad buffer more efficiently in DoDesWrite(). -* 02/22/96 Epstein Correct boundary condition in DoDesRead() to refrain -* from trying to decrypt a buffer when we don't have -* at least 8 bytes of input to work with. -* -* $Log: ni_encr.c,v $ -* Revision 6.2 1998/06/23 19:45:19 vakatov -* [WIN32,MSVC++] Made some functions be DLL-exportable -* -* Revision 6.1 1997/12/02 16:09:37 epstein -* fix use of sprintf -* -* Revision 4.2 1996/02/22 18:43:03 epstein -* Correct boundary condition in DoDesRead() -* -* Revision 4.1 1995/10/06 12:51:34 epstein -* cleaned-up port to MS Windows -* -------------------------------------------------------------------------- -*/ - -#include <ncbi.h> -#include <ni_types.h> -#include <ni_msg.h> -#include <global.h> -#include <des.h> -#include <rsaref.h> -#ifdef OS_UNIX -#include <sys/time.h> -#endif /* OS_UNIX */ - -#define ENCR_DES_TYPE 1 - -#define ENCR_DES_STATE_IDLE 0 -#define ENCR_DES_STATE_GOT1LENBYTE 1 -#define ENCR_DES_STATE_INSTREAM 2 - - - - -/* - * Purpose: Encrypts a buffer using DES - * - * Parameters: - * encr Encryption data structure, includes Cypher-block-chaining info - * buf Input buffer - * len Length of buf - * tmpbuf Output buffer - * - * Returns: - * The length of the resulting encrypted data - * - * Description: - * Encodes the specified input buffer using two bytes which contain - * the length of the _plaintext_ data which follows, followed by - * the encrypted text. Thus, for example, an input buffer of - * length 9 will result in 0x0, 0x9, followed by 16 bytes of - * encrypted data. - * - * Note: - * For safety, the output buffer must be large enough to accomodate - * the two-byte header, plus the length of the input buffer, plus - * an additional seven bytes. - * - * DES cipher-block chaining (CBC) is used, and the CBC information - * is encoded in the desWriteContext data structure. - */ - -static Int4 -DoDesWrite(NI_EncrDataPtr encr, CharPtr buf, int len, CharPtr tmpbuf) -{ - int encrLen; - UcharPtr encrBuf; - UcharPtr outbuf = (UcharPtr) tmpbuf; - - outbuf[0] = len / 256; /* high order byte */ - outbuf[1] = len % 256; /* low order byte */ - - encrLen = ((len + 7) / 8) * 8; - encrBuf = (UcharPtr) MemNew(encrLen); - - /* pad with zeros */ - MemSet ((CharPtr) &encrBuf[len], '\0', encrLen - len); - - MemCpy ((CharPtr) encrBuf, buf, len); - DES_CBCUpdate ((DES_CBC_CTX PNTR) encr->desWriteContext, &outbuf[2], - encrBuf, encrLen); - MemFree (encrBuf); - return (encrLen + 2); -} - - -/* - * Purpose: Encryption write-filter for DES - * - * Parameters: - * mhvoid Pointer to message handle data structure - * buf Input buffer - * len Length of buf - * tmpbuf Output buffer - * - * Returns: - * The length of the resulting encrypted data - * - * Description: - * Validates the input and then processes the data using - * DoDesWrite(). - */ - -static Int4 LIBCALL -DesWriteFilt(VoidPtr mhvoid, CharPtr buf, int len, CharPtr tmpbuf) -{ - NI_HandPtr mh = (NI_HandPtr) mhvoid; - - if (len <= 0 || tmpbuf == NULL || buf == NULL || mh == NULL || - mh->encryption == NULL) - return 0; - return DoDesWrite(mh->encryption, buf, len, tmpbuf); -} - - -/* - * Purpose: Decrypts a buffer using DES - * - * Parameters: - * encr Encryption data structure, includes Cypher-block-chaining info - * buf Input buffer containing encrypted data, and output plaintext - * bytesRead Length of input data in buf - * len Max # of bytes which will fit in buf (requested read length) - * - * Returns: - * The length of the resulting plaintext which has been processed - * - * Description: - * Decodes the specified input buffer, using a protocol which - * consists of two bytes of length information (realDataLeft) - * followed by bytesToRead bytes of encrypted data, where bytesToRead - * is realDataLeft padded out to a multiple of eight bytes. - * - * The algorithm uses a state machine to process as much of the input - * buffer as possible, and to store the remainder of the unprocessed - * input data in encr->deferredData. - * - * - * Note: - * - * DES cipher-block chaining (CBC) is used, and the CBC information - * is encoded in the desReadContext data structure. Also note that - * the history of the CBC consists of the entire communications - * session between client and server up to this point in time. - */ - -static Int4 -DoDesRead(NI_EncrDataPtr encr, CharPtr buf, int bytesRead, int len) -{ - UcharPtr scratchInbuf; - UcharPtr ip; /* ptr to next byte in scratchInbuf */ - Int4 retval; - Int2 roomInBuffer; - Int2 avail; - Int2 bytesToDecrypt; - Int2 bytesToCopy; - UcharPtr scratchOutbuf; - Boolean done; - - if (bytesRead <= 0 || buf == NULL || encr == NULL) - return 0; - - if (encr->state == ENCR_DES_STATE_IDLE) - { - encr->numDeferredBytes = 0; - encr->realDataLeft = 0; - encr->bytesToRead = 0; - } - - if ((scratchInbuf = (UcharPtr) MemNew(bytesRead + encr->numDeferredBytes)) == - NULL) - return 0; - ip = scratchInbuf; - - MemCpy ((CharPtr) scratchInbuf, (CharPtr) encr->deferredData, - encr->numDeferredBytes); - MemCpy ((CharPtr) &scratchInbuf[encr->numDeferredBytes], buf, bytesRead); - bytesRead += encr->numDeferredBytes; - encr->numDeferredBytes = 0; - retval = 0; - done = FALSE; - - while (bytesRead > 0 && ! done) - { - switch (encr->state) { - case ENCR_DES_STATE_IDLE: - if (bytesRead == 1) - { - encr->realDataLeft = *ip++; - encr->state = ENCR_DES_STATE_GOT1LENBYTE; - done = TRUE; - bytesRead--; - } else { - encr->realDataLeft = ip[0] * 256 + ip[1]; - encr->bytesToRead = ((encr->realDataLeft + 7) / 8) * 8; - encr->numDeferredBytes = 0; - ip += 2; - bytesRead -= 2; - encr->state = ENCR_DES_STATE_INSTREAM; - } - break; - case ENCR_DES_STATE_GOT1LENBYTE: - encr->realDataLeft = encr->realDataLeft * 256 + *ip++; - encr->bytesToRead = ((encr->realDataLeft + 7) / 8) * 8; - encr->numDeferredBytes = 0; - bytesRead--; - encr->state = ENCR_DES_STATE_INSTREAM; - break; - case ENCR_DES_STATE_INSTREAM: - avail = MIN(encr->bytesToRead, bytesRead); - roomInBuffer = (Int2) (len - retval); - bytesToDecrypt = (MIN(roomInBuffer, avail) / 8) * 8; - if (bytesToDecrypt <= 0) - { - if (roomInBuffer >= MAX(encr->realDataLeft, 0) && avail >= 8) - { /* we can squeeze this in, and there's enough to process */ - bytesToDecrypt = 8; - } else { - done = TRUE; - break; - } - } - scratchOutbuf = (UcharPtr) MemNew(bytesToDecrypt); - DES_CBCUpdate ((DES_CBC_CTX PNTR) encr->desReadContext, - scratchOutbuf, ip, bytesToDecrypt); - bytesToCopy = MIN(encr->realDataLeft, bytesToDecrypt); - MemCpy (buf, (CharPtr) scratchOutbuf, bytesToCopy); - MemFree (scratchOutbuf); - buf += bytesToCopy; - retval += bytesToCopy; - ip += bytesToDecrypt; - bytesRead -= bytesToDecrypt; - encr->bytesToRead -= bytesToDecrypt; - encr->realDataLeft -= bytesToDecrypt; - if (encr->bytesToRead <= 0) - { - encr->state = ENCR_DES_STATE_IDLE; - encr->numDeferredBytes = 0; - encr->realDataLeft = 0; - encr->bytesToRead = 0; - } - break; - } - } - - if (bytesRead > 0) - { - encr->numDeferredBytes = bytesRead; - if (bytesRead > sizeof(encr->deferredData)) - { - ErrPostEx(SEV_ERROR, 0, 0, "Too much deferred decryption data %d bytes", bytesRead); - } else { - MemCpy ((CharPtr) encr->deferredData, (CharPtr) ip, bytesRead); - } - } - - MemFree (scratchInbuf); - - return retval; -} - - -/* - * Purpose: DES read filter - * - * Parameters: - * mhvoid Pointer to message handle data structure - * buf Input buffer containing encrypted data, and output plaintext - * bytesRead Length of input data in buf - * len Max # of bytes which will fit in buf (requested read length) - * extra_buf unused, but required for NI_ReadFilt declaration - * extra_buf_len unused, but required for NI_ReadFilt declaration - * - * Returns: - * The length of the resulting plaintext which has been processed - * - * Description: - * Uses DoDesRead() to process input data, and returns to caller - */ - -static Int4 LIBCALL -DesReadFilt(VoidPtr mhvoid, CharPtr buf, int bytesRead, int len, CharPtr PNTR extra_buf, Int4Ptr extra_buf_len) -{ - NI_HandPtr mh = (NI_HandPtr) mhvoid; - - if (bytesRead <= 0 || buf == NULL || mh == NULL || - mh->encryption == NULL) - return 0; - return DoDesRead(mh->encryption, buf, bytesRead, len); -} - - -/* - * Purpose: Setup DES encryption for this message handle - * - * Parameters: - * mh Pointer to message handle data structure - * desKey DES key to be used for the life of this session - * - * Returns: - * TRUE if setup was successful, FALSE otherwise - * - * Description: - * Allocates an encryption data structure to attach to the message - * handle, as well as the RSAREF data structures for both reading - * and writing data. Note that the read and write data structures - * are each handling an independent half-duplex channel, i.e, - * either client->server or server->client data. - * - * Note: - * A caller which uses this function must also call - * NI_DestroyEncrStruct() when it is time to destroy the message - * handle. - */ - -NLM_EXTERN Boolean LIBCALL -NI_SetupDESEncryption(NI_HandPtr mh, UcharPtr desKey) -{ - Uchar iv[8]; - NI_EncrDataPtr encr; - - if (mh->encryption != NULL) - return FALSE; - if ((encr = MemNew(sizeof(*encr))) == NULL) - return FALSE; - mh->encryption = encr; - encr->encrType = ENCR_DES_TYPE; /* the only possibility, for now */ - encr->state = ENCR_DES_STATE_IDLE; - encr->write_filter = DesWriteFilt; - encr->read_filter = DesReadFilt; - encr->desWriteContext = (DES_CBC_CTX PNTR) MemNew(sizeof(DES_CBC_CTX)); - MemSet((CharPtr) iv, '\0', sizeof(iv)); - DES_CBCInit((DES_CBC_CTX PNTR) encr->desWriteContext, desKey, iv, TRUE); - encr->desReadContext = (DES_CBC_CTX PNTR) MemNew(sizeof(DES_CBC_CTX)); - MemSet((CharPtr) iv, '\0', sizeof(iv)); - DES_CBCInit((DES_CBC_CTX PNTR) encr->desReadContext, desKey, iv, FALSE); - - return TRUE; -} - - -/* - * Purpose: Seed the random number generator if necessary - * - * Description: - * If this function has not previously been called, it seeds the NCBI - * random number generator with the best pseudo-random data available - * on all systems, namely the current time in seconds, and a notion - * of the application's process ID. A high-granularity time is - * also included when available. - * - * Note: - * It would be helpful to have another NCBI function which returns - * the highest-granularity time available, e.g., many systems have - * microsecond and/or ticks available. Any other creative data - * available on this system (e.g., for UNIX systems, how many inodes - * are in use in the root filesystem of this computer) would also be - * helpful to help defeat malicious attempts to crack the security - * of this encryption subsystem. - */ - -static void -SetRandomSeed(void) -{ - static Boolean inited = FALSE; - Int4 highGranularity = 0; -#ifdef OS_UNIX - struct timeval tv; - - gettimeofday(&tv, NULL); - highGranularity = tv.tv_usec; -#endif -#ifdef OS_MAC - highGranularity = clock(); -#endif -#ifdef WIN_MSWIN - highGranularity = (Int4) GetCurrentTime(); -#endif - - if (! inited) - { - RandomSeed ((long) (GetSecs() | Nlm_GetAppProcessID() | highGranularity)); - inited = TRUE; - } -} - - - -/* - * Purpose: Initialize an RSAREF random data structure used for RSA encryption - * - * Parameters: - * randomStruct The data structure to be populated - * - * Description: - * Seed the random number generator if necessary, create a random - * R_RANDOM_STRUCT data structure, and populate it with - * pseudo-random data. When available, data from the NCBI config. - * file is exclusive-ORed into each pseudo-random number, so - * that an RSA key cannot subsequently be broken by trying all - * 2^^32 possible values of the random number generator. - */ - -static void InitRandomStruct (randomStruct) -R_RANDOM_STRUCT *randomStruct; -{ - unsigned int bytesNeeded; - long ran; - Int4 seednum = 0; - Char buf[22]; - Char moredata[10]; - - SetRandomSeed(); - R_RandomInit (randomStruct); - - while (1) { - R_GetRandomBytesNeeded (&bytesNeeded, randomStruct); - if (bytesNeeded == 0) - break; - - ran = RandomNum(); - sprintf (buf, "CONFOUND_%ld", (long) seednum); - GetAppParam("NCBI", "NET_SERV", buf, "0", moredata, sizeof moredata); - ran ^= atoi(moredata); - seednum++; - R_RandomUpdate (randomStruct, (UcharPtr) &ran, MIN(bytesNeeded, sizeof ran)); - } -} - - - -/* - * Purpose: Convert pub encryption key from RSAREF format to internal NCBI fmt - * - * Parameters: - * publicKey Key in RSAREF format - * - * Returns: - * Key in NCBI format, or NULL if an error occurred - * - * Description: - * Convert RSAREF public key data structure into a form which is - * suitable for being stored and transmitted in ASN.1 - */ - -static NI_PubKeyPtr -PubKeyToInternalFormat(R_RSA_PUBLIC_KEY PNTR publicKey) -{ - NI_PubKeyPtr retval = (NI_PubKeyPtr) MemNew(sizeof(*retval)); - - if (retval == NULL || publicKey == NULL) - return NULL; - retval->bits = publicKey->bits; - retval->modulus = BSNew(sizeof(publicKey->modulus)); - BSWrite(retval->modulus, (VoidPtr) publicKey->modulus, sizeof(publicKey->modulus)); - retval->exponent = BSNew(sizeof(publicKey->exponent)); - BSWrite(retval->exponent, (VoidPtr) publicKey->exponent, sizeof(publicKey->exponent)); - return retval; -} - - - -/* - * Purpose: Convert pub encryption key from internal NCBI format to RSAREF fmt - * - * Parameters: - * internal Key in NCBI format - * - * Returns: - * Key in RSAREF format, or NULL if an error occurred - * - * Description: - * Produce RSAREF public key data structure from a form which is - * suitable for being stored and transmitted in ASN.1 - */ - -static R_RSA_PUBLIC_KEY PNTR -InternalToPubKeyFormat(NI_PubKeyPtr internal) -{ - R_RSA_PUBLIC_KEY PNTR retval; - - if (internal == NULL || internal->modulus == NULL || - internal->exponent == NULL) - return NULL; - retval = (R_RSA_PUBLIC_KEY PNTR) MemNew(sizeof(*retval)); - retval->bits = internal->bits; - BSSeek (internal->modulus, 0, SEEK_SET); - BSSeek (internal->exponent, 0, SEEK_SET); - BSRead(internal->modulus, retval->modulus, sizeof(retval->modulus)); - BSRead(internal->exponent, retval->exponent, sizeof(retval->exponent)); - return retval; -} - - -/* - * Purpose: Compare two public encryption keys for equality - * - * Parameters: - * x Public key #1 - * y Public key #2 - * - * Returns: - * TRUE if keys match, FALSE otherwise - * - * Description: - * Converts keys into RSAREF format, because these are flat data - * structures and hence easy to compare. - */ - -NLM_EXTERN Boolean LIBCALL -NI_PubKeysEqual(NI_PubKeyPtr x, NI_PubKeyPtr y) -{ - R_RSA_PUBLIC_KEY PNTR xRsa = InternalToPubKeyFormat(x); - R_RSA_PUBLIC_KEY PNTR yRsa = InternalToPubKeyFormat(y); - Boolean retval; - - if (xRsa == NULL && yRsa== NULL) - return TRUE; - if (xRsa == NULL || yRsa== NULL) - { - retval = FALSE; - } else { - retval = MemCmp((CharPtr) xRsa, (CharPtr) yRsa, sizeof (*xRsa)) == 0; - } - MemFree (xRsa); - MemFree (yRsa); - return retval; -} - - - -/* - * Purpose: Pseudo-randomly generate an 8-byte DES key - * - * Parameters: - * desKey Resulting DES key - * - * Description: - * Generates 8-byte DES key, grabbing 2 bytes from each of 4 pseudo- - * randomly generated long integers. - * - * Note: - * Only 2 bytes are used from the long integer, because it's - * conceivable that a machine exists without 4-byte long integers. - * In hindsight, sizeof(long) could be used to determine how much to - * use, but this is a reasonable implementation. - */ - -NLM_EXTERN void -NI_GenerateDESKey(UcharPtr desKey) -{ - Int2 i; - long ran; - - SetRandomSeed(); - for (i = 0; i < 8;) - { - ran = RandomNum(); - desKey[i++] = (Uchar) (ran & 255); - desKey[i++] = (Uchar) ((ran >> 8) & 255); - } -} - - - -/* - * Purpose: Generate pub encryption public + private keys, and write to files - * - * Parameters: - * bits Length of key modulus in bits, within a restricted range - * pubAip AsnIoPtr to where public-key should be stored - * privFp File pointer to where private key should be stored - * - * Returns: - * TRUE if operations were successful, FALSE otherwise - * - * Description: - * Generates public and private keys using RSAREF function, and then - * output to AsnIoPtr and file pointer. - * - * Note: - * An AsnIoPtr is used for the public key, because the public key - * must be transmittable in a canonical format. Since private keys - * are never transmitted, a single block of memory is used for - * private keys, and private keys are stored in a single chunk on - * disk. This reduces the number of special data structures and - * ASN.1 object loaders which needed to be constructed to add - * encryption to NCBI Network Services. - */ - -NLM_EXTERN Boolean LIBCALL -NI_GenAndWritePEMKeys(Int2 bits, AsnIoPtr pubAip, FILE *privFp) -{ - R_RSA_PUBLIC_KEY publicKey; - R_RSA_PRIVATE_KEY privateKey; - R_RSA_PROTO_KEY protoKey; - R_RANDOM_STRUCT randomStruct; - int retval; - AsnModulePtr amp; - AsnTypePtr pubAtp; - NI_PubKeyPtr internalPub; - NI_HandPtr dummyHand; - - if (bits < MIN_RSA_MODULUS_BITS || bits > MAX_RSA_MODULUS_BITS) - return FALSE; - if (pubAip == NULL || privFp == NULL) - return FALSE; - /* create a dummy message handle to ensure that ASN.1 is loaded */ - dummyHand = (NI_HandPtr) MsgMakeHandle(FALSE); - MsgDestroyHandle(dummyHand); - if ((amp = AsnAllModPtr()) == NULL) - return FALSE; - if ((pubAtp = AsnTypeFind(amp, "RSA-Pubkey")) == NULL) - return FALSE; - InitRandomStruct (&randomStruct); - protoKey.bits = bits; - protoKey.useFermat4 = 1; - retval = R_GeneratePEMKeys(&publicKey, &privateKey, &protoKey, &randomStruct); - if (retval != 0) - { - ErrPostEx(SEV_ERROR, 0, 0, "Error when generating PEM keys %d", retval); - } - internalPub = PubKeyToInternalFormat(&publicKey); - NI_WritePubKey(pubAip, pubAtp, (NIPubKeyPtr) internalPub); - - FileWrite(&privateKey, sizeof(privateKey), 1, privFp); - - return TRUE; -} - - - -/* - * Purpose: Write a public key to a standard location on client machines - * - * Parameters: - * - * pub The public-key to be written to standard file - * - * Returns: - * TRUE if operations were successful, FALSE otherwise - * - * Description: - * Writes public-key to a file in the DATA directory. - * Alternatively, the public-key could be stored anywhere ... - * originally it was stored in the NCBI configuration file. - */ - -NLM_EXTERN Boolean LIBCALL -NI_WritePubKeyToConfig (NI_PubKeyPtr pub) -{ - Char fname[PATH_MAX]; - AsnIoPtr aip; - AsnModulePtr amp; - AsnTypePtr pubAtp; - NI_HandPtr dummyHand; - - if (pub == NULL) - { - return FALSE; - } - - /* create a dummy message handle to ensure that ASN.1 is loaded */ - dummyHand = (NI_HandPtr) MsgMakeHandle(FALSE); - MsgDestroyHandle(dummyHand); - if ((amp = AsnAllModPtr()) == NULL) - return FALSE; - if ((pubAtp = AsnTypeFind(amp, "RSA-Pubkey")) == NULL) - return FALSE; - - if (! FindPath("ncbi", "ncbi", "data", fname, sizeof (fname))) - { - ErrPost(CTX_NCBIOBJ, 1, "FindPath failed"); - return FALSE; - } - - StringCat(fname, "pubkey.enc"); - - if ((aip = AsnIoOpen(fname, "w")) == NULL) - { - return FALSE; - } - NI_WritePubKey(aip, pubAtp, (NIPubKeyPtr) pub); - AsnIoClose(aip); - return TRUE; -} - -/* - * Purpose: Read a public key from a standard configuration location - * - * Returns: - * A pointer to the allocated public-key, or NULL if failed - * - * Description: - * Reads public-key from a file in the DATA directory. - * Alternatively, the public-key could be stored anywhere ... - * originally it was stored in the NCBI configuration file. - */ - -NLM_EXTERN NI_PubKeyPtr LIBCALL -NI_ReadPubKeyFromConfig (void) -{ - Char fname[PATH_MAX]; - AsnIoPtr aip; - NI_PubKeyPtr pub; - NIPubKeyPtr pub2; - FILE *fp; - - if (! FindPath("ncbi", "ncbi", "data", fname, sizeof (fname))) - { - ErrPost(CTX_NCBIOBJ, 1, "FindPath failed"); - return NULL; - } - - StringCat(fname, "pubkey.enc"); - /* try opening the file first, to suppress AsnIoOpen messages */ - if ((fp = FileOpen(fname, "r")) == NULL) - { - return NULL; - } else { - FileClose(fp); - } - if ((aip = AsnIoOpen(fname, "r")) == NULL) - { - FileRemove(fname); - return NULL; - } - /* pub = (NI_PubKeyPtr) NI_MakePubKey(); */ - pub2 = NI_MakePubKey(); - pub = (NI_PubKeyPtr) pub2; - if (NI_ReadPubKey(aip, NULL, (NIPubKeyPtr) pub) < 0) - { - NI_DestroyPubKey((NIPubKeyPtr) pub); - pub = NULL; - } - AsnIoClose(aip); - - return pub; -} - -/* - * Purpose: Make a copy of a public key - * - * Parameters: - * orig The key to be copied - * - * Returns: - * A pointer to the copy of the public-key, or NULL if failed - * - * Description: - * Makes a copy of a public key - */ - -NLM_EXTERN NI_PubKeyPtr LIBCALL -NI_PubKeyDup (NI_PubKeyPtr orig) -{ - NI_PubKeyPtr dup; - - if (orig == NULL) - return NULL; - dup = MemNew(sizeof(*dup)); - dup->bits = orig->bits; - dup->modulus = BSDup(orig->modulus); - dup->exponent = BSDup(orig->exponent); - return dup; -} - - -/* - * Purpose: Load a private-key from the specified file pointer - * - * Parameters: - * fp File pointer from which to read private key - * privKeyLenPtr Pointer to where the length of private key may be stored - * - * Returns: - * A pointer to the resulting data structure, or NULL if unsuccessful - * - * Description: - * Reads private key from data file. - */ - -NLM_EXTERN VoidPtr LIBCALL -NI_LoadPrivKey(FILE *fp, Int2Ptr privKeyLenPtr) -{ - R_RSA_PRIVATE_KEY PNTR privKey; - - privKey = (R_RSA_PRIVATE_KEY PNTR) MemNew(sizeof(*privKey)); - - FileRead(privKey, sizeof(*privKey), 1, fp); - - if (privKeyLenPtr != NULL) - { - *privKeyLenPtr = sizeof(*privKey); - } - - return privKey; -} - -/* - * Purpose: Perform public-key decryption - * - * Parameters: - * pKey Private key - * plainText Pointer to resulting plaintext - * cipherText Ciphertext to be decrypted - * cipherTextLen Length of cipherText - * - * Returns: - * The length of resulting plaintext, or a negative error code - * - * Description: - * Decrypts the specified ciphertext using the specified private - * key. Subsequently resizes the resulting plaintext to be only - * as large as is needed. - * - * Note: - * The caller must free the pointer to the resulting plaintext. - */ - -NLM_EXTERN Int2 LIBCALL -NI_PubKeyDecrypt(VoidPtr pKey, UcharPtr PNTR plainText, UcharPtr cipherText, Int2 cipherTextLen) -{ - R_RSA_PRIVATE_KEY PNTR privKey = (R_RSA_PRIVATE_KEY PNTR) pKey; - int plainTextLen; - UcharPtr pText1, pText2; - - if (pKey == NULL || plainText == NULL || cipherText == NULL) - return -1; - - *plainText = NULL; - /* plain text is certainly shorter than ciphertext */ - pText1 = (UcharPtr) MemNew(cipherTextLen); - - if (RSAPrivateDecrypt(pText1, &plainTextLen, cipherText, cipherTextLen, privKey) != 0) - { - MemFree (pText1); - return -2; - } - pText2 = (UcharPtr) MemDup(pText1, plainTextLen); - MemFree (pText1); - *plainText = pText2; - return ((Int2) plainTextLen); -} - - -/* - * Purpose: Perform public-key encryption - * - * Parameters: - * pub Public key - * plainText Plaintext to be encrypted - * plainTextLen Length of plainText - * cipherText Pointer to resulting ciphertext - * - * Returns: - * The length of resulting ciphertext, or a negative error code - * - * Description: - * Encrypts the specified plaintext using the specified public - * key. Subsequently resizes the resulting ciphertext to be only - * as large as is needed. - * - * Note: - * The caller must free the pointer to the resulting ciphertext. - */ - -NLM_EXTERN Int2 LIBCALL -NI_PubKeyEncrypt(NI_PubKeyPtr pub, UcharPtr plainText, Int2 plainTextLen, UcharPtr PNTR cipherText) -{ - R_RSA_PUBLIC_KEY PNTR pubKeyPtr; - R_RANDOM_STRUCT randomStruct; - UcharPtr cipher, cipher2; - int cipherTextLen = 0; - - if (pub == NULL || plainText == NULL || cipherText == NULL) - { - return -1; - } - *cipherText = NULL; - if ((pubKeyPtr = InternalToPubKeyFormat(pub)) == NULL) - { - return -2; - } - cipher = (UcharPtr) MemNew(plainTextLen * 2 + 64); - InitRandomStruct (&randomStruct); - if (RSAPublicEncrypt(cipher, &cipherTextLen, plainText, plainTextLen, pubKeyPtr, &randomStruct) != 0) - { - MemFree (cipher); - MemFree (pubKeyPtr); - return -3; - } - MemFree (pubKeyPtr); - /* reduce to the proper length */ - cipher2 = (UcharPtr) MemDup(cipher, cipherTextLen); - MemFree (cipher); - *cipherText = cipher2; - return ((Int2) cipherTextLen); -} - -/* - * Purpose: Free an encryption data structure, and erase secret data - * - * Parameters: - * encr Encryption data structure to be destroyed - * - * - * Description: - * Frees an encryption data structure, and erases secret data - * which could be used by a hostile party to break the encryption. - * The caller must free the pointer to the resulting ciphertext. - */ - -NLM_EXTERN void -NI_DestroyEncrStruct (NI_EncrDataPtr encr) -{ - if (encr == NULL) - return; - if (encr->desReadContext != NULL) - { - /* clear this memory for security reasons */ - MemSet(encr->desReadContext, '\0', sizeof(DES_CBC_CTX)); - MemFree(encr->desReadContext); - } - if (encr->desWriteContext != NULL) - { - /* clear this memory for security reasons */ - MemSet(encr->desWriteContext, '\0', sizeof(DES_CBC_CTX)); - MemFree(encr->desWriteContext); - } - MemFree(encr); -} - -/* - * Purpose: Indicates whether encryption is available - * - * Returns: Always TRUE for this file, always FALSE for stub file - * - * - * Description: - * Indicates to the caller whether encryption is available, and - * whether or not it is safe to call the other encryption - * functions. - */ - -NLM_EXTERN Boolean LIBCALL -NI_EncrAvailable(void) -{ - return TRUE; -} diff --git a/network/nsclilib/ni_encr.h b/network/nsclilib/ni_encr.h deleted file mode 100644 index b0b578c9..00000000 --- a/network/nsclilib/ni_encr.h +++ /dev/null @@ -1,102 +0,0 @@ -/* -* =========================================================================== -* -* PUBLIC DOMAIN NOTICE -* National Center for Biotechnology Information -* -* This software/database is a "United States Government Work" under the -* terms of the United States Copyright Act. It was written as part of -* the author's official duties as a United States Government employee and -* thus cannot be copyrighted. This software/database is freely available -* to the public for use. The National Library of Medicine and the U.S. -* Government have not placed any restriction on its use or reproduction. -* -* Although all reasonable efforts have been taken to ensure the accuracy -* and reliability of the software and data, the NLM and the U.S. -* Government do not and cannot warrant the performance or results that -* may be obtained by using this software or data. The NLM and the U.S. -* Government disclaim all warranties, express or implied, including -* warranties of performance, merchantability or fitness for any particular -* purpose. -* -* Please cite the author in any work or product based on this material. -* -* =========================================================================== -* -* File Name: ni_encr.h -* -* Author: Epstein -* -* Version Creation Date: 2/14/94 -* -* $Revision: 6.0 $ -* -* File Description: -* Header for for RSAREF-based encryption support in NCBI network services -* -* -* Modifications: -* -------------------------------------------------------------------------- -* Date Name Description of modification -* ------- ---------- ----------------------------------------------------- -* -* -* RCS Modification History: -* $Log: ni_encr.h,v $ -* Revision 6.0 1997/08/25 18:38:34 madden -* Revision changed to 6.0 -* -* Revision 5.1 1997/07/01 19:12:42 vakatov -* [WIN32] DLL'd "netcli.lib" -* -* Revision 5.0 1996/05/28 14:11:55 ostell -* Set to revision 5.0 -* - * Revision 4.0 1995/07/26 13:56:32 ostell - * force revision to 4.0 - * - * Revision 1.4 1995/05/17 17:52:03 epstein - * add RCS log revision history - * -*/ - -#ifndef _NI_ENCR_ -#define _NI_ENCR_ - -#undef NLM_EXTERN -#ifdef NLM_IMPORT -#define NLM_EXTERN NLM_IMPORT -#else -#define NLM_EXTERN extern -#endif - -#ifdef __cplusplus -extern "C" { -#endif - -NLM_EXTERN Boolean LIBCALL NI_SetupDESEncryption PROTO((NI_HandPtr mh, UcharPtr desKey)); -NLM_EXTERN Boolean LIBCALL NI_PubKeysEqual PROTO((NI_PubKeyPtr x, NI_PubKeyPtr y)); -NLM_EXTERN void NI_GenerateDESKey PROTO((UcharPtr desKey)); -NLM_EXTERN Boolean LIBCALL NI_GenAndWritePEMKeys PROTO((Int2 bits, AsnIoPtr pubAip, FILE *privFp)); -NLM_EXTERN Boolean LIBCALL NI_WritePubKeyToConfig PROTO((NI_PubKeyPtr pub)); -NLM_EXTERN NI_PubKeyPtr LIBCALL NI_ReadPubKeyFromConfig PROTO((void)); -NLM_EXTERN NI_PubKeyPtr LIBCALL NI_PubKeyDup PROTO((NI_PubKeyPtr orig)); -NLM_EXTERN VoidPtr LIBCALL NI_LoadPrivKey PROTO((FILE *fp, Int2Ptr privKeyLenPtr)); -NLM_EXTERN Int2 LIBCALL NI_PubKeyDecrypt PROTO((VoidPtr pKey, UcharPtr PNTR plainText, UcharPtr cipherText, Int2 cipherTextLen)); -NLM_EXTERN Int2 LIBCALL NI_PubKeyEncrypt PROTO((NI_PubKeyPtr pub, UcharPtr plainText, Int2 plainTextLen, UcharPtr PNTR cipherText)); -NLM_EXTERN void NI_DestroyEncrStruct PROTO((NI_EncrDataPtr encr)); -NLM_EXTERN Boolean LIBCALL NI_EncrAvailable PROTO((void)); - -#ifdef __cplusplus -} -#endif - -#undef NLM_EXTERN -#ifdef NLM_EXPORT -#define NLM_EXTERN NLM_EXPORT -#else -#define NLM_EXTERN -#endif - -#endif /* _NI_ENCR_ */ - diff --git a/network/nsclilib/ni_encrs.c b/network/nsclilib/ni_encrs.c deleted file mode 100644 index 868de937..00000000 --- a/network/nsclilib/ni_encrs.c +++ /dev/null @@ -1,104 +0,0 @@ -/* -* =========================================================================== -* -* PUBLIC DOMAIN NOTICE -* National Center for Biotechnology Information -* -* This software/database is a "United States Government Work" under the -* terms of the United States Copyright Act. It was written as part of -* the author's official duties as a United States Government employee and -* thus cannot be copyrighted. This software/database is freely available -* to the public for use. The National Library of Medicine and the U.S. -* Government have not placed any restriction on its use or reproduction. -* -* Although all reasonable efforts have been taken to ensure the accuracy -* and reliability of the software and data, the NLM and the U.S. -* Government do not and cannot warrant the performance or results that -* may be obtained by using this software or data. The NLM and the U.S. -* Government disclaim all warranties, express or implied, including -* warranties of performance, merchantability or fitness for any particular -* purpose. -* -* Please cite the author in any work or product based on this material. -* -* =========================================================================== -* -* File Name: ni_encrs.c -* -* Author: Epstein -* -* Version Creation Date: 2/14/94 -* -* $Revision: 6.0 $ -* -* File Description: -* Stub replacement for ni_encr.c. This makes it easy to build NCBI Network -* Services tools either with or without encryption support. -* -* Modifications: -* -------------------------------------------------------------------------- -* Date Name Description of modification -* ------- ---------- ----------------------------------------------------- -* 2/15/94 Epstein Replaced nice macro with explicit definitions, due to -* inconsistency involving C pre-processors. -* -* -* RCS Modification History: -* $Log: ni_encrs.c,v $ -* Revision 6.0 1997/08/25 18:38:36 madden -* Revision changed to 6.0 -* -* Revision 5.1 1997/07/01 19:12:43 vakatov -* [WIN32] DLL'd "netcli.lib" -* -* Revision 5.0 1996/05/28 14:11:55 ostell -* Set to revision 5.0 -* - * Revision 4.0 1995/07/26 13:56:32 ostell - * force revision to 4.0 - * - * Revision 1.5 1995/05/17 17:52:06 epstein - * add RCS log revision history - * -*/ - -#include <ncbi.h> -#include <ni_types.h> - - -/* this is the only function which may be called legally */ -NLM_EXTERN Boolean LIBCALL NI_EncrAvailable (void) -{ return FALSE; } - -NLM_EXTERN Boolean LIBCALL NI_SetupDESEncryption (NI_HandPtr mh, UcharPtr desKey) -{ ErrPostEx(SEV_ERROR,0,0,"Invalid call to encryption function NI_SetupDESEncryption"); return FALSE; } - -NLM_EXTERN Boolean LIBCALL NI_PubKeysEqual (NI_PubKeyPtr x, NI_PubKeyPtr y) -{ ErrPostEx(SEV_ERROR,0,0,"Invalid call to encryption function NI_PubKeysEqual"); return FALSE; } - -NLM_EXTERN void NI_GenerateDESKey (UcharPtr desKey) -{ ErrPostEx(SEV_ERROR,0,0,"Invalid call to encryption function NI_GenerateDESKey"); } - -NLM_EXTERN Boolean LIBCALL NI_GenAndWritePEMKeys (Int2 bits, AsnIoPtr pubAip, FILE *privFp) -{ ErrPostEx(SEV_ERROR,0,0,"Invalid call to encryption function NI_GenAndWritePEMKeys"); return FALSE; } - -NLM_EXTERN Boolean LIBCALL NI_WritePubKeyToConfig (NI_PubKeyPtr pub) -{ ErrPostEx(SEV_ERROR,0,0,"Invalid call to encryption function NI_WritePubKeyToConfig"); return FALSE; } - -NLM_EXTERN NI_PubKeyPtr LIBCALL NI_ReadPubKeyFromConfig (void) -{ ErrPostEx(SEV_ERROR,0,0,"Invalid call to encryption function NI_ReadPubKeyFromConfig"); return NULL; } - -NLM_EXTERN NI_PubKeyPtr LIBCALL NI_PubKeyDup (NI_PubKeyPtr orig) -{ ErrPostEx(SEV_ERROR,0,0,"Invalid call to encryption function NI_PubKeyDup"); return NULL; } - -NLM_EXTERN VoidPtr LIBCALL NI_LoadPrivKey (FILE *fp, Int2Ptr privKeyLenPtr) -{ ErrPostEx(SEV_ERROR,0,0,"Invalid call to encryption function NI_LoadPrivKey"); return NULL; } - -NLM_EXTERN Int2 LIBCALL NI_PubKeyDecrypt (VoidPtr pKey, UcharPtr PNTR plainText, UcharPtr cipherText, Int2 cipherTextLen) -{ ErrPostEx(SEV_ERROR,0,0,"Invalid call to encryption function NI_PubKeyDecrypt"); return -1; } - -NLM_EXTERN Int2 LIBCALL NI_PubKeyEncrypt (NI_PubKeyPtr pub, UcharPtr plainText, Int2 plainTextLen, UcharPtr PNTR cipherText) -{ ErrPostEx(SEV_ERROR,0,0,"Invalid call to encryption function NI_PubKeyDecrypt"); return -1; } - -NLM_EXTERN void NI_DestroyEncrStruct (NI_EncrDataPtr encr) -{ ErrPostEx(SEV_ERROR,0,0,"Invalid call to encryption function NI_DestroyEncrStruct"); } diff --git a/network/nsclilib/ni_lib.c b/network/nsclilib/ni_lib.c deleted file mode 100644 index 43326eda..00000000 --- a/network/nsclilib/ni_lib.c +++ /dev/null @@ -1,3848 +0,0 @@ -/* -* =========================================================================== -* -* PUBLIC DOMAIN NOTICE -* National Center for Biotechnology Information -* -* This software/database is a "United States Government Work" under the -* terms of the United States Copyright Act. It was written as part of -* the author's official duties as a United States Government employee and -* thus cannot be copyrighted. This software/database is freely available -* to the public for use. The National Library of Medicine and the U.S. -* Government have not placed any restriction on its use or reproduction. -* -* Although all reasonable efforts have been taken to ensure the accuracy -* and reliability of the software and data, the NLM and the U.S. -* Government do not and cannot warrant the performance or results that -* may be obtained by using this software or data. The NLM and the U.S. -* Government disclaim all warranties, express or implied, including -* warranties of performance, merchantability or fitness for any particular -* purpose. -* -* Please cite the author in any work or product based on this material. -* -* =========================================================================== -* -* File Name: ni_lib.c -* -* Author: Beatty, Gish, Epstein -* -* Version Creation Date: 1/1/92 -* -* $Revision: 6.15 $ -* -* File Description: -* This file is a library of functions to be used by server application -* and client software, using the NCBI "network services" paradigm. -* -* -* Modifications: -* -------------------------------------------------------------------------- -* Date Name Description of modification -* ------- ---------- ----------------------------------------------------- -* 4/27/92 Epstein Added extensive in-line commentary, and removed all tabs. -* 5/11/92 Epstein Removed unused function NI_SVCRequestGet(); added support -* for the connection ID to be written to a CONID file each -* time that the value of conid is updated; in practice, -* only dispatcher will update a CONID file. -* 6/22/92 Epstein For UNIX signals, catch the SIGPIPE error which can -* occur when writing to a socket which is no longer -* connected. -* 7/06/92 Epstein Changed sokselectw() to examine the SO_ERROR socket option -* after select()-ing a socket to which we were attempting a -* connection. This eliminates "false connects", i.e., -* unsuccessful connection attempts which look successful -* because the select() call returns 1. -* 7/14/92 Epstein Changed NI_SetDispatcher() and NI_InitServices() to use -* a configurable timeout parameter, and in the process -* also changed sokselectw() to have a timeout parameter, -* 1/21/93 Epstein Add dispatcher-list support, and add dispatcher-list -* parameter to NI_InitServices(). -* 2/12/93 Epstein Use new boolean parameter to MsgMakeHandle(), indicating -* whether or not it should create a socket. This was -* an attempted fix for a Mac problem ... it later -* turned out to be an incorrect problem-fix, but also -* does no harm. -* 2/24/93 Epstein Fix long-standing Mac bug, by correctly destroying -* services handle and hence closing an open socket. -* 3/02/93 Epstein Add functions to write dispatcher-configuration info -* to a config file. This provides a standardized -* mechanisms which applications may use for net services -* configuration. Also added platform functions, so -* that dispatcher/server complex can know what type -* of platform a client is running on, assuming that the -* client is telling the truth. -* 3/03/93 Epstein Cleanup variable initialization. -* 3/08/93 Epstein Improve error messages & cleanup to NI_InitServices, -* include reason in login failure message, and add -* client platform to service request. -* 3/09/93 Epstein Add HaltServices() function to simplify cleanup. -* 3/22/93 Epstein Fix typecast for getsockopt(), and, more importantly, -* remember to return the computed value in NI_GetPlatform. -* 3/23/93 Epstein Support VMS/TGV, and add NETP_INET_ prefixes to -* conditional-compilation symbols. -* 3/24/93 Epstein Clear the caller's pointer in NI_SetDispConfig(). -* 3/31/93 Epstein Add dispatcher pointer as context for all network -* services operations; this allows an application -* to use more than one dispatcher at a time, at the -* expense of slightly greater complexity. Also add -* a "Generic Init" function, which can be used by -* an application to obtain network-services in a -* simplified, standardized manner. -* 3/31/93 Epstein Move debug and module variables to their correct home. -* 4/02/93 Epstein Add WinSock support. -* 4/12/93 Schuler Add MAKEWORD macro. -* 4/21/93 Schuler Removed function prototypes for NI_AsnRead, NI_AsnWrite -* 5/07/93 Epstein Move WSAStartup() code to a better place, add workaround -* for connection attempt on a non-blocking socket in PC-NFS -* 4.0, add more platform definitions. -* 5/24/93 Epstein Add separate error codes for TCP/IP initialization -* failure and inability to resolve local host name. -* 5/25/93 Epstein Add configuration-file workaround for PC-NFS 5.0 bug, -* where NIS sometimes fails on the PC's own host name. -* 5/27/93 Epstein Incorporate pragmatic "Gestalt" code for Vibrant -* scrolling workaround for WinSock under Windows 3.1, -* add add SOCK_INDEX_ERRNO macro to workaround another -* WinSock pecularity. -* 6/02/93 Schuler Change "Handle" to "MonitorPtr" for Monitors. -* 6/07/93 Epstein Added generic timer functions. -* Also add missing revision history, derived from -* RCS file. -* 6/09/93 Epstein Added activity hook to report network activity back -* to an application. -* 6/14/93 Epstein Changed "Generic" logic to cause UNIX/VMS loginname -* to override loginname, rather than vice versa. Also -* setup DispatchConnect() logic to set client's declared -* IP address to 0.0.0.0, rather than causing an error, -* in the case where the client cannot resolve its own -* host name. In this case, the dispatcher will set its -* own opinion of the client address based upon -* getpeername(). -* 6/15/93 Epstein Eliminate "Gestalt" code for Vibrant scrolling -* workaround for WinSock under Windows 3.1, since the -* solution for this problem does not require its use. -* 6/25/93 Epstein Fix activity-hook action for service disconnection (had -* erroneously announced dispatcher-disconnection), and -* add logic to try to avoid getservbyname() by looking -* up dispatcher port # and (loport,hiport) in NCBI -* configuration file instead of in NIS. As a last resort, -* look up the name in NIS if the entry in the NCBI -* config. file is non-numeric. Also, change the client -* port lookup mechanism for Macintoshes to add a configured -* "delta" value to the low port number. This results in -* allowing several Network Services applications to run -* concurrently on a Mac without port conflicts. -* 7/08/93 Epstein Fix list traversal error in NI_ProcessTimers() -* 7/08/93 Epstein Added a counter as a failsafe mechanism in -* NI_ProcessTimers(), since previous fix attempt failed. -* 7/09/93 Epstein Changed a few #define names to avoid Alpha compilation -* warnings, and added reference count to dispatcher data -* structure. -* 8/09/93 Epstein Improve diagnostics when a listen() call fails -* 8/23/93 Epstein Add currentDisp variable so that the currently-attached -* dispatcher is used when the parameter to NI_SetDispatcher -* is NULL. -* 8/31/93 Epstein Fix host vs. network order when comparing port numbers. -* 9/08/93 Epstein Added new stackDescription variable, to be able to -* report to the dispatcher the identity of the vendor -* of the WinSock stack -* 9/09/93 Epstein Fix use of currentDisp variable to correctly compare -* new dispatcher request again current dispatcher. -*11/24/93 Epstein Added code to support standalone servers and clients -* which communicate with standalone servers or "service -* brokers", which listen on a specific port (to be -* augmented later). -*11/30/93 Epstein Made standalone server code UNIX-only, to avoid -* possible compilation errors on other platforms. However, -* it should be possible in principle to run and test a -* standalone server on a non-UNIX host. Also, added -* limited security to standalone servers. -*12/08/93 Epstein Fixed service connection activity hook, per discussion -* with Kyle Hart. -*01/19/94 Schuler Post error (SEV_INFO) on WinSock initialization -* failure showing WinSock's error code. -*01/28/94 Schuler Replace "NETP_INET_MACTCP" with "NETP_INET_MACTCP" -*01/28/94 Schuler Defined THIS_MODULE and THIS_FILE -*02/14/94 Epstein Add preliminary RSAREF encryption support -*02/22/94 Epstein Add DISP_RECONN_ACTION logic to allow users to breakout -* or quit if unable to contact primary dispatcher. -*02/24/94 Epstein Make use of new NI_DupPubKey function, and insert -* newlines in macros to make editing easier. -*03/03/94 Epstein Reduce memory leaks, suppress non-printing characters -* in winsock.dll. -*04/22/94 Epstein Change error handling to use SEV_ERROR and SEV_WARNING -* (ErrPostEx). Also do a better job of detecting -* inability to connect to dispatcher in DispatchConnect(), -* because under Solaris getsockopt() doesn't correctly -* detect an error. -*04/25/94 Epstein Cosmetic change for error when NACK received from -* Dispatcher. -*05/04/94 Epstein Add logic to allow a mixture of encrypted and -* unencrypted services, determined by ENCRYPTION=FALSE -* fields in the appropriate sections in the config. -* files. -*06/08/94 Epstein Add SOCKS support (probably not correct yet) by -* asking Dispatcher to provide a SVC_PRE_RESPONSE message -* which contains the server's IP address. -*06/10/94 Epstein More SOCKS refinement, plus added tracing for SOCKS -*06/15/94 Epstein Produce working SOCKS version, by changing the protocol -* so that a SOCKSified client uses two service request -* messages; one to learn the IP address of the server -* to which it will be assigned, and the second "real" -* service request after it has bound the 'listen' port -* on the SOCKS daemon. -*07/01/94 Epstein Determine at runtime whether or not to use SOCKS, -* methodology, based upon presence or absence of -* SOCKS_CONF file. -*07/07/94 Epstein Updated commentary. -*09/22/94 Epstein Improved standalone server code by using SO_REUSEADDR -* option, making it possible for identical servers to -* run consecutively without waiting for sockets to -* shutdown. -*12/02/94 Epstein Changed NI_GenericGetService() to have environment -* variables override configuration file for SERVICE_NAME -* and RESOURCE_TYPE. This is mostly just a convenience -* for internal NCBI use, allowing the use of a single -* config. file while using scripts to force the use -* of a different service. -*12/06/94 Epstein Added connectDelay, adminInfo and motd fields. -* The client reports the time which it took to -* establish a connection in their connectDelay field. -* The Dispatcher provides the name of the Network -* administrator and a secondary message-of-the-day in -* the other two fields. -*12/21/94 Epstein Added instrumentation for socket management -*01/11/95 Epstein Change socket instrumentation to suppress some -* errors for WinSock 1.1. -*01/13/95 Epstein Add new GetLAPType() function to report Mac clients' -* TCP/IP implementation ("Ethernet", "PPP", etc.) to -* the Dispatcher. -*03/20/95 Epstein Fix InitServices/EndServices logic to correctly only -* establish a single Dispatcher connection for multiple -* services. -*03/29/95 Epstein Reduce calls to Message() in favor of ErrPostEx(). -*06/02/95 Epstein Fix bindPort() to address host/network byte ordering; -* this should correct a byte-ordering problem on little- -* endian hosts which use SOCKS. -*06/06/95 Epstein For UNIX, try to get the user's name from the USER -* environment variable before inquiring getlogin(); -* this can save CPU time and contention on some systems, -* since access to utmp can be slow. -*06/12/95 Epstein Another byte-ordering fix for SOCKS for the SOCKS -* proxy's port number. -*10/19/95 Epstein Bug fix to accomodate logic correct in Nlm_StringCmp() -* -*11/15/95 Shavirin Added new ability of clients to get direct connection -* to the server. -* Created new function: NI_DirectServiceRequest to connect - to the server directly and to send SVC_REQUEST -* Added new parameter in configuration file - DIRECT_SVC_CON -* This parameter updates new field in dispatcher stucture: -* disp->useOutServ. If this parameter set to FALSE - old style -* communication will be used. TRUE is set for direct -* connection. -* To handle direct connection protocol of the service request -* function was changed. In the case of old style everything -* remained the same (except reconnect switch option - to -* try direct connection if old style failed - currently disabled) -* In the case when disp->useOutServ is set client sends -* service request with field svcreq->want_ticket = TRUE. -* Dispatcher will sent back SVC_REQUEST with the prepared ticket -* or NACK in the case of error. Client will send SVC_REQUEST -* directly to the server and will wait until SVC_RESPONCE or -* NACK will be received from the dispatcher. After SVC_RESPONCE -* received communication transfers to the upper layers. -*01/17/96 Epstein Add protection for DIRECT_SVC_CON mode; this comes into -* play with Mac OpenTransport (OT) -*02/02/96 Epstein Add PROXY_SERV_OVERRIDE GetAppParam() flag for -* DIRECT_SVC_CON mode. This makes it easier for a -* machine behind a firewall to get through the firewall, -* although it assumes a priori knowledge of the IP -* address of the server, and the port numbers on the -* server. -*02/21/96 Epstein Fix brokered-services for little-endian clients -* ========================================================================== -* -* -* RCS Modification History: -* $Log: ni_lib.c,v $ -* Revision 6.15 2002/11/06 21:30:13 ucko -* Don't assume MIPS is IRIX, or HPPA is HP/UX; allow Linux too, for both. -* -* Revision 6.14 2001/01/04 22:35:02 vakatov -* NI_ServerACK(), NI_ServerNACK() -- to do nothing, always return 0. -* -* Revision 6.13 2000/10/30 18:12:01 beloslyu -* FreeBSD was added -* -* Revision 6.12 1999/07/30 19:11:08 vakatov -* Use "strerror()" instead of "sys_errlist[]" -* -* Revision 6.11 1999/06/07 18:31:43 beloslyu -* NetBSD port -* -* Revision 6.10 1998/04/10 19:24:45 vakatov -* NI_SetInterface(): return the overridden(old) interface value; check -* for the validity of the new interface -* -* Revision 6.9 1998/03/31 23:44:53 vakatov -* "interface" gets #defined in MS-Win headers; just #undef it -* -* Revision 6.8 1998/03/31 21:35:34 vakatov -* Added stub NI_IsInterfaceSupported(), NI_SetAddress() and -* NI_SetInterface() for the forward compatibility with "ni_lib_.h" -* -* Revision 6.7 1998/03/30 23:05:52 vakatov -* fixed minor typo -* -* Revision 6.6 1998/03/17 18:55:42 shavirin -* Rolling back to version 6.3 -* -* Revision 6.3 1997/11/18 21:14:42 epstein -* identify Linux Alpha client -* -* Revision 6.2 1997/10/06 21:21:50 shavirin -* Fixed memory leak and uninitiolized memory read errors -* -* Revision 6.1 1997/09/11 18:08:24 epstein -* add output of uname -a to Unix clients' self-identifying string -* -* Revision 6.0 1997/08/25 18:38:44 madden -* Revision changed to 6.0 -* -* Revision 5.5 1997/07/01 19:12:49 vakatov -* [WIN32] DLL'd "netcli.lib" -* -* Revision 5.4 1997/06/17 18:52:17 epstein -* fix numerous memory problems associated with timers -* -* Revision 5.3 1997/04/24 12:53:33 ostell -* fixed typo in call to AsnTypeStringToHex -* - * Revision 5.2 1997/04/24 12:44:36 ostell - * changed calls to AsnTypeStringToHex to match new arguments and returns - * - * Revision 5.1 1996/10/02 18:18:20 epstein - * add function NI_FqdnToIpaddr() to simplify layering of netcnfg.c - * - * Revision 5.0 1996/05/28 14:11:55 ostell - * Set to revision 5.0 - * - * Revision 4.15 1996/05/22 15:12:54 epstein - * adopt more reasonable semantics for brokered services: by default, only first service is brokered - * - * Revision 4.14 1996/04/29 15:29:19 epstein - * add disp to NI_HandPtr so that service-handle can encapsulate greater context - * - * Revision 4.13 1996/02/21 15:50:07 epstein - * Fix brokered-services for little-endian clients - * - * Revision 4.12 1996/02/02 14:53:41 epstein - * add PROXY_SERV_OVERRIDE setting for DIRECT_SVC_CON mode - * - * Revision 4.11 1996/01/17 20:33:09 epstein - * Add protection for DIRECT_SVC_CON mode; this comes into play with Mac OpenTransport - * - * Revision 4.10 1995/12/21 19:55:47 epstein - * make socket non-blocking for brokered services - * - * Revision 4.9 1995/11/30 19:58:08 epstein - * make NI_DirectServiceRequest() function static - * - * Revision 4.8 1995/11/29 17:50:24 epstein - * fix byte-ordering for direct-service connection - * - * Revision 4.7 1995/11/28 21:39:06 epstein - * remove unneeded sleep() call from non-UNIX platforms - * - * Revision 4.6 1995/11/28 20:18:41 epstein - * fix leaky-socket problem for non-direct-connection services - * - * Revision 4.5 1995/11/27 20:59:17 epstein - * add client support for direct-connection services - * - * Revision 4.2 95/10/19 20:29:06 epstein - * Bug fix to accomodate logic correct in Nlm_StringCmp() - * - * Revision 4.1 1995/08/01 13:48:33 epstein - * remember to initialize someBrokered - * - * Revision 4.0 1995/07/26 13:56:32 ostell - * force revision to 4.0 - * - * Revision 1.74 1995/07/12 14:53:28 epstein - * Another byte-ordering fix for SOCKS - * - * Revision 1.73 1995/06/06 10:04:52 epstein - * use USER environment variable in lieu of getlogin() - * - * Revision 1.72 95/06/02 16:58:43 epstein - * fix bindPort() using htonl() to correct byte-ordering problem on little-endian clients which use SOCKS - * - * Revision 1.71 95/05/17 17:52:18 epstein - * add RCS log revision history - * -*/ - -#define _NCBINET_LOCAL_VARS -#define THIS_MODULE g_nsclient_module -#define THIS_FILE _this_file -#define __NI_LIB__ -#include "ncbinet.h" -#include "ni_lib.h" -#include "ni_msg.h" - -char * g_nsclient_module = "nsclient"; -static char *_this_file = __FILE__; - - -#define ERR_KEY_MISMATCH "The public encryption key received from the dispatcher does\n\ -not match what is on file. There is a slight security risk\n\ -that this key is being presented by a \"spoofer\" rather than\n\ -the real dispatcher. You may wish to contact the NCBI by\n\ -other means to determine whether this new key is valid. Do\n\ -you wish to accept this as the new key and continue?" -#define ERR_KEY_NOPREVKEY "A public encryption key was just received from the dispatcher,\n\ -but no key is currently on file. There is a slight security\n\ -risk that this key is being presented by a \"spoofer\" rather\n\ -than the real dispatcher. You may wish to contact the NCBI by\n\ -other means to determine whether this new key is valid. Do\n\ -you wish to accept this as the new key and continue?" - -#ifdef NETP_INET_NEWT - -#define SIN_ADDR sin_addr.S_un.S_addr -#define H_ADDR_TYPE Uint4Ptr -#else -#define SIN_ADDR sin_addr -#define H_ADDR_TYPE struct in_addr * -#endif - -#ifdef WIN16 -#ifndef MAKEWORD -#define MAKEWORD(a,b) ((WORD)(((BYTE)(a)) | ((WORD)((BYTE)(b))) <<8)) -#endif -#endif - -#define NULL_TIMER 0 - - -typedef struct NI_Timer { - time_t timeout; - NI_TimeoutHook hook; - Pointer hookParam; -} NI_Timer, PNTR NI_TimerPtr; - - -/* GLOBALS */ -static FILE *conid_fp = NULL; /* File pointer for CONID */ -static NodePtr timerHead = NULL; /* list of timers */ -static NI_NetServHook activityHook = NULL; -static NI_DispatcherPtr currentDisp = NULL; -static CharPtr stackDescription = NULL; -static fd_set openfds; - - -#ifdef NETP_INET_WSOCK -static Int4 wsaStartupCount = 0; -#endif - -NILoginPtr NI_MakeMsgLogin PROTO((void)); -static Int2 SetIdentity PROTO((NI_DispatcherPtr disp, CharPtr user, CharPtr group, CharPtr domain)); -static void HaltServices PROTO((NI_DispatcherPtr disp)); -static NI_HandPtr DispatchConnect PROTO((NI_DispatcherPtr disp, CharPtr host, CharPtr name, int timeout)); -static Uint2 bindPort PROTO((int sok, struct sockaddr_in PNTR sokadr, Int2 loport, Int2 hiport, Uint4 remoteHost)); -static Int2 CopyIdentity PROTO((NI_DispatcherPtr disp, NI_UidPtr uid)); -static NI_HandPtr NI_DirectServiceRequest PROTO((NIMsgPtr imp, NI_HandPtr sconnhp)); - - -int sokselectr PROTO((int fd)); -int sokselectw PROTO((int fd, int timeout)); - -int getAsnError PROTO((char * str)); -void SetConFilePtr PROTO((FILE *fp)); -void CloseConFile PROTO((void)); - - -/* Added for the forward compatibility with "ni_lib_.h": - * NI_IsInterfaceSupported() - * NI_SetAddress() - * NI_SetInterface() - */ -NLM_EXTERN Boolean NI_IsInterfaceSupported(ENIInterface ni_interface) { - return (Boolean)(ni_interface == eNII_Dispatcher); -} -NLM_EXTERN void NI_SetAddress(const Char *address) {;} -NLM_EXTERN ENIInterface NI_SetInterface(ENIInterface ni_interface) { - return eNII_Dispatcher; -} - - - - -/* - * Purpose: Specify which dispatcher a client should try to connect to - * - * Parameters: - * disp Usually NULL, the pointer to a pre-existing Dispatcher - * structure - * host Name of the host (Fully Qualified Domain Name) to use - * svc Name of the "service" to try to use on that host - * dispserialnum Serial number of dispatcher-list. Use -1 if no response - * list is desired, or 0 if the serial number is not known. - * - * - * Description: - * Set up the dispatcher name which should be used, and the - * name of the service on that dispatcher. If other parameters - * have been specified previously, free the memory associated - * with those names. - * - * Note: - * There are useful defaults for "svc". When in doubt, call - * this function with a second arguement of NULL. - */ - -NLM_EXTERN NI_DispatcherPtr NI_SetDispatcher(NI_DispatcherPtr disp, CharPtr host, CharPtr svc, int timeout, - Int4 dispserialnum, ValNodePtr encryption, Boolean useOutServ) -{ - if (disp == NULL) { - if (currentDisp != NULL && !currentDisp->someBrokered) - { /* use current dispatcher if it matches what the caller wants */ - if ((svc == NULL || - StringCmp(svc, currentDisp->dispServiceName) == 0 ) && - StringCmp(host, currentDisp->dispHostName) == 0) { - return currentDisp; - } - } - - disp = (NI_DispatcherPtr) MemNew(sizeof(NI_Dispatcher)); - if (disp == NULL) - return NULL; - disp->useOutServ = useOutServ; /* value from configfile */ - disp->reqResponse = NULL; - disp->dispHostName = NULL; - disp->dispServiceName = NULL; - disp->dispSerialNo = 0; - disp->localHostAddr[0] = '\0'; - disp->dispHP = NULL; - disp->svcsHP = NULL; - disp->clientPort = 0; - disp->identity = NULL; - disp->dispTimeout = 0; - disp->referenceCount = 0; - disp->someBrokered = FALSE; - disp->brokeredDummy = FALSE; - disp->encryptInfo = encryption; - disp->useSocks = FALSE; -#ifdef SOCKS_CONF - { - FILE *fp; - - if ((fp = FileOpen(SOCKS_CONF, "r")) != NULL) - { - disp->useSocks = TRUE; - FileClose(fp); - } - } -#endif /* SOCKS_CONF */ - } - if (disp->dispHostName != NULL) { - MemFree(disp->dispHostName); - disp->dispHostName = NULL; - } - if (disp->dispServiceName != NULL) { - MemFree(disp->dispServiceName); - disp->dispServiceName = NULL; - } - if (host != NULL) - disp->dispHostName = StringSave(host); - if (svc != NULL) - disp->dispServiceName = StringSave(svc); - - disp->dispSerialNo = dispserialnum; - disp->dispTimeout = timeout; - - return disp; -} /* NI_SetDispatcher */ - - - -/* - * Purpose: Try to establish a connection to the dispatcher - * - * Parameters: - * disp A pointer to the dispatcher structure - * user User name to try on the dispatcher - * group Group name to try on the dispatcher - * password Password for this user name - * dip A pointer to the caller's list of dispatchers; this should - * be used by the caller to update its information - * regarding which dispatchers to try in the future - * (if dip == NULL, then no retries will be made to get - * alternate dispatchers) - * - * Returns: - * -1, if something failed (ni_errno indicates the nature of - * the problem) - * 0, if everything was successful - * 1, if we are connected to the dispatcher which we requested, - * but the list of current dispatchers has changed - * 2, if we are connected to a dispatcher, but not the one - * which we requested - * - * - * Description: - * Perform any WinSock and/or SOCKS initialization as necessary - * Connect to the dispatcher - * Set-up a socket for an incoming connection from a server - * application process (non-SOCKS clients only) - * Send a LOGIN message to the dispatcher - * Wait for an ACK or NACK response from the dispatcher (or for - * a timeout to occur) - * If the response was a NACK due to the dispatcher being a - * backup dispatcher, then try the dispatcher which it - * directs us to - */ - -NLM_EXTERN Int2 NI_InitServices(NI_DispatcherPtr disp, CharPtr user, CharPtr group, CharPtr password, NI_DispInfoPtr PNTR dip) -{ - NIMsgPtr mp, imp; - NILoginPtr loginp; - struct sockaddr_in svcsAddr; - struct timeval timeout; - int ready; - NIDispInfoPtr dispinfo = NULL; - Boolean newDispToTry; - Int2 altDispTries = 0; - Int2 retval = 0; - int status; - fd_set readfds; - NI_PubKeyPtr pubKey = NULL; - Boolean failed; -#ifdef NETP_INET_WSOCK - WSADATA wsaData; -#endif /* NETP_INET_WSOCK */ -#if defined(OS_MAC) && defined(NETP_INET_MACTCP) - extern char * GetLAPType(void); - char *lapType = GetLAPType(); -#endif /* OS_MAC && NETP_INET_MACTCP */ - - if (disp == NULL) - { - ni_errno = NIE_MISC; - return -1; - } - - if (disp->referenceCount > 0 && disp->dispHP != NULL) - { /* already connected */ - disp->referenceCount++; - return 0; - } - -#ifdef NETP_INET_WSOCK - status = WSAStartup(MAKEWORD(1,1),&wsaData); - if (status != 0) - ErrPostEx(SEV_ERROR,0,0,"WinSock 1.1 initialization failure, code %d", status-WSABASEERR); - /* Try WinSock 1.1 and 1.0 in that order of preference */ - if (status != 0 && (status = WSAStartup(MAKEWORD(1,0),&wsaData)) != 0) - { - ErrPostEx(SEV_ERROR,0,0,"WinSock 1.0 initialization failure, code %d", status-WSABASEERR); - ni_errno = NIE_TCPINITFAIL; - return -1; - } - TRACE("%s\n", wsaData.szDescription); - if (stackDescription != NULL) - { - MemFree(stackDescription); - } - stackDescription = StringSave(wsaData.szDescription); - for (status = StrLen(stackDescription) - 1; status >= 0; status--) - { - /* convert characters which are incompatible with VisibleString */ - if (stackDescription[status] < ' ' || stackDescription[status] > '~') - stackDescription[status] = '#'; - } - wsaStartupCount++; - -#endif -#if defined(OS_MAC) && defined(NETP_INET_MACTCP) - if (lapType != NULL) - { - stackDescription = StringSave(lapType); - } -#endif /* OS_MAC && NETP_INET_MACTCP */ -#ifdef OS_UNIX - { - FILE *fp; - char buffer[128]; - int status; - - MemSet(buffer, 0, sizeof(buffer)); - - if ((fp = popen("uname -a","r")) != NULL) - { - FileRead (buffer, 1, sizeof (buffer), fp); - stackDescription = StringSave(buffer); - pclose(fp); - for (status = StrLen(stackDescription) - 1; status >= 0; status--) - { - /* convert characters which are incompatible with VisibleString */ - if (stackDescription[status] < ' ' || stackDescription[status] > '~') - stackDescription[status] = '#'; - } - - } - } -#endif /* OS_UNIX */ -#ifdef NETP_SOCKS - if (disp->useSocks) - { - char path[128]; - - Nlm_ProgramPath(path, sizeof path); - - SOCKSinit(path); - TRACE("Performed SOCKSinit(%s)\n", path); - } -#endif /* NETP_SOCKS */ - - if (disp->dispHostName == NULL) - disp->dispHostName = StringSave(NI_DEFAULT_HOST); - if (disp->dispServiceName == NULL) - disp->dispServiceName = StringSave(NI_DEFAULT_SERVICE); - - do { - newDispToTry = FALSE; - disp->svcsHP = NULL; - if ((disp->dispHP = DispatchConnect(disp, disp->dispHostName, disp->dispServiceName, disp->dispTimeout)) - == NULL) { - NI_DestroyDispInfo(dispinfo); - HaltServices (disp); - ErrPostEx(SEV_WARNING,0,0, "NI_InitServices: Unable to connect to host <%s>, error <%s>", disp->dispHostName, ni_errlist[ni_errno]); - return -1; /* ni_errno remains set */ - } - - if ((disp->svcsHP = MsgMakeHandle(TRUE)) == NULL) { - NI_DestroyDispInfo(dispinfo); - HaltServices (disp); - ErrPostEx (SEV_ERROR, CTX_NCBICORE, CORE_UNKNOWN, "NI_InitServices: Unable to allocate resources to communicate with %s", disp->dispHostName); - return -1; - } - - if (disp->dispTimeout > 0) - { - MsgSetReadTimeout(disp->svcsHP, disp->dispTimeout); - } - - if (!disp->useOutServ) - { /* we need no listening if we are using direct connection */ - if ((disp->clientPort = bindPort(disp->svcsHP->sok, &svcsAddr, disp->loport, disp->hiport, 0)) == 0) { - MsgDestroyHandle(disp->svcsHP); - disp->svcsHP = NULL; - ni_errno = NIE_NOBIND; /* can't bind a free application socket */ - NI_DestroyDispInfo(dispinfo); - HaltServices (disp); - ErrPostEx (SEV_ERROR, CTX_NCBICORE, CORE_UNKNOWN, "NI_InitServices: <%s>", ni_errlist[ni_errno]); - return -1; - } - if ((status = NI_LISTEN(disp->svcsHP->sok, 5)) < 0) { -#ifdef NETP_INET_NEWT - SOCK_ERRNO = ABS(status); -#endif - StringCpy(ni_errtext, strerror(SOCK_INDEX_ERRNO)); - ni_errno = NIE_NOLISTEN; - NI_DestroyDispInfo(dispinfo); - HaltServices (disp); - ErrPostEx (SEV_ERROR, CTX_NCBICORE, CORE_UNKNOWN, "NI_InitServices: <%s> <port %d, errno %d>", ni_errlist[ni_errno], (int) disp->clientPort, (int) SOCK_ERRNO); - return -1; - } - } - - SetIdentity(disp, user, group, NI_DEFAULT_DOMAIN); - - loginp = NI_MakeMsgLogin(); - NI_DestroyUid(loginp->uid); - loginp->uid = NI_MakeUid(); - loginp->seqno = disp->dispHP->seqno++; - loginp->dispserialno = disp->dispSerialNo; - loginp->connectDelay = disp->dispHP->connectDelay; - if (disp->encryptInfo != NULL && NI_EncrAvailable()) - { - loginp->encryptionDesired = TRUE; - if (disp->encryptInfo->data.ptrvalue != NULL) - { - pubKey = (NI_PubKeyPtr) disp->encryptInfo->data.ptrvalue; - loginp->pubKey = (NIPubKeyPtr) NI_PubKeyDup(pubKey); - } - } - CopyIdentity(disp, loginp->uid); - if (password != NULL) - loginp->password = StringSave(password); - mp = MsgBuild(NI_LOGIN, disp->dispHP->conid, (VoidPtr) loginp); - - if (MsgWrite(disp->dispHP, mp, FALSE) < 0) { - if (getAsnError(ni_errtext) == ECONNRESET) - ni_errno = NIE_MAXCONNS; - else - ni_errno = NIE_MSGWRITE; - MsgDestroyHandle(disp->svcsHP); - disp->svcsHP = NULL; - NI_DestroyDispInfo(dispinfo); - HaltServices (disp); - ErrPostEx (SEV_ERROR, CTX_NCBICORE, CORE_UNKNOWN, "NI_InitServices: <%s>", ni_errlist[ni_errno]); - return -1; - } - - /* blocks until ACK or ERROR from dispatcher or TIMEOUT */ - - timeout.tv_sec = (Uint4) NI_TIMEOUT_SECS; - timeout.tv_usec = 0; - FD_ZERO(&readfds); - FD_SET(disp->dispHP->sok, &readfds); - while ((ready = NI_select(FD_SETSIZE, &readfds, NULL, NULL, &timeout)) < 0) { - if (SOCK_ERRNO == EINTR) - ; /* repeat while interrupted */ - else { - MsgDestroyHandle(disp->svcsHP); - disp->svcsHP = NULL; - ni_errno = NIE_SELECT; /* select error */ - NI_DestroyDispInfo(dispinfo); - ErrPostEx (SEV_ERROR, CTX_NCBICORE, CORE_UNKNOWN, "NI_InitServices: <%s>", ni_errlist[ni_errno]); - return -1; - } - } - - if (FD_ISSET(disp->dispHP->sok, &readfds) != 0) { - if ((imp = MsgRead(disp->dispHP, FALSE)) == NULL) { - if (getAsnError(ni_errtext) == ECONNRESET) - ni_errno = NIE_MAXCONNS; - else - ni_errno = NIE_MSGREAD; - - MsgDestroyHandle(disp->svcsHP); - disp->svcsHP = NULL; - NI_DestroyDispInfo(dispinfo); - HaltServices (disp); - ErrPostEx (SEV_ERROR, CTX_NCBICORE, CORE_UNKNOWN, "NI_InitServices: <%s>", ni_errlist[ni_errno]); - return -1; - } - switch (imp->type) { - case NI_ACK: - /************************************************************/ - /* even though we connected successfully to the dispatcher, */ - /* it may have given us more up-to-date information on the */ - /* latest list of dispatchers which should be tried; if so, */ - /* pass the updated list back to the caller */ - /************************************************************/ - if (imp->msun.ack->dispinfo != NULL) { - if (dispinfo != NULL) - { - NI_DestroyDispInfo(dispinfo); - dispinfo = NULL; - } - dispinfo = imp->msun.ack->dispinfo; - imp->msun.ack->dispinfo = NULL; /* for clean free */ - } - if (disp->encryptInfo != NULL && NI_EncrAvailable()) - { - if (dispinfo != NULL && dispinfo->pubKey != NULL) - { - failed = FALSE; - if (pubKey == NULL) - { - failed = Message(MSG_YN, ERR_KEY_NOPREVKEY) == - ANS_NO; - ni_errno = NIE_NEWKEYNOTACCPT; - } else { - if (! NI_PubKeysEqual(pubKey, (NI_PubKeyPtr) dispinfo->pubKey)) - { - failed = Message(MSG_YN, ERR_KEY_MISMATCH) == - ANS_NO; - ni_errno = NIE_NEWKEYMISMATCH; - } - } - if (failed) - { - HaltServices(disp); - MsgDestroy(imp); - return -1; - } else { - /* replace the key */ - NI_DestroyPubKey((NIPubKeyPtr) pubKey); - pubKey = (NI_PubKeyPtr) dispinfo->pubKey; - dispinfo->pubKey = NULL; - disp->encryptInfo->data.ptrvalue = (Pointer) pubKey; - } - } - } - if (dispinfo != NULL && dip != NULL) { - if (*dip != NULL) - NI_DestroyDispInfo((NIDispInfoPtr) *dip); - *dip = (NI_DispInfoPtr) dispinfo; - dispinfo = NULL; - retval = 1; - } - else { - NI_DestroyDispInfo(dispinfo); - } - if (imp->msun.ack->motd != NULL && - imp->msun.ack->motd[0] != NULLB) - { - disp->motd = imp->msun.ack->motd; - imp->msun.ack->motd = NULL; /* for clean free */ - } - if (imp->msun.ack->adminInfo != NULL && - imp->msun.ack->adminInfo[0] != NULLB) - { - disp->adminInfo = imp->msun.ack->adminInfo; - imp->msun.ack->adminInfo = NULL; /* for clean free */ - } -#ifdef OS_UNIX - signal(SIGPIPE, SIG_IGN); /* catch socket errors */ -#endif /* OS_UNIX */ - MsgDestroy(imp); - disp->referenceCount++; - if (currentDisp == NULL) - { - currentDisp = disp; - } - return retval; /* only good return */ - - case NI_NACK: - ni_errno = (enum ni_error) imp->msun.nack->code; - if (imp->msun.nack->reason != NULL) - { - StringCpy(ni_errtext, imp->msun.nack->reason); - } else { - ni_errtext[0] = '\0'; - } - if (dispinfo != NULL) - { - NI_DestroyDispInfo(dispinfo); - dispinfo = NULL; - } - dispinfo = imp->msun.nack->dispinfo; - imp->msun.nack->dispinfo = NULL; /* for clean free */ - if (ni_errno == NIE_BACKUPDISP && dispinfo != NULL && - dispinfo->numdispatchers > 0 && dip != NULL && - ++altDispTries < MAX_ALT_DISP_TRIES) - { - MsgDestroy(imp); - HaltServices (disp); - NI_SetDispatcher(disp, dispinfo->displist[0], disp->dispServiceName, - disp->dispTimeout, dispinfo->serialno, disp->encryptInfo, - disp->useOutServ); - newDispToTry = TRUE; - retval = 2; - break; - } - MsgDestroy(imp); - MsgDestroyHandle(disp->svcsHP); - disp->svcsHP = NULL; - NI_DestroyDispInfo(dispinfo); - HaltServices (disp); - ErrPostEx (SEV_ERROR, CTX_NCBICORE, CORE_UNKNOWN, "NI_InitServices: <%s>\n%s", ni_errlist[ni_errno], ni_errtext); - return -1; - - default: - MsgDestroy(imp); - ni_errno = NIE_MSGUNK; - MsgDestroyHandle(disp->svcsHP); - disp->svcsHP = NULL; - NI_DestroyDispInfo(dispinfo); - HaltServices (disp); - ErrPostEx (SEV_ERROR, CTX_NCBICORE, CORE_UNKNOWN, "NI_InitServices: <%s>", ni_errlist[ni_errno]); - return -1; - } - } - } while (newDispToTry); - - MsgDestroyHandle(disp->svcsHP); - disp->svcsHP = NULL; - ni_errno = NIE_LOGTIMEOUT; /* TIMEOUT */ - NI_DestroyDispInfo(dispinfo); - HaltServices (disp); - ErrPostEx (SEV_ERROR, CTX_NCBICORE, CORE_UNKNOWN, "NI_InitServices: <%s>", ni_errlist[ni_errno]); - return -1; -} /* NI_InitServices */ - - -/* - * Purpose: Init network services based on information in config file - * - * Parameters: - * configFile Name of NCBI-style configuration file. If NULL, defaults - * to "NCBI" - * configSection Section with NCBI-style configuration file. If NULL, - * defaults to "NET_SERV" - * showMonitor Boolean; if TRUE, display a monitor while re-trying - * for an alternate dispatcher - * lastDispatcher Pointer to where this function should store the name - * of the dispatcher which was actually used (may be NULL - * if the caller does not care about this value) - * lastDispLen Maximum length of lastDispatcher - * - * Returns: - * NULL, if unable to contact dispatcher - * a pointer to the Dispatcher structure, otherwise - * - * - * Description: - * Extracts a dispatcher name and a user name from a configuration - * file. If necessary, tries other dispatchers, in order, as - * listed in configuration file. Also sets up encryption, if - * the client is encryption-capable and encryption is requested - * in the configuration file. - * - * - * Note: - * This function is provided as a convenience to developers who - * wish to use Network Services. Use of this function is not - * integral to the use of Network Services ... it is merely a - * convenience. - */ - -NLM_EXTERN NI_DispatcherPtr NI_GenericInit (CharPtr configFile, CharPtr configSection, Boolean showMonitor, CharPtr lastDispatcher, Int2 lastDispLen) -{ - char *def_user; - char username[64]; - char groupname[20]; - char password[20]; - char dispname[60]; - char disp_config[10]; - char disp_msg[110]; - char buf[60]; - Boolean more_disps; - int alternate = 1; - int disp_timeout; - Int4 disp_serialno; - Monitor *mon = NULL; - NI_DispInfoPtr dip = NULL; - NI_DispatcherPtr disp = NULL; - Boolean someBrokered; - Boolean useOutServ; - ValNodePtr encryptInfo = NULL; - NI_PubKeyPtr keyCopy = NULL; - Boolean doEncr = FALSE; - Boolean quitOnDispConnFailure = FALSE; - Boolean showMessage = FALSE; - Int4 numBrokeredServices; -#ifdef OS_UNIX - char *getlogin PROTO((void)); -#endif - - /******************* open the network connnection *********/ -#define NI_DISP_NAME "dispatch1.nlm.nih.gov" -#define NI_USER_NAME "anonymous" -#define NI_GROUP_NAME "GUEST" - - def_user = NI_USER_NAME; - - if (configFile == NULL) - configFile = "NCBI"; - if (configSection == NULL) - configSection = "NET_SERV"; - - GetAppParam(configFile, configSection, "DISP_USERNAME", NI_USER_NAME, username, - sizeof username); - /* the user's login name overrides the config file */ - /* for UNIX or VMS systems (or, for the future, any system where the */ - /* user name can be determined), use the user's login name as the default */ - def_user = NULL; -#ifdef OS_UNIX - if ((def_user = getenv("USER")) == NULL) - { - def_user = getlogin(); - } -#endif -#ifdef OS_VMS - def_user = getenv("USER"); -#endif - if (def_user != NULL) - { - StrNCpy(username, def_user, sizeof username); - } - - GetAppParam(configFile, configSection, "DISP_GROUPNAME", NI_GROUP_NAME, groupname, - sizeof groupname); - GetAppParam(configFile, configSection, "DISP_PASSWORD", "", password, - sizeof password); /* default = NONE */ - - GetAppParam(configFile, configSection, "DISP_TIMEOUT", "0", buf, sizeof buf); - disp_timeout = atoi(buf); - - GetAppParam(configFile, configSection, "DISPSERIALNO", "0", buf, sizeof buf); - disp_serialno = atoi(buf); - - GetAppParam(configFile, configSection, "DISPATCHER", NI_DISP_NAME, dispname, - sizeof dispname); - - GetAppParam(configFile, configSection, "DIRECT_SVC_CON", "FALSE", buf, - sizeof(buf)); - useOutServ = StrICmp(buf, "TRUE") == 0; - - GetAppParam(configFile, configSection, "SOME_BROKERED", "FALSE", buf, sizeof buf); - someBrokered = StrICmp(buf, "TRUE") == 0; - if (someBrokered) { - GetAppParam(configFile, configSection, "BROKERED_COUNT", "1", buf, sizeof buf); - numBrokeredServices = atoi(buf); - if (numBrokeredServices <= 0) { - someBrokered = FALSE; - } else { - sprintf (buf, "%ld", (long) numBrokeredServices - 1); - TransientSetAppParam(configFile, configSection, "BROKERED_COUNT", buf); - } - } - - GetAppParam(configFile, configSection, "DISP_RECONN_ACTION", "CONT", buf, sizeof buf); - showMessage = StrICmp(buf, "ASK") == 0; - quitOnDispConnFailure = StrICmp(buf, "QUIT") == 0; - - GetAppParam(configFile, configSection, "ENCRYPTION_DESIRED", "FALSE", buf, sizeof buf); - if (StrICmp(buf, "TRUE") == 0 && NI_EncrAvailable()) - { - doEncr = TRUE; - encryptInfo = ValNodeNew(NULL); - encryptInfo->data.ptrvalue = (Pointer) NI_ReadPubKeyFromConfig(); - keyCopy = NI_PubKeyDup((NI_PubKeyPtr) encryptInfo->data.ptrvalue); - } - - do { - if (alternate == 2 && showMonitor) - { - mon = MonitorStrNew("Unable to contact primary dispatcher", 35); - } - if (alternate >= 2) - { - if (showMessage) - { - sprintf (disp_msg, "Unable to contact primary dispatcher. Ready to try\ndispatcher #%d <", alternate); - StrCat(disp_msg, dispname); - StrCat(disp_msg, ">. Continue?"); - if (Message(MSG_YN, disp_msg) == ANS_NO) - break; - } else { - sprintf(disp_msg, "Trying dispatcher #%d <", alternate); - StrCat(disp_msg, dispname); - StrCat(disp_msg, ">"); - if (showMonitor) { - MonitorStrValue(mon, disp_msg); - } - } - } - - if (lastDispatcher != NULL) { - StrNCpy(lastDispatcher, dispname, lastDispLen); - } - - disp = NI_SetDispatcher (NULL, dispname, NULL, disp_timeout, disp_serialno, encryptInfo, useOutServ); - - if (someBrokered) { - disp->brokeredDummy = TRUE; - disp->someBrokered = TRUE; - disp->referenceCount++; - ValNodeFree (encryptInfo); - return disp; - } - - if (NI_InitServices(disp, username, groupname[0] == '\0' ? 0 : groupname, - password[0] == '\0' ? 0 : password, &dip) >= 0) - { - if (dip != NULL && dip->serialno != disp_serialno) { - NI_SetDispConfig (&dip, dispname, sizeof dispname); - } - if (mon != NULL) - MonitorFree(mon); - if (disp->encryptInfo != NULL && - disp->encryptInfo->data.ptrvalue != NULL && - ! NI_PubKeysEqual(keyCopy, - (NI_PubKeyPtr) disp->encryptInfo->data.ptrvalue)) - { - NI_WritePubKeyToConfig ((NI_PubKeyPtr) disp->encryptInfo->data.ptrvalue); - } - NI_DestroyPubKey ((NIPubKeyPtr) keyCopy); - return disp; - } - ErrShow (); - NI_EndServices (disp); - sprintf(disp_config, "DISP_ALT_%d", alternate++); - more_disps = GetAppParam(configFile, configSection, disp_config, "", dispname, - sizeof dispname); - if (doEncr) - { - encryptInfo = ValNodeNew(NULL); - encryptInfo->data.ptrvalue = (Pointer) - NI_PubKeyDup((NI_PubKeyPtr) keyCopy); - } - } while (more_disps && ! quitOnDispConnFailure); - - if (mon != NULL) - MonitorFree(mon); - - ValNodeFree (encryptInfo); - NI_DestroyPubKey ((NIPubKeyPtr) keyCopy); - ErrPostEx(SEV_ERROR,0,0, "NI_InitServices: Unable to connect to any dispatcher"); - return NULL; -} - - -/* - * Purpose: Get a network service based on information in config file - * - * Parameters: - * disp Pointer to the dispatcher structure obtained from a - * previous call to NI_SetDispatcher or NI_GenericInit - * configFile Name of NCBI-style configuration file. If NULL, defaults - * to "NCBI" - * defService The default service/resource/resource-type name, if - * not specified otherwise in configuration file. - * hasResource Boolean; if TRUE, ask for a resource when requesting - * service - * - * Returns: - * NULL, if unable to obtain service - * a pointer to the service-structure, otherwise - * - * - * Description: - * Extracts a service name and other service data from a - * configuration file, and attempts to obtain that service. - * As a special case, handle communication with a "brokered - * server" (a server which is already listening on a port, where - * no communication needs to be performed with the dispatcher). - * Also disable data encryption for this service request, if - * explicitly specified in the configuration file. - * - * - * Note: - * This function is provided as a convenience to developers who - * wish to use Network Services. Use of this function is not - * integral to the use of Network Services ... it is merely a - * convenience. - * - * For UNIX systems, environment variables can be used to - * override the config. file's values for SERVICE_NAME and - * RESOURCE_TYPE. - */ - -NLM_EXTERN NI_HandPtr NI_GenericGetService (NI_DispatcherPtr disp, CharPtr configFile, CharPtr configSection, CharPtr defService, Boolean hasResource) -{ - char buf[40]; - char service[40]; - char resource[40]; - char res_type[40]; - int serv_min; - int serv_max; - int res_min; - int res_max; - char brokeredIpaddr[40]; - Uint2 port; - NI_HandPtr result; - ValNodePtr savEncrypt; -#ifdef OS_UNIX - CharPtr envName = (CharPtr)MemNew(StrLen(configSection) + 20); - CharPtr envValue; -#endif - - if (configFile == NULL) - configFile = "NCBI"; - - GetAppParam(configFile, configSection, "SERVICE_NAME", defService, - service, sizeof service); -#ifdef OS_UNIX - /* environment variable overrides config. file */ - sprintf (envName, "NI_SERVICE_NAME_%s", configSection); - if ((envValue = getenv(envName)) != NULL) - { - StrCpy (service, envValue); - } -#endif /* OS_UNIX */ - GetAppParam(configFile, configSection, "SERV_VERS_MIN", "1", - buf, sizeof buf); - serv_min = atoi(buf); - GetAppParam(configFile, configSection, "SERV_VERS_MAX", "0", - buf, sizeof buf); - serv_max = atoi(buf); - - res_min = 1; - res_max = 0; - - if (hasResource) { - GetAppParam(configFile, configSection, "RESOURCE_NAME", defService, - resource, sizeof resource); - GetAppParam(configFile, configSection, "RESOURCE_TYPE", defService, - res_type, sizeof res_type); -#ifdef OS_UNIX - /* environment variable overrides config. file */ - sprintf (envName, "NI_RESOURCE_TYPE_%s", configSection); - if ((envValue = getenv(envName)) != NULL) - { - StrCpy (res_type, envValue); - } -#endif /* OS_UNIX */ - GetAppParam(configFile, configSection, "RES_VERS_MIN", "1", - buf, sizeof buf); - res_min = atoi(buf); - GetAppParam(configFile, configSection, "RES_VERS_MAX", "0", - buf, sizeof buf); - res_max = atoi(buf); - } - -#ifdef OS_UNIX - MemFree (envName); -#endif /* OS_UNIX */ - - if (disp->someBrokered) - { - GetAppParam(configFile, configSection, "BROKERED_PORT", "0", - buf, sizeof buf); - port = htons(atoi(buf)); - GetAppParam(configFile, configSection, "BROKERED_IPADDR", "", - brokeredIpaddr, sizeof brokeredIpaddr); - if (port != 0 && brokeredIpaddr[0] != '\0') - { /* simulate service request by connecting to that port */ - struct sockaddr_in serv_addr; - NI_HandPtr sHP; - int timeout = 30; - int status; - - MemFill((VoidPtr) &serv_addr, '\0', sizeof(serv_addr)); - serv_addr.sin_family = AF_INET; - serv_addr.sin_addr.s_addr = inet_addr(brokeredIpaddr); - serv_addr.sin_port = port; - - if ((sHP = MsgMakeHandle(TRUE)) == NULL) - return NULL; - MsgSetLJError(sHP); - sHP->hostname = StringSave(brokeredIpaddr); - - if (activityHook != NULL) - { - activityHook(sHP, NetServHook_svcreq, 0); - } - - RETRY: -#ifndef NETP_INET_NEWT - if ((status = NI_CONNECT(sHP->sok, (struct sockaddr PNTR) &serv_addr, sizeof(serv_addr))) < 0) { /* } */ -#else - if ((status = NI_CONNECT(sHP->sok, &serv_addr, sizeof(serv_addr))) < 0) { - SOCK_ERRNO = ABS(status); -#endif - switch (SOCK_ERRNO) { - case EINTR: - goto RETRY; - -#ifdef NETP_INET_PCNFS - /* This is apparently a bug in PC-NFS 4.0 ... a connection attempt */ - /* on a non-blocking socket yields errno == 0 */ - case 0: -#endif /* NETP_INET_PCNFS */ - case EWOULDBLOCK: - case EINPROGRESS: - /* if the connect()ion is not established immediately, a */ - /* select() can be performed where the corresponding "write" */ - /* file descriptor will be enabled once the connect()ion has been*/ - /* established */ - if (sokselectw(sHP->sok, timeout) == 0) { - return sHP; - } - break; - - default: - break; - } - MsgDestroyHandle(sHP); - ni_errno = NIE_BROKSVCCONN; /* can't connect to brokered service */ - return NULL; - } - { - Char buf[16]; - Char key[8]; - Int2 len; - - if ((len = GetAppParam("NCBI", "NET_SERV", "DESKEY", "", buf, sizeof buf)) > 0 && - (AsnTypeStringToHex(buf, len, key, NULL) == 0)) - - { - NI_SetupDESEncryption(sHP, (UcharPtr) key); - } - } - return sHP; - } else { - if (disp->brokeredDummy) - { /* JAE ... establish a true dispatcher connection here */ - } - } - } - - savEncrypt = disp->encryptInfo; - if (GetAppParam(configFile, configSection, "ENCRYPTION", "TRUE", - buf, sizeof buf) > 0 && StrICmp(buf, "FALSE") == 0) - { - /* temporarily disable encryption */ - disp->encryptInfo = NULL; - } - result = NI_ServiceGet(disp, service, serv_min, serv_max, - hasResource ? resource : 0, res_type, res_min, - res_max); - disp->encryptInfo = savEncrypt; - - return result; -} - - -/* - * Purpose: Write dispatcher-configuration information to a config file - * - * Parameters: - * dipp A pointer to the caller's list of dispatchers, obtained - * from NI_InitServices() - * dispatcher The caller's dispatcher string - * dispLen Length of the caller's dispatcher string - * - * Returns: - * 0, if bad parameters were provided - * the dispatcher-list serial number, otherwise - * - * - * Description: - * Sets up the "NCBI" configuration file with the following - * entries in the "NET_SERV" section: - * * DISPATCHER is the primary dispatcher name - * * DISP_ALT_n for every alternate dispatcher, 1 <= n, a smaller - * n indicates a higher priority alternate dispatcher - * * DISPSERIALNO is the serial number of the dispatcher list - * obtained from a remote dispatcher. This serial number should - * be unique for all time ... the dispatcher's serial number - * must be changed whenever the master list is modified. - * - * Note: - * This configuration mechanism is only _one_ recommended - * mechanism for network services dispatcher configuration. The - * application may perform this configuration in any manner - * deemed appropriate by the application programmer. - * - * The value returned by this function is the recommended value - * for the dispserialno parameter in a subsequent call to - * NI_InitDispatcher(). - */ - -NLM_EXTERN Int4 NI_SetDispConfig(NI_DispInfoPtr PNTR dipp, CharPtr dispatcher, Int2 dispLen) -{ - Int2 num; - Char dispConfig[20]; - char buf[10]; - Int4 retval; - NI_DispInfoPtr dip; - - if (dipp == NULL || (dip = *dipp) == NULL) - { - if (dispatcher != NULL) - { - dispatcher[0] = '\0'; - } - return 0; - } - - if (dip->numdispatchers > 0 && dip->displist != NULL) - { - StringNCpy (dispatcher, dip->displist[0], dispLen); - SetAppParam ("NCBI", "NET_SERV", "DISPATCHER", dip->displist[0]); - } - - for (num = 1; num < dip->numdispatchers; num++) - { - sprintf (dispConfig, "DISP_ALT_%d", num); - SetAppParam ("NCBI", "NET_SERV", dispConfig, dip->displist[num]); - } - - /* wipe out any extraneous old configuration */ - for (num = dip->numdispatchers; num < 100; num++) - { - sprintf (dispConfig, "DISP_ALT_%d", num); - if (GetAppParam("NCBI", "NET_SERV", dispConfig, "", buf, sizeof buf) <= 0) - { - break; - } - SetAppParam ("NCBI", "NET_SERV", dispConfig, NULL); - } - - retval = dip->serialno; - sprintf (buf, "%ld", (long) dip->serialno); - SetAppParam ("NCBI", "NET_SERV", "DISPSERIALNO", buf); - - NI_DestroyDispInfo ((NIDispInfoPtr) dip); - *dipp = NULL; - - return retval; -} - - -/* - * Purpose: End use of network services - * - * Parameters: - * disp A pointer to the dispatcher structure - * - * Returns: - * 0 (always) - * - * - * Description: - * Tear down the sockets and data structures associated with - * the dispatcher and a server, and free all memory associated - * with data structures. - */ - -NLM_EXTERN Int2 NI_EndServices(NI_DispatcherPtr disp) -{ - Int2 openSockets; - - if (disp == NULL) - return 0; - - if (disp->referenceCount > 0) - disp->referenceCount--; - - if (disp->referenceCount <= 0) - { - if (disp == currentDisp) - { - currentDisp = NULL; - } - - HaltServices (disp); - NI_SetDispatcher(disp, NULL, NULL, 0, 0, NULL, FALSE); /* free mem */ - - if (stackDescription != NULL) - { - MemFree(stackDescription); - stackDescription = NULL; - } - MemFree(disp->adminInfo); - MemFree(disp->motd); - MemFree(disp); - - /* For historical reasons pertaining to Network Entrez, a single open - socket does not constitute an error in this context. However, at - program exit time, a single open socket does constitute a serious - problem. */ - if ((openSockets = NI_SocketsOpen()) > 1) - { - ErrPostEx(SEV_WARNING,0,0, "At end-services time, %d sockets are still open", openSockets); - } - } - - return 0; -} /* NI_EndServices */ - - - -/* - * Purpose: Request a catalog from the dispatcher - * - * Parameters: - * disp A pointer to the dispatcher structure - * - * Returns: - * NULL, if unable to obtain the catalog - * a pointer to the received catalog data structure, otherwise - * - * - * Description: - * Send a request to the dispatcher, requesting a catalog, and - * wait (up to some timeout) for a response. The dispatcher's - * response should either be that catalog, or a NACK. - */ - -NLM_EXTERN NICatalogPtr NI_GetCatalog(NI_DispatcherPtr disp) -{ - NICatalogPtr catp; - NIMsgPtr mp, imp; - NICmdPtr cmdp; - struct timeval timeout; - int ready; - fd_set readfds; - - if (disp == NULL) - return NULL; - - cmdp = (NICmdPtr) NI_MakeMsgCmd(); - cmdp->seqno = disp->dispHP->seqno++; - cmdp->code = NI_SEND_CATALOG; - if ((mp = MsgBuild(NI_COMMAND, disp->dispHP->conid, (VoidPtr) cmdp)) == NULL) { - ni_errno = NIE_MISC; /* unable to alloc mem for Msg */ - return NULL; - } - if (MsgWrite(disp->dispHP, mp, FALSE) < 0) { - ni_errno = NIE_MSGWRITE; - return NULL; - } - - /* blocks until response from dispatcher or TIMEOUT */ - - timeout.tv_sec = (Uint4) NI_TIMEOUT_SECS; - timeout.tv_usec = 0; - FD_ZERO(&readfds); - FD_SET(disp->dispHP->sok, &readfds); - while ((ready = NI_select(FD_SETSIZE, &readfds, NULL, NULL, &timeout)) < 0) { - if (SOCK_ERRNO == EINTR) - ; /* repeat while interrupted */ - else { - ni_errno = NIE_SELECT; /* select error */ - return NULL; - } - } - - if (FD_ISSET(disp->dispHP->sok, &readfds) != 0) { - if ((imp = MsgRead(disp->dispHP, FALSE)) == NULL) { - LOG_SOCKET(disp->dispHP->sok, FALSE); - NI_CLOSESOCKET(disp->dispHP->sok); - ni_errno = NIE_MSGREAD; - return NULL; - } - switch (imp->type) { - case NI_CATALOG: - catp = imp->msun.catalog; - imp->msun.catalog = NULL; - ni_errno = NIE_NO_ERROR; - MsgDestroy(imp); - return catp; - - case NI_NACK: - ni_errno = (enum ni_error) imp->msun.nack->code; - if (imp->msun.nack->reason != NULL) - StringCpy(ni_errtext, imp->msun.nack->reason); - else - ni_errtext[0] = '\0'; - MsgDestroy(imp); - return NULL; - - default: - MsgDestroy(imp); - ni_errno = NIE_MSGUNK; /* Unknown MSG type */ - return NULL; - } - } - ni_errno = NIE_CMDTIMEOUT; /* TIMEOUT */ - return NULL; -} /* NI_GetCatalog */ - - - -/* - * Purpose: Create the data structure for a service request - * - * Parameters: - * disp A pointer to the dispatcher structure - * - * Returns: - * a pointer to the newly created data structure - * - * - * Description: - * Allocate the memory for a service request data structure, - * and fill in some of the fields. - * Note: - * There are two ways for a program to issue a service request: - * (1) Multi-step, general method (like IRS form 1040) - * * Build a request with NI_SVCRequestBuild() - * * Populate the request with a specific service request using - * NI_RequestSetService() - * * Populate the request with zero or more resource requests - * calling NI_RequestAddResource() once for every resource - * * Send the request with NI_ServiceRequest(), and (hopefully) - * obtain a connection to a service provider - * * At some later time, delete the request (to save memory) - * (2) One-stop shopping, for simple requirement (like form 1040EZ) - * * Do everything for a service and up to one resource using - * NI_ServiceGet() - */ - -NLM_EXTERN NI_ReqPtr NI_SVCRequestBuild(NI_DispatcherPtr disp) -{ - NI_ReqPtr reqp; - - if (disp == NULL) - return NULL; - - reqp = (NI_ReqPtr) NI_MakeRequest(); - reqp->clientPort = (Uint2) disp->clientPort; - if (disp->useSocks) - { - /* tell the Dispatcher that it should use getpeername() to determine */ - /* the IP address of the SOCKS daemon */ - reqp->clientAddr = StringSave("0.0.0.0"); - } else { - reqp->clientAddr = StringSave(disp->localHostAddr); - } - reqp->dispatcher = disp; /* should not be freed when destroying Req */ - - return reqp; -} /* NI_SVCRequestBuild */ - - - -/* - * Purpose: Destroy a service request data structure - * - * Parameters: - * reqp A pointer to the data structure to be destroyed - * - * - * Description: - * Free all the resources associated with a service request - */ - -NLM_EXTERN void NI_SVCRequestDestroy(NI_ReqPtr reqp) -{ - NI_DestroyRequest(reqp); -} /* NI_SVCRequestDestroy */ - - - -/* - * Purpose: Make a service request for a service and up to one resource - * - * Parameters: - * disp A pointer to the dispatcher structure - * svc Name of requested service - * svcvermin Minimum version number requested for this service - * svcvermax Maximum version number requested for this service - * res Name of requested resource (possibly NULL) - * resvermin Minimum version number requested for this resource - * resvermax Maximum version number requested for this resource - * - * Returns: - * The result of the service request - * - * - * Description: - * Create and issue a service request for the specified - * parameters. - */ - -NLM_EXTERN NI_HandPtr NI_ServiceGet(NI_DispatcherPtr disp, CharPtr svc, Uint2 svcvermin, Uint2 svcvermax, CharPtr res, CharPtr restype, Uint2 resvermin, Uint2 resvermax) -{ - NI_ReqPtr reqp; - - if (disp == NULL) - return NULL; - - reqp = NI_SVCRequestBuild(disp); - NI_RequestSetService(reqp, svc, svcvermin, svcvermax); - if (res != NULL) - NI_RequestAddResource(reqp, res, restype, resvermin, resvermax); - - return NI_ServiceRequest(reqp); -} /* NI_ServiceGet */ - - - -/* - * Purpose: Issue the specified service request - * - * Parameters: - * req The pre-formatted service request - * - * Returns: - * A message handle to the server which is servicing our request, - * if successful - * NULL, otherwise (ni_errno will indicate a more precise cause) - * - * - * Description: - * Create and issue a service request for the specified - * service request, as follows: - * - * * Create a data structure to which the resulting service - * connection can be attached - * * Send the service request to the dispatcher - * - * old - style connection: - * - * * Wait for the following two events, in either order: - * (1) A response from the dispatcher, which is either a - * SVC_RESPONSE (good), or a NACK (bad) {or a timeout} - * (2) A connection request from the server, which we then - * accept() - * * If both of the two events occur successfully, return with - * success, else, return with failure. - * - * old-style / direct connection switch - * (currently disabled) - * - * * After NACK was received in old - style connection we don't - * worry, set disp->useOutServ to TRUE and return to the beginning - * of the function. All service request will be repeated with - * direct connection. - * - * direct connection: - * - * * Wait for the following events: - * (1) A response from the dispatcher, which is either a - * SVC_REQUEST (good), or a NACK (bad) {or a timeout} - * * In the case of SVC_REQUEST we send this request directly - * to the server and wait for next event: - * (2) A response from the dispatcher, which is either a - * SVC_RESPONSE (good), or a NACK (bad) {or a timeout} - * * If both of the two events occur successfully, return with - * success, else, return with failure. - * - * Note: - * If the caller's Dispatcher data structure indicates that - * encryption should be performed, then a DES key is - * pseudorandomly generated prior to issuing the service request, - * and is encrypted using public-key encryption. Following - * successful establishment of the client<->server session, the - * DES key is used to encrypt the ensuing session using - * cypher-block-chaining. - * - * For SOCKSified clients, a different protocol is used where - * the client first sends a "pre-service-request", asking the - * IP address of the computer to which the Dispatcher will assign - * the request. Upon receipt of a NI_SVC_PRE_RESPONSE message - * containing that IP address, the client performs a SOCKSified - * bind()ing indicating that the specified IP address will - * "call back". Having determine the port number which has - * been bound on the SOCKS proxy, the client sends the "real" - * service request containing the SOCKS proxy's port number - * and a reminder as to which IP address the Dispatcher - * "promised" would be assigned. After that, processing - * proceeds normally, with the server connecting-back (via - * the SOCKS proxy) and the Dispatcher sending a SVC_RESPONSE - * acknowledgement. - * - * Note that SOCKS and encryption are completely orthogonal - * with respect to each other, and a client may use either, both, - * or neither. - */ - -NLM_EXTERN NI_HandPtr NI_ServiceRequest(NI_ReqPtr req) -{ - NI_HandPtr sconnhp; -#ifdef NETP_INET_MACTCP - Int4 sconnlen; -#else - int sconnlen; -#endif - struct sockaddr_in sconnaddr; - NIMsgPtr mp, imp; - NISvcReqPtr svcreqp; - struct timeval timeout; - Monitor *mon = NULL; - int ready; - Boolean disp_contact = FALSE, serv_contact = FALSE; - Uint4 this_req; - fd_set readfds; - NI_DispatcherPtr disp = req->dispatcher; - Uchar desKey[8]; -#ifdef NETP_SOCKS - struct sockaddr_in svcsAddr; - Int2 status; -#endif - -NEXTTRY: - ni_errtext[0] = '\0'; - if (disp->useOutServ) { - if ((sconnhp = MsgMakeHandle(TRUE)) == NULL) { - ni_errno = NIE_MAKEHAND; - return NULL; - } - } else { - if ((sconnhp = MsgMakeHandle(FALSE)) == NULL) { - ni_errno = NIE_MAKEHAND; - return NULL; - } - } - - svcreqp = NI_MakeMsgSvcreq(); - svcreqp->seqno = disp->dispHP->seqno++; - svcreqp->platform = (Uint4) NI_GetPlatform(); - if (stackDescription != NULL) - { - svcreqp->applId = StringSave(stackDescription); - } - if (disp->encryptInfo != NULL && NI_EncrAvailable()) - { - UcharPtr encryptedDesKey; - Int2 encryptedLen; - - NI_GenerateDESKey (desKey); - encryptedLen = NI_PubKeyEncrypt((NI_PubKeyPtr) disp->encryptInfo->data.ptrvalue, - desKey, sizeof desKey, &encryptedDesKey); - if (encryptedLen <= 0) - { - NI_DestroyRequest(req); - MsgDestroyHandle(sconnhp); - ni_errno = NIE_PUBKEYENCRFAIL; - return NULL; - } - /* convert the DES key into a ByteStore */ - svcreqp->desKey = BSNew(encryptedLen); - BSWrite (svcreqp->desKey, (VoidPtr) encryptedDesKey, encryptedLen); - MemFree (encryptedDesKey); - } - this_req = svcreqp->seqno; - CopyIdentity(disp, svcreqp->uid); - NI_DestroyRequest(svcreqp->request); - svcreqp->request = req; - - if (disp->useSocks) - { - svcreqp->wantPreResponse = TRUE; - } - /* we want to get a ticket for the direct connection */ - if (disp->useOutServ) { - svcreqp->want_ticket = TRUE; - } - - if ((mp = MsgBuild(NI_SVC_REQUEST, disp->dispHP->conid, (VoidPtr) svcreqp)) == NULL) { - NI_DestroyRequest(req); - MsgDestroyHandle(sconnhp); - ni_errno = NIE_MISC; /* unable to alloc mem for Msg */ - return NULL; - } - - if (MsgWrite(disp->dispHP, mp, disp->useSocks) < 0) { - MsgDestroyHandle(sconnhp); - ni_errno = NIE_MSGWRITE; - return NULL; - } - - /* blocks until SVC_RESPONSE from dispatcher and service or NACK or TIMEOUT */ - while ( !disp_contact || !serv_contact) { - timeout.tv_sec = (Uint4) NI_TIMEOUT_SECS; - timeout.tv_usec = 0; - FD_ZERO(&readfds); - FD_SET(disp->dispHP->sok, &readfds); - if (! disp->useOutServ) - FD_SET(disp->svcsHP->sok, &readfds); - while ((ready = NI_select(FD_SETSIZE, &readfds, NULL, NULL, &timeout)) < 0) { - if (SOCK_ERRNO == EINTR) - ; /* repeat while interrupted */ - else { - MsgDestroyHandle(sconnhp); - ni_errno = NIE_SELECT; /* select error */ - return NULL; - } - } - if (ready == 0) { - MsgDestroyHandle(sconnhp); - ni_errno = NIE_DSPTIMEOUT; /* TIMEOUT */ - return NULL; - } - if (FD_ISSET(disp->dispHP->sok, &readfds) != 0) { - if ((imp = MsgRead(disp->dispHP, FALSE)) == NULL) { - LOG_SOCKET(disp->dispHP->sok, FALSE); - NI_CLOSESOCKET(disp->dispHP->sok); - MsgDestroyHandle(sconnhp); - ni_errno = NIE_MSGREAD; - return NULL; - } - disp_contact = TRUE; - switch (imp->type) { - case NI_SVC_PRE_RESPONSE: -#ifdef NETP_SOCKS - if (disp->useSocks) - { - /* must defer binding and listening for SOCKS connection */ - /* until server's IP address is known */ - - TRACE("Processing SOCKS SVC_PRE_RESPONSE\n"); - /* SOCKS can't deal well with non-blocking connections */ - NI_SETBLOCKING(disp->svcsHP->sok); - - if ((disp->clientPort = bindPort(disp->svcsHP->sok, &svcsAddr, disp->loport, disp->hiport, imp->msun.preresp->server_ip)) == 0) { - TRACE("bindPort failed\n"); - MsgDestroyHandle(sconnhp); - disp->svcsHP = NULL; - ni_errno = NIE_NOBIND; /* can't bind a free application socket */ - ErrPost (CTX_NCBICORE, CORE_UNKNOWN, "NI_ServiceRequest: <%s>", ni_errlist[ni_errno]); - return NULL; - } - TRACE("bindPort succeeded, port = %d\n", disp->clientPort); - if (NI_GETSOCKNAME(disp->svcsHP->sok, &svcsAddr, &sconnlen) >= 0) - disp->clientPort = ntohs(svcsAddr.sin_port); - req->clientPort = disp->clientPort; - svcreqp->server_ip = imp->msun.preresp->server_ip; - svcreqp->wantPreResponse = FALSE; - if (MsgWrite(disp->dispHP, mp, FALSE) < 0) { - MsgDestroyHandle(sconnhp); - ni_errno = NIE_MSGWRITE; - return NULL; - } - disp_contact = FALSE; /* now waiting to hear one more msg */ - - TRACE("After GETSOCKNAME, port = %d\n", disp->clientPort); - if ((status = NI_LISTEN(disp->svcsHP->sok, 5)) < 0) { -#ifdef NETP_INET_NEWT - SOCK_ERRNO = ABS(status); -#endif - TRACE("Listen failed, errno = %d\n", SOCK_ERRNO); - MsgDestroyHandle(sconnhp); - StringCpy(ni_errtext, strerror(SOCK_INDEX_ERRNO)); - ni_errno = NIE_NOLISTEN; - ErrPost (CTX_NCBICORE, CORE_UNKNOWN, "NI_ServiceRequest: <%s> <port %d, errno %d>", ni_errlist[ni_errno], (int) disp->clientPort, (int) SOCK_ERRNO); - return NULL; - } - } -#endif - /* non-SOCKS clients ignore this message, and should never receive it */ - TRACE("Listen succeeded\n"); - MsgDestroy(imp); - break; - - case NI_SVC_RESPONSE: - if (disp->useSocks) - { - TRACE("Got SOCKS service response from Dispatcher\n"); - } - ni_errno = NIE_NO_ERROR; - NI_DestroyRequest(disp->reqResponse); - disp->reqResponse = imp->msun.svcresp->request; - sconnhp->hostname = StringSave(disp->reqResponse->clientAddr); - imp->msun.svcresp->request = NULL; - MsgDestroy(imp); - if (mon != NULL) { - MonitorStrValue(mon, "Direct connection established"); -#ifdef OS_UNIX - sleep(1); -#endif /* OS_UNIX */ - MonitorFree(mon); - } - break; - - case NI_NACK: - if (disp->useSocks) - { - TRACE("Got SOCKS NACK from Dispatcher\n"); - } - ni_errno = (enum ni_error) imp->msun.nack->code; - if (imp->msun.nack->reason != NULL) - StringCpy(ni_errtext, imp->msun.nack->reason); - else - ni_errtext[0] = '\0'; - MsgDestroy(imp); - - /* retry in the case when old style connection failed now is disabled */ - - if (FALSE && !disp->useOutServ) { - disp->useOutServ = TRUE; - mon = MonitorStrNew("Old type of connection failed", 40); - MonitorStrValue(mon, "Trying to establish direct connection"); - serv_contact = FALSE; - disp_contact = FALSE; - goto NEXTTRY; - } - else { - MsgDestroyHandle(sconnhp); - return NULL; - } - /* Message with direct connection ticket was received */ - case NI_SVC_REQUEST: - if ((sconnhp = NI_DirectServiceRequest(imp, sconnhp)) == NULL) { - TRACE("Unable to establish direct connection\n"); - return NULL; - } - if (mon != NULL) - MonitorStrValue(mon, "Received ticket for direct connection"); - - serv_contact = TRUE; - disp_contact = FALSE; /* we are looking for SVC_RESPONCE */ - break; - - - default: - if (disp->useSocks) - { - TRACE("Got SOCKS unknown message type from Dispatcher\n"); - } - MsgDestroy(imp); - MsgDestroyHandle(sconnhp); - ni_errno = NIE_MSGUNK; /* Unknown MSG type */ - sprintf(ni_errtext, "%d", imp->type); - return NULL; - } - } - if (!disp->useOutServ && (FD_ISSET(disp->svcsHP->sok, &readfds) != 0) && !serv_contact) { - sconnlen = sizeof(sconnaddr); -#ifdef NETP_INET_NEWT - sconnhp->sok = NI_ACCEPT(disp->svcsHP->sok, &sconnaddr, &sconnlen); -#else - sconnhp->sok = NI_ACCEPT(disp->svcsHP->sok, (struct sockaddr PNTR) &sconnaddr, &sconnlen); -#endif /* NETP_INET_NEWT */ - LOG_SOCKET(sconnhp->sok, TRUE); -#ifdef NETP_SOCKS - if (disp->useSocks) - { - TRACE("Got connection from server, socket %d\n", sconnhp->sok); - MsgDestroyHandle(disp->svcsHP); - disp->svcsHP = MsgMakeHandle(TRUE); /* for next time */ - } -#endif /* NETP_SOCKS */ - if (sconnhp->sok < 0) { -#ifdef NETP_INET_NEWT - SOCK_ERRNO = ABS(sconnhp->sok); -#endif - MsgDestroyHandle(sconnhp); - StringCpy(ni_errtext, strerror(SOCK_INDEX_ERRNO)); - ni_errno = NIE_NOACCEPT; /* application accept error */ - return NULL; - } - serv_contact = TRUE; - } - } - - if (activityHook != NULL) - { - (*activityHook)(sconnhp, NetServHook_svcreq, 0); - } - - if (disp->encryptInfo != NULL && NI_EncrAvailable()) - { - NI_SetupDESEncryption(sconnhp, desKey); - } - - if (sconnhp != NULL) - { - sconnhp->disp = disp; - } - - return sconnhp; -} /* NI_ServiceRequest */ - - - -/* - * Purpose: Issue the specified direct service request - * - * Parameters: - * - * imp The pre-formatted service request - * sconnhp server handle to connect to - * - * Returns: - * - * sconnhp A message handle to the server which is servicing our request, - * if successful - * - * Description: This function connects directly to server specified by sconnhp - * and sends SVC_REQUEST message imp, formated and completed by - * dispatcher and received by NI_ServiceRequest function of the client - * - * - */ -static NI_HandPtr -NI_DirectServiceRequest(NIMsgPtr imp, NI_HandPtr sconnhp) -{ - int timeout = 30; - int status; - struct sockaddr_in sconnaddr; - char buf[20]; - - MemFill((VoidPtr) &sconnaddr, '\0', sizeof(sconnaddr)); - sconnaddr.sin_family = AF_INET; - sconnaddr.sin_addr.s_addr = htonl(imp->msun.svcreq->server_ip); - if (GetAppParam("NCBI", "NET_SERV", "PROXY_SERV_OVERRIDE", "", buf, sizeof buf) > 0) - { - sconnaddr.sin_addr.s_addr = inet_addr(buf); - } - sconnaddr.sin_port = htons(imp->msun.svcreq->server_port); - -RETRY1: - - -#ifndef NETP_INET_NEWT - status = NI_CONNECT(sconnhp->sok, (struct sockaddr PNTR) &sconnaddr, - sizeof(sconnaddr)); -#else - status = NI_CONNECT(sconnhp->sok, &sconnaddr, sizeof(sconnaddr)); -#endif - if (status < 0) { -#ifdef NETP_INET_NEWT - SOCK_ERRNO = ABS(status); -#endif - switch (SOCK_ERRNO) { - case EINTR: - goto RETRY1; - -#ifdef NETP_INET_PCNFS - case 0: -#endif /* NETP_INET_PCNFS */ - case EWOULDBLOCK: - case EINPROGRESS: - /* if the connect()ion is not established immediately, a */ - /* select() can be performed where the corresponding "write" */ - /* file descriptor will be enabled once the connect()ion has been*/ - /* established */ - - if (sokselectw(sconnhp->sok, timeout) != 0) { - MsgDestroyHandle(sconnhp); - return NULL; - } - break; - - default: - MsgDestroyHandle(sconnhp); - ni_errno = NIE_DIRUNCONNECT; /* cannot establish direct connection */ - return NULL; - } - } - - /* Now we are sending service request directly to the server */ - - if (MsgWrite(sconnhp, imp, TRUE) < 0) { - MsgDestroyHandle(sconnhp); - ni_errno = NIE_DIRUNCONNECT; - return NULL; - } - return sconnhp; -} - - - -/* - * Purpose: Disconnect from a service provider - * - * Parameters: - * mhp Message handle for the server - * - * Returns: - * 0, always - * - * - * Description: - * Disconnect from a service provider, essentially by just - * closing the communication socket to that service provider. - */ - -NLM_EXTERN Int2 NI_ServiceDisconnect(NI_HandPtr mhp) -{ - if (activityHook != NULL) - { - activityHook(mhp, NetServHook_svcdisconn, 0); - } - - MsgDestroyHandle(mhp); - return 0; -} /* NI_ServiceDisconnect */ - - - -/* - * Purpose: Obtain the read file descriptor from a "message handle" - * - * Parameters: - * handp Message handle - * - * Returns: - * Socket associated with message handle - * - * - * Description: - * Get the read file desciptor from a message handle. This - * might be useful, for example, when wishing to perform - * "direct" I/O to the socket after a connection has been - * established with a server/client. - */ - -NLM_EXTERN int NI_ServiceGetReadFd(NI_HandPtr handp) -{ - return handp->sok; -} /* NI_ServiceGetReadFd */ - - - -/* - * Purpose: Obtain the write file descriptor from a "message handle" - * - * Parameters: - * handp Message handle - * - * Returns: - * Socket associated with message handle - * - * - * Description: - * Get the write file desciptor from a message handle. This - * might be useful, for example, when wishing to perform - * "direct" I/O to the socket after a connection has been - * established with a server/client. - */ - -NLM_EXTERN int NI_ServiceGetWriteFd(NI_HandPtr handp) -{ - return handp->sok; -} /* NI_ServiceGetWriteFd */ - - - -/* - * Purpose: Populate a service request with a service name and version #s - * - * Parameters: - * req Service request - * name Service name - * vermin Minimum version number for this service - * vermax Maximum version number for this service - * - * Returns: - * -1, if the name is a NULL pointer - * 0, otherwise - * - * - * Description: - * Populate the service request with the specified service name - * and version numbers, dynamically allocating space for the - * service name. - */ - -NLM_EXTERN Int2 NI_RequestSetService(NI_ReqPtr req, CharPtr name, Uint2 vermin, Uint2 vermax) -{ - if (name == NULL) { - ni_errno = NIE_INVAL; - return -1; - } - req->service->name = StringSave(name); - req->service->minVersion = vermin; - req->service->maxVersion = vermax; - req->service->typeL = NULL; - return 0; -} /* NI_RequestSetService */ - - - -/* - * Purpose: Populate a service request with an additional resource - * - * Parameters: - * req Service request - * name Resource name - * type Service type - * vermin Minimum version number for this resource - * vermax Maximum version number for this resource - * - * Returns: - * -1, if the name is a NULL pointer - * 0, otherwise - * - * - * Description: - * Insert the information for this resource into a list of - * resources associated with this service request. This - * function may be called one or more times (or, not at all) to - * populate a service request with one or more resources. - */ - -NLM_EXTERN Int2 NI_RequestAddResource(NI_ReqPtr req, CharPtr name, CharPtr type, Uint2 vermin, Uint2 vermax) - -{ - NIResPtr resp; - - if (name == NULL) { - ni_errno = NIE_INVAL; - return -1; - } - resp = NI_MakeResource(); - resp->name = StringSave(name); - if (type != NULL) - resp->type = StringSave(type); - resp->minVersion = vermin; - resp->maxVersion = vermax; - req->resourceL = ListInsertPrev((VoidPtr) resp, req->resourceL); /* add to end of list */ - return 0; -} /* NI_RequestAddResource */ - - - -/* THESE FUNCTIONS NOT VISIBLE TO API USER */ - -/* - * Purpose: Partially halt Network Services - * - * Parameters: - * disp A pointer to the dispatcher structure - * - * Description: - * Halt network services, except refrain from freeing the - * parameters which are set by NI_SetDispatcher(). - */ - -static void -HaltServices (NI_DispatcherPtr disp) -{ - if (disp == NULL) - return; - - if (disp->referenceCount > 0) - return; - - if (activityHook != NULL) - { - activityHook((NI_HandPtr) disp, NetServHook_dispdisconn, 0); - } - - MsgDestroyHandle(disp->dispHP); - MsgDestroyHandle(disp->svcsHP); - NI_DestroyRequest(disp->reqResponse); - if (disp->identity != NULL) { - MemFree (disp->identity->username); - MemFree (disp->identity->group); - MemFree (disp->identity->domain); - MemFree (disp->identity); - disp->identity = NULL; - } - disp->dispHP = NULL; - disp->svcsHP = NULL; - disp->reqResponse = NULL; - if (disp->encryptInfo != NULL) - { - if (disp->encryptInfo != NULL) - NI_DestroyPubKey((NIPubKeyPtr) disp->encryptInfo->data.ptrvalue); - ValNodeFree(disp->encryptInfo); - } - -#ifdef NETP_INET_WSOCK - /* we have an obligation to perform one cleanup call for every Startup */ - while (wsaStartupCount-- > 0) - { - WSACleanup(); - } -#endif -} - - -/* - * Purpose: Lookup a port # in config file and possible NIS - * - * Parameters: - * service Name of config. file entry - * networkOrder Boolean, indicates whether value should be returned in host - * order or network order. - * - * Description: - * Look up the specified entry in the NCBI config. file, and - * lookup in NIS the name obtained from the config file if it's - * non-numeric. - * - * Note: - * The intent of this function is that, in most cases, the - * GetAppParam() entry will not be present, and a default value - * will be used instead. The getservbyname() call is intended - * to be a last resort, because this may be slow on some systems. - */ - -static Uint2 -GetByConfigOrServ(CharPtr service, Boolean networkOrder) -{ - struct servent PNTR portEntry; - Char buf[50]; - Uint2 port; - - if (GetAppParam("NCBI", "NET_SERV", service, "", buf, sizeof buf) <= 0) - { - port = 0; - } else { - if (StrSpn(buf, "0123456789") == StrLen(buf)) - { /* all numeric */ - port = atoi(buf); - if (networkOrder) - port = htons(port); - } else { - /* entry from configuration file is name to use in getservbyname */ - if ((portEntry = getservbyname(buf, "tcp")) == NULL) - { - port = 0; - } else { - port = portEntry->s_port; - if (! networkOrder) - port = ntohs(port); - } - } - } - - return port; -} - - -/* - * Purpose: Connect to the dispatcher - * - * Parameters: - * disp A pointer to the dispatcher structure - * host Name of the host on which dispatcher resides - * service Name of the "service" (i.e., port) to which we should connect - * timeout How long to wait for dispatcher to respond, 0 ==> use default - * - * Returns: - * NULL, if the attempt to connect failed - * a pointer to the "Msg" structure for the dispatcher, otherwise - * - * - * Description: - * Connect to the dispatcher on the specified hostname on the - * specified service (where a service maps to a port number). - * This is done by establishing a socket to the dispatcher, - * and then connect()ing to that socket; the dispatcher should - * be listen()ing on that socket, and should subsequently accept() - * the connection request. - * - * While doing this, also obtain other useful information; - * namely, the dotted IP address of the local host, and the - * high and low port numbers to be used when attempting - * dispatcher connections. This global information is used - * elsewhere. - */ - -#ifndef INADDR_NONE -#define INADDR_NONE -1 -#endif /* INADDR_NONE */ - -static NI_HandPtr -DispatchConnect(NI_DispatcherPtr disp, CharPtr host, CharPtr service, int timeout) -{ - struct hostent PNTR dispHost, PNTR localHost; - struct sockaddr_in serv_addr; - NI_HandPtr dHP; - Uint2 disp_port; - Uint4 srvadd; - Char servInetAddr[INETADDR_SIZ], localHostName[SVC_HOST_SIZ]; - Char t_service[64]; - int status; - Int4 connectStartTime; - - if (disp == NULL) - return NULL; - - - serv_addr.sin_family = AF_INET; - - srvadd = inet_addr(host); - if ((Int4)srvadd != INADDR_NONE) /* malformed request */ - MemCopy((VoidPtr) &serv_addr.sin_addr, (VoidPtr) &srvadd, sizeof(srvadd)); - else { - if ((dispHost = gethostbyname(host)) == NULL) { - ni_errno = NIE_NOHOSTENT; - return NULL; - } -/* MemCopy((VoidPtr)&serv_addr.sin_addr, (VoidPtr)(dispHost->h_addr), dispHost->h_length);*/ - MemCopy(&serv_addr.sin_addr, dispHost->h_addr, dispHost->h_length); - } - StringCpy(servInetAddr, inet_ntoa(serv_addr.SIN_ADDR)); - - if ((disp_port = GetByConfigOrServ(service, TRUE)) == 0) - { - if (service) - StringCpy(t_service, service); /* because Windows barfs on the pointer */ - else - t_service[0] = 0; - if ((disp_port = htons(atoi(t_service))) == 0) - disp_port = htons(NI_DFLT_SVC_PORT); - } - if (ntohs(disp_port) <= NI_LAST_RESERVED_PORT) { - ni_errno = NIE_NOSERVENT; - return NULL; - } - - /* get the Internet address of the "local host" */ -#ifdef NETP_INET_MACTCP - /* simpler solution to avoid the hazards of gethostname() */ - { - unsigned long localHostId; - - localHostId = gethostid(); - StringCpy(disp->localHostAddr, inet_ntoa(* (H_ADDR_TYPE) &localHostId)); - } -#else - gethostname(localHostName, SVC_HOST_SIZ); - if ((localHost = gethostbyname(localHostName)) == NULL) { - /* GetAppParam() workaround for PC-NFS 5.0 bug */ - if (GetAppParam("NCBI", "NET_SERV", "HOST_ADDRESS", "", - disp->localHostAddr, sizeof(disp->localHostAddr)) <= 0) - { /* use a bogus address which the dispatcher will try to fix */ - StringCpy(disp->localHostAddr, "0.0.0.0"); - - } - } else { - StringCpy(disp->localHostAddr, inet_ntoa(* (H_ADDR_TYPE) localHost->h_addr)); - } -#endif /* NETP_INET_MACTCP */ - - if ((disp->loport = GetByConfigOrServ(NI_CLIENT_PORT_LO_NAME, FALSE)) == 0) - { - if ((disp->loport = atoi(NI_CLIENT_PORT_LO_NAME)) == 0) - disp->loport = NI_DFLT_CLILO_PORT; - } - if (disp->loport <= NI_LAST_RESERVED_PORT) { - ni_errno = NIE_BADPORT; /* bad low client port */ - return NULL; - } - - if ((disp->hiport = GetByConfigOrServ(NI_CLIENT_PORT_HI_NAME, FALSE)) == 0) - { - if ((disp->hiport = atoi(NI_CLIENT_PORT_HI_NAME)) == 0) - disp->hiport = NI_DFLT_CLIHI_PORT; - } - if (disp->hiport <= NI_LAST_RESERVED_PORT) { - ni_errno = NIE_BADPORT; /* bad high client port */ - return NULL; - } - - MemFill((VoidPtr) &serv_addr, '\0', sizeof(serv_addr)); - serv_addr.sin_family = AF_INET; - serv_addr.sin_addr.s_addr = inet_addr(servInetAddr); - serv_addr.sin_port = disp_port; - - if ((dHP = MsgMakeHandle(TRUE)) == NULL) - return NULL; - MsgSetLJError(dHP); - if (timeout > 0) - MsgSetReadTimeout(dHP, timeout); - - if (activityHook != NULL) - { - activityHook((NI_HandPtr) disp, NetServHook_dispconn, 0); - } - -#ifdef NETP_SOCKS - if (disp->useSocks) - { /* SOCKS can't deal well with blocking connections */ - NI_SETBLOCKING(dHP->sok); - } -#endif - - connectStartTime = Nlm_GetSecs(); - - RETRY: -#ifndef NETP_INET_NEWT - if ((status = NI_CONNECT(dHP->sok, (struct sockaddr PNTR) &serv_addr, sizeof(serv_addr))) < 0) { /* } */ -#else - if ((status = NI_CONNECT(dHP->sok, &serv_addr, sizeof(serv_addr))) < 0) { - SOCK_ERRNO = ABS(status); -#endif - switch (SOCK_ERRNO) { - case EINTR: - goto RETRY; - -#ifdef NETP_INET_PCNFS - /* This is apparently a bug in PC-NFS 4.0 ... a connection attempt */ - /* on a non-blocking socket yields errno == 0 */ - case 0: -#endif /* NETP_INET_PCNFS */ - case EWOULDBLOCK: - case EINPROGRESS: - /* if the connect()ion is not established immediately, a */ - /* select() can be performed where the corresponding "write" */ - /* file descriptor will be enabled once the connect()ion has been*/ - /* established */ - status = sizeof(serv_addr); - if (sokselectw(dHP->sok, timeout) == 0 -#ifdef OS_UNIX - && getpeername(dHP->sok,(struct sockaddr *) &serv_addr, &status) == 0 -#endif - ) { - dHP->state = NI_CONNECTED; - dHP->connectDelay = Nlm_GetSecs() - connectStartTime; - return dHP; - } - break; - - default: - break; - } - MsgDestroyHandle(dHP); - ni_errno = NIE_DISPCONN; /* can't connect to dispatcher */ - return NULL; - } - dHP->state = NI_CONNECTED; - dHP->connectDelay = Nlm_GetSecs() - connectStartTime; - return dHP; -} /* DispatchConnect */ - - -/* - * Purpose: Convert an FQDN to an IP address - * - * Parameters: - * fqdn A fully-qualified domain name, like "dispatch1.nlm.nih.gov" - * ipbuf An output buffer for the dotted-decimal IP address - * ipbuflen The length of ipbuf - * - * Returns: - * TRUE, if the address was resolved successfully, FALSE otherwise - */ - -NLM_EXTERN Boolean NI_FqdnToIpaddr(CharPtr fqdn, CharPtr ipbuf, Int2 ipbuflen) -{ - struct hostent PNTR dispHost; - struct sockaddr_in serv_addr; - - serv_addr.sin_family = AF_INET; - if ((dispHost = gethostbyname(fqdn)) != NULL) - { - MemCopy (&serv_addr.sin_addr, dispHost->h_addr, dispHost->h_length); - StringNCpy (ipbuf, inet_ntoa (serv_addr.SIN_ADDR), ipbuflen-1); - return TRUE; - } else { - return FALSE; - } -} - - - - -/* - * Purpose: Get the platform on which this client is running - * - * Parameters: - * none - * - * Returns: - * the client's platform, or NI_PLATFORM_UNKNOWN - * - * - * Description: - * Calculate what platform this client is running on. - * - * - * Note: - * Although the initial implementation of this function - * calculates the platform-type at compile-time, it is - * legitimate to perform some computation at run time, e.g., - * to determine whether this client is using a particular - * low-level driver. - * - * The dispatcher and servers should not rely on the - * information which is received for platform-type, because - * the client may be lying, either because of a coding error - * or malice on the part of a client developer. - */ - -NLM_EXTERN Int2 NI_GetPlatform (void) -{ - static Boolean alreadyInited = FALSE; - static Int2 retval; - - if (alreadyInited) - { - return retval; - } - - alreadyInited = TRUE; - - retval = NI_PLATFORM_UNKNOWN; - -#ifdef NETP_INET_MACTCP - retval = NI_PLATFORM_MAC; -#endif - -#ifdef OS_VMS -#ifdef NETP_INET_TGV - retval = NI_PLATFORM_VMS_TGV; -#endif -#ifdef NETP_INET_TWG - retval = NI_PLATFORM_VMS_TWG; -#endif -#ifdef NETP_INET_WPW - retval = NI_PLATFORM_VMS_WPW; -#endif -#ifdef NETP_INET_UCX - retval = NI_PLATFORM_VMS_UCX; -#endif -#ifdef OS_AXP_VMS - retval = NI_PLATFORM_AXP_OPENVMS; -#endif -#endif /* OS_VMS */ - -#ifdef OS_UNIX - retval = NI_PLATFORM_GENERIC_UNIX; -#ifdef PROC_IBM370 - retval = NI_PLATFORM_IBM370AIX; -#endif -#ifdef OS_UNIX_SUN - retval = NI_PLATFORM_SUN; -#endif -#if defined(OS_UNIX_OSF1) && defined(PROC_ALPHA) - retval = NI_PLATFORM_ALPHA_OSF1; -#endif -#ifdef COMP_AUX - retval = NI_PLATFORM_AUX; -#endif -#if defined(COMP_CRAY) && defined(PROC_YMP) - retval = NI_PLATFORM_CRAY; -#endif -#ifdef PROC_CONVEX - retval = NI_PLATFORM_CONVEX; -#endif -#if defined(PROC_HPPA) && !defined(OS_UNIX_LINUX) - retval = NI_PLATFORM_HPUX; -#endif -#ifdef OS_UNIX_NEXT - retval = NI_PLATFORM_NEXT; -#endif -#if defined(PROC_MIPS) && !defined(OS_UNIX_LINUX) - retval = NI_PLATFORM_SGI; -#endif -#ifdef OS_UNIX_ULTRIX - retval = NI_PLATFORM_ULTRIX; -#endif -#if defined(OS_UNIX_SYSV) && defined(PROC_SPARC) - retval = NI_PLATFORM_SYSV_ON_SPARC; -#endif -#ifdef OS_UNIX_AIX - retval = NI_PLATFORM_AIX; -#endif -#ifdef OS_UNIX_LINUX -#ifdef PROC_ALPHA - retval = NI_PLATFORM_LINUX_ALPHA; -#else - retval = NI_PLATFORM_LINUX; -#endif -#endif -#ifdef OS_UNIX_NETBSD - retval = NI_PLATFORM_NETBSD; -#endif -#ifdef OS_UNIX_FREEBSD - retval = NI_PLATFORM_FREEBSD; -#endif -#endif /* OS_UNIX */ - -#ifdef OS_DOS - retval = NI_PLATFORM_DOS; -#ifdef WIN16 - retval = NI_PLATFORM_WIN16; -#endif -#ifdef NETP_INET_NEWT - retval = NI_PLATFORM_WIN_NEWT; -#endif -#ifdef NETP_INET_PCNFS - retval = NI_PLATFORM_WIN_PCNFS; -#endif -#ifdef WINSOCK - retval = NI_PLATFORM_WIN_WINSOCK; -#endif -#endif /* OS_DOS */ - -#ifdef OS_WINNT - retval = NI_PLATFORM_WINNT; -#endif - - return retval; -} - - -/* - * Purpose: Set the "identity" of this client - * - * Parameters: - * disp A pointer to the dispatcher structure - * user New Username - * group New Groupname - * domain New DomainName - * - * Returns: - * 0, always - * - * - * Description: - * Allocate the space for the "UID" structure, if not already - * allocated, and populate it with the user name, group name, - * and domain name. - */ - -static Int2 -SetIdentity(NI_DispatcherPtr disp, CharPtr user, CharPtr group, CharPtr domain) -{ - if (disp == NULL) - return 0; - - if (disp->identity == NULL) - disp->identity = NI_MakeUid(); - - if (disp->identity->username != NULL) - MemFree(disp->identity->username); - disp->identity->username = StringSave(user); - if (disp->identity->group != NULL) - MemFree(disp->identity->group); - if (group != NULL) - disp->identity->group = StringSave(group); - else - disp->identity->group = NULL; - if (disp->identity->domain != NULL) - MemFree(disp->identity->domain); - disp->identity->domain = StringSave(domain); - return 0; -} /* SetIdentity */ - - - -/* - * Purpose: Copy from the "identity" UID to the specified UID data struct - * - * Parameters: - * disp A pointer to the dispatcher structure - * uid UID structure to be copied into - * - * Returns: - * -1, if invalid arguments - * 0, otherwise - * - * - * Description: - * Copy fields from the "identity" UID data structure into the - * UID data structure provided by the caller. - */ - -static Int2 -CopyIdentity(NI_DispatcherPtr disp, NI_UidPtr uid) -{ - if (disp == NULL || disp->identity == NULL || uid == NULL) - return -1; - if (uid->username != NULL) - MemFree(uid->username); - uid->username = StringSave(disp->identity->username); - if (uid->group != NULL) - MemFree(uid->group); - uid->group = StringSave(disp->identity->group); - if (uid->domain != NULL) - MemFree(uid->domain); - uid->domain = StringSave(disp->identity->domain); - return 0; -} /* CopyIdentity */ - - - -/* - * Purpose: Select the next available port within the given range, - * and bind a socket to it. - * - * Parameters: - * sok Socket to be bound to a port (INPUT) - * sokadr Socket data structure to be populated (OUTPUT) - * loport Minimum acceptable port number - * hiport Maximum acceptable port number - * - * Returns: - * 0, if unable to bind to a port - * the selected ("bound") port number, otherwise - * - * - * Description: - * Iterate through the range of acceptable port numbers, until - * an unused port number can be selected to which the socket - * can be bound. - */ - -static Uint2 -bindPort(int sok, struct sockaddr_in PNTR sokadr, Int2 loport, Int2 hiport, Uint4 remoteHost) -{ - int status; -#ifdef NETP_INET_MACTCP - int delta = 0; - Char buf[20]; -#endif - - if (hiport == 0) - hiport = loport; - if (loport > hiport) - return 0; - -#ifdef NETP_INET_MACTCP - /* use a hint from the configuration file to avoid port # conflicts */ - if (hiport > loport && GetAppParam("NCBI", "NET_SERV", "PORT_DELTA", "0", - buf, sizeof buf) > 0) - { - delta = atoi(buf); - loport += delta % (hiport - loport); - sprintf (buf, "%d", delta + 1); - SetAppParam("NCBI", "NET_SERV", "PORT_DELTA", buf); - } -#endif - - MemFill((VoidPtr) sokadr, '\0', sizeof(struct sockaddr_in)); - sokadr->sin_family = AF_INET; - sokadr->sin_addr.s_addr = INADDR_ANY; - - while (loport <= hiport) { - sokadr->sin_port = htons(loport); -#ifdef NETP_INET_NEWT - if ((status = NI_BIND(sok, sokadr, sizeof(struct sockaddr_in), htonl(remoteHost))) == 0) -#else - if ((status = NI_BIND(sok, (struct sockaddr PNTR) sokadr, sizeof(struct sockaddr_in), htonl(remoteHost))) == 0) -#endif /* NETP_INET_NEWT */ - return (Uint2) ntohs(sokadr->sin_port); - else { -#ifdef NETP_INET_NEWT - SOCK_ERRNO = ABS(status); -#endif - loport++; - } - } - return 0; -} /* bindPort */ - - - -/* SERVER FUNCTIONS */ - -static int writepipe PROTO((int fd, char *buf, int len)); - -/* - * Purpose: Write a message on the pipe from a child server application - * process to its parent NCBID. - * - * Parameters: - * fd Pipe file descriptor - * buf Buffer to be written - * len Length of buffer - * - * Returns: - * 0, if unable to write because the pipe is full - * number of bytes written, otherwise - * - * - * Description: - * Write the specified number of bytes to a pipe, and handle - * multiple write attempts if necessary, to handle the case where - * a write() may be interrupted by a signal. - * - * Note: - * This routine is only used by a child process after it has been - * forked and before it has been execed. - */ - -static int -writepipe(int fd, char *buf, int len) -{ - int byteswrit; - - WriteAgain: - if ((byteswrit = write(fd, buf, len)) < 0) { - switch (errno) { - case EINTR: - goto WriteAgain; - - case EWOULDBLOCK: - default: - return 0; - } - } - - return byteswrit; -} /* writepipe */ - -static Int2 StandAlonePort(void) -{ - CharPtr env; - -#ifdef OS_UNIX - if ((env = getenv("NI_STANDALONE_SERVER")) == NULL) - { - return 0; - } - - return atoi(env); -#else - return 0; -#endif -} - - -/* - * Purpose: Send an "ACK" from a child server application process to its - * parent NCBID. - * - * Returns: - * 0, if the ACK was sent successfully - * -1, otherwise - * - * - * Description: - * Write an "ACK" from a child server application process to its - * parent NCBID, on the pipe connecting the two processes. - * - * Note: - * This routine should be called by a child process after it has - * determined that it has started successfully. At most one - * of NI_ServerACK() and NI_ServerNACK() may be called. - */ - -#define TEMP_BUF_SIZ 256 - -NLM_EXTERN int NI_ServerACK(void) -{ -#if 0 - int wstat; - Char temp_buf[TEMP_BUF_SIZ]; - Int2 port; - - if ((port = StandAlonePort()) == 0) - { /* not stand-alone */ - sprintf(temp_buf, PIPE_MSG_FMT, NIE_SERVACK, "OK"); - if ((wstat = writepipe(STDPIPE, temp_buf, strlen(temp_buf))) <= 0) { - ni_errno = NIE_PIPEIO; - strcpy(ni_errtext, (wstat == 0) ? "EWOULDBLOCK" : strerror(errno)); - return -1; - } - } else { /* stand-alone */ -#ifdef OS_UNIX - /* non-UNIX platforms currently experience compilation errors */ - struct sockaddr_in soktAddr; - NI_HandPtr hp; - int sok; - int status; - struct sockaddr_in sockaddr; - int soktLen; - CharPtr security; - int one = 1; /* for SO_REUSEADDR */ - - hp = MsgMakeHandle(TRUE); - NI_SETBLOCKING(hp->sok); - - MemFill(&sockaddr, '\0', sizeof(struct sockaddr_in)); - sockaddr.sin_family = AF_INET; - sockaddr.sin_addr.s_addr = INADDR_ANY; - sockaddr.sin_port = htons(port); - - if (setsockopt(hp->sok, SOL_SOCKET, SO_REUSEADDR, (char *) &one, - sizeof(one)) < 0) - { - Message (MSG_ERROR, "Unable to set socket re-usability, errno = %d", errno); - } - -#ifdef NETP_INET_NEWT - if ((status = bind(hp->sok, &sockaddr, sizeof(struct sockaddr_in))) == 0) -#else - if ((status = bind(hp->sok, (struct sockaddr PNTR) &sockaddr, sizeof(struct sockaddr_in))) != 0) -#endif /* NETP_INET_NEWT */ - { /* error */ - ErrPostEx(SEV_FATAL,0,0, - "Bind failed on socket %d, status = %d, errno = %d", - hp->sok, status, errno); - return -1; - } - - NI_LISTEN(hp->sok, 1); - close(0); /* so that accept() will return 0 */ - soktLen = sizeof(soktAddr); - - /* accept the connection */ - if ((sok = NI_ACCEPT(hp->sok, (struct sockaddr *) &soktAddr, &soktLen)) < 0) - { /* error */ - ErrPostEx(SEV_FATAL,0,0, "Accept returned bad file descriptor %d, errno = %d", - sok, errno); - return -1; - } - LOG_SOCKET(sok, TRUE); - NI_SETNONBLOCKING(sok); - MsgDestroyHandle(hp); - if ((security = getenv("NI_STANDALONE_SECURITY")) != NULL) - { /* security must be substring of client address */ - if (StrNCmp(inet_ntoa(soktAddr.SIN_ADDR), security, StrLen(security)) != 0) - { - close(sok); - ErrPostEx(SEV_FATAL,0,0, "Security violation from IP address %s, security = %s\n", - inet_ntoa(soktAddr.SIN_ADDR), security); - return -1; - } - } -#endif /* OS_UNIX */ - } -#endif /* 0 */ - - return 0; -} /* NI_ServerACK */ - - - -/* - * Purpose: Send an "NACK" from a child server application process to its - * parent NCBID. - * - * Returns: - * 0, if the NACK was sent successfully - * -1, otherwise - * - * - * Description: - * Write an "NACK" from a child server application process to its - * parent NCBID, on the pipe connecting the two processes. - * - * Note: - * This routine should be called by a child process after it has - * determined that it will be unable to start successfully. In - * the event that this routine is not called (or is unable to - * perform its function), a timeout mechanism must be relied - * upon for the NCBID to realize that a child has started - * unsuccessfully. - * - * At most one of NI_ServerACK() and NI_ServerNACK() may be called. - */ - -NLM_EXTERN int NI_ServerNACK(CharPtr err_text) -{ -#if 0 - int wstat; - Char temp_buf[TEMP_BUF_SIZ]; - - sprintf(temp_buf, PIPE_MSG_FMT, NIE_SERVNACK, err_text); - if (StandAlonePort() == 0) - { /* not stand-alone */ - if ((wstat = writepipe(STDPIPE, temp_buf, strlen(temp_buf))) <= 0) { - ni_errno = NIE_PIPEIO; - strcpy(ni_errtext, (wstat == 0) ? "EWOULDBLOCK" : strerror(errno)); - return -1; - } - } else { /* stand-alone */ - ErrPostEx(SEV_FATAL,0,0, "Stand-alone server failed startup {%s}", temp_buf); - return -1; - } -#endif /* 0 */ - - return 0; -} /* NI_ServerNACK */ - - - -/* - * Purpose: Open the stream to be used for ASN I/O between a server - * application process and its client. - * - * Returns: - * NULL, if something went wrong - * a pointer to the Msg structure, otherwise - * - * - * Description: - * Create a "Msg" structure for ASN I/O, and associate the Msg's - * socket with the standard input file descriptor (STDIN), which is - * the communication socket between the server application process - * and its client. - * - * Note: - * This routine should only be called by a child application - * process (not by a client). - */ - -NLM_EXTERN NI_HandPtr NI_OpenASNIO(void) -{ - NI_HandPtr hp; - - if ((hp = MsgMakeHandle(FALSE)) == NULL) - return NULL; - - MsgSetReadTimeout(hp, NI_SERV_LISTEN_TIMEOUT); /* set default for servers to listen */ - - if ((hp->sok = dup(STDIN)) == -1) { /* STDOUT points to same socket */ - MsgDestroyHandle(hp); - return NULL; - } - LOG_SOCKET(hp->sok, TRUE); - { - CharPtr buf; - Char key[8]; - - if ((buf = getenv("NI_DESKEY")) != NULL && - (AsnTypeStringToHex(buf, StrLen(buf), key, NULL) == 0)) - { - NI_SetupDESEncryption(hp, (UcharPtr) key); - } - } - return hp; -} /* NI_OpenASNIO */ - - - -/* - * Purpose: Close the ASN stream between a server application process and - * its client. - * - * Returns: - * -1 if something went wrong - * 0, otherwise - * - * - * Description: - * Close the stream by closing the socket and deleting the - * associated data structures. - * - * Note: - * This routine should only be called by a child application - * process (not by a client). - */ - -NLM_EXTERN Int2 NI_CloseASNIO(NI_HandPtr hp) -{ - return MsgDestroyHandle(hp); -} /* NI_CloseANSIO */ - - - -/* MISC FUNCTIONS */ - -/* sokselectr and sokselectw are not prototyped in ni_lib.h */ - -/* - * Purpose: Wait for a "read" socket to become ready to read, or for - * a timeout to occur. - * - * Returns: - * -1 if something went wrong - * 0, otherwise - * - * - * Description: - * Wait for the indicated "read" socket to be marked as - * "selected" by a socket() call. - * - * Note: - * This routine is presently unused. - * - * The timeout mechanism is not exactly enforced, because - * received signals could result in a longer timeout period. - */ - -int sokselectr(int fd) -{ - fd_set rfds; - int ready; - struct timeval timeout; - - FD_ZERO(&rfds); - FD_SET(fd, &rfds); - timeout.tv_sec = NI_SELECT_TIMEOUT; - timeout.tv_usec = 0; - while ((ready = select(fd+1, &rfds, NULL, NULL, &timeout)) == -1) { - switch (SOCK_ERRNO) { - case EINTR: - continue; - - default: - ni_errno = NIE_MISC; - sprintf(ni_errtext, "%s", strerror(SOCK_INDEX_ERRNO)); - return -1; - } - } - if (ready == 0) { - strcpy(ni_errtext, ni_errlist[ni_errno]); - ni_errno = NIE_TIMEOUT; - return -1; - } - if (FD_ISSET(fd, &rfds)) - return 0; - else - return -1; -} /* sokselectr */ - - - -/* - * Purpose: Wait for a "write" socket to become ready to write, or for - * a timeout to occur. - * - * Returns: - * -1 if something went wrong - * 0, otherwise - * - * - * Description: - * Wait for the indicated "write" socket to be marked as - * "selected" by a socket() call. - * - * Note: - * This routine can be used when waiting for a connect() to go - * through successfully. - * - * The timeout mechanism is not exactly enforced, because - * received signals could result in a longer timeout period. - */ - -int sokselectw(int fd, int seconds) -{ - fd_set wfds; - int ready; - struct timeval timeout; - - FD_ZERO(&wfds); - FD_SET(fd, &wfds); - timeout.tv_sec = NI_SELECT_TIMEOUT; - if (seconds > 0) /* override default */ - timeout.tv_sec = seconds; - timeout.tv_usec = 0; - while ((ready = select(fd+1, NULL, &wfds, NULL, &timeout)) == -1) { - switch (SOCK_ERRNO) { - case EINTR: - continue; - - default: - ni_errno = NIE_MISC; - sprintf(ni_errtext, "%s", strerror(SOCK_INDEX_ERRNO)); - return -1; - } - } - if (ready == 0) { - strcpy(ni_errtext, ni_errlist[ni_errno]); - ni_errno = NIE_TIMEOUT; - return -1; - } - if (FD_ISSET(fd, &wfds)) - { -#ifdef OS_UNIX - int err; - int optlen; - - optlen = sizeof(int); - if (getsockopt(fd, SOL_SOCKET, SO_ERROR, (char *) &err, &optlen) >= 0 && - err != 0) /* check for an error */ - return -1; /* got some error */ -#endif /* OS_UNIX */ - return 0; - } - else - return -1; -} /* sokselectw */ - - - -/* - * Purpose: Parse the error number from an ASN error string which was - * formatted at a low level. - * - * Returns: - * -1, if unable to parse the string - * the parsed error number, otherwise - * - * - * Description: - * Parse the error number from an ASN error string which was - * prepared by the ASN tools, and formatted at a low level. - * - * Note: - * The parsing mechanism is dependent upon any future format - * changes which may occur in the ASN tools. - */ - -int getAsnError(char *str) -{ - int errnum; - - if (sscanf(str, "%*s %*s %*s [-%d]", &errnum) < 1) - errnum = -1; - return errnum; -} /* getAsnError */ - - -/* - * Purpose: Set the Connection ID file pointer - * - * Parameters: - * fp The new value for the file descriptor - * - * - * Description: - * Set the Connection ID file pointer. This is used to update - * the connection ID each time it is updated, to keep the - * value current. - * - * Note: - * In reality, this should only be called by the dispatcher. - */ - -void SetConFilePtr (FILE *fp) -{ - conid_fp = fp; -} - - -/* - * Purpose: Update the connection ID file - * - * Parameters: - * conid The new connection ID value - * - * - * Description: - * Update the connection ID file, and be sure to flush the stream, - * to try to ensure that output really occurs. - * - * Note: - * Should be called every time the "next" connection ID is - * modified. - */ - -NLM_EXTERN void WriteConFile (Uint4 conid) -{ - if (conid_fp != NULL) { - (void) fseek(conid_fp, 0L, SEEK_SET); - (void) FileWrite((CharPtr) &conid, 1, sizeof(conid), conid_fp); - (void) fflush (conid_fp); - } -} - - -/* - * Purpose: Close the connection ID file - * - * - * Description: - * Close the connection ID file. - * to try to ensure that output really occurs. - * - * Note: - * In reality, this should only be called by the dispatcher. - */ - -void CloseConFile (void) -{ - if (conid_fp != NULL) { - fclose (conid_fp); - conid_fp = NULL; - } -} - - - -/* - * Purpose: Check for expired timers - * - * - * Description: - * For every expired timer, call the specified timer - * callback function, which is in turn responsible for cancelling - * the timer. - * - * Note: - * Timer checks only take place when this function is called. - * Therefore, it is the responsibility of an application to - * intermitently call this function. This could be done, e.g. - * using the UNIX alarm clock mechanism, or inside of an event - * loop. - * - * The order of operations is significant here, because the - * hook function must cancel the timer. To perform the linked - * list traversal in a less careful manner could result in - * illegal memory accesses. - * - * The timer list in managed in a very unsophisticated manner; - * if lots of timers were anticipated, the list would be - * maintained sorted by time, and all of the timer functions - * would need to maintain and traverse the timer list based - * upon this criterion. - * - * A count is used as a failsafe mechanism against infinite loops. - */ - -#define NI_MAX_TIMERS 1000 - -NLM_EXTERN void NI_ProcessTimers(void) -{ - NodePtr t; - NodePtr tnew; - NI_TimerPtr timer; - NodePtr timersToBeFired = NULL; - time_t curtime; - int count = NI_MAX_TIMERS; - - if ((t = timerHead) == NULL) - { - return; - } - - curtime = GetSecs(); - - do { - timer = (NI_TimerPtr) t->elem; - tnew = ListGetNext(t); - if (timer != NULL && timer->timeout != NULL_TIMER && - timer->timeout <= curtime) - { /* note the timer to be fired */ - timersToBeFired = ListInsert(timer, timersToBeFired); - } - if (t == tnew) - { /* data structure error, time to bail out */ - break; - } - t = tnew; - } while (t != timerHead && t != NULL && --count > 0); - - if ((t = timersToBeFired) == NULL) - return; - - count = NI_MAX_TIMERS; - - do { - timer = (NI_TimerPtr) t->elem; - tnew = ListGetNext(t); - - /* mark the timer so it won't fire again */ - timer->timeout = NULL_TIMER; - if (timer->hook != NULL) - { - timer->hook(timer->hookParam); - } - t = tnew; - } while (t != timersToBeFired && t != NULL && --count > 0); - - ListDelete(timersToBeFired); -} - - -/* - * Purpose: Return the time when the next timeout will occur - * - * Returns: The time, in seconds, when the next scheduled timeout will - * occur, or NULL_TIMER, if there are no timers set. - * - * Description: - * Return the time when the next timer timeout will occur. - * This information is typically used with the select() - * system call, to ensure that a timeout parameter is passed - * to select() which is sufficiently short to ensure that - * the application will call NI_ProcessTimers() at an - * appropriate time. - * - * Note: - * The timer list in managed in a very unsophisticated manner; - * if lots of timers were anticipated, the list would be - * maintained sorted by time, and all of the timer functions - * would need to maintain and traverse the timer list based - * upon this criterion. - */ - -NLM_EXTERN time_t NI_GetNextWakeup(void) -{ - time_t next_wakeup = NULL_TIMER; - NodePtr t; - NI_TimerPtr timer; - - NI_ProcessTimers(); - - if ((t = timerHead) == NULL) - { - return NULL_TIMER; - } - - do { - t = ListGetNext(t); - timer = (NI_TimerPtr) t->elem; - if (next_wakeup == NULL_TIMER || (timer->timeout != NULL_TIMER && - timer->timeout < next_wakeup)) - { - next_wakeup = timer->timeout; - } - } while (t != timerHead && t != NULL); - - return next_wakeup; -} - - -/* - * Purpose: Set a timer - * - * Parameters: - * timeout The time in seconds when the timer should expire - * hook Callback to be called when (if) the timer expires - * hookParam Parameter to be passed to caller's hook when the timer expires - * - * - * Returns: The "timer ID", really a pointer to the timer data structure - * - * - * Description: - * Sets a timer with the appropriate parameters. - * - * Note: - * The timer list in managed in a very unsophisticated manner; - * if lots of timers were anticipated, the list would be - * maintained sorted by time, and all of the timer functions - * would need to maintain and traverse the timer list based - * upon this criterion. - * - * It is the responsibility of the application (usually the - * hook function) to cancel the timer. - */ - -NodePtr -NI_SetTimer(time_t timeout, NI_TimeoutHook hook, Pointer hookParam) -{ - NodePtr t; - NI_TimerPtr timer; - - timer = (NI_TimerPtr) MemNew(sizeof(NI_Timer)); - timer->timeout = timeout; - timer->hook = hook; - timer->hookParam = hookParam; - t = ListInsert(timer, timerHead); - timerHead = t; - - return t; -} - - -/* - * Purpose: Cancel a timer - * - * Parameters: - * timerID The ID of the timer - * - * - * Description: - * Cancel the specified timer by deleting the entry and its - * associated data structure. - * - * Note: - * The timer list in managed in a very unsophisticated manner; - * if lots of timers were anticipated, the list would be - * maintained sorted by time, and all of the timer functions - * would need to maintain and traverse the timer list based - * upon this criterion. - */ - -NLM_EXTERN void NI_CancelTimer(NodePtr timerId) -{ - if (timerId != NULL) - { - MemFree (timerId->elem); - timerHead = ListDelete(timerId); - } -} - - -/* - * Purpose: Set an activity hook, to inform the application of key events - * - * Parameters: - * hook The hook (callback function) - * - * - * Description: - * Setup a hook function which will subsequently be used to - * inform the application of various events; these currently - * include: - * * Connection to dispatcher - * * Disconnection from dispatcher - * * Service connection - * * Service disconnection - * * Bytes written - * * Bytes read - * - * Note: - * This hook is global for the running application. - */ - -NLM_EXTERN void NI_SetActivityHook (NI_NetServHook hook) -{ - activityHook = hook; -} - - -/* - * Purpose: Return the current activity hook - * - * - * Description: - * Return the current activity hook. This is only intended - * to be used internally by the Network Services library. - * This function is used to avoid making activityHook into a - * global variable. - */ - -NLM_EXTERN NI_NetServHook NI_ActivityHook (void) -{ - return activityHook; -} - - -/* - * Purpose: Initialize socket management - * - * Description: - * If not already initialized, initialize the socket management - * data structures - */ - -static void InitLogSocket(void) -{ - static Boolean inited = FALSE; - - if (! inited) - { - FD_ZERO(&openfds); - inited = TRUE; - } -} - - -/* - * Purpose: Count the number of open sockets - */ - -NLM_EXTERN Int2 NI_SocketsOpen(void) -{ - int sok; - int count = 0; - - InitLogSocket(); - for (sok = 0; sok < FD_SETSIZE; sok++) - { - if (FD_ISSET(sok, &openfds)) - count++; - } - return count; -} - -/* - * Purpose: Log each socket transaction - */ - -NLM_EXTERN void NI_LogSocket(int sok, Boolean opening, CharPtr filename, int lineno) -{ - int localsok; - - InitLogSocket(); - - if (sok == INVALID_SOCKET || sok < 0 || sok >= FD_SETSIZE) - { -#ifndef NETP_INET_WSOCK - /* FD_SETSIZE doesn't accurately describe the socket range for - WinSock applications, so don't generate misleading error msgs */ - ErrPostEx(SEV_WARNING,0,0, "Bad %s operation on socket %d at %s:%d", - opening ? "opening" : "closing", sok, filename, lineno); -#endif /* NETP_INET_WSOCK */ - return; - } - - if (opening) - { - TRACE("Just opened socket %d at %s:%d\n", sok, filename, lineno); - if (FD_ISSET(sok, &openfds)) - { - ErrPostEx(SEV_ERROR,0,0, "Duplicate open of socket %d at %s:%d", - sok, filename, lineno); - } else { - FD_SET(sok, &openfds); - } - } else { - TRACE("Trying to close socket %d at %s:%d\n", sok, filename, lineno); - if (FD_ISSET(sok, &openfds)) - { - FD_CLR(sok, &openfds); - } else { - ErrPostEx(SEV_ERROR,0,0, "Duplicate close of socket %d at %s:%d", - sok, filename, lineno); - } - } - -#ifdef DEBUG - for (localsok = 0; localsok < FD_SETSIZE; localsok++) - { - if (FD_ISSET(localsok, &openfds)) - { - TRACE("Socket %d is currently open\n", localsok); - } - } -#endif /* DEBUG */ -} - diff --git a/network/nsclilib/ni_lib.h b/network/nsclilib/ni_lib.h index 05ef2844..48bbc624 100644 --- a/network/nsclilib/ni_lib.h +++ b/network/nsclilib/ni_lib.h @@ -29,7 +29,7 @@ * * Version Creation Date: 1/1/92 * -* $Revision: 6.0 $ +* $Revision: 6.1 $ * * File Description: * @@ -46,6 +46,9 @@ * * RCS Modification History: * $Log: ni_lib.h,v $ +* Revision 6.1 2005/07/25 18:06:48 lavr +* Remove deprecated ni_ API references +* * Revision 6.0 1997/08/25 18:38:49 madden * Revision changed to 6.0 * @@ -66,8 +69,6 @@ #include "ncbinet.h" #include "ni_net.h" -#include "ni_msg.h" - /* DEFINES */ #define NI_TIMEOUT_SECS 60 /* timeout for connections, requests, etc. */ diff --git a/network/nsclilib/ni_list.c b/network/nsclilib/ni_list.c deleted file mode 100644 index d49092b2..00000000 --- a/network/nsclilib/ni_list.c +++ /dev/null @@ -1,494 +0,0 @@ -#ifdef NOWAY_ABOUT_TO_BE_ZOMBIED -/* -* =========================================================================== -* -* PUBLIC DOMAIN NOTICE -* National Center for Biotechnology Information -* -* This software/database is a "United States Government Work" under the -* terms of the United States Copyright Act. It was written as part of -* the author's official duties as a United States Government employee and -* thus cannot be copyrighted. This software/database is freely available -* to the public for use. The National Library of Medicine and the U.S. -* Government have not placed any restriction on its use or reproduction. -* -* Although all reasonable efforts have been taken to ensure the accuracy -* and reliability of the software and data, the NLM and the U.S. -* Government do not and cannot warrant the performance or results that -* may be obtained by using this software or data. The NLM and the U.S. -* Government disclaim all warranties, express or implied, including -* warranties of performance, merchantability or fitness for any particular -* purpose. -* -* Please cite the author in any work or product based on this material. -* -* =========================================================================== -* -* File Name: ni_list.c -* -* Author: Beatty, Gish -* -* Version Creation Date: 1/1/92 -* -* $Revision: 6.0 $ -* -* File Description: -* List and ring management functions. -* -* -* Modifications: -* -------------------------------------------------------------------------- -* Date Name Description of modification -* ------- ---------- ----------------------------------------------------- -* 4/23/92 Epstein Added extensive in-line commentary, and removed all tabs -* 5/11/92 Epstein Changed ListSwapAdj() to provide more rigorous testing -* that its two arguments are adjacent in the list. -* 5/14/92 Epstein Added ListStrCopy() and ListStrDel() -* 7/06/92 Epstein Fixed bug in ListStrCopy(), where the newly created -* list was not being returned to the caller ... whoops. -* -* ========================================================================== -* -* -* RCS Modification History: -* $Log: ni_list.c,v $ -* Revision 6.0 1997/08/25 18:38:51 madden -* Revision changed to 6.0 -* -* Revision 5.1 1997/01/28 21:23:42 epstein -* prepare to be zombied; functionality has been moved to ncbimisc.[ch] -* - * Revision 5.0 1996/05/28 14:11:55 ostell - * Set to revision 5.0 - * - * Revision 4.0 1995/07/26 13:56:32 ostell - * force revision to 4.0 - * - * Revision 1.2 1995/05/17 17:52:27 epstein - * add RCS log revision history - * -*/ - -#include "ni_list.h" - - - -/* - * Purpose: Insert an item as the next element in a doubly linked list(ring) - * - * Parameters: - * elem Next element to be inserted; this is data only,not a NodePtr - * ap Insertion point - * - * Returns: - * The newly allocated NodePtr, containing forward and backward - * pointers and a pointer to elem - * - * - * Description: - * Allocate the necessary memory for a "Node", attach the - * caller's data to that Node, and insert the Node after the - * specified node in the list, maintaining the integrity of - * a doubly-linked ring. If there are no other items in the - * ring, create a "minimal" ring which consists of the single - * Node pointing to itself in both directions. - * - * Note: - * Most "list" data is actually stored in a doubly-linked ring, as - * shown below. Furthermore, note that each node only contains a - * pointer to the actual data in the list, rather than the actual - * data itself. - * - * +------------------------------------------------------------------+ - * ^ | - * | +-------------------------------------------------------+ | - * | | ^ | - * | V | | - * | +-------+ +-------+ +-------+ | | - * | | next |------>| next |------> ... ------->| next |-->+ | - * | +-------+ +-------+ +-------+ | - * +<--| last |<------| last |<------ ... <-------| last |<-----+ - * +-------+ +-------+ +-------+ - * | elem | | elem | | elem | - * +-------+ +-------+ +-------+ - * | | | - * | | | - * V V V - * +-------+ +-------+ +-------+ - * | actual| | actual| | actual| - * | data | | data | | data | - * +-------+ +-------+ +-------+ - */ - -NodePtr -ListInsert(VoidPtr elem, NodePtr ap) /* ptr to node to insert after */ -{ - NodePtr np; - - if (elem == NULL) - return NULL; - - np = (NodePtr) MemNew(sizeof(Node)); - np->elem = elem; - - if (ap == NULL) { /* no nodes in list */ - np->last = np; - np->next = np; - return np; - } - else { /* 1 or more nodes in list */ - np->next = ap->next; - ap->next = np; - np->next->last = np; - np->last = ap; - return np; - } -} /* ListInsert */ - - - -/* - * Purpose: Insert an item as the previous element in a doubly linked - * list(ring) - * - * Parameters: - * elem Next element to be inserted; this is data only,not a NodePtr - * ap Insertion point - * - * Returns: - * The newly allocated NodePtr, containing forward and backward - * pointers and a pointer to elem - * - * - * Description: - * Insert the specified item into the ring, before the specified - * insertion point. In the case where the specified insertion - * point was NULL, this is equivalent to ListInsert(). - */ - -NodePtr -ListInsertPrev(VoidPtr elem, NodePtr ap) /* ptr to node to insert before */ -{ - NodePtr np; - - np = ap; - if (ap != NULL) - ap = ap->last; /* previous node */ - - ap = ListInsert(elem, ap); - return (np == NULL) ? ap : np; -} /* ListInsertPrev */ - - - -/* - * Purpose: Delete a single node from a list or ring - * - * Parameters: - * np Node to be deleted - * - * Returns: - * A pointer to the "next" node in the list/ring, after the - * deleted node. - * - * - * Description: - * Delete the specified node from a list or ring. It is the - * responsibility of the caller to free the memory associated - * with the "elem" (data), if appropriate. - */ - -NodePtr -ListDelete(NodePtr np) -{ - NodePtr nextnode, lastnode; - - if (np == NULL) - return NULL; - - nextnode = np->next; - lastnode = np->last; - - if (nextnode == NULL && lastnode == NULL) /* only node in a list */ - ; - else if (nextnode == NULL) { /* last in a list */ - np->last->next = NULL; - nextnode = np->last; - } - else if (lastnode == NULL) { /* first in a list */ - np->next->last = NULL; - nextnode = np->next; - } - else if (np == nextnode) /* last in a ring */ - nextnode = NULL; - else { /* node with both neighbors */ - np->last->next = nextnode; - np->next->last = np->last; - } - - MemFree(np); /* assumes element memory has been freed */ - return nextnode; -} /* ListDelete */ - - - -/* - * Purpose: Get the next element from a list or ring (non-destructively) - * - * Parameters: - * np Node before the node to be selected - * - * Returns: - * A pointer to the "next" node in the list/ring (or NULL - * if the list/ring was NULL). Note that for a list, the - * returned value can also be NULL. - * - * - * Description: - * Return the "next" node in the list or rin.g - */ - -NodePtr -ListGetNext(NodePtr np) -{ - if (np == NULL) - return NULL; - return np->next; -} /* ListGetNext */ - - - -/* - * Purpose: Swap two adjacent nodes in a list or ring - * - * Parameters: - * np1 "Prior" node - * np2 "Next" node - * - * - * Description: - * Swap the two specified elements, provided that they are - * adjacent, and np1 precedes np2. - */ - -void -ListSwapAdj(NodePtr np1, NodePtr np2) /* priornode, nextnode */ -{ - if (np1 == NULL || np2 == NULL || np1->next->last != np1) /* must be sane */ - return; - - if (np1->next != np2 || np2->last != np1) /* must be in order */ - return; - - if (np1->last != NULL) - np1->last->next = np2; - - if (np2->next != NULL) - np2->next->last = np1; - - np1->next = np2->next; - np2->last = np1->last; - - np1->last = np2; - np2->next = np1; -} /* ListSwapAdj */ - - - -/* - * Purpose: Sort the specified ring/list - * - * Parameters: - * head Head of the list to be sorted - * cmpfunc Comparison function (return values are like memcmp()) - * order ASCEND or DESCEND - * - * Returns: - * A pointer to the first element of the sorted ring or list - * - * - * Description: - * Sort the specified list, in place, using bubble sort, and - * the specified comparison function. Determine prior to sorting - * whether this is a list or a ring. If it's a ring, break the - * ring prior to sorting, and restore it to a ring topology - * after sorting has been completed. - */ - -NodePtr -ListSort(NodePtr head, int (*cmpfunc )PROTO ((NodePtr, NodePtr )), int order) /* 0 if equal, LT 0 if 1st element > 2nd element */ -{ - NodePtr np; - Boolean sorted = FALSE, ring; - int result; - - if (head == NULL) - return NULL; - if (head->last == NULL) - ring = FALSE; - else - ring = TRUE; - if (ring) - ListBreakRing(head); - - /* just bubble sort for now */ - - while (! sorted) { - np = head; - sorted = TRUE; - - while (np->next != NULL) { - result = (*cmpfunc)(np, np->next); - if ((result > 0 && order == ASCEND) || (result < 0 && order == DESCEND)) { - sorted = FALSE; - if (np == head) - head = np->next; /* keep head pointing at 1st element */ - ListSwapAdj(np, np->next); - } - else - np = np->next; - } - } - - if (ring) - ListConnectRing(head); - return head; /* ptr to first element */ -} /* ListSort */ - - - -/* - * Purpose: Break the specified ring into a non-circular (linear) list - * - * Parameters: - * np Head of the ring to be broken - * - * - * Description: - * Break the specified ring between its head and tail. - * - * Note: - * This function may be called safely (without effect) if the - * passed parameter is already a list, rather than a ring. - */ - -void -ListBreakRing(NodePtr np) -{ - if (np == NULL) - return; - if (np->last == NULL) - return; - - np->last->next = NULL; - np->last = NULL; -} /* ListBreakRing */ - - - -/* - * Purpose: Convert a list into a ring. - * - * Parameters: - * head Head of the list to be connected - * - * - * Description: - * Connect the specified list between its head and tail, producing - * a ring. - * - * Note: - * This function may be called safely (without effect) if the - * passed parameter is already a ring, rather than a list. - */ - -void -ListConnectRing(NodePtr head) -{ - NodePtr np; - - if (head == NULL) - return; - - np = head; - - while (np->next != NULL) { - np = np->next; - if (np == head) - return; - } - - np->next = head; - head->last = np; -} /* ListConnectRing */ - - -/* - * Purpose: Copy a list where the list elements are character strings - * - * Parameters: - * strlist List to be copied - * - * Returns: - * A copy of the original list (which may be NULL) - * - * - * Description: - * Create a list which is a copy of the original list, and - * also make copies of the strings. - * - * Note: - * There is no obvious way to make a generic list copying - * routine, because, in general, the length of each list - * element is unknown. This is a simple case where it is - * easy to copy a list. - */ - -NodePtr -ListStrCopy (NodePtr strlist) -{ - NodePtr newlist = NULL; - NodePtr np = strlist; - CharPtr stringtext; - - if (strlist == NULL) - return NULL; - - do { - stringtext = StringSave((CharPtr) np->elem); - newlist = ListInsert(stringtext, newlist); - np = ListGetNext(np); - } while (np != NULL && np != strlist); - - return newlist->next; /* points to 1st element in new list */ -} - - -/* - * Purpose: Delete a list where the list elements are character strings - * - * Parameters: - * np List to be deleted - * - * - * Description: - * Delete the list nodes and the character string data associated - * with each node. - * - * Note: - * This routine will work for any list element which is a single - * block of memory. However, it will not work in the more general - * case where a list element in turn references other memory - * which must also be freed. - */ - -void -ListStrDel (NodePtr np) -{ - while (np != NULL) - { - MemFree (np->elem); - np = ListDelete(np); - } -} -#endif /* NOWAY_ABOUT_TO_BE_ZOMBIED */ diff --git a/network/nsclilib/ni_list.h b/network/nsclilib/ni_list.h deleted file mode 100644 index 2ddbe113..00000000 --- a/network/nsclilib/ni_list.h +++ /dev/null @@ -1,98 +0,0 @@ -#ifdef NOWAY_ABOUT_TO_BE_ZOMBIED -/* -* =========================================================================== -* -* PUBLIC DOMAIN NOTICE -* National Center for Biotechnology Information -* -* This software/database is a "United States Government Work" under the -* terms of the United States Copyright Act. It was written as part of -* the author's official duties as a United States Government employee and -* thus cannot be copyrighted. This software/database is freely available -* to the public for use. The National Library of Medicine and the U.S. -* Government have not placed any restriction on its use or reproduction. -* -* Although all reasonable efforts have been taken to ensure the accuracy -* and reliability of the software and data, the NLM and the U.S. -* Government do not and cannot warrant the performance or results that -* may be obtained by using this software or data. The NLM and the U.S. -* Government disclaim all warranties, express or implied, including -* warranties of performance, merchantability or fitness for any particular -* purpose. -* -* Please cite the author in any work or product based on this material. -* -* =========================================================================== -* -* File Name: ni_list.h -* -* Author: Beatty, Gish -* -* Version Creation Date: 1/1/92 -* -* $Revision: 6.0 $ -* -* File Description: -* -* -* Modifications: -* -------------------------------------------------------------------------- -* Date Name Description of modification -* ------- ---------- ----------------------------------------------------- -* 5/12/92 Epstein Converted tabs to spaces -* -* -* ========================================================================== -* -* -* RCS Modification History: -* $Log: ni_list.h,v $ -* Revision 6.0 1997/08/25 18:38:53 madden -* Revision changed to 6.0 -* -* Revision 5.1 1997/01/28 21:23:46 epstein -* prepare to be zombied; functionality has been moved to ncbimisc.[ch] -* - * Revision 5.0 1996/05/28 14:11:55 ostell - * Set to revision 5.0 - * - * Revision 4.0 1995/07/26 13:56:32 ostell - * force revision to 4.0 - * - * Revision 1.2 1995/05/17 17:52:30 epstein - * add RCS log revision history - * -*/ - -#ifndef _NI_LIST_ -#define _NI_LIST_ - -#include "ncbinet.h" - -#define ASCEND 0 /* order for ListSort */ -#define DESCEND 1 - - -/* FUNCTIONS */ - -extern NodePtr ListInsert PROTO((VoidPtr elem, NodePtr after)); - -extern NodePtr ListInsertPrev PROTO((VoidPtr elem, NodePtr before)); - -extern NodePtr ListDelete PROTO((NodePtr node)); - -extern NodePtr ListGetNext PROTO((NodePtr after)); - -extern void ListSwapAdj PROTO((NodePtr priornode, NodePtr nextnode)); - -extern NodePtr ListSort PROTO((NodePtr sl, int (*cmpfunc)(NodePtr, NodePtr), int order)); - -extern void ListBreakRing PROTO((NodePtr np)); - -extern void ListConnectRing PROTO((NodePtr np)); -extern NodePtr ListStrCopy PROTO((NodePtr strlist)); -extern void ListStrDel PROTO((NodePtr np)); - - -#endif -#endif /* NOWAY_ABOUT_TO_BE_ZOMBIED */ diff --git a/network/nsclilib/ni_msg.asn b/network/nsclilib/ni_msg.asn deleted file mode 100644 index d67ee117..00000000 --- a/network/nsclilib/ni_msg.asn +++ /dev/null @@ -1,232 +0,0 @@ ---$Revision: 6.0 $ --- =========================================================================== --- --- PUBLIC DOMAIN NOTICE --- National Center for Biotechnology Information --- --- This software/database is a "United States Government Work" under the --- terms of the United States Copyright Act. It was written as part of --- the author's official duties as a United States Government employee and --- thus cannot be copyrighted. This software/database is freely available --- to the public for use. The National Library of Medicine and the U.S. --- Government have not placed any restriction on its use or reproduction. --- --- Although all reasonable efforts have been taken to ensure the accuracy --- and reliability of the software and data, the NLM and the U.S. --- Government do not and cannot warrant the performance or results that --- may be obtained by using this software or data. The NLM and the U.S. --- Government disclaim all warranties, express or implied, including --- warranties of performance, merchantability or fitness for any particular --- purpose. --- --- Please cite the author in any work or product based on this material. --- --- =========================================================================== --- --- File Name: ni_msg.asn --- --- Author: Beatty, Gish, Epstein --- --- Version Creation Date: 1/1/92 --- --- File Description: --- ASN.1 message header --- --- Modifications: --- ========================================================================== --- Date Name Description of modification --- ======= ========== ===================================================== --- 5/12/92 Epstein Added type to SVC-Entry --- --- --- ========================================================================== - - -NCBI-MESSAGE DEFINITIONS ::= -BEGIN - -EXPORTS SVC-Entry, RES-Entry, Toolset, Identity, Request, MSG-ACK, MSG-NACK, MSG-Login, MSG-SVC-List, - MSG-SVC-Request, MSG-SVC-Response, MSG-Cmd, MSG-Acct, MSG-Catalog, Message; - -SVC-Entry ::= SEQUENCE { - name VisibleString, -- name of service - minvers INTEGER, -- minimum legal version - maxvers INTEGER, -- maximum legal version - id INTEGER OPTIONAL, -- ID that is unique on host - priority INTEGER OPTIONAL, -- priority of service - group VisibleString OPTIONAL, -- group with access to service - description VisibleString OPTIONAL, -- description of service - types SET OF VisibleString OPTIONAL, -- types of allowed resources - priority-timeout INTEGER OPTIONAL, -- priority penalization timeout - priority-penalty INTEGER OPTIONAL, -- penalty exacted after timeout - encryption-supported BOOLEAN OPTIONAL, -- service supports encryption - tracking-period INTEGER OPTIONAL, -- time period (minutes) to track service - tracking-count INTEGER OPTIONAL -- # service requests during tracking-period from this IP - -} - -RES-Entry ::= SEQUENCE { - name VisibleString, -- name of resource - type VisibleString, -- type of resource - minvers INTEGER, -- minimum legal version - maxvers INTEGER, -- maximum legal version - id INTEGER OPTIONAL, -- ID that is unique on host - group VisibleString OPTIONAL, -- group with access to service - description VisibleString OPTIONAL -- description of service -} - -Region-Descr ::= SEQUENCE { - region-name VisibleString, -- name describing region - priority-delta INTEGER OPTIONAL -- priority incentive for client -} - -Toolset ::= SEQUENCE { - host VisibleString, -- name of host - motd VisibleString OPTIONAL, -- message of the day on host - services SET OF SVC-Entry OPTIONAL, - resources SET OF RES-Entry OPTIONAL, - regions SET OF Region-Descr OPTIONAL -} - -Identity ::= SEQUENCE { - username VisibleString, -- kerberos principle - group VisibleString OPTIONAL, -- kerberos instance - domain VisibleString OPTIONAL -- kerberos realm -} - -RSA-Pubkey ::= SEQUENCE { - bits INTEGER, - modulus OCTET STRING, - exponent OCTET STRING -} - -Dispatcher-Info ::= SEQUENCE { - serial-no INTEGER, -- unique ID assoc w/disp list - is-alternate-list BOOLEAN, -- is this an alternate dispatcher list? - num-dispatchers INTEGER, - disp-list SEQUENCE OF VisibleString, - pub-key RSA-Pubkey OPTIONAL -} - -Request ::= SEQUENCE { - address VisibleString OPTIONAL, -- client internet address - port INTEGER OPTIONAL, -- client contact port - svcentry SVC-Entry, -- service requested - resentry SET OF RES-Entry OPTIONAL -- resources requested -} - -MSG-ACK ::= SEQUENCE { - seqno INTEGER, -- sequence number of the acked message - disp-info Dispatcher-Info OPTIONAL, - admin-info VisibleString OPTIONAL, - motd VisibleString OPTIONAL -} - -MSG-NACK ::= SEQUENCE { - seqno INTEGER, -- sequence number of the nacked message - code INTEGER, -- exception code, (-1) means nonspecific error - reason VisibleString OPTIONAL , -- human-readable explanation - disp-info Dispatcher-Info OPTIONAL -} - -MSG-Login ::= SEQUENCE { - seqno INTEGER, -- sequence number - uid Identity, - password VisibleString OPTIONAL, -- should be encrypted - disp-serial-no INTEGER OPTIONAL, -- unique ID assoc w/disp list - encryption-desired BOOLEAN OPTIONAL, - pub-key RSA-Pubkey OPTIONAL, - des-key OCTET STRING OPTIONAL, -- from ncbid only - connect-delay INTEGER OPTIONAL , -- connect delay when contacting Disp - server-port INTEGER OPTIONAL -- from ncbid only -} - -MSG-SVC-List ::= SEQUENCE { - seqno INTEGER, -- sequence number - toollist Toolset, -- one set - knows-tracking BOOLEAN OPTIONAL -- aware of tracking-count/periods -} - -MSG-SVC-Request ::= SEQUENCE { - seqno INTEGER, -- sequence number - conid INTEGER, -- connection number for client accounting - uid Identity, -- client user ID struct - request Request, -- client address and request - platform INTEGER OPTIONAL, -- client's platform - appl-id VisibleString OPTIONAL, -- identifies client application - des-key OCTET STRING OPTIONAL, -- DES key to be used for session (key is encrypted using RSA) - want-pre-response BOOLEAN OPTIONAL, -- If TRUE, requesting MSG-SVC-Pre-Response - server-ip INTEGER OPTIONAL, -- IP address of server machine - server-port INTEGER OPTIONAL, -- port on server machine - want-ticket BOOLEAN OPTIONAL, -- If TRUE, requesting SVC-Request containing ticket - ticket Ticket OPTIONAL -} - -Ticket ::= SEQUENCE { - seqno INTEGER, - -- all fields that follow are encrypted using ncbid's DES key - confounding-rand-num OCTET STRING, -- used to confound forgery attempts - client-ip-1 OCTET STRING, -- ticket is valid from either of these 2 addrs - client-ip-2 OCTET STRING OPTIONAL, - server-ip OCTET STRING, -- this ticket is only valid at this server IP - client-des-key OCTET STRING OPTIONAL, - ticket-expiration OCTET STRING, - checksum OCTET STRING -} - - -MSG-SVC-Response ::= SEQUENCE { - seqno INTEGER, -- sequence number - request Request -- client address and request -} - -MSG-SVC-Pre-Response ::= SEQUENCE { - seqno INTEGER, -- sequence number - server-ip INTEGER -- IP address of server machine -} - -MSG-Cmd ::= SEQUENCE { - seqno INTEGER, -- sequence number - command INTEGER -} - -MSG-Acct ::= SEQUENCE { - seqno INTEGER, -- sequence number - conid INTEGER, -- connection number of client - jobname VisibleString, - usertime INTEGER, - systemtime INTEGER -} - -MSG-Catalog ::= SEQUENCE { - seqno INTEGER, -- sequence number - motd VisibleString OPTIONAL, -- message of the day - toollists SET OF Toolset OPTIONAL -- one set for each ncbid -} - -MSG-Load-Status ::= SEQUENCE { - load REAL, -- current load on this machine - power REAL, -- power of this machine - light-thresh REAL, -- when load is below this value, machine is considered to be lightly-loaded - heavy-thresh REAL, -- when load is above this value, machine is considered to be over-loaded - job-penalty REAL -- penalty per outstanding job on this server -} - -Message ::= CHOICE { - ack MSG-ACK, - nack MSG-NACK, - login MSG-Login, - svc-list MSG-SVC-List, - svc-request MSG-SVC-Request, - svc-response MSG-SVC-Response, - command MSG-Cmd, - acct MSG-Acct, - catalog MSG-Catalog, - svc-pre-response MSG-SVC-Pre-Response, - load-status MSG-Load-Status -} - -END - - - diff --git a/network/nsclilib/ni_msg.c b/network/nsclilib/ni_msg.c deleted file mode 100644 index 322f0b5d..00000000 --- a/network/nsclilib/ni_msg.c +++ /dev/null @@ -1,4603 +0,0 @@ -/* -* =========================================================================== -* -* PUBLIC DOMAIN NOTICE -* National Center for Biotechnology Information -* -* This software/database is a "United States Government Work" under the -* terms of the United States Copyright Act. It was written as part of -* the author's official duties as a United States Government employee and -* thus cannot be copyrighted. This software/database is freely available -* to the public for use. The National Library of Medicine and the U.S. -* Government have not placed any restriction on its use or reproduction. -* -* Although all reasonable efforts have been taken to ensure the accuracy -* and reliability of the software and data, the NLM and the U.S. -* Government do not and cannot warrant the performance or results that -* may be obtained by using this software or data. The NLM and the U.S. -* Government disclaim all warranties, express or implied, including -* warranties of performance, merchantability or fitness for any particular -* purpose. -* -* Please cite the author in any work or product based on this material. -* -* =========================================================================== -* -* File Name: ni_msg.c -* -* Author: Beatty, Gish, Epstein -* -* Version Creation Date: 1/1/92 -* -* $Revision: 6.4 $ -* -* File Description: -* This file consists mostly of functions for creating, destroying, reading, -* and writing message structures. It also contains the high-level functions -* for reading or writing a message, as well as the lowest-level functions -* which are read, write, and error 'hooks' for the ASN library. -* -* Modifications: -* -------------------------------------------------------------------------- -* Date Name Description of modification -* ------- ---------- ----------------------------------------------------- -* 5/01/92 Epstein Added extensive in-line commentary, and removed all tabs -* 5/01/92 Epstein Modified to support un-blocked reads, by storing state -* information and returning to the caller. -* 5/11/92 Epstein Changed MsgBuild() to free memory in the event of -* an invalid message type; fixed MsgDestroy() to -* return -1 rather than NULL (NULL is the wrong type); -* added logic to allow the dispatcher to update the -* CONID file when the value of "conid" is incremented -* 6/18/92 Epstein Added AsnIoSetBufsize() for write socket, to improve -* network throughput. -* 6/22/92 Epstein Changed all NI_AsnRead() and NI_AsnWrite() error return -* codes to be the negative of the absolute value of errno, -* because errno's can be negative on Macintoshes. -* 7/10/92 Epstein Changed MsgSaveData() to set the current index -* (mh->cur_index) to match the number of queued bytes; -* this avoids unintentional re-reading of queued data -* unless a read fails. -* 2/12/93 Epstein Add an argument to MsgMakeHandle() to indicate whether -* or not a socket should be created. -* 2/19/93 Epstein Add PC-NFS 4.0 support. -* 2/24/93 Epstein Fix memory leak -* 3/08/93 Epstein Add optional client platform to service request -* 3/11/93 Epstein Add "is-alternate-list" boolean to dispatcher-list, -* to make it easier for a dispatcher-monitor-client -* to distinguish between primary and backup dispatchers. -* 3/23/93 Epstein Change platform conditional-compilation to include -* the NETP_INET_ prefix, add VMS/TGV support. -* 4/02/93 Epstein Remember to initialize conid to a known value ... this -* avoids clients connecting with all sorts of wild conid -* values. -* 4/02/93 Epstein Add preliminary WinSock support. -* 4/13/93 Epstein Add subSet fields to toolset to support catalog -* filtering by dispatcher. -* 4/21/93 Schuler Removed (IoFuncType) typecast on calls to AsnIoNew() -* in order to enable compile-time type checking. -* 4/21/93 Schuler Changed implementation of NI_AsnNew(), NI_AsnWrite(), and -* NI_ASNIOError() to use LIBCALLBACK calling convention. -* 4/21/93 Epstein Fix MsgBuild() return error (was incorrectly returning -* FALSE instead of NULL). -* 5/07/93 Epstein Fixup NI_SetBlocking() and NI_SetNonBlocking(), which -* had been backwards. Also add Wollongong (TWG) support, -* and use INVALID_SOCKET #define, per WinSock spec. -* 5/25/93 Epstein Add regional support, and add application ID to -* service request. -* 5/27/93 Epstein Provide separate error code for ASN.1 dynamic object -* loader failure, try to do separate PeekMessage, etc. -* code for WinSock in the never-ending battle to fix -* scrollbar behavior under WinSock. -* 5/28/93 Epstein Re-work Disable-vibrant code to use new pragmatic -* "Gestalt" functions, rather than making explicit -* calls into Vibrant. This decouples Network Services -* from Vibrant. -* 6/02/93 Epstein Fixup sys_errlist references to correctly use new -* SOCK_INDEX_ERRNO macro, to accomodate yet another -* WinSock peculiarity. -* 6/07/93 Epstein Use new timer mechanism to support "hung timeout"; -* also add new function MsgSetTimeoutHooks(). -* Also add missing revision history, derived from -* RCS file. -* 6/09/93 Epstein Added activity hook to report network activity back -* to an application. -* 6/15/93 Epstein Fix long-standing WinSock scrolling problem, by changing -* NI_poll_select() to refrain from processing -* WM_LBUTTONUP messages. For some reason, reading these -* messages off the queue and processing them resulted -* in a failure to correctly interpret the WM_LBUTTONUP -* message as an "end scrolling" message. -* Also clean-up Windows compilation warnings. -* 6/17/93 Epstein Temporarily change NI_SetNonBlocking() to provide -* incorrect (blocking!) semantics for TWG. This must -* be fixed at a later date. -* 6/22/93 Epstein Support UCX, although NI_SetNonBlocking() and -* NI_SetBlocking() are currently completely unsupported. -* This should be fixed at a later date if it turns out -* that UCX actually supports these features. -* 8/09/93 Epstein Remove annoying cursor modification, except for NEWT, -* where it may be necessary. -*01/21/94 Schuler Calls to Yield() bracketed by #ifdef WIN61/#endif -*01/28/94 Schuler Replaced "OS_MAC" with "NETP_INET_MACTCP" -*01/28/94 Schuler Defined THIS_MODULE and THIS_FILE -*02/14/94 Epstein Added encryption support -*02/16/94 Epstein Replaced Gestalt calls with SetAppProperty() -*02/24/94 Epstein Move des-key from dispinfo to login to allow ncbid -* to send a DES key to dispatcher. Also performed some -* cleanup. -*06/08/94 Epstein Add messages needed for SOCKS support -*06/15/94 Epstein Add parameter to MsgWrite(), and add server-ip to -* service request, both to accomodate SOCKS. -*12/06/94 Epstein Added connectDelay, adminInfo and motd field to -* client<->Dispatcher communication. Also populated -* the priority field in the Catalog. -*12/21/94 Epstein Make use of new socket instrumentation -* ========================================================================== -* -* -* RCS Modification History: -* $Log: ni_msg.c,v $ -* Revision 6.4 2004/04/01 13:43:07 lavr -* Spell "occurred", "occurrence", and "occurring" -* -* Revision 6.3 2002/12/17 23:01:36 kans -* support for OS_UNIX_DARWIN for Mach-O executables (RGS) -* -* Revision 6.2 2001/08/29 18:00:01 juran -* Under Carbon, define missing POSIX macros in terms of Mac counterparts. -* -* Revision 6.1 1999/07/30 19:11:09 vakatov -* Use "strerror()" instead of "sys_errlist[]" -* -* Revision 6.0 1997/08/25 18:39:01 madden -* Revision changed to 6.0 -* -* Revision 5.3 1997/07/01 19:12:55 vakatov -* [WIN32] DLL'd "netcli.lib" -* -* Revision 5.2 1996/06/28 17:14:21 epstein -* add job-penalty -* - * Revision 5.1 1996/06/27 17:17:54 epstein - * add load-balancing - * - * Revision 5.0 1996/05/28 14:11:55 ostell - * Set to revision 5.0 - * - * Revision 4.5 1996/04/30 16:06:54 kans - * UsingOpenTransport checks gestalt (JAE) - * - * Revision 4.4 1996/04/02 13:21:08 epstein - * avoid a rare, unexplained condition by zapping a file descriptor - * - * Revision 4.3 1995/11/28 16:55:14 kans - * changed return NULL to return FALSE - * - * Revision 4.2 1995/11/27 20:59:24 epstein - * add client support for direct-connection services - * - * Revision 4.0 95/07/26 13:56:32 ostell - * force revision to 4.0 - * - * Revision 1.37 1995/05/24 12:08:54 epstein - * add support for tracking of how many times a client IP has used a service within a time interval - * - * Revision 1.36 95/05/17 17:52:39 epstein - * add RCS log revision history - * -*/ - -extern char * g_nsclient_module; -#define THIS_MODULE g_nsclient_module -static char * _this_file = __FILE__; -#define THIS_FILE _this_file - -#include <ncbi.h> -#include "ni_msg.h" -#include "ni_asn.h" /* produced by ASNTOOL */ - -#if TARGET_API_MAC_CARBON && !defined(O_NDELAY) -#define O_NDELAY kO_NDELAY -#endif - -/* macros */ -#if defined(NETP_INET_NEWT) || defined(NETP_INET_WSOCK) -/* cooperation may be required with Vibrant to avoid runaway scrollbars */ -#define DisabVibrant() { Nlm_SetAppProperty("disable_vibrant", "1"); SetHourGlass(); } -#define EnabVibrant() { Nlm_RemoveAppProperty("disable_vibrant"); PopHourGlass(); } -#else -#define DisabVibrant() -#define EnabVibrant() -#endif /* NETP_INET_NEWT */ - -static NIAckPtr readACK PROTO((void)); -static void writeACK PROTO((NIAckPtr ackp)); -static NINackPtr readNACK PROTO((void)); -static void writeNACK PROTO((NINackPtr nackp)); -static NILoginPtr readLOGIN PROTO ((void)); -static void writeLOGIN PROTO((NILoginPtr loginp)); -static NISvcListPtr readSVC_LIST PROTO ((void)); -static void writeSVC_LIST PROTO((NISvcListPtr svclistp)); -static NISvcReqPtr readSVC_REQUEST PROTO ((void)); -static void writeSVC_REQUEST PROTO((NISvcReqPtr svcreqp)); -static NISvcRespPtr readSVC_RESPONSE PROTO ((void)); -static void writeSVC_RESPONSE PROTO((NISvcRespPtr svcrespp)); -static NICmdPtr readCOMMAND PROTO ((void)); -static void writeCOMMAND PROTO((NICmdPtr cmdp)); -static NIPreRespPtr readPRE_RESPONSE PROTO ((void)); -static void writePRE_RESPONSE PROTO((NIPreRespPtr prp)); - -extern NITicketPtr NI_DestroyTicket PROTO ((NITicketPtr)); -static NITicketPtr NI_ReadTicket PROTO ((void)); -static Boolean NI_WriteTicket PROTO ((NITicketPtr)); - -static NIAcctPtr readACCT PROTO ((void)); -static void writeACCT PROTO((NIAcctPtr accp)); -static NICatalogPtr readCATALOG PROTO ((void)); -static void writeCATALOG PROTO((NICatalogPtr catp)); - -static NIStatusPtr readSTATUS PROTO ((void)); -static void writeSTATUS PROTO((NIStatusPtr statp)); - -static int readRequest PROTO ((ReqPtr rp)); -static void writeRequest PROTO((ReqPtr reqp)); -static int readUid PROTO ((NI_UidPtr uid)); -static void writeUid PROTO((NI_UidPtr uidp)); -static int readService PROTO ((NISvcPtr svcp)); -static void writeService PROTO((NISvcPtr svcp)); -static int readResource PROTO ((NIResPtr resp)); -static void writeResource PROTO((NIResPtr resp)); -static int readRegion PROTO ((NIRegionPtr regp)); -static void writeRegion PROTO((NIRegionPtr regp)); -static int readToolset PROTO ((NIToolsetPtr tsp)); -static void writeToolset PROTO((NIToolsetPtr tsp)); -static int readPubKey PROTO ((NIPubKeyPtr pubkey)); -static void writePubKey PROTO((NIPubKeyPtr pubkey)); -static int readDispInfo PROTO ((NIDispInfoPtr dip)); -static void writeDispInfo PROTO((NIDispInfoPtr dip)); - -static Boolean InitMsg PROTO((void)); -static void WriteCleanup PROTO((CharPtr tmpbuf)); -static Boolean MsgHaveSavedData PROTO((MHandPtr mh)); -static void MsgSaveData PROTO((MHandPtr mh, CharPtr buf, - Uint2 len)); -static int MsgReadSavedData PROTO((MHandPtr mh, - CharPtr buf, Uint2 len)); -static void MsgFreeSavedData PROTO((MHandPtr mh)); -static void SetHourGlass PROTO((void)); -static void PopHourGlass PROTO((void)); - - -/* VARS */ - -Uint4 conid = 1; /* globally unique connection ID counter */ -Jumpbuf ni_env; /* saved environment for LongJump (servers only) */ - -static AsnTypePtr atp; -static AsnIoPtr aip; - - - -/* FUNCTIONS */ - -/******************************************************************************/ -/* */ -/* Functions for creating, destroying, reading, and writing message structures*/ -/* */ -/******************************************************************************/ - - - - -/************************************ ACK *************************************/ - -NLM_EXTERN NIAckPtr NI_MakeMsgAck(void) -{ - NIAckPtr ap; - - ap = (NIAckPtr) MemNew(sizeof(NIAck)); - ap->seqno = 0; - ap->dispinfo = NULL; - ap->adminInfo = NULL; - ap->motd = NULL; - return ap; -} /* NI_MakeMsgAck */ - - -NLM_EXTERN Int2 NI_DestroyMsgAck(NIAckPtr mp) -{ - if (mp == NULL) - return 1; - if (mp->dispinfo != NULL) - { - NI_DestroyDispInfo(mp->dispinfo); - } - if (mp->adminInfo != NULL) - { - MemFree(mp->adminInfo); - } - if (mp->motd != NULL) - { - MemFree(mp->motd); - } - MemFree(mp); - return 0; -} /* NI_MakeMsgAck */ - - -static NIAckPtr -readACK(void) -{ - DataVal value; - NIAckPtr ackp; - - ackp = NI_MakeMsgAck(); - if ((atp = AsnReadId(aip, amp, atp)) == NULL) /* seqno */ - goto AckFail; - if (AsnReadVal(aip, atp, &value) < 0) - goto AckFail; - ackp->seqno = value.intvalue; - atp = AsnReadId(aip, amp, atp); - if (atp == MSG_ACK_disp_info) { - if (AsnReadVal(aip, atp, &value) < 0) - goto AckFail; - ackp->dispinfo = NI_MakeDispInfo(); - if (readDispInfo(ackp->dispinfo) < 0) - goto AckFail; - if ((atp = AsnReadId(aip, amp, atp)) == NULL) - goto AckFail; - } - if (atp == MSG_ACK_admin_info) { - if (AsnReadVal(aip, atp, &value) < 0) - goto AckFail; - ackp->adminInfo = (CharPtr) value.ptrvalue; - if ((atp = AsnReadId(aip, amp, atp)) == NULL) - goto AckFail; - } - if (atp == MSG_ACK_motd) { - if (AsnReadVal(aip, atp, &value) < 0) - goto AckFail; - ackp->motd = (CharPtr) value.ptrvalue; - if ((atp = AsnReadId(aip, amp, atp)) == NULL) - goto AckFail; - } - if (atp != MESSAGE_ack) - goto AckFail; - if (AsnReadVal(aip, atp, &value) < 0) - goto AckFail; - return ackp; - - AckFail: - NI_DestroyMsgAck(ackp); - return NULL; -} /* readACK */ - - -static void -writeACK(NIAckPtr ackp) -{ - DataVal value; - - AsnStartStruct(aip, MESSAGE_ack); - value.intvalue = (Int4) ackp->seqno; - AsnWrite(aip, MSG_ACK_seqno, &value); - if (ackp->dispinfo != NULL) { - AsnStartStruct(aip, MSG_ACK_disp_info); - writeDispInfo(ackp->dispinfo); - AsnEndStruct(aip, MSG_ACK_disp_info); - } - if (ackp->adminInfo != NULL) { - value.ptrvalue = (Pointer) ackp->adminInfo; - AsnWrite(aip, MSG_ACK_admin_info, &value); - } - if (ackp->motd != NULL) { - value.ptrvalue = (Pointer) ackp->motd; - AsnWrite(aip, MSG_ACK_motd, &value); - } - - AsnEndStruct(aip, MESSAGE_ack); -} /* writeACK */ - - -/************************************ NACK ***********************************/ - -NLM_EXTERN NINackPtr NI_MakeMsgNack(void) -{ - NINackPtr np; - - np = (NINackPtr) MemNew(sizeof(NINack)); - np->seqno = 0; - np->reason = NULL; - np->dispinfo = NULL; - return np; -} /* NI_MakeMsgNack */ - - -NLM_EXTERN Int2 NI_DestroyMsgNack(NINackPtr mp) -{ - if (mp == NULL) - return 1; - if (mp->reason != NULL) - MemFree(mp->reason); - if (mp->dispinfo != NULL) - NI_DestroyDispInfo(mp->dispinfo); - MemFree(mp); - return 0; -} /* NI_DestroyMsgNack */ - - -static NINackPtr -readNACK(void) -{ - DataVal value; - NINackPtr nackp; - - nackp = NI_MakeMsgNack(); - if ((atp = AsnReadId(aip, amp, atp)) == NULL) /* seqno */ - goto NackFail; - if (AsnReadVal(aip, atp, &value) < 0) - goto NackFail; - nackp->seqno = value.intvalue; - if ((atp = AsnReadId(aip, amp, atp)) == NULL) /* code */ - goto NackFail; - if (AsnReadVal(aip, atp, &value) < 0) - goto NackFail; - nackp->code = (NI_Error) value.intvalue; - - if ((atp = AsnReadId(aip, amp, atp)) == MSG_NACK_reason) { /* reason */ - if (AsnReadVal(aip, atp, &value) < 0) - goto NackFail; - nackp->reason = (CharPtr) value.ptrvalue; - if ((atp = AsnReadId(aip, amp, atp)) == NULL) - goto NackFail; - } - if (atp == MSG_NACK_disp_info) { - if (AsnReadVal(aip, atp, &value) < 0) - goto NackFail; - nackp->dispinfo = NI_MakeDispInfo(); - if (readDispInfo(nackp->dispinfo) < 0) - goto NackFail; - if ((atp = AsnReadId(aip, amp, atp)) == NULL) - goto NackFail; - } - if (atp != MESSAGE_nack) - goto NackFail; - if (AsnReadVal(aip, atp, &value) < 0) - goto NackFail; - return nackp; - - NackFail: - NI_DestroyMsgNack(nackp); - return NULL; -} /* readNACK */ - - -static void -writeNACK(NINackPtr nackp) -{ - DataVal value; - - AsnStartStruct(aip, MESSAGE_nack); - value.intvalue = (Int4) nackp->seqno; - AsnWrite(aip, MSG_NACK_seqno, &value); - value.intvalue = (Int4) nackp->code; - AsnWrite(aip, MSG_NACK_code, &value); - - if (nackp->reason != NULL) { - value.ptrvalue = (Pointer) nackp->reason; - AsnWrite(aip, MSG_NACK_reason, &value); - } - if (nackp->dispinfo != NULL) { - AsnStartStruct(aip, MSG_NACK_disp_info); - writeDispInfo(nackp->dispinfo); - AsnEndStruct(aip, MSG_NACK_disp_info); - } - AsnEndStruct(aip, MESSAGE_nack); -} - - -/************************************ LOGIN ***********************************/ - -NLM_EXTERN NILoginPtr NI_MakeMsgLogin(void) -{ - NILoginPtr lp; - - lp = (NILoginPtr) MemNew(sizeof(NILogin)); - lp->seqno = 0; - lp->uid = NI_MakeUid(); - lp->password = NULL; - lp->dispserialno = -1; - lp->encryptionDesired = FALSE; - lp->pubKey = NULL; - lp->desKey = NULL; - lp->connectDelay = -1; - lp->server_port = 0; - return lp; -} /* NI_MakeMsgLogin() */ - - -NLM_EXTERN Int2 NI_DestroyMsgLogin(NILoginPtr lp) -{ - if (lp == NULL) - return 1; - if (lp->uid != NULL) - NI_DestroyUid(lp->uid); - if (lp->password != NULL) - MemFree(lp->password); - if (lp->pubKey != NULL) - NI_DestroyPubKey(lp->pubKey); - if (lp->desKey != NULL) - BSFree(lp->desKey); - MemFree(lp); - return 0; -} /* NI_DestroyMsgLogin() */ - - -static NILoginPtr -readLOGIN(void) -{ - DataVal value; - NILoginPtr loginp; - - loginp = NI_MakeMsgLogin(); - if ((atp = AsnReadId(aip, amp, atp)) == NULL) /* seqno */ - goto LoginFail; - if (AsnReadVal(aip, atp, &value) < 0) - goto LoginFail; - loginp->seqno = value.intvalue; - - if ((atp = AsnReadId(aip, amp, atp)) == NULL) /* MSG_LOGIN_uid */ - goto LoginFail; - if (AsnReadVal(aip, atp, &value) < 0) - goto LoginFail; - if (readUid(loginp->uid) < 0) - goto LoginFail; - - if ((atp = AsnReadId(aip, amp, atp)) == NULL) /* password ? */ - goto LoginFail; - - if (atp == MSG_LOGIN_password) { - if (AsnReadVal(aip, atp, &value) < 0) - goto LoginFail; - loginp->password = (CharPtr) value.ptrvalue; - - if ((atp = AsnReadId(aip, amp, atp)) == NULL) /* disp_serial_no ? */ - goto LoginFail; - } - - if (atp == MSG_LOGIN_disp_serial_no) { - if (AsnReadVal(aip, atp, &value) < 0) - goto LoginFail; - loginp->dispserialno = value.intvalue; - - if ((atp = AsnReadId(aip, amp, atp)) == NULL) /* encryption desired ? */ - goto LoginFail; - } - - if (atp == MSG_LOGIN_encryption_desired) { - if (AsnReadVal(aip, atp, &value) < 0) - goto LoginFail; - loginp->encryptionDesired = value.boolvalue; - - if ((atp = AsnReadId(aip, amp, atp)) == NULL) /* pub_key ? */ - goto LoginFail; - - } - - if (atp == MSG_LOGIN_pub_key) { - if (AsnReadVal(aip, atp, &value) < 0) - goto LoginFail; - loginp->pubKey = NI_MakePubKey(); - if (readPubKey(loginp->pubKey) < 0) - goto LoginFail; - if ((atp = AsnReadId(aip, amp, atp)) == NULL) /* des_key ? */ - goto LoginFail; - } - - if (atp == MSG_LOGIN_des_key) { - if (AsnReadVal(aip, atp, &value) < 0) - goto LoginFail; - loginp->desKey = (ByteStorePtr) value.ptrvalue; - - if ((atp = AsnReadId(aip, amp, atp)) == NULL) /* connect_delay ? */ - goto LoginFail; - } - - if (atp == MSG_LOGIN_connect_delay) { - if (AsnReadVal(aip, atp, &value) < 0) - goto LoginFail; - loginp->connectDelay = value.intvalue; - - if ((atp = AsnReadId(aip, amp, atp)) == NULL) /* server_port ? */ - goto LoginFail; - } - - if (atp == MSG_LOGIN_server_port) { - if (AsnReadVal(aip, atp, &value) < 0) - goto LoginFail; - - loginp->server_port = value.intvalue; - - if ((atp = AsnReadId(aip, amp, atp)) == NULL) /* last message ? */ - goto LoginFail; - } - if (atp != MESSAGE_login) - goto LoginFail; - if (AsnReadVal(aip, atp, &value) < 0) - goto LoginFail; - return loginp; - - LoginFail: - NI_DestroyMsgLogin(loginp); - return NULL; -} /* readLOGIN */ - - -static void -writeLOGIN(NILoginPtr loginp) -{ - DataVal value; - - AsnStartStruct(aip, MESSAGE_login); - value.intvalue = (Int4) loginp->seqno; - AsnWrite(aip, MSG_LOGIN_seqno, &value); - AsnStartStruct(aip, MSG_LOGIN_uid); - writeUid(loginp->uid); - AsnEndStruct(aip, MSG_LOGIN_uid); - - if (loginp->password != NULL) { - value.ptrvalue = (Pointer) loginp->password; - AsnWrite(aip, MSG_LOGIN_password, &value); - } - if (loginp->dispserialno >= 0) { - value.intvalue = loginp->dispserialno; - AsnWrite(aip, MSG_LOGIN_disp_serial_no, &value); - } - if (loginp->encryptionDesired) { - value.boolvalue = loginp->encryptionDesired; - AsnWrite(aip, MSG_LOGIN_encryption_desired, &value); - } - if (loginp->pubKey != NULL) { - AsnStartStruct(aip, MSG_LOGIN_pub_key); - writePubKey(loginp->pubKey); - AsnEndStruct(aip, MSG_LOGIN_pub_key); - } - if (loginp->desKey != NULL) { - value.ptrvalue = (Pointer) loginp->desKey; - AsnWrite(aip, MSG_LOGIN_des_key, &value); - } - if (loginp->connectDelay >= 0) { - value.intvalue = loginp->connectDelay; - AsnWrite(aip, MSG_LOGIN_connect_delay, &value); - } - - if (loginp->server_port > 0) { - value.intvalue = loginp->server_port; - AsnWrite(aip, MSG_LOGIN_server_port, &value); - } - - - AsnEndStruct(aip, MESSAGE_login); -} /* writeLOGIN */ - - -/************************************ SVC_LIST ********************************/ - -NLM_EXTERN NISvcListPtr NI_MakeMsgSvclist(void) -{ - NISvcListPtr sp; - - sp = (NISvcListPtr) MemNew(sizeof(NISvcList)); - sp->seqno = 0; - sp->toolset = NI_MakeToolset(); - sp->knowsTracking = FALSE; - return sp; -} /* NI_MakeMsgSvclist */ - - -NLM_EXTERN Int2 NI_DestroyMsgSvclist(NISvcListPtr sp) -{ - if (sp == NULL) - return 1; - if (sp->toolset != NULL) - NI_DestroyToolset(sp->toolset); - MemFree(sp); - return 0; -} /* NI_DestroyMsgSvclist */ - - -static NISvcListPtr -readSVC_LIST(void) -{ - DataVal value; - NISvcListPtr svclistp; - - svclistp = NI_MakeMsgSvclist(); - - if ((atp = AsnReadId(aip, amp, atp)) == NULL) /* MSG_SVC_LIST_seqno */ - goto SvcListFail; - if (AsnReadVal(aip, atp, &value) < 0) - goto SvcListFail; - svclistp->seqno = value.intvalue; - - if ((atp = AsnReadId(aip, amp, atp)) == NULL) /* MSG_SVC_LIST_toollist */ - goto SvcListFail; - if (AsnReadVal(aip, atp, &value) < 0) - goto SvcListFail; - if (readToolset(svclistp->toolset) < 0) - goto SvcListFail; - if ((atp = AsnReadId(aip, amp, atp)) == NULL) - goto SvcListFail; - if (AsnReadVal(aip, atp, &value) < 0) - goto SvcListFail; - - if (atp == MSG_SVC_LIST_knows_tracking) - { - svclistp->knowsTracking = value.boolvalue; - if ((atp = AsnReadId(aip, amp, atp)) == NULL) - goto SvcListFail; - if (AsnReadVal(aip, atp, &value) < 0) - goto SvcListFail; - } - - if (atp != MESSAGE_svc_list) - goto SvcListFail; - return svclistp; - - SvcListFail: - NI_DestroyMsgSvclist(svclistp); - return NULL; -} /* readSVC_LIST */ - - -static void -writeSVC_LIST(NISvcListPtr svclistp) -{ - DataVal value; - - AsnStartStruct(aip, MESSAGE_svc_list); - value.intvalue = (Int4) svclistp->seqno; - AsnWrite(aip, MSG_SVC_LIST_seqno, &value); - - AsnStartStruct(aip, MSG_SVC_LIST_toollist); - writeToolset(svclistp->toolset); - AsnEndStruct(aip, MSG_SVC_LIST_toollist); - if (svclistp->knowsTracking) - { - value.boolvalue = svclistp->knowsTracking; - AsnWrite(aip, MSG_SVC_LIST_knows_tracking, &value); - } - - AsnEndStruct(aip, MESSAGE_svc_list); -} /* writeSVC_LIST */ - - -/************************************ SVC_REQUEST *****************************/ - -NLM_EXTERN NISvcReqPtr NI_MakeMsgSvcreq(void) -{ - NISvcReqPtr sp; - - sp = (NISvcReqPtr) MemNew(sizeof(NISvcReq)); - sp->seqno = 0; - sp->uid = NI_MakeUid(); - sp->request = NI_MakeRequest(); - sp->platform = NI_PLATFORM_UNKNOWN; - sp->applId = NULL; - sp->desKey = NULL; - sp->wantPreResponse = FALSE; - sp->server_ip = 0; - sp->server_port = 0; - sp->want_ticket = FALSE; - sp->ticket = NULL; - return sp; -} /* NI_MakeMsgSvcreq() */ - - -NLM_EXTERN Int2 NI_DestroyMsgSvcreq(NISvcReqPtr sp) -{ - if (sp == NULL) - return 1; - if (sp->uid != NULL) - NI_DestroyUid(sp->uid); - if (sp->request != NULL) - NI_DestroyRequest(sp->request); - if (sp->applId != NULL) - MemFree(sp->applId); - if (sp->desKey != NULL) - BSFree (sp->desKey); - if (sp->ticket != NULL) - NI_DestroyTicket (sp->ticket); - MemFree(sp); - return 0; -} /* NI_DestroyMsgSvcreq() */ - - -static NISvcReqPtr -readSVC_REQUEST(void) -{ - DataVal value; - NISvcReqPtr svcreqp; - - svcreqp = NI_MakeMsgSvcreq(); - if ((atp = AsnReadId(aip, amp, atp)) == NULL) /* MSG_SVC_REQUEST_seqno */ - goto SvcReqFail; - if (AsnReadVal(aip, atp, &value) < 0) - goto SvcReqFail; - svcreqp->seqno = value.intvalue; - - if ((atp = AsnReadId(aip, amp, atp)) == NULL) /* MSG_SVC_REQUEST_conid */ - goto SvcReqFail; - if (AsnReadVal(aip, atp, &value) < 0) - goto SvcReqFail; - svcreqp->conid = value.intvalue; - - if ((atp = AsnReadId(aip, amp, atp)) == NULL) /* MSG_SVC_REQUEST_uid */ - goto SvcReqFail; - if (AsnReadVal(aip, atp, &value) < 0) - goto SvcReqFail; - if (readUid(svcreqp->uid) < 0) - goto SvcReqFail; - - if ((atp = AsnReadId(aip, amp, atp)) == NULL) /* MSG_SVC_REQUEST_request */ - goto SvcReqFail; - if (AsnReadVal(aip, atp, &value) < 0) - goto SvcReqFail; - if (readRequest(svcreqp->request) < 0) - goto SvcReqFail; - - if ((atp = AsnReadId(aip, amp, atp)) == MSG_SVC_REQUEST_platform) { - if (AsnReadVal(aip, atp, &value) < 0) - goto SvcReqFail; - svcreqp->platform = (Uint4) value.intvalue; - atp = AsnReadId(aip, amp, atp); - } - - if (atp == MSG_SVC_REQUEST_appl_id) { - if (AsnReadVal(aip, atp, &value) < 0) - goto SvcReqFail; - svcreqp->applId = (CharPtr) value.ptrvalue; - atp = AsnReadId(aip, amp, atp); - } - - if (atp == MSG_SVC_REQUEST_des_key) { - if (AsnReadVal(aip, atp, &value) < 0) - goto SvcReqFail; - svcreqp->desKey = (ByteStorePtr) value.ptrvalue; - atp = AsnReadId(aip, amp, atp); - } - - if (atp == SVC_REQUEST_want_pre_response) { - if (AsnReadVal(aip, atp, &value) < 0) - goto SvcReqFail; - svcreqp->wantPreResponse = value.boolvalue; - atp = AsnReadId(aip, amp, atp); - } - - if (atp == MSG_SVC_REQUEST_server_ip) { - if (AsnReadVal(aip, atp, &value) < 0) - goto SvcReqFail; - svcreqp->server_ip = value.intvalue; - atp = AsnReadId(aip, amp, atp); - } - if (atp == MSG_SVC_REQUEST_server_port) { - if (AsnReadVal(aip, atp, &value) < 0) - goto SvcReqFail; - svcreqp->server_port = value.intvalue; - atp = AsnReadId(aip, amp, atp); - } - if (atp == MSG_SVC_REQUEST_want_ticket) { - if (AsnReadVal(aip, atp, &value) < 0) - goto SvcReqFail; - svcreqp->want_ticket = value.boolvalue; - atp = AsnReadId(aip, amp, atp); - } - if (svcreqp->want_ticket) { - - if (atp == MSG_SVC_REQUEST_ticket) { - if (AsnReadVal(aip, atp, &value) < 0) - goto SvcReqFail; - if((svcreqp->ticket = NI_ReadTicket()) == 0) - goto SvcReqFail; - atp = AsnReadId(aip, amp, atp); - } - } - - if (atp != MESSAGE_svc_request) - goto SvcReqFail; - if (AsnReadVal(aip, atp, &value) < 0) - goto SvcReqFail; - return svcreqp; - - SvcReqFail: - NI_DestroyMsgSvcreq(svcreqp); - return NULL; -} /* readSVC_REQUEST */ - - -static void -writeSVC_REQUEST(NISvcReqPtr svcreqp) -{ - DataVal value; - - AsnStartStruct(aip, MESSAGE_svc_request); - value.intvalue = (Int4) svcreqp->seqno; - AsnWrite(aip, MSG_SVC_REQUEST_seqno, &value); - value.intvalue = (Int4) svcreqp->conid; - AsnWrite(aip, MSG_SVC_REQUEST_conid, &value); - AsnStartStruct(aip, MSG_SVC_REQUEST_uid); - writeUid(svcreqp->uid); - AsnEndStruct(aip, MSG_SVC_REQUEST_uid); - AsnStartStruct(aip, MSG_SVC_REQUEST_request); - writeRequest(svcreqp->request); - AsnEndStruct(aip, MSG_SVC_REQUEST_request); - value.intvalue = (Int4) svcreqp->platform; - AsnWrite(aip, MSG_SVC_REQUEST_platform, &value); - - if (svcreqp->applId != NULL) - { - value.ptrvalue = (Pointer) svcreqp->applId; - AsnWrite(aip, MSG_SVC_REQUEST_appl_id, &value); - } - - if (svcreqp->desKey != NULL) - { - value.ptrvalue = (Pointer) svcreqp->desKey; - AsnWrite(aip, MSG_SVC_REQUEST_des_key, &value); - } - - if (svcreqp->wantPreResponse) - { - value.boolvalue = svcreqp->wantPreResponse; - AsnWrite(aip, SVC_REQUEST_want_pre_response, &value); - } - - if (svcreqp->server_ip != 0) - { - value.intvalue = svcreqp->server_ip; - AsnWrite(aip, MSG_SVC_REQUEST_server_ip, &value); - } - - if (svcreqp->server_port != 0) - { - value.intvalue = svcreqp->server_port; - AsnWrite(aip, MSG_SVC_REQUEST_server_port, &value); - } - - if (svcreqp->want_ticket) { - - value.boolvalue = svcreqp->want_ticket; - AsnWrite(aip, MSG_SVC_REQUEST_want_ticket, &value); - - if (svcreqp->ticket != NULL) { - AsnStartStruct(aip, MSG_SVC_REQUEST_ticket); - NI_WriteTicket(svcreqp->ticket); - AsnEndStruct(aip, MSG_SVC_REQUEST_ticket); - } - } - AsnEndStruct(aip, MESSAGE_svc_request); -} /* writeSVC_REQUEST */ - -/********************************* TICKET *************************************/ - -NLM_EXTERN NITicketPtr NI_MakeTicket(void) -{ - NITicketPtr ptr = MemNew((size_t) sizeof(NITicket)); - return ptr; -} - -extern NITicketPtr NI_DestroyTicket(NITicketPtr ptr) -{ - if (ptr == NULL) { - return NULL; - } - BSFree(ptr -> confounding_rand_num); - BSFree(ptr -> client_ip_1); - BSFree(ptr -> client_ip_2); - BSFree(ptr -> server_ip); - BSFree(ptr -> client_des_key); - BSFree(ptr -> ticket_expiration); - BSFree(ptr -> checksum); - return MemFree(ptr); -} - -static NITicketPtr -NI_ReadTicket(void) -{ - DataVal av; - NITicketPtr ptr; - ptr = NI_MakeTicket(); - - if ((atp = AsnReadId(aip,amp, atp)) == NULL) - goto TicketFail; - - if (atp == TICKET_seqno) { - if ( AsnReadVal(aip, atp, &av) < 0) { - goto TicketFail; - } - ptr -> seqno = av.intvalue; - if ((atp = AsnReadId(aip,amp, atp)) == NULL) - goto TicketFail; - } - if (atp == TICKET_confounding_rand_num) { - if ( AsnReadVal(aip, atp, &av) < 0) { - goto TicketFail; - } - ptr -> confounding_rand_num = (ByteStorePtr) av.ptrvalue; - atp = AsnReadId(aip,amp, atp); - } - if (atp == TICKET_client_ip_1) { - if ( AsnReadVal(aip, atp, &av) < 0) { - goto TicketFail; - } - ptr -> client_ip_1 = (ByteStorePtr) av.ptrvalue; - atp = AsnReadId(aip,amp, atp); - } - if (atp == TICKET_client_ip_2) { - if ( AsnReadVal(aip, atp, &av) < 0) { - goto TicketFail; - } - ptr -> client_ip_2 = (ByteStorePtr) av.ptrvalue; - atp = AsnReadId(aip,amp, atp); - } - if (atp == TICKET_server_ip) { - if ( AsnReadVal(aip, atp, &av) < 0) { - goto TicketFail; - } - ptr -> server_ip = (ByteStorePtr) av.ptrvalue; - atp = AsnReadId(aip,amp, atp); - } - if (atp == TICKET_client_des_key) { - if ( AsnReadVal(aip, atp, &av) < 0) { - goto TicketFail; - } - ptr -> client_des_key = (ByteStorePtr) av.ptrvalue; - atp = AsnReadId(aip,amp, atp); - } - if (atp == TICKET_ticket_expiration) { - if ( AsnReadVal(aip, atp, &av) < 0) { - goto TicketFail; - } - ptr -> ticket_expiration = (ByteStorePtr) av.ptrvalue; - atp = AsnReadId(aip,amp, atp); - } - if (atp == TICKET_checksum) { - if ( AsnReadVal(aip, atp, &av) < 0) { - goto TicketFail; - } - ptr -> checksum = (ByteStorePtr) av.ptrvalue; - atp = AsnReadId(aip,amp, atp); - } - - if (AsnReadVal(aip, atp, &av) < 0) { - goto TicketFail; - } - /* end struct */ - - return ptr; - -TicketFail: - - NI_DestroyTicket(ptr); - return NULL; -} - -static Boolean -NI_WriteTicket(NITicketPtr ptr) -{ - DataVal av; - Boolean retval = FALSE; - - av.intvalue = ptr -> seqno; - retval = AsnWrite(aip, TICKET_seqno, &av); - if (ptr -> confounding_rand_num != NULL) { - av.ptrvalue = (Pointer) ptr -> confounding_rand_num; - retval = AsnWrite(aip, TICKET_confounding_rand_num, &av); - } - if (ptr -> client_ip_1 != NULL) { - av.ptrvalue = (Pointer) ptr -> client_ip_1; - retval = AsnWrite(aip, TICKET_client_ip_1, &av); - } - if (ptr -> client_ip_2 != NULL) { - av.ptrvalue = (Pointer) ptr -> client_ip_2; - retval = AsnWrite(aip, TICKET_client_ip_2, &av); - } - if (ptr -> server_ip != NULL) { - av.ptrvalue = (Pointer) ptr -> server_ip; - retval = AsnWrite(aip, TICKET_server_ip, &av); - } - if (ptr -> client_des_key != NULL) { - av.ptrvalue = (Pointer) ptr -> client_des_key; - retval = AsnWrite(aip, TICKET_client_des_key, &av); - } - if (ptr -> ticket_expiration != NULL) { - av.ptrvalue = (Pointer) ptr -> ticket_expiration; - retval = AsnWrite(aip, TICKET_ticket_expiration, &av); - } - if (ptr -> checksum != NULL) { - av.ptrvalue = (Pointer) ptr -> checksum; - retval = AsnWrite(aip, TICKET_checksum, &av); - } - - if (!retval) - goto TicketFail; - return retval; - -TicketFail: - - NI_DestroyTicket(ptr); - return FALSE; - -} - - - -/********************************* SVC_RESPONSE *******************************/ - -NLM_EXTERN NISvcRespPtr NI_MakeMsgSvcresp(void) -{ - NISvcRespPtr sp; - - sp = (NISvcRespPtr) MemNew(sizeof(NISvcResp)); - sp->seqno = 0; - sp->request = NI_MakeRequest(); - return sp; -} /* NI_MakeMsgSvcresp() */ - - -NLM_EXTERN Int2 NI_DestroyMsgSvcresp(NISvcRespPtr sp) -{ - if (sp == NULL) - return 1; - if (sp->request != NULL) - NI_DestroyRequest(sp->request); - MemFree(sp); - return 0; -} /* NI_DestroyMsgSvcresp() */ - - -static NISvcRespPtr -readSVC_RESPONSE(void) -{ - DataVal value; - NISvcRespPtr svcrespp; - - svcrespp = NI_MakeMsgSvcresp(); - if ((atp = AsnReadId(aip, amp, atp)) == NULL) /* MSG_SVC_RESPONSE_seqno */ - goto SvcRespFail; - if (AsnReadVal(aip, atp, &value) < 0) - goto SvcRespFail; - svcrespp->seqno = value.intvalue; - - if ((atp = AsnReadId(aip, amp, atp)) == NULL) /* MSG_SVC_RESPONSE_request */ - goto SvcRespFail; - if (AsnReadVal(aip, atp, &value) < 0) - goto SvcRespFail; - if (readRequest(svcrespp->request) < 0) - goto SvcRespFail; - if ((atp = AsnReadId(aip, amp, atp)) == NULL) /* MSG_SVC_RESPONSE_request */ - goto SvcRespFail; - if (AsnReadVal(aip, atp, &value) < 0) - goto SvcRespFail; - - if (atp != MESSAGE_svc_response) - goto SvcRespFail; - return svcrespp; - - SvcRespFail: - NI_DestroyMsgSvcresp(svcrespp); - return NULL; -} /* readSVC_RESPONSE */ - - -static void -writeSVC_RESPONSE(NISvcRespPtr svcrespp) -{ - DataVal value; - - AsnStartStruct(aip, MESSAGE_svc_response); - value.intvalue = (Int4) svcrespp->seqno; - AsnWrite(aip, MSG_SVC_RESPONSE_seqno, &value); - AsnStartStruct(aip, MSG_SVC_RESPONSE_request); - writeRequest(svcrespp->request); - AsnEndStruct(aip, MSG_SVC_RESPONSE_request); - AsnEndStruct(aip, MESSAGE_svc_response); -} /* writeSVC_RESPONSE */ - - -/************************************ COMMAND *********************************/ - -NLM_EXTERN NICmdPtr NI_MakeMsgCmd(void) -{ - NICmdPtr cp; - - cp = (NICmdPtr) MemNew(sizeof(NICmd)); - cp->seqno = 0; - return cp; -} /* NI_MakeMsgCmd() */ - - -NLM_EXTERN Int2 NI_DestroyMsgCmd(NICmdPtr cp) -{ - if (cp == NULL) - return 1; - MemFree(cp); - return 0; -} /* NI_DestroyMsgCmd() */ - - -static NICmdPtr -readCOMMAND(void) -{ - DataVal value; - NICmdPtr cmdp; - - cmdp = NI_MakeMsgCmd(); - if ((atp = AsnReadId(aip, amp, atp)) == NULL) /* seqno */ - goto CmdFail; - if (AsnReadVal(aip, atp, &value) < 0) - goto CmdFail; - cmdp->seqno = value.intvalue; - if ((atp = AsnReadId(aip, amp, atp)) == NULL) /* command */ - goto CmdFail; - if (AsnReadVal(aip, atp, &value) < 0) - goto CmdFail; - cmdp->code = (MsgCommand) value.intvalue; - if ((atp = AsnReadId(aip, amp, atp)) != MESSAGE_command) - goto CmdFail; - if (AsnReadVal(aip, atp, &value) < 0) - goto CmdFail; - return cmdp; - - CmdFail: - NI_DestroyMsgCmd(cmdp); - return NULL; -} /* readCOMMAND */ - - -static void -writeCOMMAND(NICmdPtr cmdp) -{ - DataVal value; - - AsnStartStruct(aip, MESSAGE_command); - value.intvalue = (Int4) cmdp->seqno; - AsnWrite(aip, MSG_CMD_seqno, &value); - value.intvalue = (Int4) cmdp->code; - AsnWrite(aip, MSG_CMD_command, &value); - AsnEndStruct(aip, MESSAGE_command); -} /* writeCOMMAND */ - - -/************************************ PRE-RESPONSE *********************************/ - -NLM_EXTERN NIPreRespPtr NI_MakeMsgPreResp(void) -{ - NIPreRespPtr cp; - - cp = (NIPreRespPtr) MemNew(sizeof(NIPreResp)); - cp->seqno = 0; - return cp; -} /* NI_MakeMsgPreResp() */ - - -NLM_EXTERN Int2 NI_DestroyMsgPreResp(NIPreRespPtr cp) -{ - if (cp == NULL) - return 1; - MemFree(cp); - return 0; -} /* NI_DestroyMsgPreResp() */ - - -static NIPreRespPtr -readPRE_RESPONSE(void) -{ - DataVal value; - NIPreRespPtr prp; - - prp = NI_MakeMsgPreResp(); - if ((atp = AsnReadId(aip, amp, atp)) == NULL) /* seqno */ - goto PrFail; - if (AsnReadVal(aip, atp, &value) < 0) - goto PrFail; - prp->seqno = value.intvalue; - if ((atp = AsnReadId(aip, amp, atp)) == NULL) /* server IP */ - goto PrFail; - if (AsnReadVal(aip, atp, &value) < 0) - goto PrFail; - prp->server_ip = value.intvalue; - if ((atp = AsnReadId(aip, amp, atp)) != MESSAGE_svc_pre_response) - goto PrFail; - if (AsnReadVal(aip, atp, &value) < 0) - goto PrFail; - return prp; - - PrFail: - NI_DestroyMsgPreResp(prp); - return NULL; -} /* readPRE_RESPONSE */ - - -static void -writePRE_RESPONSE(NIPreRespPtr prp) -{ - DataVal value; - - AsnStartStruct(aip, MESSAGE_svc_pre_response); - value.intvalue = (Int4) prp->seqno; - AsnWrite(aip, MSG_SVC_PRE_RESPONSE_seqno, &value); - value.intvalue = (Int4) prp->server_ip; - AsnWrite(aip, MSG_SVC_PRE_RESPONSE_server_ip, &value); - AsnEndStruct(aip, MESSAGE_svc_pre_response); -} /* writePRE_RESPONSE */ - -/************************************ ACCT ************************************/ - -NLM_EXTERN NIAcctPtr NI_MakeMsgAcct(void) -{ - NIAcctPtr ap; - - ap = (NIAcctPtr) MemNew(sizeof(NIAcct)); - ap->seqno = 0; - ap->jobname = NULL; - return ap; -} /* NI_MakeMsgAcct() */ - - -NLM_EXTERN Int2 NI_DestroyMsgAcct(NIAcctPtr ap) -{ - if (ap == NULL) - return 1; - if (ap->jobname != NULL) - MemFree(ap->jobname); - MemFree(ap); - return 0; -} /* NI_DestroyMsgAcct() */ - - -static NIAcctPtr -readACCT(void) -{ - DataVal value; - NIAcctPtr accp; - - accp = NI_MakeMsgAcct(); - if ((atp = AsnReadId(aip, amp, atp)) == NULL) /* seqno */ - goto AcctFail; - if (AsnReadVal(aip, atp, &value) < 0) - goto AcctFail; - accp->seqno = value.intvalue; - if ((atp = AsnReadId(aip, amp, atp)) == NULL) /* conid */ - goto AcctFail; - if (AsnReadVal(aip, atp, &value) < 0) - goto AcctFail; - accp->conid = value.intvalue; - if ((atp = AsnReadId(aip, amp, atp)) == NULL) /* jobname */ - goto AcctFail; - if (AsnReadVal(aip, atp, &value) < 0) - goto AcctFail; - accp->jobname = (CharPtr) value.ptrvalue; - if ((atp = AsnReadId(aip, amp, atp)) == NULL) /* usertime */ - goto AcctFail; - if (AsnReadVal(aip, atp, &value) < 0) - goto AcctFail; - accp->usertime = value.intvalue; - if ((atp = AsnReadId(aip, amp, atp)) == NULL) /* systemtime */ - goto AcctFail; - if (AsnReadVal(aip, atp, &value) < 0) - goto AcctFail; - accp->systemtime = value.intvalue; - if ((atp = AsnReadId(aip, amp, atp)) != MESSAGE_acct) - goto AcctFail; - if (AsnReadVal(aip, atp, &value) < 0) - goto AcctFail; - return accp; - - AcctFail: - NI_DestroyMsgAcct(accp); - return NULL; -} /* NIreadACCT */ - - -static void -writeACCT(NIAcctPtr accp) -{ - DataVal value; - - AsnStartStruct(aip, MESSAGE_acct); - value.intvalue = (Int4) accp->seqno; - AsnWrite(aip, MSG_ACCT_seqno, &value); - value.intvalue = (Int4) accp->conid; - AsnWrite(aip, MSG_ACCT_conid, &value); - value.ptrvalue = (Pointer) accp->jobname; - AsnWrite(aip, MSG_ACCT_jobname, &value); - value.intvalue = (Int4) accp->usertime; - AsnWrite(aip, MSG_ACCT_usertime, &value); - value.intvalue = (Int4) accp->systemtime; - AsnWrite(aip, MSG_ACCT_systemtime, &value); - AsnEndStruct(aip, MESSAGE_acct); -} /* NIwriteACCT */ - - -/************************************ CATALOG *********************************/ - -NLM_EXTERN NICatalogPtr NI_MakeMsgCatalog(void) -{ - NICatalogPtr cp; - - cp = (NICatalogPtr) MemNew(sizeof(NICatalog)); - cp->motd = NULL; - cp->toolsetL = NULL; - return cp; -} /* NI_MakeCatalog */ - - -NLM_EXTERN Int2 NI_DestroyMsgCatalog(NICatalogPtr cp) -{ - NodePtr np; - - - if (cp == NULL) - return 1; - if (cp->motd != NULL) - MemFree(cp->motd); - if ((np = cp->toolsetL) != NULL) { - do { - NI_DestroyToolset((NIToolsetPtr) np->elem); - np = ListDelete(np); - } while (np != NULL); - } - MemFree(cp); - return 0; -} /* NI_DestroyMsgCatalog */ - - -static NICatalogPtr -readCATALOG(void) -{ - DataVal value; - NICatalogPtr catp; - NIToolsetPtr tsp; - - catp = NI_MakeMsgCatalog(); - if ((atp = AsnReadId(aip, amp, atp)) == NULL) /* MSG_CATALOG_seqno */ - goto CatalogFail; - if (AsnReadVal(aip, atp, &value) < 0) - goto CatalogFail; - catp->seqno = value.intvalue; - if ((atp = AsnReadId(aip, amp, atp)) == NULL) - goto CatalogFail; - - if (atp == MSG_CATALOG_motd) { /* MSG_CATALOG_motd ? */ - if (AsnReadVal(aip, atp, &value) < 0) - goto CatalogFail; - catp->motd = (CharPtr) value.ptrvalue; - if ((atp = AsnReadId(aip, amp, atp)) == NULL) - goto CatalogFail; - } - - if (atp == MSG_CATALOG_toollists) { /* MSG_CATALOG_toollists ? */ - if (AsnReadVal(aip, atp, &value) < 0) - goto CatalogFail; - while ((atp = AsnReadId(aip, amp, atp)) == MSG_CATALOG_toollists_E) { - if (AsnReadVal(aip, atp, &value) < 0) - goto CatalogFail; - tsp = NI_MakeToolset(); - if (readToolset(tsp) < 0) - goto CatalogFail; - ListBreakRing(tsp->services); - ListBreakRing(tsp->resources); - catp->toolsetL = ListInsert((VoidPtr) tsp, catp->toolsetL); /* end of list */ - } - if (atp == NULL) - goto CatalogFail; - catp->toolsetL = catp->toolsetL->next; /* point to first */ - if (AsnReadVal(aip, atp, &value) < 0) /* MSG_CATALOG_toollists */ - goto CatalogFail; - ListBreakRing(catp->toolsetL); - if ((atp = AsnReadId(aip, amp, atp)) == NULL) - goto CatalogFail; - } - - if (atp != MESSAGE_catalog) - goto CatalogFail; - if (AsnReadVal(aip, atp, &value) < 0) - goto CatalogFail; - return catp; - - CatalogFail: - NI_DestroyMsgCatalog(catp); - return NULL; -} /* readCATALOG */ - - -static void -writeCATALOG(NICatalogPtr catp) -{ - DataVal value; - NodePtr np, lastnode; - - AsnStartStruct(aip, MESSAGE_catalog); - value.intvalue = (Int4) catp->seqno; - AsnWrite(aip, MSG_CATALOG_seqno, &value); - if (catp->motd != NULL) { - value.ptrvalue = (Pointer) catp->motd; - AsnWrite(aip, MSG_CATALOG_motd, &value); - } - - np = catp->toolsetL; - if (np != NULL) { - AsnStartStruct(aip, MSG_CATALOG_toollists); - lastnode = np->last; - while (np != NULL) { - AsnStartStruct(aip, MSG_CATALOG_toollists_E); - writeToolset((NIToolsetPtr) np->elem); - AsnEndStruct(aip, MSG_CATALOG_toollists_E); - if (np == lastnode) - break; - np = np->next; - } - AsnEndStruct(aip, MSG_CATALOG_toollists); - } - - AsnEndStruct(aip, MESSAGE_catalog); -} /* writeCatalog */ - - -/************************************ LOAD STATUS *********************************/ - -NLM_EXTERN NIStatusPtr NI_MakeMsgStatus(void) -{ - NIStatusPtr sp; - - sp = (NIStatusPtr) MemNew(sizeof(NIStatus)); - sp->load = 0.0; - sp->power = 0.0; - sp->lightThresh = 0.0; - sp->heavyThresh = 0.0; - sp->jobPenalty = 0.0; - return sp; -} /* NI_MakeStatus */ - - -NLM_EXTERN Int2 NI_DestroyMsgStatus(NIStatusPtr sp) -{ - NodePtr np; - - - if (sp == NULL) - return 1; - MemFree(sp); - return 0; -} /* NI_DestroyMsgStatus */ - -static NIStatusPtr -readSTATUS(void) -{ - DataVal value; - NIStatusPtr statusp; - - statusp = NI_MakeMsgStatus(); - if ((atp = AsnReadId(aip, amp, atp)) == NULL) /* MSG_LOAD_STATUS_load */ - goto StatusFail; - if (AsnReadVal(aip, atp, &value) < 0) - goto StatusFail; - statusp->load = value.realvalue; - - if ((atp = AsnReadId(aip, amp, atp)) == NULL) /* MSG_LOAD_STATUS_power */ - goto StatusFail; - if (AsnReadVal(aip, atp, &value) < 0) - goto StatusFail; - statusp->power = value.realvalue; - - if ((atp = AsnReadId(aip, amp, atp)) == NULL) /* MSG_LOAD_STATUS_light_thresh */ - goto StatusFail; - if (AsnReadVal(aip, atp, &value) < 0) - goto StatusFail; - statusp->lightThresh = value.realvalue; - - if ((atp = AsnReadId(aip, amp, atp)) == NULL) /* MSG_LOAD_STATUS_heavy_thresh */ - goto StatusFail; - if (AsnReadVal(aip, atp, &value) < 0) - goto StatusFail; - statusp->heavyThresh = value.realvalue; - - if ((atp = AsnReadId(aip, amp, atp)) == NULL) /* MSG_LOAD_STATUS_job_penalty */ - goto StatusFail; - if (AsnReadVal(aip, atp, &value) < 0) - goto StatusFail; - statusp->jobPenalty = value.realvalue; - - if ((atp = AsnReadId(aip, amp, atp)) == NULL) - goto StatusFail; - - if (atp != MESSAGE_load_status) - goto StatusFail; - if (AsnReadVal(aip, atp, &value) < 0) - goto StatusFail; - return statusp; - - StatusFail: - NI_DestroyMsgStatus(statusp); - return NULL; -} /* readSTATUS */ - - -static void -writeSTATUS(NIStatusPtr statp) -{ - DataVal value; - - AsnStartStruct(aip, MESSAGE_load_status); - - value.realvalue = (FloatLo) statp->load; - AsnWrite(aip, MSG_LOAD_STATUS_load, &value); - value.realvalue = (FloatLo) statp->power; - AsnWrite(aip, MSG_LOAD_STATUS_power, &value); - value.realvalue = (FloatLo) statp->lightThresh; - AsnWrite(aip, MSG_LOAD_STATUS_light_thresh, &value); - value.realvalue = (FloatLo) statp->heavyThresh; - AsnWrite(aip, MSG_LOAD_STATUS_heavy_thresh, &value); - value.realvalue = (FloatLo) statp->jobPenalty; - AsnWrite(aip, MSG_LOAD_STATUS_job_penalty, &value); - - AsnEndStruct(aip, MESSAGE_load_status); -} /* writeStatus */ - - -/************************************ REQUEST *********************************/ - -NLM_EXTERN ReqPtr NI_MakeRequest(void) -{ - ReqPtr rp; - - rp = (ReqPtr) MemNew(sizeof(Request)); - rp->clientAddr = NULL; - rp->clientPort = 0; - rp->service = NI_MakeService(); - rp->resourceL = NULL; - return(rp); -} /* NI_MakeRequest() */ - - -NLM_EXTERN Int2 NI_DestroyRequest(ReqPtr rp) -{ - if (rp == NULL) - return 1; - if (rp->clientAddr != NULL) - MemFree(rp->clientAddr); - if (rp->service != NULL) - NI_DestroyService(rp->service); - if (rp->resourceL != NULL) { /* destroy list of nodes and resources they point to */ - while (rp->resourceL != NULL) { - NI_DestroyResource((NIResPtr)rp->resourceL->elem); - rp->resourceL = ListDelete(rp->resourceL); - } - } - MemFree(rp); - return 0; -} /* NI_DestroyRequest() */ - - -static int -readRequest(ReqPtr reqp) -{ - DataVal value; - NIResPtr resp; - - if ((atp = AsnReadId(aip, amp, atp)) == NULL) - goto RequestFail; - if (atp == REQUEST_address) { /* REQUEST_address ? */ - if (AsnReadVal(aip, atp, &value) < 0) - goto RequestFail; - reqp->clientAddr = (CharPtr) value.ptrvalue; - if ((atp = AsnReadId(aip, amp, atp)) == NULL) - goto RequestFail; - } - if (atp == REQUEST_port) { /* REQUEST_port ? */ - if (AsnReadVal(aip, atp, &value) < 0) - goto RequestFail; - reqp->clientPort = (Uint2) value.intvalue; - if ((atp = AsnReadId(aip, amp, atp)) == NULL) - goto RequestFail; - } - if (AsnReadVal(aip, atp, &value) < 0) /* REQUEST_svcentry */ - goto RequestFail; - if (readService(reqp->service) < 0) - goto RequestFail; - - if ((atp = AsnReadId(aip, amp, atp)) == REQUEST_resentry) { - if (AsnReadVal(aip, atp, &value) < 0) - goto RequestFail; - - while ((atp = AsnReadId(aip, amp, atp)) == REQUEST_resentry_E) { - if (AsnReadVal(aip, atp, &value) < 0) - goto RequestFail; - resp = NI_MakeResource(); - if (readResource(resp) < 0) { - NI_DestroyResource(resp); - goto RequestFail; - } - reqp->resourceL = ListInsert((VoidPtr) resp, reqp->resourceL); /* end of list */ - } - if (atp == NULL) - goto RequestFail; - reqp->resourceL = reqp->resourceL->next; /* point to first */ - if (AsnReadVal(aip, atp, &value) < 0) /* REQUEST_resentry */ - goto RequestFail; - if ((atp = AsnReadId(aip, amp, atp)) == NULL) - goto RequestFail; - } - if (atp == NULL) - goto RequestFail; - - if (AsnReadVal(aip, atp, &value) < 0) - goto RequestFail; - return 0; - - RequestFail: - if (reqp->resourceL != NULL) { /* destroy list of nodes and resources they point to */ - while (reqp->resourceL != NULL) { - NI_DestroyResource((NIResPtr)reqp->resourceL->elem); - reqp->resourceL = ListDelete(reqp->resourceL); - } - } - return -1; -} /* readrequest */ - - -static void -writeRequest(ReqPtr reqp) -{ - DataVal value; - NodePtr np, lastnode; - - if (reqp->clientAddr != NULL) { - value.ptrvalue = (Pointer) reqp->clientAddr; - AsnWrite(aip, REQUEST_address, &value); - } - if (reqp->clientPort != 0) { - value.intvalue = (Int4) reqp->clientPort; - AsnWrite(aip, REQUEST_port, &value); - } - AsnStartStruct(aip, REQUEST_svcentry); - writeService(reqp->service); - AsnEndStruct(aip, REQUEST_svcentry); - - np = reqp->resourceL; - if (np != NULL) { - AsnStartStruct(aip, REQUEST_resentry); - lastnode = np->last; - while (np != NULL) { - AsnStartStruct(aip, REQUEST_resentry_E); - writeResource((NIResPtr) np->elem); - AsnEndStruct(aip, REQUEST_resentry_E); - if (np == lastnode) - break; - np = np->next; - } - AsnEndStruct(aip, REQUEST_resentry); - } -} /* writeRequest */ - - -/************************************ UID *************************************/ - -NLM_EXTERN NI_UidPtr NI_MakeUid(void) -{ - NI_UidPtr up; - - up = (NI_UidPtr) MemNew(sizeof(NI_Uid)); - up->username = NULL; - up->group = NULL; - up->domain = NULL; - return up; -} /* NI_MakeUid */ - - -NLM_EXTERN Int2 NI_DestroyUid(NI_UidPtr up) -{ - if (up == NULL) - return 1; - if (up->username != NULL) - MemFree(up->username); - if (up->group != NULL) - MemFree(up->group); - if (up->domain != NULL) - MemFree(up->domain); - MemFree(up); - return 0; -} /* NI_DestroyUid */ - - -static int -readUid(NI_UidPtr uidptr) -{ - DataVal value; - - if ((atp = AsnReadId(aip, amp, atp)) == NULL || atp != IDENTITY_username) /* username */ - goto UidFail; - if (AsnReadVal(aip, atp, &value) < 0) - goto UidFail; - uidptr->username = (CharPtr) value.ptrvalue; - - if ((atp = AsnReadId(aip, amp, atp)) == NULL) /* group ? */ - goto UidFail; - if (atp == IDENTITY_group) { - if (AsnReadVal(aip, atp, &value) < 0) - goto UidFail; - uidptr->group = (CharPtr) value.ptrvalue; - if ((atp = AsnReadId(aip, amp, atp)) == NULL) /* domain ? */ - goto UidFail; - } - if (atp == IDENTITY_domain) { - if (AsnReadVal(aip, atp, &value) < 0) - goto UidFail; - uidptr->domain = (CharPtr) value.ptrvalue; - if ((atp = AsnReadId(aip, amp, atp)) == NULL) - goto UidFail; - } - if (AsnReadVal(aip, atp, &value) < 0) - goto UidFail; - return 0; - - UidFail: - return -1; -} /* readUid */ - - -static void -writeUid(NI_UidPtr uidptr) -{ - DataVal value; - - value.ptrvalue = (Pointer) uidptr->username; - AsnWrite(aip, IDENTITY_username, &value); - - if (uidptr->group != NULL) { - value.ptrvalue = (Pointer) uidptr->group; - AsnWrite(aip, IDENTITY_group, &value); - } - if (uidptr->domain != NULL) { - value.ptrvalue = (Pointer) uidptr->domain; - AsnWrite(aip, IDENTITY_domain, &value); - } -} /* writeUid */ - - -/************************************ SERVICE *********************************/ - -NLM_EXTERN NISvcPtr NI_MakeService(void) -{ - NISvcPtr sp; - - sp = (NISvcPtr) MemNew(sizeof(NIService)); - sp->name = NULL; - sp->minVersion = 0; - sp->maxVersion = 0; - sp->id = 0; - sp->priority = 0; - sp->priorityTimeout = 0; - sp->priorityPenalty = 0; - sp->group = NULL; - sp->descrip = NULL; - sp->typeL = NULL; - sp->encryptionSupported = FALSE; - sp->trackingPeriod = 0; - sp->trackingCount = 0; - return sp; -} /* NI_MakeService() */ - - -NLM_EXTERN Int2 NI_DestroyService(NISvcPtr sp) -{ - if (sp == NULL) - return 1; - if (sp->name != NULL) - MemFree(sp->name); - if (sp->group != NULL) - MemFree(sp->group); - if (sp->descrip != NULL) - MemFree(sp->descrip); - if (sp->typeL != NULL) { /* destroy list of service types */ - ListStrDel(sp->typeL); - } - if (sp->subSetList != NULL) { - ListStrDel(sp->subSetList); - } - if (sp->superSetList != NULL) { - ListStrDel(sp->superSetList); - } - - MemFree(sp); - return 0; -} /* NI_DestroyService() */ - - -static int -readService(NISvcPtr svcptr) -{ - DataVal value; - CharPtr svctype; - - if ((atp = AsnReadId(aip, amp, atp)) == NULL) /* SVC_ENTRY_name */ - goto ServiceFail; - if (AsnReadVal(aip, atp, &value) < 0) - goto ServiceFail; - svcptr->name = (CharPtr) value.ptrvalue; - if ((atp = AsnReadId(aip, amp, atp)) == NULL) /* SVC_ENTRY_minvers */ - goto ServiceFail; - if (AsnReadVal(aip, atp, &value) < 0) - goto ServiceFail; - svcptr->minVersion = (Uint2) value.intvalue; - if ((atp = AsnReadId(aip, amp, atp)) == NULL) /* SVC_ENTRY_maxvers */ - goto ServiceFail; - if (AsnReadVal(aip, atp, &value) < 0) - goto ServiceFail; - svcptr->maxVersion = (Uint2) value.intvalue; - - if ((atp = AsnReadId(aip, amp, atp)) == NULL) - goto ServiceFail; - if (atp == SVC_ENTRY_id) { /* SVC_ENTRY_id ? */ - if (AsnReadVal(aip, atp, &value) < 0) - goto ServiceFail; - svcptr->id = (Uint2) value.intvalue; - if ((atp = AsnReadId(aip, amp, atp)) == NULL) - goto ServiceFail; - } - if (atp == SVC_ENTRY_priority) { /* SVC_ENTRY_priority ? */ - if (AsnReadVal(aip, atp, &value) < 0) - goto ServiceFail; - svcptr->priority = (Uint2) value.intvalue; - if ((atp = AsnReadId(aip, amp, atp)) == NULL) - goto ServiceFail; - } - if (atp == SVC_ENTRY_group) { /* SVC_ENTRY_group ? */ - if (AsnReadVal(aip, atp, &value) < 0) - goto ServiceFail; - svcptr->group = (CharPtr) value.ptrvalue; - if ((atp = AsnReadId(aip, amp, atp)) == NULL) - goto ServiceFail; - } - if (atp == SVC_ENTRY_description) { /* SVC_ENTRY_description ? */ - if (AsnReadVal(aip, atp, &value) < 0) - goto ServiceFail; - svcptr->descrip = (CharPtr) value.ptrvalue; - if ((atp = AsnReadId(aip, amp, atp)) == NULL) - goto ServiceFail; - } - if (atp == SVC_ENTRY_types) { - if (AsnReadVal(aip, atp, &value) < 0) - goto ServiceFail; - - /* read the list of service types */ - while ((atp = AsnReadId(aip, amp, atp)) == SVC_ENTRY_types_E) - { - if (AsnReadVal(aip, atp, &value) < 0) - goto ServiceFail; - svctype = value.ptrvalue; - svcptr->typeL = ListInsert((VoidPtr) svctype, svcptr->typeL); - } - if (atp == NULL) - goto ServiceFail; - svcptr->typeL = svcptr->typeL->next; /* point to first */ - if (AsnReadVal(aip, atp, &value) < 0) /* SVC_ENTRY_types */ - goto ServiceFail; - if ((atp = AsnReadId(aip, amp, atp)) == NULL) - goto ServiceFail; - } - - if (atp == SVC_ENTRY_priority_timeout) { - if (AsnReadVal(aip, atp, &value) < 0) - goto ServiceFail; - svcptr->priorityTimeout = (Uint2) value.intvalue; - if ((atp = AsnReadId(aip, amp, atp)) == NULL) - goto ServiceFail; - } - - if (atp == SVC_ENTRY_priority_penalty) { - if (AsnReadVal(aip, atp, &value) < 0) - goto ServiceFail; - svcptr->priorityPenalty = (Uint2) value.intvalue; - if ((atp = AsnReadId(aip, amp, atp)) == NULL) - goto ServiceFail; - } - - if (atp == SVC_ENTRY_encryption_supported) { - if (AsnReadVal(aip, atp, &value) < 0) - goto ServiceFail; - svcptr->encryptionSupported = value.boolvalue; - if ((atp = AsnReadId(aip, amp, atp)) == NULL) - goto ServiceFail; - } - - if (atp == SVC_ENTRY_tracking_period) { - if (AsnReadVal(aip, atp, &value) < 0) - goto ServiceFail; - svcptr->trackingPeriod = value.intvalue; - if ((atp = AsnReadId(aip, amp, atp)) == NULL) - goto ServiceFail; - } - - if (atp == SVC_ENTRY_tracking_count) { - if (AsnReadVal(aip, atp, &value) < 0) - goto ServiceFail; - svcptr->trackingCount = value.intvalue; - if ((atp = AsnReadId(aip, amp, atp)) == NULL) - goto ServiceFail; - } - - if (atp == NULL) - goto ServiceFail; - - if (AsnReadVal(aip, atp, &value) < 0) - goto ServiceFail; - return 0; - - ServiceFail: - return -1; -} /* readService */ - - -static void -writeService(NISvcPtr svcptr) -{ - DataVal value; - NodePtr np; - NodePtr lastnode; - - value.ptrvalue = (Pointer) svcptr->name; - AsnWrite(aip, SVC_ENTRY_name, &value); - value.intvalue = (Int4) svcptr->minVersion; - AsnWrite(aip, SVC_ENTRY_minvers, &value); - value.intvalue = (Int4) svcptr->maxVersion; - AsnWrite(aip, SVC_ENTRY_maxvers, &value); - - if (svcptr->id != 0) { - value.intvalue = (Int4) svcptr->id; - AsnWrite(aip, SVC_ENTRY_id, &value); - } - if (svcptr->priority != 0) { - value.intvalue = (Int4) svcptr->priority; - AsnWrite(aip, SVC_ENTRY_priority, &value); - } - if (svcptr->group != NULL) { - value.ptrvalue = (Pointer) svcptr->group; - AsnWrite(aip, SVC_ENTRY_group, &value); - } - if (svcptr->descrip != NULL) { - value.ptrvalue = (Pointer) svcptr->descrip; - AsnWrite(aip, SVC_ENTRY_description, &value); - } - - np = svcptr->typeL; - if (np != NULL) { - AsnStartStruct(aip, SVC_ENTRY_types); - lastnode = np->last; - while (np != NULL) { - value.ptrvalue = (Pointer) np->elem; - AsnWrite(aip, SVC_ENTRY_types_E, &value); - if (np == lastnode) - break; - np = np->next; - } - AsnEndStruct(aip, SVC_ENTRY_types); - } - - if (svcptr->priorityTimeout != 0) - { - value.intvalue = svcptr->priorityTimeout; - AsnWrite(aip, SVC_ENTRY_priority_timeout, &value); - } - - if (svcptr->priorityPenalty != 0) - { - value.intvalue = svcptr->priorityPenalty; - AsnWrite(aip, SVC_ENTRY_priority_penalty, &value); - } - - if (svcptr->encryptionSupported) - { - value.boolvalue = svcptr->encryptionSupported; - AsnWrite(aip, SVC_ENTRY_encryption_supported, &value); - } - - if (svcptr->trackingPeriod != 0) - { - value.intvalue = svcptr->trackingPeriod; - AsnWrite(aip, SVC_ENTRY_tracking_period, &value); - } - - if (svcptr->trackingCount != 0) - { - value.intvalue = svcptr->trackingCount; - AsnWrite(aip, SVC_ENTRY_tracking_count, &value); - } -} /* writeService */ - - -/************************************ RESOURCE ********************************/ - -NLM_EXTERN NIResPtr NI_MakeResource(void) -{ - NIResPtr rp; - - rp = (NIResPtr) MemNew(sizeof(NIResource)); - rp->name = NULL; - rp->type = NULL; - rp->minVersion = 0; - rp->maxVersion = 0; - rp->id = 0; - rp->group = NULL; - rp->descrip = NULL; - return rp; -} /* NI_MakeResource() */ - - -NLM_EXTERN Int2 NI_DestroyResource(NIResPtr rp) -{ - if (rp == NULL) - return 1; - if (rp->name != NULL) - MemFree(rp->name); - if (rp->type != NULL) - MemFree(rp->type); - if (rp->group != NULL) - MemFree(rp->group); - if (rp->descrip != NULL) - MemFree(rp->descrip); - MemFree(rp); - return 0; -} /* NI_DestroyResource */ - - -static int -readResource(NIResPtr resptr) -{ - DataVal value; - - if ((atp = AsnReadId(aip, amp, atp)) == NULL) /* RES_ENTRY_name */ - goto ResourceFail; - if (AsnReadVal(aip, atp, &value) < 0) - goto ResourceFail; - resptr->name = (CharPtr) value.ptrvalue; - if ((atp = AsnReadId(aip, amp, atp)) == NULL) /* RES_ENTRY_type */ - goto ResourceFail; - if (AsnReadVal(aip, atp, &value) < 0) - goto ResourceFail; - resptr->type = (CharPtr) value.ptrvalue; - if ((atp = AsnReadId(aip, amp, atp)) == NULL) /* RES_ENTRY_minvers */ - goto ResourceFail; - if (AsnReadVal(aip, atp, &value) < 0) - goto ResourceFail; - resptr->minVersion = (Uint2) value.intvalue; - if ((atp = AsnReadId(aip, amp, atp)) == NULL) /* RES_ENTRY_maxvers */ - goto ResourceFail; - if (AsnReadVal(aip, atp, &value) < 0) - goto ResourceFail; - resptr->maxVersion = (Uint2) value.intvalue; - - if ((atp = AsnReadId(aip, amp, atp)) == NULL) - goto ResourceFail; - if (atp == RES_ENTRY_id) { /* RES_ENTRY_id */ - if (AsnReadVal(aip, atp, &value) < 0) - goto ResourceFail; - resptr->id = (Uint2) value.intvalue; - if ((atp = AsnReadId(aip, amp, atp)) == NULL) - goto ResourceFail; - } - if (atp == RES_ENTRY_group) { /* RES_ENTRY_group */ - if (AsnReadVal(aip, atp, &value) < 0) - goto ResourceFail; - resptr->group = (CharPtr) value.ptrvalue; - if ((atp = AsnReadId(aip, amp, atp)) == NULL) - goto ResourceFail; - } - if (atp == RES_ENTRY_description) { /* RES_ENTRY_description */ - if (AsnReadVal(aip, atp, &value) < 0) - goto ResourceFail; - resptr->descrip = (CharPtr) value.ptrvalue; - if ((atp = AsnReadId(aip, amp, atp)) == NULL) - goto ResourceFail; - } - if (AsnReadVal(aip, atp, &value) < 0) - goto ResourceFail; - return 0; - - ResourceFail: - return -1; -} /* readResource */ - - -static void -writeResource(NIResPtr resptr) -{ - DataVal value; - - value.ptrvalue = (Pointer) resptr->name; - AsnWrite(aip, RES_ENTRY_name, &value); - value.ptrvalue = (Pointer) resptr->type; - AsnWrite(aip, RES_ENTRY_type, &value); - value.intvalue = (Int4) resptr->minVersion; - AsnWrite(aip, RES_ENTRY_minvers, &value); - value.intvalue = (Int4) resptr->maxVersion; - AsnWrite(aip, RES_ENTRY_maxvers, &value); - - if (resptr->id != 0) { - value.intvalue = (Int4) resptr->id; - AsnWrite(aip, RES_ENTRY_id, &value); - } - if (resptr->group != NULL) { - value.ptrvalue = (Pointer) resptr->group; - AsnWrite(aip, RES_ENTRY_group, &value); - } - if (resptr->descrip != NULL) { - value.ptrvalue = (Pointer) resptr->descrip; - AsnWrite(aip, RES_ENTRY_description, &value); - } -} /* writeResource */ - - -/************************************ REGION *********************************/ - -NLM_EXTERN NIRegionPtr NI_MakeRegion(void) -{ - NIRegionPtr rp; - - rp = (NIRegionPtr) MemNew(sizeof(NIRegion)); - rp->regionName = NULL; - rp->priorityDelta = 0; - return rp; -} /* NI_MakeRegion() */ - - -NLM_EXTERN Int2 NI_DestroyRegion(NIRegionPtr rp) -{ - if (rp == NULL) - return 1; - if (rp->regionName != NULL) - MemFree(rp->regionName); - - MemFree(rp); - return 0; -} /* NI_DestroyRegion() */ - - -static int -readRegion(NIRegionPtr regptr) -{ - DataVal value; - - if ((atp = AsnReadId(aip, amp, atp)) == NULL) /* REGION_DESCR_region_name */ - goto RegionFail; - if (AsnReadVal(aip, atp, &value) < 0) - goto RegionFail; - regptr->regionName = (CharPtr) value.ptrvalue; - if ((atp = AsnReadId(aip, amp, atp)) == NULL) /* REGION_DESCR_priority_delta */ - goto RegionFail; - if (AsnReadVal(aip, atp, &value) < 0) - goto RegionFail; - regptr->priorityDelta = (Uint2) value.intvalue; - - if ((atp = AsnReadId(aip, amp, atp)) == NULL) - goto RegionFail; - - if (AsnReadVal(aip, atp, &value) < 0) - goto RegionFail; - return 0; - - RegionFail: - return -1; -} /* readRegion */ - - -static void -writeRegion(NIRegionPtr regptr) -{ - DataVal value; - - value.ptrvalue = (Pointer) regptr->regionName; - AsnWrite(aip, REGION_DESCR_region_name, &value); - value.intvalue = (Int4) regptr->priorityDelta; - AsnWrite(aip, REGION_DESCR_priority_delta, &value); -} /* writeRegion */ - - - -/************************************ PubKey ********************************/ - -NLM_EXTERN NIPubKeyPtr NI_MakePubKey(void) -{ - NIPubKeyPtr pubkey; - - pubkey = (NIPubKeyPtr) MemNew(sizeof(NIPubKey)); - pubkey->bits = 0; - pubkey->modulus = NULL; - pubkey->exponent = NULL; - return pubkey; -} /* NI_MakePubKey */ - - -NLM_EXTERN Int2 NI_DestroyPubKey(NIPubKeyPtr pubkey) -{ - if (pubkey == NULL) - return 1; - if (pubkey->modulus != NULL) - BSFree (pubkey->modulus); - if (pubkey->exponent != NULL) - BSFree (pubkey->exponent); - MemFree(pubkey); - return 0; -} - - -static int -readPubKey(NIPubKeyPtr pubkey) -{ - DataVal value; - - if ((atp = AsnReadId(aip, amp, atp)) == NULL || atp != RSA_PUBKEY_bits) - goto PubKeyFail; - if (AsnReadVal(aip, atp, &value) < 0) - goto PubKeyFail; - pubkey->bits = (Int2) value.intvalue; - - /* modulus */ - if ((atp = AsnReadId(aip, amp, atp)) == NULL) - goto PubKeyFail; - if (AsnReadVal(aip, atp, &value) < 0) - goto PubKeyFail; - pubkey->modulus = (ByteStorePtr) value.ptrvalue; - - /* exponent */ - if ((atp = AsnReadId(aip, amp, atp)) == NULL) - goto PubKeyFail; - if (AsnReadVal(aip, atp, &value) < 0) - goto PubKeyFail; - pubkey->exponent = (ByteStorePtr) value.ptrvalue; - - /* end struct */ - if ((atp = AsnReadId(aip, amp, atp)) == NULL) - goto PubKeyFail; - if (AsnReadVal(aip, atp, &value) < 0) - goto PubKeyFail; - return 0; - - PubKeyFail: - return -1; -} - -static void -writePubKey(NIPubKeyPtr pubkey) -{ - DataVal value; - - if (pubkey == NULL) - return; - value.intvalue = pubkey->bits; - AsnWrite(aip, RSA_PUBKEY_bits, &value); - value.ptrvalue = pubkey->modulus; - AsnWrite(aip, RSA_PUBKEY_modulus, &value); - value.ptrvalue = pubkey->exponent; - AsnWrite(aip, RSA_PUBKEY_exponent, &value); -} - -NLM_EXTERN int NI_ReadPubKey(AsnIoPtr extaip, AsnTypePtr extatp, NIPubKeyPtr pubkey) -{ - AsnIoPtr savaip = aip; - AsnTypePtr savatp = atp; - DataVal value; - int retval = -1; - - if (! InitMsg()) - return 0; - aip = extaip; - atp = extatp; - if ((atp = AsnReadId(aip, amp, atp)) == RSA_PUBKEY) - { - if (AsnReadVal(aip, atp, &value) >= 0) - { - retval = readPubKey(pubkey); - } - } - aip = savaip; - atp = savatp; - return retval; -} - -NLM_EXTERN void NI_WritePubKey(AsnIoPtr extaip, AsnTypePtr extatp, NIPubKeyPtr pubkey) -{ - AsnIoPtr savaip = aip; - AsnTypePtr savatp = atp; - - if (! InitMsg()) - return; - aip = extaip; - atp = extatp; - if (extatp != NULL) - AsnStartStruct(extaip, extatp); - writePubKey(pubkey); - if (extatp != NULL) - AsnEndStruct(extaip, extatp); - aip = savaip; - atp = savatp; -} - - - -/************************************ DispInfo ********************************/ - -NLM_EXTERN NIDispInfoPtr NI_MakeDispInfo(void) -{ - NIDispInfoPtr dip; - - dip = (NIDispInfoPtr) MemNew(sizeof(NIDispInfo)); - dip->serialno = -1; - dip->isalternatelist = FALSE; - dip->numdispatchers = 0; - dip->displist = NULL; - dip->pubKey = NULL; - return dip; -} /* NI_MakeDispInfo */ - - -NLM_EXTERN Int2 NI_DestroyDispInfo(NIDispInfoPtr dip) -{ - Int2 num; - - if (dip == NULL) - return 1; - if (dip->displist != NULL) - { - for (num = 0; num < dip->numdispatchers; num++) - { - dip->displist[num] = (CharPtr) MemFree(dip->displist[num]); - } - MemFree(dip->displist); - } - if (dip->pubKey != NULL) - { - NI_DestroyPubKey(dip->pubKey); - } - MemFree(dip); - return 0; -} /* NI_DestroyDispInfo */ - - -static int -readDispInfo(NIDispInfoPtr dip) -{ - DataVal value; - int num; - - if ((atp = AsnReadId(aip, amp, atp)) == NULL || atp != DISPATCHER_INFO_serial_no) - goto DispInfoFail; - if (AsnReadVal(aip, atp, &value) < 0) - goto DispInfoFail; - dip->serialno = value.intvalue; - - if ((atp = AsnReadId(aip, amp, atp)) == NULL) /* is altlist?*/ - goto DispInfoFail; - if (atp == INFO_is_alternate_list) { - if (AsnReadVal(aip, atp, &value) < 0) - goto DispInfoFail; - dip->isalternatelist = value.boolvalue; - if ((atp = AsnReadId(aip, amp, atp)) == NULL) /* num disps ?*/ - goto DispInfoFail; - } - - if (atp == DISPATCHER_INFO_num_dispatchers) { - if (AsnReadVal(aip, atp, &value) < 0) - goto DispInfoFail; - dip->numdispatchers = (int) value.intvalue; - if ((atp = AsnReadId(aip, amp, atp)) == NULL) /* disps ? */ - goto DispInfoFail; - } - if (atp == DISPATCHER_INFO_disp_list) { - if (AsnReadVal(aip, atp, &value) < 0) - goto DispInfoFail; - dip->displist = (CharPtr PNTR) MemNew(sizeof(CharPtr) * dip->numdispatchers); - atp = AsnReadId(aip, amp, atp); - for (num = 0; num < dip->numdispatchers && - atp == DISPATCHER_INFO_disp_list_E; num++) - { - if (AsnReadVal(aip, atp, &value) <= 0) - goto DispInfoFail; - dip->displist[num] = (CharPtr) value.ptrvalue; - atp = AsnReadId(aip, amp, atp); - } - if (AsnReadVal(aip, atp, &value) <= 0) - goto DispInfoFail; - atp = AsnReadId(aip, amp, atp); - } - if (atp == DISPATCHER_INFO_pub_key) { - if (AsnReadVal(aip, atp, &value) < 0) - goto DispInfoFail; - dip->pubKey = NI_MakePubKey(); - if (readPubKey(dip->pubKey) < 0) - goto DispInfoFail; - if ((atp = AsnReadId(aip, amp, atp)) == NULL) - goto DispInfoFail; - } - - if (AsnReadVal(aip, atp, &value) < 0) - goto DispInfoFail; - return 0; - - DispInfoFail: - return -1; -} /* readDispInfo */ - - -static void -writeDispInfo(NIDispInfoPtr dip) -{ - DataVal value; - int num; - - if (dip == NULL) - return; - value.intvalue = dip->serialno; - AsnWrite(aip, DISPATCHER_INFO_serial_no, &value); - value.boolvalue = dip->isalternatelist; - AsnWrite(aip, INFO_is_alternate_list, &value); - value.intvalue = dip->numdispatchers; - AsnWrite(aip, DISPATCHER_INFO_num_dispatchers, &value); - if (dip->displist != NULL) { - AsnStartStruct (aip, DISPATCHER_INFO_disp_list); - for (num = 0; num < dip->numdispatchers; num++) { - value.ptrvalue = dip->displist[num]; - AsnWrite (aip, DISPATCHER_INFO_disp_list_E, &value); - } - AsnEndStruct (aip, DISPATCHER_INFO_disp_list); - } - if (dip->pubKey != NULL) { - AsnStartStruct (aip, DISPATCHER_INFO_pub_key); - writePubKey (dip->pubKey); - AsnEndStruct (aip, DISPATCHER_INFO_pub_key); - } -} /* writeDispInfo */ - -NLM_EXTERN int NI_ReadDispInfo(AsnIoPtr extaip, AsnTypePtr extatp, NIDispInfoPtr dip) -{ - AsnIoPtr savaip = aip; - AsnTypePtr savatp = atp; - DataVal value; - int retval = -1; - - if (! InitMsg()) - return 0; - aip = extaip; - atp = extatp; - if ((atp = AsnReadId(aip, amp, atp)) == DISPATCHER_INFO) - { - if (AsnReadVal(aip, atp, &value) >= 0) - { - retval = readDispInfo(dip); - } - } - aip = savaip; - atp = savatp; - return retval; -} - -NLM_EXTERN void NI_WriteDispInfo(AsnIoPtr extaip, AsnTypePtr extatp, NIDispInfoPtr dip) -{ - AsnIoPtr savaip = aip; - AsnTypePtr savatp = atp; - - if (! InitMsg()) - return; - aip = extaip; - atp = extatp; - if (extatp != NULL) - AsnStartStruct(extaip, extatp); - writeDispInfo(dip); - if (extatp != NULL) - AsnEndStruct(extaip, extatp); - aip = savaip; - atp = savatp; -} - - -/************************************ TOOLSET *********************************/ - -NLM_EXTERN NIToolsetPtr NI_MakeToolset(void) -{ - NIToolsetPtr tsp; - - tsp = (NIToolsetPtr) MemNew(sizeof(NIToolset)); - tsp->host = NULL; - tsp->motd = NULL; - tsp->services = NULL; - tsp->resources = NULL; - tsp->regions = NULL; - return tsp; -} /* NI_MakeToolset */ - - -NLM_EXTERN Int2 NI_DestroyToolset(NIToolsetPtr tsp) -{ - NodePtr np; - - if (tsp == NULL) - return 1; - if (tsp->host != NULL) - MemFree(tsp->host); - if (tsp->motd != NULL) - MemFree(tsp->motd); - - if ((np = tsp->services) != NULL) { - do { - NI_DestroyService((NISvcPtr)np->elem); - np = ListDelete(np); - } while (np != NULL); - } - - if ((np = tsp->resources) != NULL) { - do { - NI_DestroyResource((NIResPtr)np->elem); - np = ListDelete(np); - } while (np != NULL); - } - - if ((np = tsp->regions) != NULL) { - do { - NI_DestroyRegion((NIRegionPtr)np->elem); - np = ListDelete(np); - } while (np != NULL); - } - - MemFree(tsp); - return 0; -} /* NI_DestroyToolset */ - - -NLM_EXTERN NIToolsetPtr NI_GetCatToolset(NIToolsetPtr tsp) -{ - NIToolsetPtr dtsp; - NISvcPtr svcp, tsvcp; - NIResPtr resp, tresp; - NodePtr np; - - dtsp = NI_MakeToolset(); - - if (tsp->host != NULL) - dtsp->host = StringSave(tsp->host); - if (tsp->motd != NULL) - dtsp->motd = StringSave(tsp->motd); - - if (tsp->services != NULL) { - np = tsp->services->last; - do { - np = ListGetNext(np); - svcp = (NISvcPtr) np->elem; - /* note that services which are a "subset" of another listed */ - /* service are filtered-out here */ - if (svcp != NULL && svcp->subSetList == NULL) { - tsvcp = NI_MakeService(); - if (svcp->name != NULL) - tsvcp->name = StringSave(svcp->name); - - if (svcp->typeL != NULL) - { /* make a copy of the list */ - tsvcp->typeL = ListStrCopy(svcp->typeL); - } - - tsvcp->minVersion = svcp->minVersion; - tsvcp->maxVersion = svcp->maxVersion; - tsvcp->priority = svcp->priority; - tsvcp->id = 0; /* these two not sent in catalog */ - tsvcp->group = NULL; - if (svcp->descrip != NULL) - tsvcp->descrip = StringSave(svcp->descrip); - dtsp->services = ListInsert((VoidPtr) tsvcp, dtsp->services); - } - } while (np != tsp->services->last); - if (dtsp->services != NULL) - { - dtsp->services = dtsp->services->next; /* point to first */ - } - } - - if (tsp->resources != NULL) { - np = tsp->resources->last; - do { - np = ListGetNext(np); - resp = (NIResPtr) np->elem; - if (resp != NULL) { - tresp = NI_MakeResource(); - if (resp->name != NULL) - tresp->name = StringSave(resp->name); - if (resp->type != NULL) - tresp->type = StringSave(resp->type); - tresp->minVersion = resp->minVersion; - tresp->maxVersion = resp->maxVersion; - tresp->id = 0; /* these two not sent in catalog */ - tresp->group = NULL; - if (resp->descrip != NULL) - tresp->descrip = StringSave(resp->descrip); - dtsp->resources = ListInsert((VoidPtr) tresp, dtsp->resources); - } - } while (np != tsp->resources->last); - if (dtsp->resources != NULL) - { - dtsp->resources = dtsp->resources->next; /* point to first */ - } - } - - return dtsp; -} /* NI_GetCatToolset */ - - -static int -readToolset(NIToolsetPtr tsp) -{ - DataVal value; - NISvcPtr svcp; - NIResPtr resp; - NIRegionPtr reg; - - if ((atp = AsnReadId(aip, amp, atp)) == NULL) /* TOOLSET_host */ - goto ToolsetFail; - if (AsnReadVal(aip, atp, &value) < 0) - goto ToolsetFail; - tsp->host = (CharPtr) value.ptrvalue; - if ((atp = AsnReadId(aip, amp, atp)) == NULL) - goto ToolsetFail; - - if (atp == TOOLSET_motd) { /* TOOLSET_motd ? */ - if (AsnReadVal(aip, atp, &value) < 0) - goto ToolsetFail; - tsp->motd = (CharPtr) value.ptrvalue; - if ((atp = AsnReadId(aip, amp, atp)) == NULL) - goto ToolsetFail; - } - if (atp == TOOLSET_services) { - if (AsnReadVal(aip, atp, &value) < 0) - goto ToolsetFail; - while ((atp = AsnReadId(aip, amp, atp)) == TOOLSET_services_E) { - if (AsnReadVal(aip, atp, &value) < 0) - goto ToolsetFail; - svcp = NI_MakeService(); - readService(svcp); - tsp->services = ListInsert((VoidPtr) svcp, tsp->services); - } - if (atp == NULL) - goto ToolsetFail; - tsp->services = tsp->services->next; /* point to first */ - if (AsnReadVal(aip, atp, &value) < 0) - goto ToolsetFail; - if ((atp = AsnReadId(aip, amp, atp)) == NULL) - goto ToolsetFail; - } - if (atp == TOOLSET_resources) { - if (AsnReadVal(aip, atp, &value) < 0) - goto ToolsetFail; - while ((atp = AsnReadId(aip, amp, atp)) == TOOLSET_resources_E) { - if (AsnReadVal(aip, atp, &value) < 0) - goto ToolsetFail; - resp = NI_MakeResource(); - readResource(resp); - tsp->resources = ListInsert((VoidPtr) resp, tsp->resources); - } - if (atp == NULL) - goto ToolsetFail; - tsp->resources = tsp->resources->next; /* point to first */ - if (AsnReadVal(aip, atp, &value) < 0) - goto ToolsetFail; - if ((atp = AsnReadId(aip, amp, atp)) == NULL) - goto ToolsetFail; - } - if (atp == TOOLSET_regions) { - if (AsnReadVal(aip, atp, &value) < 0) - goto ToolsetFail; - while ((atp = AsnReadId(aip, amp, atp)) == TOOLSET_regions_E) { - if (AsnReadVal(aip, atp, &value) < 0) - goto ToolsetFail; - reg = NI_MakeRegion(); - readRegion(reg); - tsp->regions = ListInsert((VoidPtr) reg, tsp->regions); - } - if (atp == NULL) - goto ToolsetFail; - tsp->regions = tsp->regions->next; /* point to first */ - if (AsnReadVal(aip, atp, &value) < 0) - goto ToolsetFail; - if ((atp = AsnReadId(aip, amp, atp)) == NULL) - goto ToolsetFail; - } - - if (AsnReadVal(aip, atp, &value) < 0) - goto ToolsetFail; - return 0; - - ToolsetFail: - return -1; -} /* readToolset */ - -static void -writeToolset(NIToolsetPtr tsp) -{ - DataVal value; - NodePtr np, lastnode; - - if (tsp->host != NULL) - value.ptrvalue = (Pointer) tsp->host; - else - value.ptrvalue = (Pointer) StringSave("N/A"); - AsnWrite(aip, TOOLSET_host, &value); - - if (tsp->motd != NULL) { - value.ptrvalue = (Pointer) tsp->motd; - AsnWrite(aip, TOOLSET_motd, &value); - } - np = tsp->services; - if (np != NULL) { - AsnStartStruct(aip, TOOLSET_services); - lastnode = np->last; - while (np != NULL) { - AsnStartStruct(aip, TOOLSET_services_E); - writeService((NISvcPtr) np->elem); - AsnEndStruct(aip, TOOLSET_services_E); - if (np == lastnode) - break; - np = np->next; - } - AsnEndStruct(aip, TOOLSET_services); - } - np = tsp->resources; - if (np != NULL) { - AsnStartStruct(aip, TOOLSET_resources); - lastnode = np->last; - while (np != NULL) { - AsnStartStruct(aip, TOOLSET_resources_E); - writeResource((NIResPtr) np->elem); - AsnEndStruct(aip, TOOLSET_resources_E); - if (np == lastnode) - break; - np = np->next; - } - AsnEndStruct(aip, TOOLSET_resources); - } - np = tsp->regions; - if (np != NULL) { - AsnStartStruct(aip, TOOLSET_regions); - lastnode = np->last; - while (np != NULL) { - AsnStartStruct(aip, TOOLSET_regions_E); - writeRegion((NIRegionPtr) np->elem); - AsnEndStruct(aip, TOOLSET_regions_E); - if (np == lastnode) - break; - np = np->next; - } - AsnEndStruct(aip, TOOLSET_regions); - } -} /* writeToolset */ - - -/******************************************************************************/ -/* */ -/* Message and Handle Functions */ -/* */ -/******************************************************************************/ - -/* - * Purpose: "High level" message read for ASN.1 messages - * - * Parameters: - * hp "Message handle", describing parameters of input environment - * unblocked Flag indicating whether input should "block" if unable - * to read a complete message - * - * Returns: - * NULL, if unable to read a message ... if hp->have_blocked is - * set, then this reflects an inability to read a complete - * message at this time - * a pointer to the message which was just read, otherwise - * - * - * Description: - * Try to read a message from the socket specified by the hp - * data structure. A message must begin with the "MESSAGE" - * identifier, followed by the type of the message. Once the - * type of the message has been determined, the remainder of - * the message is read using the corresponding readXXX() - * function. - * - * Matters are more complex when the "unblocked" parameter - * is TRUE. In this case, if a failure occurs on a message read, - * an attempt is made to see whether any bytes of data were - * read from the socket upon this invocation. If so, the - * have_blocked flag is set for the caller, and AsnIoReset() is - * called to deal with a future attempt to read from this socket - * when more data becomes available. - * - * Note: - * This is the highest level read function which should be - * called by an application program. All the other "static" - * functions called here should not be called directly by an - * application program. - * - * The ASN.1 error handling is performing using the setjmp()/ - * longjmp() paradigm, where a function can return to an earlier - * context if an error occurs. - * - * Currently, it is not possible to distinguish - * between an ASN.1 format error, and an ASN failure due to - * inability to read the requested quantity of data. For this - * reason, if the "unblocked" option is selected, it will take - * hp->r_timeout seconds to detect either of these - * conditions. In the best of all possible worlds, it would - * be possible to distinguish between "data not YET available" - * and "invalid data" conditions. - */ - -NLM_EXTERN NIMsgPtr MsgRead(MHandPtr hp, Boolean unblocked) -{ - DataVal value; - NIMsgPtr mp = NULL; - int start_byte_count = hp->num_queued_bytes; - NodePtr timer = NULL; - NodePtr localTimer = NULL; - - ni_errno = NIE_MSGREAD; - - hp->unblocked_mode = unblocked; - hp->have_blocked = FALSE; - - /* for unblocked I/O, set a "hangup" timeout which can be detected at */ - /* at later time, if we are unable to read a complete or valid message */ - if (unblocked && hp->readTimeoutHook != NULL) - timer = NI_SetTimer(time(NULL) + hp->r_timeout, hp->readTimeoutHook, - (VoidPtr) hp); - hp->readTimer = timer; - - if (hp->longjump == TRUE) { - if (SetJump(ni_env)) { - /* return from LongJump (error handler) */ - goto MsgReadFail; - } - } - - StringCpy(ni_errtext, "AsnReadId or AsnReadVal returned bad value"); - aip = hp->raip; - atp = MESSAGE; - if ((atp = AsnReadId(aip, amp, atp)) != MESSAGE) /* Must read a MESSAGE */ - goto MsgReadFail; /* don't have to read val as Null return is always fatal to channel */ - if (AsnReadVal(aip, atp, &value) < 0) - goto MsgReadFail; - - if ((atp = AsnReadId(aip, amp, atp)) == NULL) /* type of message */ - goto MsgReadFail; - if (AsnReadVal(aip, atp, &value) < 0) - goto MsgReadFail; - - mp = (NIMsgPtr) MemNew(sizeof(NIMessage)); - mp->conid = hp->conid; - mp->type = NI_UNKNOWN; - - if (atp == MESSAGE_ack) { - if ((mp->msun.ack = readACK()) != NULL) - mp->type = NI_ACK; - goto gotmessage; - } - - if (atp == MESSAGE_nack) { - if ((mp->msun.nack = readNACK()) != NULL) - mp->type = NI_NACK; - goto gotmessage; - } - - if (atp == MESSAGE_login) { - if ((mp->msun.login = readLOGIN()) != NULL) - mp->type = NI_LOGIN; - goto gotmessage; - } - - if (atp == MESSAGE_svc_list) { - if ((mp->msun.svclist = readSVC_LIST()) != NULL) - mp->type = NI_SVC_LIST; - goto gotmessage; - } - - if (atp == MESSAGE_svc_request) { - if ((mp->msun.svcreq = readSVC_REQUEST()) != NULL) - mp->type = NI_SVC_REQUEST; - goto gotmessage; - } - - if (atp == MESSAGE_svc_response) { - if ((mp->msun.svcresp = readSVC_RESPONSE()) != NULL) - mp->type = NI_SVC_RESPONSE; - goto gotmessage; - } - - if (atp == MESSAGE_command) { - if ((mp->msun.command = readCOMMAND()) != NULL) - mp->type = NI_COMMAND; - goto gotmessage; - } - - if (atp == MESSAGE_svc_pre_response) { - if ((mp->msun.preresp = readPRE_RESPONSE()) != NULL) - mp->type = NI_SVC_PRE_RESPONSE; - goto gotmessage; - } - - if (atp == MESSAGE_acct) { - if ((mp->msun.acct = readACCT()) != NULL) - mp->type = NI_ACCT; - goto gotmessage; - } - - if (atp == MESSAGE_catalog) { - if ((mp->msun.catalog = readCATALOG()) != NULL) - mp->type = NI_CATALOG; - goto gotmessage; - } - - if (atp == MESSAGE_load_status) { - if ((mp->msun.status = readSTATUS()) != NULL) - mp->type = NI_STATUS; - goto gotmessage; - } - - gotmessage: - if (mp->type == NI_UNKNOWN) { - StringCpy(ni_errtext, "unknown msg type"); - goto MsgReadFail; - } - else { /* got good stuff */ - MsgFreeSavedData(hp); /* free associated data */ - hp->unblocked_mode = FALSE; - hp->have_blocked = FALSE; - localTimer = hp->readTimer; - hp->readTimer = NULL; - NI_CancelTimer(localTimer); - return mp; - } - - MsgReadFail: - if (mp != NULL) - MsgDestroy(mp); - - /* if ( things didn't go well, but there was more data read from the */ - /* socket ) then */ - if (start_byte_count < hp->num_queued_bytes) - hp->have_blocked = TRUE; /* set things up to try again */ - - if (hp->have_blocked) - { /* failed due to data unavailability */ - hp->cur_index = 0; /* reset queued read pointer */ - AsnIoReset (aip); /* reset ASN input stream */ - /* caller should try again later, based upon detecting hp->have_blocked */ - } - hp->unblocked_mode = FALSE; - return NULL; -} /* MsgRead */ - - - -/* - * Purpose: "High level" message write for ASN.1 messages - * - * Parameters: - * hp "Message handle", describing parameters of I/O environment - * mp Message to be written - * noDestroy If set, refrain from destroying the message - * - * Returns: - * -1, if unable to write the message - * 0, otherwise - * - * - * Description: - * Try to write a message from the socket specified by the hp - * data structure. The writing of the message is performed - * using the writeXXX() function which corresponds to the type - * of the message to be written. - */ - -NLM_EXTERN Int2 MsgWrite(MHandPtr hp, NIMsgPtr mp, Boolean noDestroy) -{ - DataVal value; - - ni_errno = NIE_MSGWRITE; - - if (hp->longjump == TRUE) { - if (SetJump(ni_env)) { - /* return from LongJump (error handler) */ - if (! noDestroy) - MsgDestroy(mp); /* failing, so destroy it */ - return -1; - } - } - - aip = hp->waip; - AsnWrite(aip, MESSAGE, &value); - - switch (mp->type) { - case NI_ACK: - writeACK(mp->msun.ack); - break; - - case NI_NACK: - writeNACK(mp->msun.nack); - break; - - case NI_LOGIN: - writeLOGIN(mp->msun.login); - break; - - case NI_SVC_LIST: - writeSVC_LIST(mp->msun.svclist); - break; - - case NI_SVC_REQUEST: - writeSVC_REQUEST(mp->msun.svcreq); - break; - - case NI_SVC_RESPONSE: - writeSVC_RESPONSE(mp->msun.svcresp); - break; - - case NI_COMMAND: - writeCOMMAND(mp->msun.command); - break; - - case NI_SVC_PRE_RESPONSE: - writePRE_RESPONSE(mp->msun.preresp); - break; - - case NI_ACCT: - writeACCT(mp->msun.acct); - break; - - case NI_CATALOG: - writeCATALOG(mp->msun.catalog); - break; - - case NI_STATUS: - writeSTATUS(mp->msun.status); - break; - - default: - ni_errno = NIE_MSGUNK; - StringCpy(ni_errtext, "unable to write msg"); - if (! noDestroy) - MsgDestroy(mp); - return -1; - } - - AsnIoFlush(aip); - if (! noDestroy) - MsgDestroy(mp); - return 0; -} /* MsgWrite */ - - - -/* - * Purpose: Build a message of the specified type, populating it with - * a pointer to the actual message data, and the connection ID. - * - * Parameters: - * type The type of message to be built - * conn Connection ID associated with this session - * stp Pointer to the actual message data - * - * Returns: - * NULL, if unable to allocate memory for the message, or if - * the specified message type is invalid - * a pointer to the newly-build message, otherwise - * - * - * Description: - * Create a message data structure, and populate it as indicated. - */ - -NLM_EXTERN NIMsgPtr MsgBuild(MsgType type, Uint4 conn, VoidPtr stp) -{ - NIMsgPtr mp; - - if (! InitMsg()) - return NULL; - mp = (NIMsgPtr) MemNew(sizeof(NIMessage)); - if (mp == NULL) - return NULL; - mp->type = type; - mp->conid = conn; - - switch (mp->type) { - case NI_ACK: - mp->msun.ack = (NIAckPtr) stp; - break; - - case NI_NACK: - mp->msun.nack = (NINackPtr) stp; - break; - - case NI_LOGIN: - mp->msun.login = (NILoginPtr) stp; - break; - - case NI_SVC_LIST: - mp->msun.svclist = (NISvcListPtr) stp; - break; - - case NI_SVC_REQUEST: - mp->msun.svcreq = (NISvcReqPtr) stp; - break; - - case NI_SVC_RESPONSE: - mp->msun.svcresp = (NISvcRespPtr) stp; - break; - - case NI_COMMAND: - mp->msun.command = (NICmdPtr) stp; - break; - - case NI_SVC_PRE_RESPONSE: - mp->msun.preresp = (NIPreRespPtr) stp; - break; - - case NI_ACCT: - mp->msun.acct = (NIAcctPtr) stp; - break; - - case NI_CATALOG: - mp->msun.catalog = (NICatalogPtr) stp; - break; - - case NI_STATUS: - mp->msun.status = (NIStatusPtr) stp; - break; - - default: - ni_errno = NIE_MSGUNK; - StringCpy(ni_errtext, "unable to build"); - MemFree (mp); - return NULL; - } - return mp; -} /* MsgBuild */ - - - -/* - * Purpose: Destroy the specified message - * - * Parameters: - * mp A pointer to the message structure to be destroyed - * - * Returns: - * -1, if the specified pointer is NULL, or if the message - * is of an unknown type - * 0, otherwise - * - * - * Description: - * Destroy the specified message, using the appropriate message - * destructor function. - */ - -NLM_EXTERN Int2 MsgDestroy(NIMsgPtr mp) -{ - if (mp == NULL) - return -1; - - switch (mp->type) { - case NI_ACK: - NI_DestroyMsgAck(mp->msun.ack); - break; - - case NI_NACK: - NI_DestroyMsgNack(mp->msun.nack); - break; - - case NI_LOGIN: - NI_DestroyMsgLogin(mp->msun.login); - break; - - case NI_SVC_LIST: - NI_DestroyMsgSvclist(mp->msun.svclist); - break; - - case NI_SVC_REQUEST: - NI_DestroyMsgSvcreq(mp->msun.svcreq); - break; - - case NI_SVC_RESPONSE: - NI_DestroyMsgSvcresp(mp->msun.svcresp); - break; - - case NI_COMMAND: - NI_DestroyMsgCmd(mp->msun.command); - break; - - case NI_SVC_PRE_RESPONSE: - NI_DestroyMsgPreResp(mp->msun.preresp); - break; - - case NI_ACCT: - NI_DestroyMsgAcct(mp->msun.acct); - break; - - case NI_CATALOG: - NI_DestroyMsgCatalog(mp->msun.catalog); - break; - - case NI_STATUS: - NI_DestroyMsgStatus(mp->msun.status); - break; - - default: - ni_errno = NIE_MSGUNK; - StringCpy(ni_errtext, "unable to destroy msg"); - MemFree(mp); - return -1; - } - - MemFree(mp); - return 0; -} /* MsgDestroy */ - - - -/* - * Purpose: Create a message handle - * - * Returns: - * NULL, if unable to allocate the required memory, open - * a socket, set the socket to non-blocking mode, or - * initialize the ASN.1 I/O streams successfully - * a pointer to the new message handle, otherwise - * - * - * Description: - * Create a "message" handle, which is the basic unit of message - * I/O. A message handle includes, among other things, a logical - * connection ID, a socket used for both input and output, ASN.1 - * I/O stream pointers, and a queue of input data which has - * already been read from the socket, but has not yet been - * processed successfully using ASN.1. - * - * Note: - * This is currently the only place where conid is incremented, - * and therefore, the only place where conid is written to the - * Conid file. - */ - -#ifdef OS_MAC - /* workaround for weaknesses of Mac OpenTransport */ - Boolean UsingOpenTransport(void); -#endif - -NLM_EXTERN MHandPtr MsgMakeHandle(Boolean createSocket) -{ - MHandPtr mh; - Boolean dontset = FALSE; - - if (! InitMsg()) { - StringCpy(ni_errtext, "Network services ASN.1 initialization failed"); - ni_errno = NIE_ASN1SPECFAIL; - return NULL; - } - if ((mh = (MHandPtr) MemNew(sizeof(MHandle))) == NULL) { - StringCpy(ni_errtext, "unable to allocate new memory"); - return NULL; - } - mh->hostname = NULL; - mh->conid = conid++; - WriteConFile(conid); - mh->seqno = 1; - mh->sok = -1; - - if (createSocket) { - if ((mh->sok = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) == - INVALID_SOCKET) { -#ifdef NETP_INET_NEWT - SOCK_ERRNO = ABS(mh->sok); -#endif - StringCpy(ni_errtext, strerror(SOCK_INDEX_ERRNO)); - MemFree(mh); - return NULL; - } - LOG_SOCKET(mh->sok, TRUE); - if (NI_SETNONBLOCKING(mh->sok) == -1) { - StringCpy(ni_errtext, strerror(SOCK_INDEX_ERRNO)); - MemFree(mh); - return NULL; - } - } - mh->r_timeout = NI_READ_TIMEOUT; - mh->w_timeout = NI_WRITE_TIMEOUT; - mh->state = NI_CREATED; - mh->extra_proc_info = NULL; - mh->read_filter = NULL; - mh->write_filter = NULL; - mh->write_filt_pass_thru = TRUE; - mh->read_filt_pass_thru = TRUE; - mh->readTimeoutHook = NULL; - mh->writeTimeoutHook = NULL; - mh->readTimer = NULL; - mh->writeTimer = NULL; - mh->encryption = NULL; - mh->isBrokered = FALSE; - mh->brokeredPort = 0; - mh->peer = 0; - if ((mh->raip = AsnIoNew((ASNIO_BIN | ASNIO_IN), (FILE *) NULL, (Pointer) mh, NI_AsnRead, NI_AsnWrite)) == NULL) { - LOG_SOCKET(mh->sok, FALSE); - NI_CLOSESOCKET(mh->sok); - StringCpy(ni_errtext, "unable to allocate new AsnIoPtr (raip)"); - MemFree(mh); - return NULL; - } - if ((mh->waip = AsnIoNew((ASNIO_BIN | ASNIO_OUT), (FILE *) NULL, (Pointer) mh, NI_AsnRead, NI_AsnWrite)) == NULL) { - AsnIoClose(mh->raip); - LOG_SOCKET(mh->sok, FALSE); - NI_CLOSESOCKET(mh->sok); - StringCpy(ni_errtext, "unable to allocate new AsnIoPtr (waip)"); - MemFree(mh); - return NULL; - } -#ifdef OS_MAC - /* workaround for weaknesses of Mac OpenTransport */ - if (UsingOpenTransport()) - { - AsnIoSetBufsize(mh->waip, NI_BLOCKSIZE / 2); - dontset = TRUE; - } -#endif - if (! dontset) - { - AsnIoSetBufsize(mh->waip, NI_BLOCKSIZE); - } - mh->longjump = FALSE; - mh->access_time = time(NULL); - mh->have_blocked = FALSE; - mh->num_queued_bytes = 0; - mh->cur_index = 0; - mh->queued_data_list = NULL; - mh->unblocked_mode = FALSE; - return mh; -} /* MsgMakeHandle */ - - - -/* - * Purpose: Destroy the specified message handle - * - * Parameters: - * hp A pointer to the message handle to be destroyed - * - * Returns: - * -1, if the specified pointer is NULL - * 0, otherwise - * - * - * Description: - * Destroy the specified message handle, close its socket, - * close the ASN streams, and free any associated queued data. - */ - -NLM_EXTERN Int2 MsgDestroyHandle(MHandPtr hp) -{ - if (hp == NULL) - return -1; - if (hp->sok != INVALID_SOCKET) - { - LOG_SOCKET(hp->sok, FALSE); - NI_CLOSESOCKET(hp->sok); - } - if (hp->hostname != NULL) - MemFree(hp->hostname); - NI_CancelTimer(hp->readTimer); - NI_CancelTimer(hp->writeTimer); - /* avoid a rare, unexplained condition by zapping the file descriptor */ - if (hp->raip != NULL && hp->raip->fp == (FILE *) -1) - hp->raip->fp = NULL; - if (hp->waip != NULL && hp->waip->fp == (FILE *) -1) - hp->waip->fp = NULL; - AsnIoClose(hp->raip); - AsnIoClose(hp->waip); - if (hp->encryption != NULL) - { - NI_DestroyEncrStruct(hp->encryption); - } - MsgFreeSavedData(hp); - MemFree(hp); - return 0; -} /* MsgDestroyHandle */ - - - -/* - * Purpose: Set "longjump" error mechanism - * - * Parameters: - * mh A pointer to the message handle for which the "longjump" - * error is to be set. - * - * - * Description: - * Set the ASN I/O error handler to be a function which will - * simply "longjump", and hence return control to the place at - * which setjmp() was last called. The "longjump" flag should - * be check by a setjmp() caller, prior to calling setjmp(), to - * assure that the error handling mechanism is in place. - */ - -NLM_EXTERN void MsgSetLJError(MHandPtr mh) -{ - AsnIoSetErrorMsg(mh->raip, NI_ASNIOError); - AsnIoSetErrorMsg(mh->waip, NI_ASNIOError); - mh->longjump = TRUE; -} /* MsgSetLJError */ - - - -/* - * Purpose: Set the "read" timeout for this message handle - * - * Parameters: - * mh A pointer to the message handle for which the read timeout - * is to be set. - * - * - * Description: - * Set the "read" timeout for this message handle. A default - * value is set-up at the time when the message handle is created. - * - * Note: - * This timeout is also used for the "hung" timeout. - */ - -NLM_EXTERN void MsgSetReadTimeout(MHandPtr mh, int t) -{ - mh->r_timeout = t; -} /* MsgSetReadTimeout */ - - -/* - * Purpose: Set the "write" timeout for this message handle - * - * Parameters: - * mh A pointer to the message handle for which the write timeout - * is to be set. - * - * - * Description: - * Set the "write" timeout for this message handle. A default - * value is set-up at the time when the message handle is created. - */ - -NLM_EXTERN void MsgSetWriteTimeout(MHandPtr mh, int t) -{ - mh->w_timeout = t; -} /* MsgSetWriteTimeout */ - - -/* - * Purpose: Set the filter parameters for this message handle - * - * Parameters: - * mh A pointer to the message handle for which the parameters - * are to be set. - * - * ex_proc A pointer to an optional user-defined data structure to be - * used by the read and write filters. - * - * wfilt A write filter function, which may be used, e.g., to collect - * statistics, or to compress the data to be written. - * - * rfilt A read filter function, which may be used, e.g., to collect - * statistics, or to decompress the data which was read. - * - * wfilt_pass Indicates whether wfilt needs to modify the data buffer (e.g., - * this will be FALSE if doing statistics only, but TRUE if - * doing data compression). - * - * rfilt_pass Indicates whether rfilt needs to return a modified data - * buffer (e.g., this will be FALSE if doing statistics only, - * but TRUE if doing data decompression). - * - * - * Description: - * Set the I/O filters for this message handle. A default - * value (no filter) is set up at the time when the message - * handle is created. - * - * Note: - * It is the responsibility of the higher-level software (i.e., - * not this module) to free any data associated with ex_proc. - */ - -NLM_EXTERN void MsgSetFilters(MHandPtr mh, VoidPtr ex_proc, NI_WriteFilt wfilt, - NI_ReadFilt rfilt, Boolean wfilt_pass, Boolean rfilt_pass) -{ - if (mh == NULL) - return; - - mh->extra_proc_info = ex_proc; - mh->write_filter = wfilt; - mh->read_filter = rfilt; - mh->write_filt_pass_thru = wfilt_pass; - mh->read_filt_pass_thru = rfilt_pass; -} - - -/* - * Purpose: Set the timeout hooks for this message handle - * - * Parameters: - * mh A pointer to the message handle for which the parameters - * are to be set. - * - * rhook A hook to be called when the read timeout expires - * - * whook A hook to be called when the write timeout expires - * - * - * Description: - * Set the read and write timeout hooks for this message handle. - * A default value (no hook) is set up at the time when the - * message handle is created. - * - * Note: - * The write hook is currently usused (6/2/93). - */ - -NLM_EXTERN void MsgSetTimeoutHooks(MHandPtr mh, NI_TimeoutHook rhook, NI_TimeoutHook whook) -{ - if (mh == NULL) - return; - - mh->readTimeoutHook = rhook; - mh->writeTimeoutHook = whook; -} - -/* - * Purpose: Initialize the ASN.1 object loader for this module - * - * Parameters: - * none - * - * - * Description: - * Dynamically load the ASN.1 static header, if necessary. - */ - -static Boolean -InitMsg (void) -{ - static Boolean loaded = FALSE; - - if (loaded) - return TRUE; - if (! AsnLoad()) - return FALSE; - loaded = TRUE; - return TRUE; -} - - -/******************************************************************************/ -/* */ -/* Functions used by AsnTool for socket IO (readfunc and writefunc) */ -/* */ -/******************************************************************************/ - -/* - * Purpose: Read some data on behalf of the ASN.1 library - * - * Parameters: - * p A pointer to the message handle structure - * buf The buffer into which the data should be read - * len Maximum number of bytes to be read - * - * Returns: - * 0, if operating in "unblocked mode", and are unable to - * read the requested amount of data - * -ETIMEOUT, if blocked, waiting for data to be available, but - * none arrived before the read timeout expired - * -errno [ system error number ], for other errors - * the number of bytes read, otherwise - * - * - * Description: - * This is the 'readfunc' function used by ASN.1 to read some - * data from the specified ASN.1 I/O stream. - * - * First, try to read some data from the "queued data", i.e., - * data which was read from the socket on a previous iteration, - * but ASN.1 processing failed because there was insufficient - * data. - * - * Subsequently, try to read from the socket. If the data is - * unavailable, and running in "blocked" mode, wait for either - * the data to appear or for the read timeout to expire. - * - * In the case where data is read successfully, store it in - * the "queued data" area. - * - * Once data has been read successfully, optionally post-process - * it through a filter routine. This routine may, e.g., collect - * statistics or provide a de-compression mechanism. If it is - * a de-compression mechanism, any data which would not fit in - * the original buffer is stored in the "queued data" area, to - * be re-read by the next call to this function. - */ - -NLM_EXTERN Int2 LIBCALLBACK NI_AsnRead(Pointer p, CharPtr buf, Uint2 len) -{ - MHandPtr mh; - int bytesread; - int ready; - time_t secs0, secs1; - fd_set rfds; - struct timeval timeout; - CharPtr extra_buf; - Int4 extra_buf_len; - CharPtr extra_encr_buf; - Int4 extra_encr_buf_len; - NI_NetServHook activityHook; - - mh = (MHandPtr) p; - - /* always provide caller with queued data, if available */ - if (MsgHaveSavedData(mh)) - { - return MsgReadSavedData(mh, buf, len); - } - - mh->access_time = time(NULL); - - DisabVibrant(); - - while ((bytesread = NI_READSOCKET(mh->sok, buf, len)) <= 0) { -#ifndef NETP_INET_PCNFS - if (bytesread == 0) { - break; - } -#else - SOCK_ERRNO = tk_geterrno (mh->sok); -#endif -#ifdef NETP_INET_NEWT - SOCK_ERRNO = ABS(bytesread); -#endif - switch (SOCK_ERRNO) { - case EINTR: - continue; - - case EAGAIN: -#if EAGAIN != EWOULDBLOCK - case EWOULDBLOCK: -#endif /* EAGAIN != EWOULDBLOCK */ - if (mh->unblocked_mode) - { - mh->have_blocked = TRUE; - EnabVibrant(); - return 0; - } - FD_ZERO(&rfds); - FD_SET(mh->sok, &rfds); - secs0 = secs1 = time(NULL); - - RepeatSelect: - /* a simple poll is effected when timeout.tv_sec == 0 */ - timeout.tv_sec = mh->r_timeout - (secs1 - secs0); - timeout.tv_usec = 0; - ready = NI_select(mh->sok + 1, &rfds, NULL, NULL, &timeout); - if (ready > 0) - continue; - if (ready == 0) - { - EnabVibrant(); - return (-ABS(ETIMEDOUT)); - } - switch (SOCK_ERRNO) { - case EINTR: - /* update the timeout because select() does not */ - secs1 = time(NULL); - if (secs1 - secs0 > (time_t) mh->r_timeout) - secs1 = secs0 + mh->r_timeout; - goto RepeatSelect; - - default: - break; - } - EnabVibrant(); - return (-ABS(SOCK_ERRNO)); - - default: - EnabVibrant(); - return (-ABS(SOCK_ERRNO)); - } -#ifdef WIN16 -#ifdef NETP_INET_WSOCK - { - MSG msg; - - if (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)) - { - TranslateMessage(&msg); - DispatchMessage(&msg); - } - } -#else - Yield(); -#endif -#endif - } - - EnabVibrant(); - - extra_buf = NULL; - extra_encr_buf = NULL; - if (mh->read_filter != NULL) - { - if (mh->read_filt_pass_thru) - { - mh->read_filter (mh, buf, bytesread, len, NULL, NULL); - } - else { - bytesread = (int) mh->read_filter (mh, buf, bytesread, len, - &extra_buf, &extra_buf_len); - } - } - - if (mh->encryption != NULL && mh->encryption->read_filter != NULL) - { - bytesread = (int) mh->encryption->read_filter (mh, buf, bytesread, - len, &extra_encr_buf, - &extra_encr_buf_len); - } - - if ((activityHook = NI_ActivityHook()) != NULL) - { - activityHook (mh, NetServHook_read, bytesread); - } - - /* save what we just read */ - MsgSaveData (mh, buf, bytesread); - - if (extra_buf != NULL) - { /* there was some extra data which we didn't get to read */ - MsgSaveData (mh, extra_buf, (Uint2) extra_buf_len); - mh->cur_index -= extra_buf_len; /* enqueue data for next read */ - MemFree (extra_buf); - extra_buf = NULL; - } - - if (extra_encr_buf != NULL) - { /* there was some extra encrypted data which we didn't get to read */ - MsgSaveData (mh, extra_encr_buf, (Uint2) extra_encr_buf_len); - mh->cur_index -= extra_encr_buf_len; /* enqueue data for next read */ - MemFree (extra_encr_buf); - extra_encr_buf = NULL; - } - - return bytesread; -} /* NI_AsnRead */ - - - -/* - * Purpose: Write some data on behalf of the ASN.1 library - * - * Parameters: - * p A pointer to the message handle structure - * buf The buffer into which the data should be written - * len Number of bytes to be written - * - * Returns: - * -ETIMEOUT, if unable to write the data before the write - * timeout expired - * -errno [ system error number ], for other errors - * the number of bytes written, otherwise - * - * - * Description: - * This is the 'writefunc' function used by ASN.1 to write some - * data to the specified ASN.1 I/O stream. - * - * If unable to write the data immediately, block until it is - * possible to write the data, or until the write timeout expires. - * - * The data to be output is optionally passed through a filter - * routine. This routine may, for example, collect statistics - * or compress the data to be written. - * - * Note: - * It is relatively unlikely that "writing" will block, thus - * causing the calling application to block. For "writing" to - * block, there would need to be flow control imposed in the - * TCP/IP protocol suite, which is an unlikely occurrence when - * passing small quantities of data. - */ - -NLM_EXTERN Int2 LIBCALLBACK NI_AsnWrite(Pointer p, CharPtr buf, Uint2 len) -{ - MHandPtr mh; - Int2 byteswrit, bytesleft; - int ready; - fd_set wfds; - time_t secs0, secs1 = 0; - struct timeval timeout; - CharPtr newbuf; - Uint2 newlen; - CharPtr tmpbuf = NULL; - NI_NetServHook activityHook; - - mh = (MHandPtr) p; - mh->access_time = time(NULL); - - newbuf = buf; - newlen = len; - if (mh->write_filter != NULL) - { - if (mh->write_filt_pass_thru) - { /* write filter is "pass-through only" */ - mh->write_filter (mh, buf, len, NULL); - } - else { /* write filter modifies buffer to be written */ - tmpbuf = (CharPtr) MemNew(len + 5); - newlen = (Uint2) mh->write_filter(mh, buf, len, tmpbuf); - newbuf = tmpbuf; - } - } - if (mh->encryption != NULL && mh->encryption->write_filter != NULL) - { - tmpbuf = (CharPtr) MemNew(len + 9); - newlen = (Uint2) mh->encryption->write_filter(mh, newbuf, newlen, tmpbuf); - newbuf = tmpbuf; - } - - if ((activityHook = NI_ActivityHook()) != NULL) - { - activityHook (mh, NetServHook_write, newlen); - } - - DisabVibrant(); - - for (bytesleft = newlen; bytesleft > 0; bytesleft -= byteswrit, - newbuf += byteswrit) { - while ((byteswrit = NI_WRITESOCKET(mh->sok, newbuf, bytesleft)) <= 0) { - if (byteswrit == 0) - { -#ifdef NETP_INET_NEWT - /* this is a real kludge to deal with the fact that NEWT */ - /* sometimes returns 0 on a send() for no good reason; we simulate*/ - /* that we were told that the send() would block */ - byteswrit = -EWOULDBLOCK; -#else - WriteCleanup(tmpbuf); - return 0; -#endif /* NETP_INET_NEWT */ - } - -#ifdef NETP_INET_NEWT - SOCK_ERRNO = ABS(byteswrit); -#endif -#ifdef NETP_INET_PCNFS - SOCK_ERRNO = tk_geterrno (mh->sok); -#endif - - byteswrit = 0; /* don't allow byte count to become messed up */ - - switch (SOCK_ERRNO) { - case EINTR: - continue; - - case EAGAIN: -#if EAGAIN != EWOULDBLOCK - - case EWOULDBLOCK: -#endif -#ifdef NETP_INET_NEWT - /* work-around for bug in version 2.00 of NEWT; a select()*/ - /* will never recognize when it's O.K. to write to a */ - /* socket */ - if (secs1 == 0) - { - secs1 = secs0 = time(NULL); - } - else { - secs1 = time(NULL); - if (secs1 - secs0 > (time_t) mh->w_timeout) - { - WriteCleanup(tmpbuf); - return (-ABS(ETIMEDOUT)); - } - } - break; -#endif - FD_ZERO(&wfds); - FD_SET(mh->sok, &wfds); - secs0 = secs1 = time(NULL); - - RepeatSelect: - /* a simple poll is effected when timeout.tv_sec == 0 */ - timeout.tv_sec = mh->w_timeout - (secs1 - secs0); - timeout.tv_usec = 0; - ready = NI_select(mh->sok + 1, NULL, &wfds, NULL, &timeout); - if (ready > 0) - continue; - if (ready == 0) - { - WriteCleanup(tmpbuf); - return (-ABS(ETIMEDOUT)); - } - switch (SOCK_ERRNO) { - case EINTR: - /* update the timeout because select() does not */ - secs1 = time(NULL); - if (secs1 - secs0 > (time_t) mh->w_timeout) - secs1 = secs0 + mh->w_timeout; - goto RepeatSelect; - default: - break; - } - WriteCleanup(tmpbuf); - return (-ABS(SOCK_ERRNO)); - - default: - WriteCleanup(tmpbuf); - return (-ABS(SOCK_ERRNO)); - } -#ifdef WIN16 -#ifdef NETP_INET_WSOCK - { - MSG msg; - - if (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)) - { - TranslateMessage(&msg); - DispatchMessage(&msg); - } - } -#else - Yield(); -#endif -#endif - } - } - - WriteCleanup(tmpbuf); - return (Int2)len; -} /* NI_AsnWrite */ - - -/* - * Purpose: Clean-up for NI_AsnWrite - * - * Parameters: - * tmpbuf Temporary buffer to be freed, if non-NULL - * - * - * Description: - * Frees temporary buffer, and re-enables Vibrant for user - * input. Used because there are so many return paths from - * NI_AsnWrite. - * - */ - -static void -WriteCleanup (CharPtr tmpbuf) -{ - if (tmpbuf != NULL) - { - MemFree (tmpbuf); - } - EnabVibrant(); -} - - -/* - * Purpose: ASN.1 Error handling - * - * Parameters: - * level Error code to be returned - * str Error text generated by ASN.1 - * - * - * Description: - * This is the error handling function used by ASN.1; it is called - * when any ASN.1 I/O error occurs. - * - * When an ASN.1 I/O error occurs, this function stores the - * error text in a safe place, and "longjumps", returning - * control to a point where setjmp() was last called. This point - * should occur in a relatively high-level function (above the - * ASN.1 library). - * - * Note: - * Due to the implementation of setjmp()/longjmp(), if level is - * 0, then the setjmp() caller will see the value 1; this - * mechanism is used to allow a setjmp() caller to distinguish - * between the case when they have just "set" the jump environment - * (return value == 0), and all other cases. - */ - -NLM_EXTERN void LIBCALLBACK NI_ASNIOError(Int2 level, CharPtr str) -{ - StringCpy(ni_errtext, str); - LongJump(ni_env, level); -} /* NI_ASNIOError */ - - - -#if defined(NETP_INET_NEWT) || defined(NETP_INET_WSOCK) - -/* - * Purpose: Implementation of blocked select() for use with NEWT and WSOCK - * - * Parameters: - * width "width" of file descriptor bits maps - * rfds Read file descriptor bit maps - * wfds Write file descriptor bit maps - * xfds Exception file descriptor bit maps - * - * Returns: - * 0, if the timeout period elapses - * -1, if an error occurred - * the number of available file descriptors (selected file - * descriptors which are available for processing), otherwise - * - * - * Description: - * Provide a "blocked" select() mechanism, because NEWT does - * not provide one. - * - * Note: - * When calling select(), the width of the file descriptor - * maps is increased by one, to handle an off-by-one error - * associated with the NEWT library. - * - * This function is used in WinSock (rather than WinSock's - * select function) to ensure that message removal/dispatching - * is done in a manner which does not interfere with scrollbar - * management. - */ - -NLM_EXTERN int NI_poll_select(int width, fd_set PNTR rfds, fd_set PNTR wfds, fd_set PNTR xfds, struct timeval PNTR timeout) -{ - fd_set trfds, twfds, txfds; - int rdy; - time_t t_end; - struct timeval tmout; - - if (rfds != NULL) - Nlm_MemCopy(&trfds, rfds, sizeof(trfds)); - if (wfds != NULL) - Nlm_MemCopy(&twfds, wfds, sizeof(twfds)); - if (xfds != NULL) - Nlm_MemCopy(&txfds, xfds, sizeof(txfds)); - - t_end = timeout->tv_sec + Nlm_GetSecs(); - tmout.tv_sec = 0; - tmout.tv_usec = 0; -#ifdef NETP_INET_WSOCK - width--; -#endif - while (Nlm_GetSecs() < t_end) { - if (rfds != NULL) - Nlm_MemCopy(rfds, &trfds, sizeof(trfds)); - if (wfds != NULL) - Nlm_MemCopy(wfds, &twfds, sizeof(twfds)); - if (xfds != NULL) - Nlm_MemCopy(xfds, &txfds, sizeof(txfds)); - -#ifdef NETP_INET_WSOCK - { - MSG msg; - Boolean done = FALSE; - - /* get all the available messages, avoiding WM_LBUTTONUP since */ - /* this will cause scroll bars to hang, for some unknown reason */ - while (! done) - { - done = TRUE; - if (PeekMessage(&msg, NULL, 0, WM_LBUTTONUP-1, PM_REMOVE)) - { - done = FALSE; - TranslateMessage(&msg); - DispatchMessage(&msg); - } - if (PeekMessage(&msg, NULL, WM_LBUTTONUP+1, 0xffff, PM_REMOVE)) - { - done = FALSE; - TranslateMessage(&msg); - DispatchMessage(&msg); - } - } - } -#else -#ifdef WIN16 - Yield(); -#endif -#endif - /* select with (width + 1) because NetManage boundary condition error */ - - if ((rdy = select((width + 1), rfds, wfds, xfds, &tmout)) != 0) { - if (rdy < 0) { /* error */ -#ifdef NETP_INET_NEWT - errno = ABS(rdy); -#endif - rdy = -1; - } - return rdy; - } - - } - return 0; /* timed out */ -} /* NI_poll_select */ - -#endif - - -#ifdef NI_BLOCK_WITH_FUNCTION - - -/* - * Purpose: Implementation of setting non-blocked-socket mode for platforms - * for which it is difficult to perform this functionality within - * a macro. - * - * Parameters: - * fd Socket file descriptor - * - */ - -NLM_EXTERN int NI_SetNonBlocking (int fd) -{ - int mode = 1; - -#ifdef NETP_INET_WSOCK - u_long lmode = 1; - return ioctlsocket (fd, FIONBIO, &lmode); -#endif - -#ifdef NETP_INET_PCNFS - return tk_ioctl (fd, FIONBIO, &mode); -#endif -#ifdef NETP_INET_TGV - return socket_ioctl (fd, FIONBIO, &mode); -#endif -#ifdef NETP_INET_WPW - long lmode = 0; - return ioctl (fd, FIONBIO, &mode); -#endif -#ifdef NETP_INET_TWG - /**************************************************************************/ - /* WARNING: THIS IS CURRENTLY NOT IMPLEMENTED PROPERLY BECAUSE WE (W. */ - /* GILBERT/J. EPSTEIN) ARE NOT ABLE TO MAKE NETWORK SERVICES */ - /* OPERATE PROPERLY IN NON-BLOCKING MODE. AT SOME FUTURE DATE, */ - /* THE REMAINDER OF NETWORK SERVICES SHOULD BE DEBUGGED AND THE */ - /* FOLLOWING LINE SHOULD READ: lmode = 1 */ - /* 17 June 1993 */ - /**************************************************************************/ - /* - long lmode = 0; - return ioctl (fd, FIONBIO, &lmode); - */ - return 0; -#endif -#ifdef NETP_INET_UCX - /**************************************************************************/ - /* WARNING: THIS IS CURRENTLY UNIMPLEMENTED BECAUSE IT IS NOT CLEAR THAT */ - /* IT IS POSSIBLE TO SPECIFY BLOCKING/NONBLOCKING MODE FOR UCX */ - /* 22 June 1993 */ - /**************************************************************************/ - return 0; -#endif -} - -/* - * Purpose: Implementation of setting blocked-socket mode for platforms - * for which it is difficult to perform this functionality within - * a macro. - * - * Parameters: - * fd Socket file descriptor - * - */ - -NLM_EXTERN int NI_SetBlocking (int fd) -{ - int mode = 0; - -#ifdef NETP_INET_WSOCK - u_long lmode = 0; - return ioctlsocket (fd, FIONBIO, &lmode); -#endif - -#ifdef NETP_INET_PCNFS - return tk_ioctl (fd, FIONBIO, &mode); -#endif -#ifdef NETP_INET_TGV - return socket_ioctl (fd, FIONBIO, &mode); -#endif -#ifdef NETP_INET_WPW - long lmode = 0; - return ioctl (fd, FIONBIO, &lmode); -#endif -#ifdef NETP_INET_TWG - /* - long lmode = 0; - return ioctl (fd, FIONBIO, &lmode); -*/ - return 0; -#endif -#ifdef NETP_INET_UCX - /**************************************************************************/ - /* WARNING: THIS IS CURRENTLY UNIMPLEMENTED BECAUSE IT IS NOT CLEAR THAT */ - /* IT IS POSSIBLE TO SPECIFY BLOCKING/NONBLOCKING MODE FOR UCX */ - /* 22 June 1993 */ - /**************************************************************************/ - return 0; -#endif -} - -#endif /* BLOCK_WITH_FUNCTION */ - - -/* - * Purpose: Test as to whether there's available data already enqueued - * - * Parameters: - * mh Pointer to "message handle" data structure - * - * Returns: - * FALSE, if there is no data already enqueued - * TRUE, otherwise - * - * - * Description: - * Determine whether there is currently enqueued data on a - * "message handle" data structure. - */ - -static Boolean -MsgHaveSavedData(MHandPtr mh) -{ - if (!mh->unblocked_mode) - return FALSE; - if (mh->queued_data_list == NULL) - return FALSE; - if (mh->num_queued_bytes <= 0) - return FALSE; - return (mh->cur_index < mh->num_queued_bytes); -} - - -/* - * Purpose: Read data which was previously stored in this "message handle" - * - * Parameters: - * mh Pointer to "message handle" data structure - * buf Buffer where data should be stored - * len Maximum number of bytes to read out - * - * Returns: - * the number of bytes read from the enqueued data list - * - * - * Description: - * Return up to len bytes of enqueued data, by traversing - * the enqueued data structure, beginning with the location - * where the "current byte" pointer is currently pointing. - * - * Note: - * The enqueued data is stored in a list of chained blocks, where - * at all times, all the blocks are full, except (possibly) the - * last block. - */ - -#define MSG_READ_BLOCK_SIZE 1024 - -static int -MsgReadSavedData(MHandPtr mh, CharPtr buf, Uint2 len) -{ - NodePtr startpt; - NodePtr blk; - int addl_queue_data; - int local_index; - int bytes_copied; - int data_in_this_block; - int bytes_to_copy; - - if (mh->queued_data_list == NULL || len <= 0 || mh->num_queued_bytes == 0) - return 0; - blk = startpt = mh->queued_data_list; - addl_queue_data = mh->num_queued_bytes - mh->cur_index; - local_index = 0; - bytes_copied = 0; - - /* traverse the portion of the list which is necessary to get past */ - /* the current "file" pointer, and then copy up to len bytes of */ - /* data from the remaining blocks */ - do { - /* if ( this is the last block ) then */ - if (mh->num_queued_bytes - local_index < MSG_READ_BLOCK_SIZE) - data_in_this_block = mh->num_queued_bytes % MSG_READ_BLOCK_SIZE; - else - data_in_this_block = MSG_READ_BLOCK_SIZE; - - /* if ( there is more data to be skipped over ) then */ - if (local_index < mh->cur_index) - { /* there is more data to be skipped over */ - if (local_index + data_in_this_block <= mh->cur_index) - { /* skip this block */ - local_index += data_in_this_block; - continue; - } - else { /* skip a portion of this block, and copy the remainder */ - data_in_this_block -= (mh->cur_index - local_index); - local_index = mh->cur_index; - } - } - - bytes_to_copy = MIN((int) len, data_in_this_block); - MemCopy(buf, blk->elem, bytes_to_copy); - buf += bytes_to_copy; - len -= bytes_to_copy; - bytes_copied += bytes_to_copy; - mh->cur_index += bytes_to_copy; - local_index += bytes_to_copy; - } while ( (blk = ListGetNext(blk)) != startpt && len > 0); - - return bytes_copied; -} - - - -/* - * Purpose: Store len bytes of data from a buffer, for future use - * - * Parameters: - * mh Pointer to "message handle" data structure - * buf Buffer of data to be copied - * len Number of bytes to save - * - * - * Description: - * Store len bytes of data at the end of a list of "enqueued data." - * After finding the current end of the queue, data is added - * to the final block (up to its capacity), and then, if needed, - * additional blocks are allocated to store the remaining data. - */ - -static void -MsgSaveData(MHandPtr mh, CharPtr buf, Uint2 len) -{ - NodePtr tail; - int bytes_to_copy; - int starting_byte; - CharPtr newdata; - - if (len == 0 || !mh->unblocked_mode) - return; - - /* get to the correct place in the list, and then start storing */ - - tail = mh->queued_data_list; - - /* point to tail of list; in a ring, the element before the head is the */ - /* tail */ - if (tail != NULL) - tail = tail->last; - - /* if ( more room in the current element ) then */ - if ((starting_byte = mh->num_queued_bytes % MSG_READ_BLOCK_SIZE) != 0) - { - bytes_to_copy = MIN(MSG_READ_BLOCK_SIZE - starting_byte, (int) len); - newdata = (CharPtr) tail->elem; - MemCopy (&newdata[starting_byte], buf, bytes_to_copy); - len -= bytes_to_copy; - buf += len; - mh->num_queued_bytes += bytes_to_copy; - } - - /* while ( there is more data to be copied ) */ - while (len > 0) - { /* create a new element, and copy data into that element */ - - newdata = MemNew(MSG_READ_BLOCK_SIZE); - bytes_to_copy = MIN(MSG_READ_BLOCK_SIZE, len); - MemCopy (newdata, buf, bytes_to_copy); - buf += bytes_to_copy; - len -= bytes_to_copy; - mh->num_queued_bytes += bytes_to_copy; - tail = ListInsert(newdata, tail); - } - - mh->cur_index = mh->num_queued_bytes; - - if (tail == NULL) - mh->queued_data_list = NULL; - else - mh->queued_data_list = tail->next; -} - - - -/* - * Purpose: Free data associated with an "enqueued data list" - * - * Parameters: - * mh Pointer to "message handle" data structure - * - * - * Description: - * Free all the message elements associated with a list of - * enqueued data, and set other message handle elements to - * appropriate values such that software accessing those structures - * will not, erroneously, think that there is valid enqueued data - * in the structure. - */ - -static void -MsgFreeSavedData (MHandPtr mh) -{ - NodePtr np; - CharPtr elem; - - mh->unblocked_mode = FALSE; - mh->have_blocked = FALSE; - mh->num_queued_bytes = 0; - mh->cur_index = 0; - - np = mh->queued_data_list; - - mh->queued_data_list = NULL; - - while (np != NULL) - { - elem = (CharPtr) np->elem; - if (elem != NULL) - MemFree (elem); - np = ListDelete(np); - } -} - - -/* - * Purpose: Set and pop the hour-glass cursor - * - * Parameters: - * none - * - * Description: - * According to the NEWT/NetManage documentation, it is - * beneficial to make the cursor into an hourglass to block-out - * unwanted events during some socket calls. - */ - -#if defined(NETP_INET_NEWT) || defined(NETP_INET_WSOCK) -static HCURSOR saveCursor = NULL; - -static void SetHourGlass(void) -{ -#ifdef NETP_INET_NEWT - static HCURSOR hourCursor; - - hourCursor = LoadCursor(NULL, IDC_WAIT); - saveCursor = SetCursor(hourCursor); -#endif -} - -static void PopHourGlass(void) -{ -#ifdef NETP_INET_NEWT - if (saveCursor != NULL) - SetCursor(saveCursor); -#endif -} -#endif /* NETP_INET_NEWT */ - diff --git a/network/nsclilib/ni_msg.h b/network/nsclilib/ni_msg.h deleted file mode 100644 index 9d409473..00000000 --- a/network/nsclilib/ni_msg.h +++ /dev/null @@ -1,399 +0,0 @@ -/* -* =========================================================================== -* -* PUBLIC DOMAIN NOTICE -* National Center for Biotechnology Information -* -* This software/database is a "United States Government Work" under the -* terms of the United States Copyright Act. It was written as part of -* the author's official duties as a United States Government employee and -* thus cannot be copyrighted. This software/database is freely available -* to the public for use. The National Library of Medicine and the U.S. -* Government have not placed any restriction on its use or reproduction. -* -* Although all reasonable efforts have been taken to ensure the accuracy -* and reliability of the software and data, the NLM and the U.S. -* Government do not and cannot warrant the performance or results that -* may be obtained by using this software or data. The NLM and the U.S. -* Government disclaim all warranties, express or implied, including -* warranties of performance, merchantability or fitness for any particular -* purpose. -* -* Please cite the author in any work or product based on this material. -* -* =========================================================================== -* -* File Name: ni_msg.h -* -* Author: Beatty, Gish -* -* Version Creation Date: 1/1/92 -* -* $Revision: 6.0 $ -* -* File Description: -* -* -* Modifications: -* -------------------------------------------------------------------------- -* Date Name Description of modification -* ------- ---------- ----------------------------------------------------- -* 5/12/92 Epstein Converted tabs to spaces -* -* 04-21-93 Schuler Changed declaration of NI_AsnNew(), NI_AsnWrite(), -* and NI_ASNIOError() to use LIBCALLBACK calling convention. -* -* -* ========================================================================== -* -* -* RCS Modification History: -* $Log: ni_msg.h,v $ -* Revision 6.0 1997/08/25 18:39:06 madden -* Revision changed to 6.0 -* -* Revision 5.4 1997/07/01 19:13:00 vakatov -* [WIN32] DLL'd "netcli.lib" -* -* Revision 5.3 1997/01/28 21:24:50 epstein -* eliminate reference to ni_list.h -* - * Revision 5.2 1996/06/27 18:15:06 kans - * extra comma removed - * - * Revision 5.1 1996/06/27 17:18:02 epstein - * add load-balancing - * - * Revision 5.0 1996/05/28 14:11:55 ostell - * Set to revision 5.0 - * - * Revision 4.1 1995/11/27 20:59:29 epstein - * add client support for direct-connection services - * - * Revision 4.0 95/07/26 13:56:32 ostell - * force revision to 4.0 - * - * Revision 1.17 1995/05/24 12:08:49 epstein - * add support for tracking of how many times a client IP has used a service within a time interval - * - * Revision 1.16 95/05/17 17:52:44 epstein - * add RCS log revision history - * -*/ - -#ifndef _NI_MSG_ -#define _NI_MSG_ - -#include <setjmp.h> - -#include "ncbinet.h" -#include "ni_net.h" - - -#undef NLM_EXTERN -#ifdef NLM_IMPORT -#define NLM_EXTERN NLM_IMPORT -#else -#define NLM_EXTERN extern -#endif - -#ifdef __cplusplus -extern "C" { -#endif - - -#ifdef WIN16 -#define Jumpbuf CATCHBUF -#define SetJump Catch -#define LongJump Throw -#else -#define Jumpbuf jmp_buf -#define SetJump setjmp -#define LongJump longjmp -#endif - -#define NI_BLOCK_TIMEOUT 60 -#define NI_BLOCKSIZE 4096 /* matches TCP_MAXSEG in many systems */ - -/* VARS */ - -extern Uint4 conid; /* globally unique connection ID counter */ - - -/* TYPES */ - -#define MsgType enum msgtype -MsgType { - NI_UNKNOWN = 0, - NI_ACK, - NI_NACK, - NI_LOGIN, - NI_SVC_LIST, - NI_SVC_REQUEST, - NI_SVC_RESPONSE, - NI_COMMAND, - NI_ACCT, - NI_CATALOG, - NI_SVC_PRE_RESPONSE, - NI_STATUS -}; - -#define MsgCommand enum msgcommand -MsgCommand { - NI_SEND_SVCLIST = 1, /* send me a list of your services */ - NI_SEND_CATALOG, /* send me the catalog (dispatcher) */ - NI_KILL, /* kill yourself */ - NI_POLL /* health check poll */ -}; - -typedef struct NIPubKey { /* internal format for public key */ - Int2 bits; /* bits used in modulus */ - ByteStorePtr modulus; - ByteStorePtr exponent; -} NIPubKey, PNTR NIPubKeyPtr; - -typedef struct NIDispInfo { - Int4 serialno; /* unique dispatcher serial # */ - Boolean isalternatelist;/* is this an alternate disp-list ? */ - int numdispatchers; /* number of dispatchers in disp-list */ - CharPtr PNTR displist; /* list of dispatchers */ - NIPubKeyPtr pubKey; /* public RSA key */ -} NIDispInfo, PNTR NIDispInfoPtr; - -typedef struct NIAck { - Uint4 seqno; - NIDispInfoPtr dispinfo; - CharPtr adminInfo; /* info. regarding guest's admin */ - CharPtr motd; /* message of the day */ -} NIAck, PNTR NIAckPtr; - -typedef struct NINack { - Uint4 seqno; - NI_Error code; - CharPtr reason; - NIDispInfoPtr dispinfo; -} NINack, PNTR NINackPtr; - -typedef struct NILogin { - Uint4 seqno; - NI_UidPtr uid; /* ID structure */ - CharPtr password; /* must be encrypted */ - Int4 dispserialno; /* unique dispatcher serial # */ - Boolean encryptionDesired; /* encryption desired by client */ - NIPubKeyPtr pubKey; /* public RSA key */ - ByteStorePtr desKey; /* DES key for ncbid<->dispd comm */ - Int2 connectDelay; /* connection delay (seconds) */ - Uint2 server_port; /* port on server mashine */ -} NILogin, PNTR NILoginPtr; - -typedef struct NISvcList { - Uint4 seqno; - NIToolsetPtr toolset; - Boolean knowsTracking; /* does this ncbid know about tracking? */ -} NISvcList, PNTR NISvcListPtr; - -typedef struct NITicket { - Uint4 seqno; /* ticket sequence number */ - ByteStorePtr confounding_rand_num; - ByteStorePtr client_ip_1; /* ticket is valid from either of */ - ByteStorePtr client_ip_2; /* these 2 addresses */ - ByteStorePtr server_ip; /* this ticket is only valid at this server IP */ - ByteStorePtr client_des_key; /* encription key */ - ByteStorePtr ticket_expiration; /* expiration time */ - ByteStorePtr checksum; /* checksum of the ticket */ -} NITicket, PNTR NITicketPtr; - -typedef struct NISvcReq { - Uint4 seqno; - Uint4 conid; /* for client accounting */ - NI_UidPtr uid; - ReqPtr request; - Uint4 platform; /* client's platform */ - CharPtr applId; /* application identifier */ - ByteStorePtr desKey; - Boolean wantPreResponse; /* client wants to know server's IP */ - Uint4 server_ip; - Uint2 server_port; /* port on server machine */ - Boolean want_ticket; /* request of direct connection */ - NITicketPtr ticket; /* ticket for direct connection */ -} NISvcReq, PNTR NISvcReqPtr; - -typedef struct NISvcResp { - Uint4 seqno; - ReqPtr request; -} NISvcResp, PNTR NISvcRespPtr; - -typedef struct NICmd { - Uint4 seqno; - MsgCommand code; -} NICmd, PNTR NICmdPtr; - -typedef struct NIPreResp { - Uint4 seqno; - Uint4 server_ip; -} NIPreResp, PNTR NIPreRespPtr; - -typedef struct NIAcct { - Uint4 seqno; - Uint4 conid; - CharPtr jobname; - Uint4 usertime; - Uint4 systemtime; -} NIAcct, PNTR NIAcctPtr; - -typedef union NIMSun { - NIAckPtr ack; - NINackPtr nack; - NILoginPtr login; - NISvcListPtr svclist; - NISvcReqPtr svcreq; - NISvcRespPtr svcresp; - NICmdPtr command; - NIAcctPtr acct; - NICatalogPtr catalog; - NIStatusPtr status; - NIPreRespPtr preresp; -} NIMSun, PNTR NIMSunPtr; - -typedef struct NIMessage { - MsgType type; - Uint4 conid; /* for ACKing */ - NIMSun msun; /* message structure union */ -} NIMessage, PNTR NIMsgPtr; - - -/* FUNCTION PROTOTYPES */ - -NLM_EXTERN NIMsgPtr MsgRead PROTO((MHandPtr handle, Boolean unblocked)); - -NLM_EXTERN Int2 MsgWrite PROTO((MHandPtr handle, NIMsgPtr mp, Boolean noDestroy)); - -NLM_EXTERN NIMsgPtr MsgBuild PROTO((MsgType type, Uint4 conn, VoidPtr stp)); - -NLM_EXTERN Int2 MsgDestroy PROTO((NIMsgPtr mp)); - -NLM_EXTERN MHandPtr MsgMakeHandle PROTO((Boolean createSocket)); - -NLM_EXTERN Int2 MsgDestroyHandle PROTO((MHandPtr hp)); - -NLM_EXTERN void MsgSetLJError PROTO((MHandPtr mh)); - -NLM_EXTERN void MsgSetReadTimeout PROTO((MHandPtr mh, int t)); - -NLM_EXTERN void MsgSetWriteTimeout PROTO((MHandPtr mh, int t)); - -NLM_EXTERN void MsgSetFilters PROTO((MHandPtr mh, VoidPtr ex_proc, NI_WriteFilt wfilt, NI_ReadFilt rfilt, Boolean wfilt_pass, Boolean rfilt_pass)); - -NLM_EXTERN void MsgSetTimeoutHooks PROTO((MHandPtr mh, NI_TimeoutHook rhook, NI_TimeoutHook whook)); - -NLM_EXTERN Int2 LIBCALLBACK NI_AsnRead PROTO((Pointer p, CharPtr buf, Uint2 len)); - -NLM_EXTERN Int2 LIBCALLBACK NI_AsnWrite PROTO((Pointer p, CharPtr buf, Uint2 len)); - -NLM_EXTERN void LIBCALLBACK NI_ASNIOError PROTO((Int2 level, CharPtr str)); - -NLM_EXTERN int NI_poll_select PROTO((int width, fd_set PNTR rfds, fd_set PNTR wfds, fd_set PNTR xfds, struct timeval PNTR timeout)); -NLM_EXTERN int NI_SetBlocking PROTO((int sock)); -NLM_EXTERN int NI_SetNonBlocking PROTO((int sock)); - - -/* Message Type Functions */ - -NLM_EXTERN NIAckPtr NI_MakeMsgAck PROTO((void)); - -NLM_EXTERN Int2 NI_DestroyMsgAck PROTO((NIAckPtr)); - -NLM_EXTERN NINackPtr NI_MakeMsgNack PROTO((void)); - -NLM_EXTERN Int2 NI_DestroyMsgNack PROTO((NINackPtr)); - -NLM_EXTERN NILoginPtr NI_MakeMsgLogin PROTO((void)); - -NLM_EXTERN Int2 NI_DestroyMsgLogin PROTO((NILoginPtr)); - -NLM_EXTERN NISvcListPtr NI_MakeMsgSvclist PROTO((void)); - -NLM_EXTERN Int2 NI_DestroyMsgSvclist PROTO((NISvcListPtr)); - -NLM_EXTERN NISvcReqPtr NI_MakeMsgSvcreq PROTO((void)); - -NLM_EXTERN Int2 NI_DestroyMsgSvcreq PROTO((NISvcReqPtr)); - -NLM_EXTERN NISvcRespPtr NI_MakeMsgSvcresp PROTO((void)); - -NLM_EXTERN Int2 NI_DestroyMsgSvcresp PROTO((NISvcRespPtr)); - -NLM_EXTERN NICmdPtr NI_MakeMsgCmd PROTO((void)); - -NLM_EXTERN Int2 NI_DestroyMsgCmd PROTO((NICmdPtr)); - -NLM_EXTERN NIPreRespPtr NI_MakeMsgPreResp PROTO((void)); - -NLM_EXTERN Int2 NI_DestroyMsgPreResp PROTO((NIPreRespPtr)); - -NLM_EXTERN NIAcctPtr NI_MakeMsgAcct PROTO((void)); - -NLM_EXTERN Int2 NI_DestroyMsgAcct PROTO((NIAcctPtr)); - -NLM_EXTERN NISvcPtr NI_MakeService PROTO((void)); - -NLM_EXTERN Int2 NI_DestroyService PROTO((NISvcPtr)); - -NLM_EXTERN NIResPtr NI_MakeResource PROTO((void)); - -NLM_EXTERN Int2 NI_DestroyResource PROTO((NIResPtr)); - -NLM_EXTERN NIRegionPtr NI_MakeRegion PROTO((void)); - -NLM_EXTERN Int2 NI_DestroyRegion PROTO((NIRegionPtr)); - -NLM_EXTERN ReqPtr NI_MakeRequest PROTO((void)); - -NLM_EXTERN Int2 NI_DestroyRequest PROTO((ReqPtr)); - -NLM_EXTERN NITicketPtr NI_MakeTicket PROTO((void)); - -NLM_EXTERN NICatalogPtr NI_MakeMsgCatalog PROTO((void)); - -NLM_EXTERN Int2 NI_DestroyMsgCatalog PROTO((NICatalogPtr)); - -NLM_EXTERN NIStatusPtr NI_MakeMsgStatus PROTO((void)); - -NLM_EXTERN Int2 NI_DestroyMsgStatus PROTO((NIStatusPtr)); - -NLM_EXTERN NI_UidPtr NI_MakeUid PROTO((void)); - -NLM_EXTERN Int2 NI_DestroyUid PROTO((NI_UidPtr)); - -NLM_EXTERN NIPubKeyPtr NI_MakePubKey PROTO((void)); - -NLM_EXTERN Int2 NI_DestroyPubKey PROTO((NIPubKeyPtr)); - -NLM_EXTERN int NI_ReadPubKey PROTO((AsnIoPtr extaip, AsnTypePtr extatp, NIPubKeyPtr dip)); -NLM_EXTERN void NI_WritePubKey PROTO((AsnIoPtr extaip, AsnTypePtr extatp, NIPubKeyPtr dip)); - -NLM_EXTERN NIDispInfoPtr NI_MakeDispInfo PROTO((void)); - -NLM_EXTERN Int2 NI_DestroyDispInfo PROTO((NIDispInfoPtr)); - -NLM_EXTERN int NI_ReadDispInfo PROTO((AsnIoPtr extaip, AsnTypePtr extatp, NIDispInfoPtr dip)); -NLM_EXTERN void NI_WriteDispInfo PROTO((AsnIoPtr extaip, AsnTypePtr extatp, NIDispInfoPtr dip)); - -NLM_EXTERN NIToolsetPtr NI_MakeToolset PROTO((void)); - -NLM_EXTERN Int2 NI_DestroyToolset PROTO((NIToolsetPtr tsp)); - -NLM_EXTERN NIToolsetPtr NI_GetCatToolset PROTO((NIToolsetPtr tsp)); - -#ifdef __cplusplus -} -#endif - -#undef NLM_EXTERN -#ifdef NLM_EXPORT -#define NLM_EXTERN NLM_EXPORT -#else -#define NLM_EXTERN -#endif - -#endif diff --git a/network/socks/socks.cstc.4.2/CHANGES b/network/socks/socks.cstc.4.2/CHANGES deleted file mode 100644 index 79c534d3..00000000 --- a/network/socks/socks.cstc.4.2/CHANGES +++ /dev/null @@ -1,118 +0,0 @@ -Pre-release 1 of version 4.2 of SOCKS.CSTC, dated June 30, 1994 - --Made consistent use of u_int32 for alpha port. (David Mischel) - --Included partial port (server and library) for NextStep 3.2. (William Lewis) - --Made clients behave like non-SOCKSified programs if /etc/socks.conf - is absent. - --Made the printing of client banner controllable using environment - variable SOCKS_BANNER. (Bryan Curnutt) - --Added compile-time option to disable syslog from clients. (Jason Baietto) - --Added DNS_THROUGH_NIS in Makefile to accomodate sites which resolve - DNS through their NIS server and have no local /etc/resolv.conf. - --Include bsdinstall, a shell script written by Phil Hochstetler, - phil@sequent.com, which simulate BSD's install for SYSV systems. - -======================================= -Beta release of version 4.2 of SOCKS.CSTC, dated March 21, 1994 - --Added code to allow use of filenames in the *=userlist field. - The filenames must be a complete path (starting with /). Userids - and comments can be used in such files. Updated the man pages - sockd.conf.5 and soccks.conf.5 to document the new feature. - --Merged in code to show sockd's usage details in the output of - ps commamd. Only work with non-SYSV hosts. (Matt Cohen) - -======================================== -Beta release of version 4.2 of SOCKS.CSTC, dated February 22, 1994 - --Corrected mistakes in determining privileged/non-privileged port. - --Dereferenced addr in saddrtoname.c. (Anthony Starks) - --Added code to zero out all sockaddr_in structures before using them. - (Carlos Mora) - --Added code to treat IP address 0.0.0.0 as localhost. (Anthony Shipman) - --Added code to save host and port after a successful direct connect. - (Ian Dunkin) - --Made the facility and the log levels for syslog configurable in - socks.h. (Jon Luini) - --Made the optimization flag for cc configurable in Makefile. (Craig Metz) - --Made SendDst() and GetDst() quit when write() or read() returns 0. - (David Nochlin) - --Added code to use iotcl(...,FIOSSAIOOWN...) in place of - fcntl(...F_SETOWN...) for hpux. (John Brezak) - -======================================= -Beta release of version 4.2 of SOCKS.CSTC, dated February 9, 1994. - -Changes since release 4.1 - -1) Merged in SCO/ODT 2.x and BSDi v1.0 ports by Chris Riney. - -2) Merged in PS/2 AIX 1.2.1 port by Craig Metz. - -3) Merged in DEC OSF 1.3 port by Alain Mellan. - -4) Merged in the code to prevent premature closing of a TCP session - on the SOCKS server when the server is much faster than the - client host. Contributed by Andy McFadden. - -5) Merged in the code for using environment variable SOCKS_DNAME - to override the setting of SOCKS_DEFAULT_DNAME. Contributed by - Jon Luini. - -6) It handles non-blocking connect() call correctly, at least for - the way non-blocking connect()'s are done in Mosaic 2.1. This - necessitates the addition of Rselect() to the library. - -7) You can build libsocks.a with Rbind() which accepts the same - calling sequence as regular bind(), i.e., without the extra - last argument. - -8) Call to SOCKSinit() is made optional. - -9) Rrcmd() is optionally added to the library. - -The combined effect of 6) through 9) is that, for most applications, -you can do the SOOCKSification without doing anything to the code -at all. Just add - --Dconnect=Rconnect -Dbind=Rbind -Dgetsockname=Rgetsockname -Dlisten=Rlisten -Daccept=Raccept -Drcmd=Rrcmd -Dselect=Rselect - -to cc and make sure the appropraite SOCKS library is used in linking. -I hope this will encourage developers to produce SOCKSified version -of their applications. (By the way, if you really want that, you should -certainly make the effort of letting your friendly software vendors -or developers know about it. Customers's demands count a great deal -in the software market.) - -10) In anticipation of client hosts that can't run identd, a new - filed '?=n' is added to the control line for sockd.conf. This - enables the use of invoking sockd with -I option to use identd - in general but have it turned off for some specific client hosts. - (You can also use '?=I' or '?=i' to turn identd on for a line, I - just see the use of '?=n' as more likely.) - -11) Deliver out-of-band data end to end. - -12) Connection to 127.0.0.1 (localhost) is always direct. No more - need to specify that in /etc/socks.conf. - - Ying-Da Lee (214)518-3490 (214)518-3552 (FAX) - Principal Member, Technical Staff - NEC Systems Laboratory, C&C Software Technology Center / - ylee@syl.dl.nec.com - diff --git a/network/socks/socks.cstc.4.2/COPYRIGHTS b/network/socks/socks.cstc.4.2/COPYRIGHTS deleted file mode 100644 index 7d64e6bf..00000000 --- a/network/socks/socks.cstc.4.2/COPYRIGHTS +++ /dev/null @@ -1,50 +0,0 @@ ------------------------------------------------------------------ -Copyright (c) 1989 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. - ------------------------------------------------------------------ -Portions Copyright (c) 1993, 1994 by NEC Systems Laboratory. - -Permission to use, copy, modify, and distribute this software for -any purpose with or without fee is hereby granted, provided that -the above copyright notice and this permission notice appear in all -copies, and that the name of NEC Systems Laboratory not be used in -advertising or publicity pertaining to distribution of the document -or software without specific, written prior permission. - -THE SOFTWARE IS PROVIDED ``AS IS'' AND NEC SYSTEMS LABORATORY DISCLAIMS -ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NEC -SYSTEMS LABORATORY BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR -CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS -OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE -OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE -OR PERFORMANCE OF THIS SOFTWARE. diff --git a/network/socks/socks.cstc.4.2/How_to_SOCKSify b/network/socks/socks.cstc.4.2/How_to_SOCKSify deleted file mode 100644 index 3c59428f..00000000 --- a/network/socks/socks.cstc.4.2/How_to_SOCKSify +++ /dev/null @@ -1,35 +0,0 @@ -Four Easy Steps to SOCKSify (Most of) Your Favorite Network Programs - For use with SOCKS.CSTC version 4.2 - (Ying-Da Lee, ylee@syl.dl.nec.com>) -=================================================================== - -1) Find out if UDP is used in the program by doing "grep SOCK_DGRAM" on - all the source files. If any such lines are found (and are not comments), - you can't make it work with SOCKS. There is, however, a UDP relayer - which is to UDP what SOCKS is to TCP, and you may want to look into - it. It is written by Tom Fitzgerald <fitz@wang.com> and is available - from host ftp.wang.com, file /pub/fitz/udprelay-0.2.tar.Z. - -2) At or near the beginning of the main procedure, add this line: - - SOCKSinit(argv[0]); - - This step can be omitted. The only consequence is that the generic - 'SOCKSclient' rather than the actual client program name will be - used in the syslog lines on the client host. - -3) Add - - -Dconnect=Rconnect -Dgetsockname=Rgetsockname -Dbind=Rbind -Daccept=Raccept -Dlisten=Rlisten -Dselect=Rselect - - to all cc lines. If Makefile is used, this is simply done by adding - the above to the definition of macro CFLAGS. - -4) Make sure that the appropriate SOCKS library (version 4.2, built with - -DSHORTENED_RBIND) is linked in in the ld or the last cc command to - produce the executable. - -That's it for most programs. Build the program and try it, chances -are it would work. If it doesn't and you still like to have a SOCKSified -version, please read the file What_SOCKS_expects. - diff --git a/network/socks/socks.cstc.4.2/Makefile b/network/socks/socks.cstc.4.2/Makefile deleted file mode 100644 index f243dc90..00000000 --- a/network/socks/socks.cstc.4.2/Makefile +++ /dev/null @@ -1,311 +0,0 @@ -#DEBUG=-DDEBUG - -SHELL=/bin/sh - -#SOCKS=-DSOCKS -# or -SOCKS=-Dconnect=Rconnect -Dgetsockname=Rgetsockname -Dlisten=Rlisten -Daccept=Raccept -Drcmd=Rrcmd -Dbind=Rbind -Dselect=Rselect -# If the second definition of SOCKS is used, you MUST also -# define SHORTENED_RBIND - -# If your system doesn't have PWD defined, define it here: -#PWD=/projects/insg/socks.cstc.4.2beta -# It should be this current directory. - -# If your system has getcwd() but no getwd(), uncomment the next line: -#GETCWD=-DGETCWD - -# Define FASCIST if you want ftp (rftp) to log names of all files transferred -#FASCIST=-DFASCIST - -# Define RCMD and SUPPORT_RCMD if you want to support Rrcmd, which is required -# for SOCKSified rlogin, rsh, and rcp. -#RCMD=Rrcmd.o -#SUPPORT_RCMD=-DSUPPORT_RCMD - -# Define FOR_PS if your system is not SYSV and you want to have the -# command 'ps' show some details of sockd's activity. -#FOR_PS=-DFOR_PS - -# Define SHORTENED_RBIND to make Rbind() take exactly the same -# argument list as the regular bind(), i.e., without the additional -# 'remhost' argument. -SHORTENED_RBIND=-DSHORTENED_RBIND - -# optimization flag for cc -OPTIMIZE=-g -#OPTIMIZE=-O -# Be careful with the OPTIMIZE flag. SunPro's SC2.0.1, for example, is -# knwon to produce incorrect code when -O is used. - -# Define NO_CLIENT_LOG if you don't want SOCKS clients to produce -# log entries of its activities. -#NO_CLIENT_LOG= -Dopenlog= -Dsyslog= - -# Define DNS_THROUGH_NIS if your SOCKS client hosts let their NIS -# servers do the DNS loopkup for them. You are in this category if -# your client hosts has no /etc/resolv.conf but can resolve all -# internal and external names. -#DNS_THROUGH_NIS=-DDNS_THROUGH_NIS - -# Directory into which to install the man pages -MAN_DEST_DIR = /usr/local/man - -# Directory into which the SOCKS server should be installed -SERVER_BIN_DIR = /usr/etc - -# Directory into the client programs should be installed -CLIENTS_BIN_DIR = /usr/local/bin - -# SunOS 4.1.x should use -CC=cc -#CC=gcc -OTHER_CFLAGS= $(GETCWD) $(FASCIST) $(SHORTENED_RBIND) -DCOMPAT $(MONITOR) $(DEBUG) -RANLIB=ranlib -OS=sun4.1 -INSTALL=install -GETPASS=getpass.o -RESOLV_LIB=-lresolv -# ... or -#RESOLV_LIB= - -# IRIX should use -#CC=cc -#RESOLV_LIB=-lsun -#OTHER_CFLAGS=-cckr $(GETCWD) $(FASCIST) $(SHORTENED_RBIND) -DCOMPAT -#RANLIB=/bin/true -#OS=irix4 -#INSTALL=bsdinstall -#GETPASS=getpass.o - -# Ultrix 4.0 should use -#CC=cc -#OTHER_CFLAGS= $(GETCWD) $(SHORTENED_RBIND) $(FASCIST) -#RANLIB=ranlib -#OS=ultrix4.0 -#INSTALL=install -#GETPASS=getpass.o -#RESOLV_LIB=-lresolv - -# HP-UX should use -#CC=cc -#OTHER_CFLAGS= $(GETCWD) $(FASCIST) $(SHORTENED_RBIND) -DCOMPAT -#RANLIB=/bin/true -#OS=hpux9 -#INSTALL=install -#GETPASS= -#RESOLV_LIB= - -# RS/6000 AIX 3.2 should use -#CC=cc -#RESOLV_LIB=-lbsd -#OTHER_CFLAGS=-D_BSD -D_NONSTD_TYPES -D_NO_PROTO -DAIX $(GETCWD) $(FASCIST) $(SHORTENED_RBIND) -DCOMPAT -#RANLIB=ranlib -#OS=aix3.2 -#INSTALL=install -#GETPASS= - -# PS/2 AIX 1.2 should use -#CC=cc -#RESOLV_LIB=-lbsd -#OTHER_CFLAGS=-D_BSD -D_NONSTD_TYPES -D_NO_PROTO -DAIX $(GETCWD) $(FASCIST) -DCOMPAT -I/usr/local/include -DAIX_PS2 -#RANLIB=ranlib -#OS=aix_ps2 -#INSTALL=install -#GETPASS= - -# SOLARIS should use -#CC=cc -#RESOLV_LIB=-lresolv -lnsl -lsocket -#OTHER_CFLAGS=-DSOLARIS -Dindex=strchr -Drindex=strrchr $(SHORTENED_RBIND) -DUSE_DIRENT $(GETCWD) $(FASCIST) -DCOMPAT -#RANLIB=/bin/true -#OS=solaris2.2 -#INSTALL=install -#GETPASS=getpass.o - -# Interactive Systems Unix should use -#OTHER_CFLAGS = -DISC $(GETCWD) $(FASCIST) $(SHORTENED_RBIND) -DCOMPAT -#CC=cc -#RANLIB=ranlib -#OS=sun4.1 -#INSTALL=install -#GETPASS= -#RESOLV_LIB=-lresolv - -# netBSD should use -#OTHER_CFLAGS = $(GETCWD) $(SHORTENED_RBIND) $(FASCIST) -#CC=cc -#RANLIB=ranlib -#OS=netbsd0.9 -#INSTALL=install -#GETPASS= -#RESOLV_LIB= - -# LINUX should use -#CC=gcc -#RESOLV_LIB= -#OTHER_CFLAGS=-traditional -DLINUX $(GETCWD) $(FASCIST) $(SHORTENED_RBIND) -DCOMPAT -#OS=linux -#INSTALL=install -#GETPASS=getpass.o - -# UnixWare should use -#CC=cc -#RESOLV_LIB=-lresolv -lnsl -lsocket -#OTHER_CFLAGS= -DSOLARIS -Dindex=strchr -Drindex=strrchr -DUSE_DIRENT $(SHORTENED_RBIND) $(GETCWD) $(FASCIST) -DCOMPAT -#RANLIB=/bin/true -#INSTALL=/usr/ucb/install -#OS=UnixWare -#GETPASS=getpass.o - -# Alpha OSF should use: -#CC=cc -#RESOLV_LIB=-lresolv -#OS=alphaOSF -#OTHER_CFLAGS= $(GETCWD) $(FASCIST) $(SHORTENED_RBIND) -DCOMPAT -#RANLIB=ranlib -#INSTALL=install -#GETPASS= - -# SCO UNIX/ODT should use: -#CC=cc -#OS=sco -#RESOLV_LIB=-lsocket -#OTHER_CFLAGS= $(GETCWD) $(FASCIST) -DSCO -DSVR3 -Dindex=strchr -Drindex=strrc $(SHORTENED_RBIND) -DUSE_DIRENT -#RANLIB=/bin/true -#GETPASS= -#PWD=/test/chris/socks.cstc.4.1 - -# BSD/386 should use: -#CC=cc -#OS=bsdi -#RESOLV_LIB= -#OTHER_CFLAGS= $(GETCWD) $(SHORTENED_RBIND) $(FASCIST) -#RANLIB=ranlib -#GETPASS= - -# NextStep 3.2, SOCKS server and library only -# (William Lewis, wiml@omnigroup.com) -#CC=cc -#OTHER_CFLAGS= $(GETCWD) $(FASCIST) $(SHORTENED_RBIND) -DCOMPAT $(MONITOR) $(DEBUG) -Dstrdup=NXCopyStringBuffer -#RANLIB=ranlib -#GETPASS=getpass.o -#RESOLV_LIB=-lresolv -# ... or -#RESOLV_LIB= - -# >>>---------------- Others: - -# Define RESOLV_LIB if your system doesn't search resolver -# library automatically. -# Leave it undefined otherwise. -#RESOLV_LIB=-lresolv -# If your compiler or loader complains about _res_init being -# an undefined symbol, then you must define RESOLV_LIB. - -#RANLIB=ranlib -# Systems (e.g., IRIX) that do not need (and thus don't have) ranlib should use -#RANLIB=/bin/true - -# Comment out defintion of GETPASS if your system has problems -# compiling it, the version built into your system will then be used. -# The getpass() function in most Unix systems truncates passwords -# after 8 characters; the version provided here does not. -# This only affects ftp with non-anonymous login, and telnet. -# Ftp with anonymous login allows long passwords regardless -# of whether GETPASS is defined or not. -#GETPASS=getpass.o - -# The 'install' command is assumed to be the BSD variety (using -m to -# set the file mode). If the default 'install' on your system doesn't -# do that, you have to either specify an alternative one in the line below -# (e.g., /usr/ucb/install) or modify the other Makefile. -#INSTALL= install - -# Macro OS is used in making rtelnet. See the list near top of -# rtelnet/telnet/Makefile for available choices. - -# Remember to include -Dindex=strchr -Drindex=strrchr in OTHER_CFLAGS if -# you don't have index() and rindex() (Sys-V camp) - -# <<<---------------- - -# The Internet Whois server; used to be nic.ddn.mil. -WHOIS_SERVER= WHOIS_SERVER=-DWHOIS_SERVER\'=\"rs.internic.net\"\' - -SOCKS_LIB=$(PWD)/lib/libsocks.a -IDENT_LIB=$(PWD)/libident/libident.a - -#============================================================================== - -all: LIB LIBIDENT server clients - -server: LIB LIBIDENT - (cd sockd; $(MAKE) CC="$(CC)" RESOLV_LIB="$(RESOLV_LIB)" \ - OPTIMIZE="$(OPTIMIZE)" \ - SOCKS_LIB="$(SOCKS_LIB)" SUPPORT_RCMD="$(SUPPORT_RCMD)" \ - IDENT_LIB="$(IDENT_LIB)" \ - OTHER_CFLAGS="$(OTHER_CFLAGS) $(FOR_PS)") - -clients: RFINGER RFTP RTELNET - -LIB: - (cd lib; $(MAKE) CC="$(CC)" GETPASS="$(GETPASS)" \ - OPTIMIZE="$(OPTIMIZE)" \ - RCMD="$(RCMD)" SUPPORT_RCMD="$(SUPPORT_RCMD)" \ - DNS_THROUGH_NIS="$(DNS_THROUGH_NIS)" \ - OTHER_CFLAGS="$(OTHER_CFLAGS) $(NO_CLIENT_LOG)" \ - RANLIB="$(RANLIB)") - -LIBIDENT: - (cd libident; $(MAKE) CC="$(CC)" OTHER_CFLAGS="$(OTHER_CFLAGS)" \ - OPTIMIZE="$(OPTIMIZE)" RANLIB="$(RANLIB)") - -# This also build rwhois -RFINGER: LIB - (cd rfinger; $(MAKE) CC="$(CC)" $(WHOIS_SERVER) \ - OPTIMIZE="$(OPTIMIZE)" SOCKS="$(SOCKS)" \ - RESOLV_LIB="$(RESOLV_LIB)" SOCKS_LIB="$(SOCKS_LIB)" \ - OTHER_CFLAGS="$(OTHER_CFLAGS) $(NO_CLIENT_LOG)") - -RTELNET: LIB - (cd rtelnet; $(MAKE) CC="$(CC)" OS="$(OS)" SOCKS_LIB="$(SOCKS_LIB)" \ - OPTIMIZE="$(OPTIMIZE)" SOCKS="$(SOCKS)" \ - RESOLV_LIB="$(RESOLV_LIB)" \ - OTHER_CFLAGS="$(OTHER_CFLAGS) $(NO_CLIENT_LOG)") - -RFTP: LIB - (cd rftp; $(MAKE) CC="$(CC)" SOCKS_LIB="$(SOCKS_LIB)" \ - OPTIMIZE="$(OPTIMIZE)" SOCKS="$(SOCKS)" \ - RESOLV_LIB="$(RESOLV_LIB)" \ - OTHER_CFLAGS="$(OTHER_CFLAGS) $(NO_CLIENT_LOG)") - -install.server: - (cd sockd; $(MAKE) INSTALL="$(INSTALL)" MAN_DEST_DIR="$(MAN_DEST_DIR)" \ - CC="$(CC)" RESOLV_LIB="$(RESOLV_LIB)" \ - OPTIMIZE="$(OPTIMIZE)" \ - SOCKS_LIB="$(SOCKS_LIB)" SUPPORT_RCMD="$(SUPPORT_RCMD)" \ - IDENT_LIB="$(IDENT_LIB)" \ - OTHER_CFLAGS="$(OTHER_CFLAGS) $(FOR_PS)" \ - SERVER_BIN_DIR="$(SERVER_BIN_DIR)" install install.man) - -install.clients: install.man - for i in rfinger rftp rtelnet; do \ - (cd $$i ; $(MAKE) INSTALL="$(INSTALL)" \ - CC="$(CC)" OS="$(OS)" SOCKS_LIB="$(SOCKS_LIB)" \ - OPTIMIZE="$(OPTIMIZE)" SOCKS="$(SOCKS)" \ - RCMD="$(RCMD)" SUPPORT_RCMD="$(SUPPORT_RCMD)" \ - DNS_THROUGH_NIS="$(DNS_THROUGH_NIS)" \ - RESOLV_LIB="$(RESOLV_LIB)" \ - OTHER_CFLAGS="$(OTHER_CFLAGS) $(NO_CLIENT_LOG)" \ - CLIENTS_BIN_DIR="$(CLIENTS_BIN_DIR)" \ - install) done -install.man: - (cd doc; $(MAKE) INSTALL="$(INSTALL)" MAN_DEST_DIR="$(MAN_DEST_DIR)" \ - install) - -clean: - for i in lib libident sockd rfinger rftp rtelnet ; do \ - ( cd $$i ; $(MAKE) clean) done - - diff --git a/network/socks/socks.cstc.4.2/README.1st b/network/socks/socks.cstc.4.2/README.1st deleted file mode 100644 index a03de48c..00000000 --- a/network/socks/socks.cstc.4.2/README.1st +++ /dev/null @@ -1,249 +0,0 @@ -This is CSTC 4.2 release of SOCKS, a package that allows Unix hosts -behind a firewall to gain full access to the internet without requiring -direct IP reachability. It does require a SOCKS server program being -run on a hosts that can communicate directly to hosts behind the firewall -as well as hosts on the Internet at large. It is based on the original -SOCKS written by David Koblas <koblas@netcom.com>. - -The package includes full source for the SOCKS server and SOCKSified -client programs of finger, ftp, telnet, and whois. A few other SOCKSified -clients may be found on ftp.nec.com, in directory /pub/security/socks.cstc. -Increasingly, software developers are beginning to include SOCKS support -directly into their products, for example, Mosaic, Lynx, and a version -of Trumpet Winsock. - -This release is known to run on the following Unix platforms: - -SunOS 4.1.x (ylee@syl.dl.nec.com) -Irix 4.0.x (imd1707@ggr.co.uk) -Ultrix 4.3 (als@cpsg.com.au, imd1707@ggr.co.uk) -HP-UX 9.0x (als@cpsg.com.au, ken.shackelford@sdrc.com, bryan@Stoner.COM) -AIX 3.2.x (ken.shackelford@sdrc.com, bryan@Stoner.COM) -Interactive Systems Unix (ken.shackelford@sdrc.com) -Alpha OSF 1.3 (ken.shackelford@sdrc.com, amellan@acri.fr, treese@crl.dec.com) -Solaris 2.2 (ylee@syl.dl.nec.com) -NetBSD 0.9 (bryan@Stoner.COM) -UnixWare (pax@ankh.metrolink.com) -Linux 0.99pl13 (cornell@syl.dl.nec.com, cmetz@thor.tjhsst.edu) -SCO/ODT 2.x (Chris Riney) -BSDi 1.0 (Chris Riney) -PS/2 AIX 1.2.1 (cmetz@thor.tjhsst.edu) -NextStep 3.2 (server and library only, William Lewis) - -------------------- -All 4.2 clients work with all 4.x servers. 4.0 clients work -with single-homed 4.2 servers but NOT with 4.2 multi-homed servers. -4.1 clients work with 4.2 servers, both single- and multi-homed. -'sockd -ver' tells you not only the version number but also whether -it is single- or multi-homed. - -Please see below for the procedure for building and testing. -Remember that the names of the control files are all configurable -in include/socks.h. It will probably greatly reduce your frustration -while you are flipping between the old and the new versions if you -uses different file names for the new version. - -There is now a mailing list devoted to issues related -to SOCKS. To join the list, please send an email subscription request -to majordomo-request@syl.dl.nec.com with - - subscribe socks your@email.address - -in the body of the message. - -Finally, I want to thanks all the people who have helped in making -and shaping this release. Many of them are listed in the CHANGES -file, but undoubted many more are left out due to my poor memory -- -to those, my apologies. - - Ying-Da Lee (214)518-3490 (214)518-3552 (FAX) - Principal Member, Technical Staff - NEC Systems Laboratory, C&C Software Technology Center / - NEC USA, Corporate Network Administration Division - ylee@syl.dl.nec.com -==================================================================== - -Please read the file 'COPYRIGHTS' before you proceed further. - -In the following section, by 'top directory' we mean the top -directory of the SOCKS package, i.e., the directory you are -in right now. - -------------------------------------------------------------- - -HOW TO BUILD THE PROGRAMS - -1. Check and modify the following files to suit your systems: - - Makefile - include/socks.h - - Be sure that the macro 'SOCKS_DEFAULT_SERVER' in include/sosks.h - is set correctly to the host that will be running the proxy server - for your site. Although this can be overridden at run time with - environment variable SOCKS_SERVER, it is a lot simpler if you put - in the right name at compile time. Also be sure to uncomment and set - the macro 'SOCKS_DEFAULT_NS' in the same file if yor client machines - normally cann't do DNS resolution for outside hosts. - - Be sure that the macros 'ORIG_FINGER' and 'MULTIHOMED_SERVER' in - include/socks.h are set correctly. - - In most cases, you should have no needs to modify the Makefiles - in the subdirectories. But if you run into problems, you may - have to look into modifying - - sockd/Makefile - libident/Makefile - lib/Makefile - rfinger/Makefile - rftp/Makefile - rtelnet/Makefile - - If your system is not among those included in the top Makefile, - then you may also have to construct an entry for your system - in the file rtelnet/Config.local. - -2. cd to the top directory and issue 'make' command. It's a good - idea to direct stdout and stderr to a file so that you can - see what's being done afterwards. There will be a few warning - messages which you can ignore. This builds the server as well - as all the clients. - - If you only want to build the server (and the program for testing - your sever configuration file, and the program for converting the - file from the old format), use comannd 'make server' instead. - Use command 'make clients' to build only the client programs. You - can also build the individual clients using 'make RFINGER', - 'make RFTP', and 'make RTELNET', all from the top directory. - -3. All the man pages (except for libident) are in directory doc. - You are encouraged to print them out and read them before proceeding - to the next part. - -------------------------------------------------------------- - -HOW TO INSTALL THE SERVER - -1. Become superuser on the proxy server host for your site. - -2. cd to the top directory and issue 'make install.server'. - This installs programs sockd and test_sockd_conf as well - as the man pages for them. - -3. Add the line -socks 1080/tcp - to file /etc/services. It would be nice also to include -gopher 70/tcp -WWW 80/tcp - in the file if you don't already have them. - -4. Add the line -socks stream tcp nowait nobody /usr/etc/sockd sockd - to file /etc/inetd.conf. Use the actual path where sockd - is installed if not in /usr/etc. If you want to make use of - identd on your client machines when it is available, use -socks stream tcp nowait nobody /usr/etc/sockd sockd -i - If you want to REQUIRE identd be run on your client machines, - use -socks stream tcp nowait nobody /usr/etc/sockd sockd -I - Running sockd with -I will reject all requests from hosts that - do not run identd. - -5. Set up access control with file /etc/sockd.conf. You have to - read the man pages for sockd, sockd.conf, and test_sockd_conf - for the details. - For a quick test, you can use these four lines in the file: (Replace - 'client_IP' with the IP address of the host on which you will be - testing the client programs.) -permit client_IP 255.255.255.255 -# One LONG line follows: -deny 0.0.0.0 0.0.0.0 : /usr/ucb/finger @%A | /usr/ucb/mail -s 'SOCKD: rejected -- from %u@%A to host %Z (service %S)' root -# Another LONG line: -#BAD_ID: /usr/ucb/finger @%A | /usr/ucb/mail -s '%U pretends to be %u on host %A' root@%A root -# Last line: -#NO_IDENTD: /usr/ucb/mail -s 'Please run identd on %A' %u@%A root@%A - This is essentially the contents of file sockd/sockd.conf.sample. - *** NOTE *** The meanings of 1's and 0's in address masks are - reversed from 4.0 and earlier versions. If you already have a working - /etc/sockd.conf with an earlier version, use the program - sockd/flip_cfmasks to produce one for the new version. - -6. If the server host is multi-homed and you built sockd with the - macro MULTIHOMED_SERVER in include/socks.h defined, you must - also supply the file /etc/sockd.route. For a typical dual-homed - server, this can simply be a one-liner: -out_interface 0.0.0.0 0.0.0.0 - where out_interface is the IP address of the server's network - interface leading to the outside world. The format for lines - in this file should be -# comments -Interface_addr dst_addr dst_mask - - Read the man page on sockd.route !!! - -7. Run a few tests using program test_sockd_conf to make sure you - have the configuration file set up correctly. On a multi-homed - server, the program also tests /etc/sockd.route and shows which - interface is to be used. - -8. Send a SIGHUP signal to the running inetd process so that it will - use the new configuration. You may also have to do other things to - accommodate syslog facility. Read the man pages. - -------------------------------------------------------------- - -HOW TO TEST THE CLIENT PROGRAMS - - NOTE: Build and install identd on your client hosts first. This is - required if you run sockd with -I option. It is a good idea anyway. - - Set up the file /etc/socks.conf on the client host. Lines in this - file should be of the form -# comments -deny [*=userlist] dst_addr dst_mask [op port] -direct [*=userlist] dst_addr dst_mask [op port] -sockd [@=serverlist] [*=userlist] dst_addr dst_mask [op port] - Fields in square brackets are optional. The optional @=serverlist - field with a 'sockd' line specifies the list of SOCKS servers - the client should try (in the given order) instead of the default - SOCKS server. If the @=serverlist part is omitted, then the default - SOCKS server is used. Commas are used in the userlist and serverlist - as separators, no white spaces are allowed. - - Read the man page on socks.conf !!! - - On a client host (for testing purpose, this can be the same as - the proxy server), the clients rfinger, rwhois, rftp, and rtelnet, - can be tried out without any additional setup on the - client host once the server is running. They should behave like - finger, whois, ftp, and telnet, respectively. rftp DOES - echo your password IF you are using 'anonymous' as the log-in name. - - Quite a lot of details of operations of both the clients and the - server are logged. Checking the contents of the log files may be - helpful when you run into problems. You should try using these - clients to connect to both inside and outside hosts and check the - log messages to see whether the correct ways are used. - -------------------------------------------------------------- - -HOW TO INSTALL CLIENT PROGRAMS - -1. Become superuser on the client host. - -2. cd to the top directory, then issue the command 'make install.clients'. - This installs rfinger, rwhois, rftp, rtelnet, and - their man pages. - -3. Rename your regular 'finger', 'whois', 'ftp', and 'telnet' - to something else. The new name for the 'finger' program - must be EXACTLY what you used for defining the macro ORIG_FINGER in - include/socks.h. Then either rename the SOCKS clients or use symbolic - links for them. For example, if you have installed the clients in - directory /usr/local/bin and your regular 'finger', 'whois', 'ftp', - and 'telnet' were in /usr/ucb, then you should do -ln -s /usr/local/bin/rfinger /usr/ucb/finger -ln -s /usr/local/bin/rftp /usr/ucb/ftp -ln -s /usr/local/bin/rhwois /usr/ucb/whois -ln -s /usr/local/bin/rtelnet /usr/ucb/telnet diff --git a/network/socks/socks.cstc.4.2/README.4.0 b/network/socks/socks.cstc.4.2/README.4.0 deleted file mode 100644 index a1e9f992..00000000 --- a/network/socks/socks.cstc.4.2/README.4.0 +++ /dev/null @@ -1,292 +0,0 @@ -This is SOCKS, a package consisting of a proxy server (sockd) -and client programs corresponding to finger, whois, ftp, telnet, -xgopher, and xmosaic, as well as a library module (libsocks.a) -for adapting other applications into new client programs. - -The original SOCKS was written by David Koblas <koblas@netcom.com>, -which included the library module and finger, whois, and ftp clients. - -Clients programs added since the original are: - --telnet: adapted from telnet.91.03.25 by David Borman <dab@cray.com>. - This version is supposed to be much easier than the previous one - to port to many different systems. --xgopher: adapted from xgopher ver. 1.2 by Allan Tuchman <a-tuchman@uiuc.edu>. --xmosaic: adapted from xmosaic ver. 1.2 by NCSA staff (contact - Marc Andreesen, <marca@ncsa.uiuc.edu>). - -The SOCKS protocol has changed with this version. Since the server and -the clients must use the same SOCKS protocol, this server does not work -with clients of previous releases, and these clients do not work with -servers of previous releases. - -The access control mechanism has been expanded: - --A list of users can be included along with other fields (source address, - destination address, service/port) for permission/denial of access. --Identd is used (controlled by option -i and -I) in SOCKS server to try - to verify the actual user-ids. The code uses the library written by - Peter Eriksson <pen@lysator.liu.se> and /Pär Emanuelsson <pell@lysator.liu.se>. --A shell command can optionally be specified with each line. The command - is executed if the conditions of that line are satisfied. This is adapted - from the same feature and code used in the log_tcp package by Wietse - Venema <wietse@wzv.win.tue.nl>. --Special entries (#NO_IDENTD: and #BAD_ID:) can be included to specify - shell commands to be executed when the client host doesn't run identd - and when identd's report doesn't agree with what the client prgram says. - -The following can be a reasonable sockd.conf using the new features: - -# Permit root on 129.101.64.3 all services -permit *=root 129.101.64.3 0.0.0.0 -# -# Permit root and usersa on 129.101.112.10 telnet access to network 222.22.22 -permit *=usera,root 129.101.112.10 0.0.0.0 222.22.22.0 0.0.0.255 eq telnet -# -# Permit all users on network 129.101 access to ftp -permit 129.101.0.0 0.0.255.255 eq ftp -# -# Deny everything else. Upon an attempt, finger the client host and pipe -# the result into an email to root with appropriate Subject line. -deny 0.0.0.0 255.255.255.255 : finger @%A | /usr/ucb/mail -s 'SOCKD: rejected -- from %u@%A to host %Z (service %S)' root -# -# If the client doesn't run identd, tell the user and root there to run it. -#NO_IDENTD: /usr/ucb/mail -s 'Please run identd on %A' %u@%A root@%A -# -# Someone is masquerading as someone else. Finger the client host -# and pipe the result into an email message for local root and root on -# the client host with appropriate Subject line. -#BAD_ID: finger @%A | /usr/ucb/mail -s '%U pretends to be %u on host %A' root@%A root - -The test_sockd_conf program can be used to test the access control file, -including the special entries and the execution of shell commands. - -The Identd server is available through anonymous ftp from many places. -Consult archie. Or you can pick it up from ftp.inoc.dl.nec.com, the -file is pub/security/pidentd-2.1.2.tar.gz. This copy corrected a mistake -in the INSTALL file: In step 10, second paragraph, the line - TELNET session and enter "4711 , 113", where you replace 4711 with the -should read - TELNET session and enter "113 , 4711", where you replace 4711 with the -The author of pidentd is Peter Eriksson (pen@lysator.liu.se). - -Finally, the network/host byte order confusion has been cleaned up. That -should make porting to other systems a lot easier. Only machines for which -the assumptions that short=int=16 bits and long=32 bits do not hold -are still likely to have serious problems. - -The package has been ported for ULTRIX 4.3 by Ian Dunkin <imd1707@ggr.co.uk> -and Anthony Shipman <als@cpsg.com.au>, for IRIX 4.0.1 by Ian Dunkin (again), -and partially for HPUX by Anthony Shipman (again!). (We are a small bunch -of busy bees.) I also include patches by Craig Metz <cmetz@thor.tjhsst.edu> -to SOCKSize xarchie and ncftp. I have not try these patches out -myself though. - -I want to thank all the people I have mentioned so far, as well as the -following, who has helped with their bug reports, comments, and suggestions: - -Alain Mellan <amellan@acri.fr>, Heinz Naef <whna@nexos.com>, Rejane Forre -<for@pttnms.ewi.ch>, Michael Lachowski <mlachow@maverick1.erenj.com>, -Nancy Ball <nancy_ball@sematech.org>, David Vincenzetti <vince@dsi.unimi.it>, -LaMont Jones <lamont@sp1.cup.hp.com>, Brandon Butterworth -<brandon@dd.eng.bbc.co.uk>, Richard Schultz <rich@ccrwest.org>. - -Please read the file 'COPYRIGHTS' before you proceed further. - -In the following section, by 'top directory' we mean the top -directory of the SOCKS package, i.e., the directory you are -in right now. - -------------------------------------------------------------- - -HOW TO BUILD THE PROGRAMS - -1. Check and modify the following files to suit your systems: - - Makefile - include/socks.h - sockd/Makefile - libident/Makefile - lib/Makefile - rfinger/Makefile - rftp/Makefile - rtelnet/Makefile - rxgopher/Makefile - rxmosaic/Makefile - rxmosaic/libwww/Makefile - rxmosaic/libhtmlw/Makefile - rxmosaic/src/Makefile - - Be very careful with the Makefiles of rxgopher and rxmosaic. - For rxgopher, the Makefile is an exact copy of Makefile.YDL in the same - directory. If you have 'xmkmf' on your system, you may want - to use that to generate the Makefile itself. See the comment - under the section RXGOPHER in the Makefile in the top directory. - - The other Makefiles should not require much tweaking. Generally speaking, - macros RESOLV_LIB, SOCKS_LIB, IDENT_LIB, CCKR, RANLIB, and INSTALL are - defined in the top level Makfile and then passed down to lower level during - the make, overriding the settings in the lower-level Makfiles, so - you should define them in the top level Makfile and ignore them in - other Makefiles. (The redundancy is provided so that you can do - a make in the subdirectories. That is not recommended, however.) - - Be sure that the macro 'SOCKS_DEFAULT_SERVER' in include/sosks.h - is set correctly to the host that will be running the proxy server - for your site. Although this can be overridden at run time with - environment variable SOCKS_SERVER, it is a lot simpler if you put - in the right name at compile time. Also be sure to uncomment and set - the macro 'SOCKS_DEFAULT_NS' in the same file if yor client machines - normally cann't do DNS resolution for outside hosts. - -2. cd to the top directory and issue 'make' command. It's a good - idea to direct stdout and stderr to a file so that you can - see what's being done afterwards. There will be a few warning - messages which you can ignore. This builds the server as well - as all the clients. - - If you only want to build the server (and the program for testing - your sever configuration file), use comannd 'make server' instead. - Use command 'make clients' to build only the client programs. You - can also build the individual clients using 'make RFINGER', - 'make RFTP', 'make RTELNET', 'make RXGOPHER', and 'make RXMOSAIC', - all from the top directory. - - -------------------------------------------------------------- - -HOW TO INSTALL THE SERVER - -1. Become superuser on the proxy server host for your site. - -2. cd to the top directory and issue 'make install.server'. - This installs programs sockd and test_sockd_conf as well - as the man pages for them. Print the man pages and read them. - -3. Add the line -socks 1080/tcp - to file /etc/services. It would be nice also to include -gopher 70/tcp -WWW 80/tcp - in the file if you don't already have them. - -4. Add the line -socks stream tcp nowait nobody /usr/etc/sockd sockd - to file /etc/inetd.conf. Use the actual path where sockd - is installed if not in /usr/etc. If you want to make use of - identd on your client machines when it is available, use -socks stream tcp nowait nobody /usr/etc/sockd sockd -i - If you want to REQUIRE identd be run on your client machines, - use -socks stream tcp nowait nobody /usr/etc/sockd sockd -I - Running sockd with -I will reject all requests from hosts that - do not run identd. - -5. Set up access control with file /etc/sockd.conf. You have to - read the man pages for sockd and test_sockd_conf for the details. - For a quick test, you can use these four lines in the file: (Replace - 'client_IP' with the IP address of the host on which you will be - testing the client programs.) -permit client_IP 0.0.0.0 -deny 0.0.0.0 255.255.255.255 : /usr/ucb/finger @%A | /usr/ucb/mail -s 'SOCKD: rejected -- from %u@%A to host %Z (service %S)' root -#BAD_ID: /usr/ucb/finger @%A | /usr/ucb/mail -s '%U pretends to be %u on host %A' root@%A root -#NO_IDENTD: /usr/ucb/mail -s 'Please run identd on %A' %u@%A root@%A - This is essentially the contents of file sockd/sockd.conf.sample. - -6. Run a few tests using program test_sockd_conf to make sure your - have the configuration file set up correctly. - -7. Send a SIGHUP signal to the running inetd process so that it will - use the new configuration. You may also have to do other things to - accommodate syslog facility. Read the man pages. - -------------------------------------------------------------- - -HOW TO TEST THE CLIENT PROGRAMS -- EXCEPT rxgopher - - NOTE: Build and install identd on your client hosts first. This is - required if you run sockd with -I option. It is a good idea anyway. - - On a client host (for testing purpose, this can be the same - as the proxy server), the clients rfinger, rwhois, rftp, rtelnet, - and rxmosaic can be tried out without any special setup on the - client host once the server is running. They shoudl behave like - finger, whois, ftp, telnet, and xmosaic, respectively. rftp DOES - echo your password IF you are using 'anonymous' as the log-in name. - -------------------------------------------------------------- - -HOW TO TEST rxgopher -[Lifted from README file of xgopher package.] - -1. cd to rxgopher directory. - -2. Modify the application defaults file (RXgopher.ad). - Little change may be necessary. However, entries in this - file for host name, port number, help file name, etc., - override those defaults compiled into rxgopher through - the configuration file. - -3. Make the application defaults file (RXgopher.ad) known to X. - There are several ways to do this for testing without installing - the file in a system directory. Choose one of the following - - whichever is most comfortable for you. - - - IMPORTANT! Remove all of the application defaults from previous - versions of rxgopher before you attempt to run rxgopher 1.2. - - - a. xrdb -merge RXgopher.ad - - b. setenv XENVIRONMENT `pwd`/RXgopher.ad - (`pwd` will return the current directory, which should be the - rxgopher source directory.) - - c. if you have your own app-defaults directory, say ~/app-defaults: - setenv XAPPLRESDIR ~/app-defaults/ - cp RXgopher.ad ~/app-defaults/RXgopher - Note the name change. - - COLOR OPTION: If you are using a color display, it is strongly - recommended that you also include the rxgopher - color resources. if you used method (a) above, then - also use: - xrdb -merge RXgopher-color.ad -nocpp - - Otherwise, consider using the file RXgopher-complete.ad - instead of RXgopher.ad. The former file has all of the - color resources included in it. - - This is sufficient for now, and to let you test. For - permanent installation, see the later section of this - document which discusses color resources. - -4. To test, issue the command 'rxgopher' (without the quotes). - - -------------------------------------------------------------- - -HOW TO INSTALL CLIENT PROGRAMS - -1. Become superuser on the client host. - -2. cd to the top directory, then issue the command 'make install.clients'. - This installs rfinger, rwhois, rftp, rtelnet, rxgopher, rxmosaic, and - their man pages. It also installs the help file and the application - defaults file for rxgopher. - -3. For color setting and other details regarding rxgopher, please read - the README file in rxgopher directory. - - -------------------------------------------------------------- - -Good luck and enjoy it. - - Ying-Da Lee (214)518-3490 (214)518-3552 (FAX) - Principal Member Technical Staff - NEC Systems Laboratory, C&C Software Technology Center / - NEC USA, Corporate Network Administration Division - ylee@syl.dl.nec.com - diff --git a/network/socks/socks.cstc.4.2/README.4.1 b/network/socks/socks.cstc.4.2/README.4.1 deleted file mode 100644 index a7d3674f..00000000 --- a/network/socks/socks.cstc.4.2/README.4.1 +++ /dev/null @@ -1,332 +0,0 @@ -This is CSTC 4.1 release of SOCKS, a package that allows Unix hosts -behind a firewall to gain full access to the internet without requiring -direct IP reachability. It does require a SOCKS server program being -run on a hosts that can communicate directly to hosts behind the firewall -as well as hosts on the Internet at large. It is based on the original -SOCKS written by David Koblas <koblas@netcom.com>. - -The package includes full source for the SOCKS server and SOCKSified -client programs of finger, ftp, telnet, and whois. Other SOCKSified -clients such as xgopher (ver. 1.3.1) and Mosaic (ver. 2.0) can be -found on ftp.nec.com, in directory /pub/security/socks.cstc. (On -WWW, the URL is file://ftp.nec.com/pub/security/socks.cstc ) Mosaic 2.1 -as distributed by NCSA already contains the SOCKSification patch in its -source, which is available from ftp.ncsa.uiuc.edu, in /Mosaic/Mosaic-source. - -This release is known to run on the following Unix platforms: - -SunOS 4.1.x (ylee@syl.dl.nec.com) -Irix 4.0.x (imd1707@ggr.co.uk) -Ultrix 4.3 (als@cpsg.com.au, imd1707@ggr.co.uk) -HP-UX 9.0x (als@cpsg.com.au, ken.shackelford@sdrc.com, bryan@Stoner.COM) -AIX 3.2.x (ken.shackelford@sdrc.com, bryan@Stoner.COM) -Interactive Systems Unix (ken.shackelford@sdrc.com) -Alpha OSF 1.3 (ken.shackelford@sdrc.com, amellan@acri.fr, treese@crl.dec.com) -Solaris 2.2 (ylee@syl.dl.nec.com) -NetBSD 0.9 (bryan@Stoner.COM) -UnixWare (pax@ankh.metrolink.com) -Linux 0.99pl13 (cornell@syl.dl.nec.com, cmetz@thor.tjhsst.edu) - --------------------- MAJOR CHANGES SINCE 4.0 - -1)You now have the option to build 'sockd' to run on a multi-homed - host by defining the symbol 'MULTIHOMED_SERVER' in include/socks.h. - A multi-homed server requires another control file /etc/sockd.route - to tell it which of its network interfaces it should use for communicating - with which networks or hosts. For example: - -# Use interface 120.10.1.5 for host 100.1.2.3 -120.10.1.5 100.1.2.3 255.255.255.255 -# Use interface 120.10.2.10 for hosts in network 193.10.2 -120.10.2.10 193.10.2.0 255.255.255.0 -# Use interface 198.1.1.1 for all other connections -198.1.1.1 0.0.0.0 0.0.0.0 - - For a typical dual-homed server, all you need is a single line: - -outside_interface 0.0.0.0 0.0.0.0 - - where 'outside_interface' should be the IP address of the network - interface going outside of your firewall. - - test_sockd_conf has been updated so that it also checks the new control - file and tells you which interface will be used. - -2)You can now build 'versatile' clients, which uses SOCKS server(s) - to reach outside of your firewall but connects directly to hosts - within the firewall. So, for example, you can save away your regular - ftp program and replace it with the versatile SOCKS ftp client (rftp). - You have to be careful with 'finger' though and make sure that the - macro 'ORIG_FINGER' is properly defined in include/socks.h. - - All versatile clients use the file /etc/socks.conf to decide whether - a connection should be denied, done directly, or done indirectly through - SOCKS server at one or more hosts. For example: - -# Deny ftp and telnet access by baduser -deny *=baduser 0.0.0.0 0.0.0.0 eq ftp: mail -s 'ftp by baduser' root -deny *=baduser 0.0.0.0 0.0.0.0 eq telnet: mail -s 'telnet by baduser' root -# Be sure to include the next line for localhost! -direct 127.0.0.1 255.255.255.255 -# Use direct connection to all hosts in network 120.10 -direct 120.10.0.0 255.255.0.0 -# Use the defaiult SOCKS server to connect to host 13.13.13.13 -sockd 13.13.13.13 255.255.255.255 -# For other connections, try SOCKS servers at 120.10.2.3, 120.10.50.1, -# in that order -sockd @=120.10.2.3,120.10.50.1 0.0.0.0 0.0.0.0 - -3)As you may have already noticed, the interpretation of address masks - are changed. 1's in a mask now denote the bit positions that matter - while 0's denote the don't-care bit positions. In other words, they - are now interpreted the same way as IP netmasks. This holds true not - only for the two new control files mentioned above, but also for - /etc/sockd.conf. A new program 'flip_cfmasks' is provided in the sockd - subdirectory to convert the old format to the new one. Just do - -flip_cfmasks /etc/sockd.conf sockd.conf.flip - - check the output file sockd.conf.flip to see if all is well (with any - luck it should be) and then use that with the new server. - -4)An optional getpass() is provided to communicate with systems that - may require longer password (> 8 characters). This is for regular - passwords. As in 4.0, "passwords" for anonymous ftp can be longer than - 8 characters even without using the optional getpass(). - -5)Termination of a TCP session is now also logged on the SOCKS server, - including the number of bytes transported in either direction. - -6)An compile time option is provided to make ftp (rftp) log the name - of every file transferred. - -7)The man pages are substantially revamped. - -All 4.1 clients work with all 4.0 and 4.1 servers. 4.0 clients work -with single-homed 4.1 servers but NOT with 4.1 multi-homed servers. -'sockd -ver' tells you not only the version number but also whether -it is single- or multi-homed. - -Please see below for the procedure for building and testing. -Remember that the names of the control files are all configurable -in include/socks.h. It will probably greatly reduce your frustration -while you are flipping between the old and the new versions if you -uses different file names for the new version. - - -There is now a mailing list devoted to issues related -to SOCKS. To join the list, please send an email subscription request -with your email address to socks-request@inoc.dl.nec.com. - -Finally, I want to thanks all the people who have helped in making -and shaping this release. I certainly remember discussions and -contributions from the following, please forgive me (and remind me) -if I inadvertently leave your name off the list. - - brandon@dd.eng.bbc.co.uk (Brandon.Butterworth), bryan@Stoner.COM - (A. Bryan Curnutt), Ian Dunkin <imd1707@ggr.co.uk>, - Ingo_Dean@Warren.MentorG.com, Cornell Kinderknecht - <cornell@syl.dl.nec.com>, kupec@agouron.com (John W. Kupec), - jonl@hal.com (jon r. luini), amellan@acri.fr (Alain Mellan), - Craig Metz <cmetz@thor.tjhsst.edu>, montnaro@ausable.crd.ge.com - (Skip Montanaro), whna@nexos.com (Heinz Naef), nagler@olsen.ch - (Rob Nagler), "Jason Ornstein" <ornstein@xor.com>, pax@ankh.metrolink.com - (Garry M. Paxinos), mikey@netcom.com (Michael Pechner), royle@knmi.nl - (Keenan Royle), ken.shackelford@sdrc.com (Ken Shackelford), Anthony - Shipman <als@cpsg.com.au>, Rich Schultz <rich@ccrwest.org>, - treese@crl.dec.com (Win Treese), Paul.Vickers@barclays.co.uk (Paul Vickers), - vince@dsi.unimi.it (David Vincenzetti), posc!waddell@uunet.uu.net - (David Waddell) - - Ying-Da Lee (214)518-3490 (214)518-3552 (FAX) - Principal Member, Technical Staff - NEC Systems Laboratory, C&C Software Technology Center / - NEC USA, Corporate Network Administration Division - ylee@syl.dl.nec.com -==================================================================== - -Please read the file 'COPYRIGHTS' before you proceed further. - -In the following section, by 'top directory' we mean the top -directory of the SOCKS package, i.e., the directory you are -in right now. Ignore statements about rtelnet, rxgopher, and -rxmosaic if you are not building them. - -------------------------------------------------------------- - -HOW TO BUILD THE PROGRAMS - -1. Check and modify the following files to suit your systems: - - Makefile - include/socks.h - - Be sure that the macro 'SOCKS_DEFAULT_SERVER' in include/sosks.h - is set correctly to the host that will be running the proxy server - for your site. Although this can be overridden at run time with - environment variable SOCKS_SERVER, it is a lot simpler if you put - in the right name at compile time. Also be sure to uncomment and set - the macro 'SOCKS_DEFAULT_NS' in the same file if yor client machines - normally cann't do DNS resolution for outside hosts. - - Be sure that the macros 'ORIG_FINGER' and 'MULTIHOMED_SERVER' in - include/socks.h are set correctly. - - In most cases, you should have no needs to modify the Makefiles - in the subdirectories. But if you run into problems, you may - have to look into modifying - - sockd/Makefile - libident/Makefile - lib/Makefile - rfinger/Makefile - rftp/Makefile - rtelnet/Makefile - - If your system is not among those included in the top Makefile, - then you may also have to construct an entry for your system - in the file rtelnet/Config.local. - -2. cd to the top directory and issue 'make' command. It's a good - idea to direct stdout and stderr to a file so that you can - see what's being done afterwards. There will be a few warning - messages which you can ignore. This builds the server as well - as all the clients. - - If you only want to build the server (and the program for testing - your sever configuration file, AND THE PROGRAM FOR CONVERTING THE - FILE TO THE NEW FORMAT), use comannd 'make server' instead. - Use command 'make clients' to build only the client programs. You - can also build the individual clients using 'make RFINGER', - 'make RFTP', and 'make RTELNET', all from the top directory. - -3. All the man pages (except for libident) are in directory doc. - You are encouraged to print them out and read them before proceeding - to the next part. - -------------------------------------------------------------- - -HOW TO INSTALL THE SERVER - -1. Become superuser on the proxy server host for your site. - -2. cd to the top directory and issue 'make install.server'. - This installs programs sockd and test_sockd_conf as well - as the man pages for them. - -3. Add the line -socks 1080/tcp - to file /etc/services. It would be nice also to include -gopher 70/tcp -WWW 80/tcp - in the file if you don't already have them. - -4. Add the line -socks stream tcp nowait nobody /usr/etc/sockd sockd - to file /etc/inetd.conf. Use the actual path where sockd - is installed if not in /usr/etc. If you want to make use of - identd on your client machines when it is available, use -socks stream tcp nowait nobody /usr/etc/sockd sockd -i - If you want to REQUIRE identd be run on your client machines, - use -socks stream tcp nowait nobody /usr/etc/sockd sockd -I - Running sockd with -I will reject all requests from hosts that - do not run identd. - -5. Set up access control with file /etc/sockd.conf. You have to - read the man pages for sockd, sockd.conf, and test_sockd_conf - for the details. - For a quick test, you can use these four lines in the file: (Replace - 'client_IP' with the IP address of the host on which you will be - testing the client programs.) -permit client_IP 255.255.255.255 -# One LONG line follows: -deny 0.0.0.0 0.0.0.0 : /usr/ucb/finger @%A | /usr/ucb/mail -s 'SOCKD: rejected -- from %u@%A to host %Z (service %S)' root -# Another LONG line: -#BAD_ID: /usr/ucb/finger @%A | /usr/ucb/mail -s '%U pretends to be %u on host %A' root@%A root -# Last line: -#NO_IDENTD: /usr/ucb/mail -s 'Please run identd on %A' %u@%A root@%A - This is essentially the contents of file sockd/sockd.conf.sample. - *** NOTE *** The meanings of 1's and 0's in address masks are - reversed from previous versions. If you already have a working - /etc/sockd.conf with an earlier version, use the program - sockd/flip_cfmasks to produce one for the new version. - -6. If the server host is multi-homed and you built sockd with the - macro MULTIHOMED_SERVER in include/socks.h defined, you must - also supply the file /etc/sockd.route. For a typical dual-homed - server, this can simply be a one-liner: -out_interface 0.0.0.0 0.0.0.0 - where out_interface is the IP address of the server's network - interface leading to the outside world. The format for lines - in this file should be -# comments -Interface_addr dst_addr dst_mask - - Read the man page on sockd.route !!! - -7. Run a few tests using program test_sockd_conf to make sure you - have the configuration file set up correctly. On a multi-homed - server, the program also tests /etc/sockd.route and shows which - interface is to be used. - -8. Send a SIGHUP signal to the running inetd process so that it will - use the new configuration. You may also have to do other things to - accommodate syslog facility. Read the man pages. - -------------------------------------------------------------- - -HOW TO TEST THE CLIENT PROGRAMS - - NOTE: Build and install identd on your client hosts first. This is - required if you run sockd with -I option. It is a good idea anyway. - - Set up the file /etc/socks.conf on the client host. Lines in this - file should be of the form -# comments -deny [*=userlist] dst_addr dst_mask [op port] -direct [*=userlist] dst_addr dst_mask [op port] -sockd [@=serverlist] [*=userlist] dst_addr dst_mask [op port] - Fields in square brackets are optional. The optional @=serverlist - field with a 'sockd' line specifies the list of SOCKS servers - the client should try (in the given order) instead of the default - SOCKS server. If the @=serverlist part is omitted, then the default - SOCKS server is used. Commas are used in the userlist and serverlist - as separators, no white spaces are allowed. - - Read the man page on socks.conf !!! - - On a client host (for testing purpose, this can be the same as - the proxy server), the clients rfinger, rwhois, rftp, and rtelnet, - can be tried out without any additional setup on the - client host once the server is running. They should behave like - finger, whois, ftp, and telnet, respectively. rftp DOES - echo your password IF you are using 'anonymous' as the log-in name. - - Quite a lot of details of operations of both the clients and the - server are logged. Checking the contents of the log files may be - helpful when you run into problems. You should try using these - clients to connect to both inside and outside hosts and check the - log messages to see whether the correct ways are used. - -------------------------------------------------------------- - -HOW TO INSTALL CLIENT PROGRAMS - -1. Become superuser on the client host. - -2. cd to the top directory, then issue the command 'make install.clients'. - This installs rfinger, rwhois, rftp, rtelnet, and - their man pages. - -3. Rename your regular 'finger', 'whois', 'ftp', and 'telnet' - to something else. The new name for the 'finger' program - must be EXACTLY what you used for defining the macro ORIG_FINGER in - include/socks.h. Then either rename the SOCKS clients or use symbolic - links for them. For example, if you have installed the clients in - directory /usr/local/bin and your regular 'finger', 'whois', 'ftp', - and 'telnet' were in /usr/ucb, then you should do -ln -s /usr/local/bin/rfinger /usr/ucb/finger -ln -s /usr/local/bin/rftp /usr/ucb/ftp -ln -s /usr/local/bin/rhwois /usr/ucb/whois -ln -s /usr/local/bin/rtelnet /usr/ucb/telnet diff --git a/network/socks/socks.cstc.4.2/README.4.2 b/network/socks/socks.cstc.4.2/README.4.2 deleted file mode 100644 index a03de48c..00000000 --- a/network/socks/socks.cstc.4.2/README.4.2 +++ /dev/null @@ -1,249 +0,0 @@ -This is CSTC 4.2 release of SOCKS, a package that allows Unix hosts -behind a firewall to gain full access to the internet without requiring -direct IP reachability. It does require a SOCKS server program being -run on a hosts that can communicate directly to hosts behind the firewall -as well as hosts on the Internet at large. It is based on the original -SOCKS written by David Koblas <koblas@netcom.com>. - -The package includes full source for the SOCKS server and SOCKSified -client programs of finger, ftp, telnet, and whois. A few other SOCKSified -clients may be found on ftp.nec.com, in directory /pub/security/socks.cstc. -Increasingly, software developers are beginning to include SOCKS support -directly into their products, for example, Mosaic, Lynx, and a version -of Trumpet Winsock. - -This release is known to run on the following Unix platforms: - -SunOS 4.1.x (ylee@syl.dl.nec.com) -Irix 4.0.x (imd1707@ggr.co.uk) -Ultrix 4.3 (als@cpsg.com.au, imd1707@ggr.co.uk) -HP-UX 9.0x (als@cpsg.com.au, ken.shackelford@sdrc.com, bryan@Stoner.COM) -AIX 3.2.x (ken.shackelford@sdrc.com, bryan@Stoner.COM) -Interactive Systems Unix (ken.shackelford@sdrc.com) -Alpha OSF 1.3 (ken.shackelford@sdrc.com, amellan@acri.fr, treese@crl.dec.com) -Solaris 2.2 (ylee@syl.dl.nec.com) -NetBSD 0.9 (bryan@Stoner.COM) -UnixWare (pax@ankh.metrolink.com) -Linux 0.99pl13 (cornell@syl.dl.nec.com, cmetz@thor.tjhsst.edu) -SCO/ODT 2.x (Chris Riney) -BSDi 1.0 (Chris Riney) -PS/2 AIX 1.2.1 (cmetz@thor.tjhsst.edu) -NextStep 3.2 (server and library only, William Lewis) - -------------------- -All 4.2 clients work with all 4.x servers. 4.0 clients work -with single-homed 4.2 servers but NOT with 4.2 multi-homed servers. -4.1 clients work with 4.2 servers, both single- and multi-homed. -'sockd -ver' tells you not only the version number but also whether -it is single- or multi-homed. - -Please see below for the procedure for building and testing. -Remember that the names of the control files are all configurable -in include/socks.h. It will probably greatly reduce your frustration -while you are flipping between the old and the new versions if you -uses different file names for the new version. - -There is now a mailing list devoted to issues related -to SOCKS. To join the list, please send an email subscription request -to majordomo-request@syl.dl.nec.com with - - subscribe socks your@email.address - -in the body of the message. - -Finally, I want to thanks all the people who have helped in making -and shaping this release. Many of them are listed in the CHANGES -file, but undoubted many more are left out due to my poor memory -- -to those, my apologies. - - Ying-Da Lee (214)518-3490 (214)518-3552 (FAX) - Principal Member, Technical Staff - NEC Systems Laboratory, C&C Software Technology Center / - NEC USA, Corporate Network Administration Division - ylee@syl.dl.nec.com -==================================================================== - -Please read the file 'COPYRIGHTS' before you proceed further. - -In the following section, by 'top directory' we mean the top -directory of the SOCKS package, i.e., the directory you are -in right now. - -------------------------------------------------------------- - -HOW TO BUILD THE PROGRAMS - -1. Check and modify the following files to suit your systems: - - Makefile - include/socks.h - - Be sure that the macro 'SOCKS_DEFAULT_SERVER' in include/sosks.h - is set correctly to the host that will be running the proxy server - for your site. Although this can be overridden at run time with - environment variable SOCKS_SERVER, it is a lot simpler if you put - in the right name at compile time. Also be sure to uncomment and set - the macro 'SOCKS_DEFAULT_NS' in the same file if yor client machines - normally cann't do DNS resolution for outside hosts. - - Be sure that the macros 'ORIG_FINGER' and 'MULTIHOMED_SERVER' in - include/socks.h are set correctly. - - In most cases, you should have no needs to modify the Makefiles - in the subdirectories. But if you run into problems, you may - have to look into modifying - - sockd/Makefile - libident/Makefile - lib/Makefile - rfinger/Makefile - rftp/Makefile - rtelnet/Makefile - - If your system is not among those included in the top Makefile, - then you may also have to construct an entry for your system - in the file rtelnet/Config.local. - -2. cd to the top directory and issue 'make' command. It's a good - idea to direct stdout and stderr to a file so that you can - see what's being done afterwards. There will be a few warning - messages which you can ignore. This builds the server as well - as all the clients. - - If you only want to build the server (and the program for testing - your sever configuration file, and the program for converting the - file from the old format), use comannd 'make server' instead. - Use command 'make clients' to build only the client programs. You - can also build the individual clients using 'make RFINGER', - 'make RFTP', and 'make RTELNET', all from the top directory. - -3. All the man pages (except for libident) are in directory doc. - You are encouraged to print them out and read them before proceeding - to the next part. - -------------------------------------------------------------- - -HOW TO INSTALL THE SERVER - -1. Become superuser on the proxy server host for your site. - -2. cd to the top directory and issue 'make install.server'. - This installs programs sockd and test_sockd_conf as well - as the man pages for them. - -3. Add the line -socks 1080/tcp - to file /etc/services. It would be nice also to include -gopher 70/tcp -WWW 80/tcp - in the file if you don't already have them. - -4. Add the line -socks stream tcp nowait nobody /usr/etc/sockd sockd - to file /etc/inetd.conf. Use the actual path where sockd - is installed if not in /usr/etc. If you want to make use of - identd on your client machines when it is available, use -socks stream tcp nowait nobody /usr/etc/sockd sockd -i - If you want to REQUIRE identd be run on your client machines, - use -socks stream tcp nowait nobody /usr/etc/sockd sockd -I - Running sockd with -I will reject all requests from hosts that - do not run identd. - -5. Set up access control with file /etc/sockd.conf. You have to - read the man pages for sockd, sockd.conf, and test_sockd_conf - for the details. - For a quick test, you can use these four lines in the file: (Replace - 'client_IP' with the IP address of the host on which you will be - testing the client programs.) -permit client_IP 255.255.255.255 -# One LONG line follows: -deny 0.0.0.0 0.0.0.0 : /usr/ucb/finger @%A | /usr/ucb/mail -s 'SOCKD: rejected -- from %u@%A to host %Z (service %S)' root -# Another LONG line: -#BAD_ID: /usr/ucb/finger @%A | /usr/ucb/mail -s '%U pretends to be %u on host %A' root@%A root -# Last line: -#NO_IDENTD: /usr/ucb/mail -s 'Please run identd on %A' %u@%A root@%A - This is essentially the contents of file sockd/sockd.conf.sample. - *** NOTE *** The meanings of 1's and 0's in address masks are - reversed from 4.0 and earlier versions. If you already have a working - /etc/sockd.conf with an earlier version, use the program - sockd/flip_cfmasks to produce one for the new version. - -6. If the server host is multi-homed and you built sockd with the - macro MULTIHOMED_SERVER in include/socks.h defined, you must - also supply the file /etc/sockd.route. For a typical dual-homed - server, this can simply be a one-liner: -out_interface 0.0.0.0 0.0.0.0 - where out_interface is the IP address of the server's network - interface leading to the outside world. The format for lines - in this file should be -# comments -Interface_addr dst_addr dst_mask - - Read the man page on sockd.route !!! - -7. Run a few tests using program test_sockd_conf to make sure you - have the configuration file set up correctly. On a multi-homed - server, the program also tests /etc/sockd.route and shows which - interface is to be used. - -8. Send a SIGHUP signal to the running inetd process so that it will - use the new configuration. You may also have to do other things to - accommodate syslog facility. Read the man pages. - -------------------------------------------------------------- - -HOW TO TEST THE CLIENT PROGRAMS - - NOTE: Build and install identd on your client hosts first. This is - required if you run sockd with -I option. It is a good idea anyway. - - Set up the file /etc/socks.conf on the client host. Lines in this - file should be of the form -# comments -deny [*=userlist] dst_addr dst_mask [op port] -direct [*=userlist] dst_addr dst_mask [op port] -sockd [@=serverlist] [*=userlist] dst_addr dst_mask [op port] - Fields in square brackets are optional. The optional @=serverlist - field with a 'sockd' line specifies the list of SOCKS servers - the client should try (in the given order) instead of the default - SOCKS server. If the @=serverlist part is omitted, then the default - SOCKS server is used. Commas are used in the userlist and serverlist - as separators, no white spaces are allowed. - - Read the man page on socks.conf !!! - - On a client host (for testing purpose, this can be the same as - the proxy server), the clients rfinger, rwhois, rftp, and rtelnet, - can be tried out without any additional setup on the - client host once the server is running. They should behave like - finger, whois, ftp, and telnet, respectively. rftp DOES - echo your password IF you are using 'anonymous' as the log-in name. - - Quite a lot of details of operations of both the clients and the - server are logged. Checking the contents of the log files may be - helpful when you run into problems. You should try using these - clients to connect to both inside and outside hosts and check the - log messages to see whether the correct ways are used. - -------------------------------------------------------------- - -HOW TO INSTALL CLIENT PROGRAMS - -1. Become superuser on the client host. - -2. cd to the top directory, then issue the command 'make install.clients'. - This installs rfinger, rwhois, rftp, rtelnet, and - their man pages. - -3. Rename your regular 'finger', 'whois', 'ftp', and 'telnet' - to something else. The new name for the 'finger' program - must be EXACTLY what you used for defining the macro ORIG_FINGER in - include/socks.h. Then either rename the SOCKS clients or use symbolic - links for them. For example, if you have installed the clients in - directory /usr/local/bin and your regular 'finger', 'whois', 'ftp', - and 'telnet' were in /usr/ucb, then you should do -ln -s /usr/local/bin/rfinger /usr/ucb/finger -ln -s /usr/local/bin/rftp /usr/ucb/ftp -ln -s /usr/local/bin/rhwois /usr/ucb/whois -ln -s /usr/local/bin/rtelnet /usr/ucb/telnet diff --git a/network/socks/socks.cstc.4.2/README.DK b/network/socks/socks.cstc.4.2/README.DK deleted file mode 100644 index e09e62f2..00000000 --- a/network/socks/socks.cstc.4.2/README.DK +++ /dev/null @@ -1,49 +0,0 @@ - - ##### - # # #### #### # # #### - # # # # # # # # - ##### # # # #### #### - # # # # # # # - # # # # # # # # # # - ##### #### #### # # #### - - -This system was described in a paper appearing the the 1992 USENIX -Security Simposium. This code has been in use at a variety of sites -for many years, and is now available for general consumption. - -One quick disclaimer, which is that documentation isn't up to snuff, -the best best thing available is the USENIX procedings. If you -notice something in particular lacking please let me know. - -I can reached at, for any questions comments or other sudgestions: - koblas@netcom.com - -What the directories contain: - - include -- Common include file for both the daemon and library - lib -- Standard library containting replacement calls - rfinger -- Example Rconnect() program, contains both finger & whois - rftp -- The standard BSD Networking release finger, copied - from ftp.uu.net, and modified to work with Socks - sockd -- The daemon that runs on the gateway host. - doc -- Some unfinished documentation - -*** The short and simple installation instructions: - -1) Look at the socks.h in the include directory, cusomize it for your site. - -2) Put the following line in your /etc/services file - socks 1080/tcp # Socks gateway service - -3) Cusomize sockd/sockd.conf to your sites needs - -4) Copy sockd/sockd and sockd/sockd.conf to your gateway host - -5) Add the following line to your /etc/inetd.conf file on the gateway - socks stream tcp nowait nobody /etc/sockd sockd - -6) Reload your inetd on the gateway host (kill -HUP <pid of inetd>) - -7) Test out rwhois or rfinger in the rfinger directory to see if - things are working. diff --git a/network/socks/socks.cstc.4.2/What_SOCKS_expects b/network/socks/socks.cstc.4.2/What_SOCKS_expects deleted file mode 100644 index daf974d0..00000000 --- a/network/socks/socks.cstc.4.2/What_SOCKS_expects +++ /dev/null @@ -1,48 +0,0 @@ - What SOCKS Expects In the Client Programs - - Ying-Da Lee - <ylee@syl.dl.nec.com> - -SOCKS is intended for easy conversion of existing network TCP client -programs. Towards that end, it expects that the programs are written -in a certain way. - -SOCKS only pays attention to six socket functions: connect(), bind(), -getsockname(), listen(), accept(), select(), and rcmd(). (select and -rcmd() do not apply to versions prior to version 4.2 of SOCKS.CSTC.) -SOCKS makes the following assumptions. - -1) Everything is done in TCP. - -2) The very first function invoked must be connect(), or rcmd(). - -3) If connect() is used on a non-blocking socket, no I/O should occur - on that socket until after another connect() with the same arguments - returns with -1 and errno indicating EISCONN. This is required even - if select() on write is used to check the readiness of that socket. - Also, while a connection is still pending, no attempts may - be made to start another connection via connect() or the bind()-- - getsockname()--listen()--accept() sequence. - -4) bind() is used after a successful connect() call to a host for a - specific service. It is used to establish an auxiliary TCP - session with the same host in the previous connect() call and for - the same service. - -5) bind() is followed by - - getsockname() - listen() - accept() - - in the order given above. - -Most client programs fit these assumptions very well; such programs -can be SOCKSified without changing the code at all using the steps -described in the file How_to_SOCKSified. - -Some client programs use a bind() before each connect(). If the bind() -is used to claim a specific port or a specific network interface, the -current SOCKS is not able to accommodate such use. Very often though, -such a bind() call is there for no reason at all, and should simply -be deleted. diff --git a/network/socks/socks.cstc.4.2/What_are_the_risks b/network/socks/socks.cstc.4.2/What_are_the_risks deleted file mode 100644 index e8bd387d..00000000 --- a/network/socks/socks.cstc.4.2/What_are_the_risks +++ /dev/null @@ -1,70 +0,0 @@ ->From daemon@inoc.dl.nec.com Wed Dec 1 17:44:07 1993 -Date: Wed, 1 Dec 93 17:42:55 CST -From: ylee@syl.dl.nec.com (Ying-Da Lee) -Message-Id: <9312012342.AA26065@florida.syl.dl.nec.com> -To: socks@inoc.dl.nec.com, zz5@dswpa.dsdoe.ornl.gov -Subject: Re: Comparing firewall packages... -Cc: ylee@syl.dl.nec.com -X-Mailing-List: socks@syl.dl.nec.com (SOCKS discussion list) -Status: RO - ->I will be working with SOCKS now. Any information would be ->appreciated. I just want to know how secure SOCKS is, and what ->guarantees can be made about it... Thanks. - -I don't know about guarantees. Should we start with 'as far as I -know, there is no way...' and see where it ends? - -As far as I know, there is no way to initiate an attack into your -firewalled internal network through SOCKS if your SOCKS server is -properly configured. For example, if your internal network is -200.100.50 and you put the line - -deny 0.0.0.0 0.0.0.0 200.100.50.0 255.255.255.0 - -at the top of your sockd.conf, the SOCKS server will fend off -all attempts to go through it to reach your inside hosts. No -routing tricks or IP address spoofing will make any difference. - -This is not to say that you are not incurring some risks by -running SOCKS. You are, but these are the risks/vulnerabilities -accompanying the applications you allow to run on top of SOCKS, -not with SOCKS itself. For example, doing any network communication -without encryption runs the risk of having your password or other -confidential information stolen, whether you use SOCKS or not. -Blindly "displaying" a postscript file can end in a disaster -regardless of whether you retrieved the file through SOCKS or -not. SOCKS doesn't add more on top of these risks, but it doesn't -help you deal with them either. - -Should it? - -It really can't if SOCKS is to remain a general purpose TCP relayer -without delving into the specific application protocols. This accounts -for the server's high effficiency. This independence of the application -protocol also makes it easy to convert an application program into a -SOCKS client. In addition, SOCKS probably will have a fairly easy time -accommodating security devices in the application protocols if and when -they are used. - -So, if on balance you find the security risks of existing telnet, ftp, -Mosaic, etc. outweigh their usefulness to you and you are unable or -unwilling to develop a more secure version, then SOCKS is not for you. -If the balance tilts the other way, welcome to SOCKS. - -I hope that's enough for a start. - - Ying-Da Lee (214)518-3490 (214)518-3552 (FAX) - Principal Member, Technical Staff - NEC Systems Laboratory, C&C Software Technology Center / - NEC USA, Corporate Network Administration Division - ylee@syl.dl.nec.com - -************** -The rest of this message was automatically appended by the socks list -mail munger. To send a message to the entire list, address it to: -socks@inoc.dl.nec.com. However, if you want to get off the list or -change your address, please send a message to socks-request@inoc.dl.nec.com, -and NOT the entire list. Thank you. -************** - diff --git a/network/socks/socks.cstc.4.2/bsdinstall b/network/socks/socks.cstc.4.2/bsdinstall deleted file mode 100644 index a24c87ad..00000000 --- a/network/socks/socks.cstc.4.2/bsdinstall +++ /dev/null @@ -1,27 +0,0 @@ -#!/bin/sh -# A BSD-like install script for SYSV systems. -# Written by Phil Hochstetler, phil@sequent.com -if [ $# -lt 2 ]; then - echo "Usage: install [-m ddd] srcfile dstdir" 1>&2 - exit 1 -fi -if [ X"$1" = X"-m" ]; then - CMD="chmod $2 $3" - shift - shift -else - CMD= -fi - -if [ X"$1" = X -o X"$2" = X -o X"$3" != X ]; then - echo "Usage: install [-m XXX] srcfile dstdir" 1>&2 - exit 1 -fi - -FILE="$1" -DIR="$2" -if [ ! -d "$DIR" ]; then - mkdir $DIR -fi - -cp $FILE $DIR && $CMD diff --git a/network/socks/socks.cstc.4.2/doc/Makefile b/network/socks/socks.cstc.4.2/doc/Makefile deleted file mode 100644 index 30135b5c..00000000 --- a/network/socks/socks.cstc.4.2/doc/Makefile +++ /dev/null @@ -1,25 +0,0 @@ -# Directory into which the man pages are to be installed. -MAN_DEST_DIR = /usr/local/man - -# The 'install' command is assumed to be the BSD variety (using -m to -# set the file mode). If the default 'install' on your system doesn't -# do that, you have to either specify an alternative one in the line below -# (e.g., /usr/ucb/install) or modify the other Makefile. -INSTALL= install -# UnixWare should use: -#INSTALL=/usr/ucb/install -# IRIX should use: -#INSTALL=bsdinstall -#======================================================== - -install: - for i in *.1; do \ - $(INSTALL) -m 444 $$i $(MAN_DEST_DIR)/man1 ;\ - done - for i in *.5; do \ - $(INSTALL) -m 444 $$i $(MAN_DEST_DIR)/man5 ;\ - done - for i in *.8; do \ - $(INSTALL) -m 444 $$i $(MAN_DEST_DIR)/man8 ;\ - done - diff --git a/network/socks/socks.cstc.4.2/doc/rfinger.1 b/network/socks/socks.cstc.4.2/doc/rfinger.1 deleted file mode 100644 index 15f6c1ee..00000000 --- a/network/socks/socks.cstc.4.2/doc/rfinger.1 +++ /dev/null @@ -1 +0,0 @@ -.so man1/socks_clients.1 diff --git a/network/socks/socks.cstc.4.2/doc/rftp.1 b/network/socks/socks.cstc.4.2/doc/rftp.1 deleted file mode 100644 index 15f6c1ee..00000000 --- a/network/socks/socks.cstc.4.2/doc/rftp.1 +++ /dev/null @@ -1 +0,0 @@ -.so man1/socks_clients.1 diff --git a/network/socks/socks.cstc.4.2/doc/rtelnet.1 b/network/socks/socks.cstc.4.2/doc/rtelnet.1 deleted file mode 100644 index 15f6c1ee..00000000 --- a/network/socks/socks.cstc.4.2/doc/rtelnet.1 +++ /dev/null @@ -1 +0,0 @@ -.so man1/socks_clients.1 diff --git a/network/socks/socks.cstc.4.2/doc/rwhois.1 b/network/socks/socks.cstc.4.2/doc/rwhois.1 deleted file mode 100644 index 15f6c1ee..00000000 --- a/network/socks/socks.cstc.4.2/doc/rwhois.1 +++ /dev/null @@ -1 +0,0 @@ -.so man1/socks_clients.1 diff --git a/network/socks/socks.cstc.4.2/doc/sockd.8 b/network/socks/socks.cstc.4.2/doc/sockd.8 deleted file mode 100644 index cb30c537..00000000 --- a/network/socks/socks.cstc.4.2/doc/sockd.8 +++ /dev/null @@ -1,136 +0,0 @@ -.TH SOCKD 8 "February 9, 1994" -.SH NAME -sockd \- Internet firewall secure socket server (proxy server) -.SH SYNOPSIS -\fBsockd [ \-ver | \-i | \-I ]\fP -.SH DESCRIPTION -\fIsockd \fR is an internet secure socket server, often referred to -as a proxy server. It was designed -primarily to provide hosts within a firewall access to resources -outside of the firewall. - -Normally, hosts inside a firewall has no IP-accessibility to the network -outside of the firewall. This reduces the risk of being intruded -by unauthorized people from the Internet. Unfortunately, without -IP-accessibility users on the inside hosts can no longer use many -of the important tools such as telnet, ftp, xgopher, Mosaic, etc. to -access the tremendous resources available in the Internet. - -With \fIsockd\fR installed on a server host, users on the other -inside hosts can gain back the lost functionalities by using -clients programs designed to work with \fIsockd\fR proxy server, -e.g, \fIrtelnet\fR in place of \fItelnet\fR, \fIrftp\fR in place -of \fIftp\fR, \fIrfinger\fR in place of \fIfinger\fR, -etc. Since these client programs work -like their normal counterparts without requiring direct IP-accessibility -to the Internet, convenience to the uesrs is accomplished without -breaching the security. The server host that runs \fIsockd\fR does -have to be open to the Internet, and it therefore requires special -attention to make sure that it is secure. - -\fIsockd\fR is usually installed in directory /usr/etc and should -be run under the control of \fIinetd\fR. To do so, -add the line - -.nf -.in +1 -socks 1080/tcp - -.fi -.in -1 -to file \fB/etc/services\fP, and the line - -.nf -.in +1 -socks stream tcp nowait nobody /usr/etc/sockd sockd - -.fi -.in -1 -to file \fB/etc/inetd.conf\fP. Then send a SIGHUP signal to the -running \fIinetd\fR process to make it read and use the new contents -of the files. You may also choose to use \fIidentd\fR (RFC 1413) to verify -the user's identity by appending option \fB\-i\fP or \fB\-I\fP to -the line in \fB/etc/inetd.conf\fP. - -A configuration file \fB/etc/sockd.conf\fP is used to control access -to \fIsockd\fR and its services. Permission and denial of a service -request can be decided based on various combinations of the requesting -host, the destination host, the type of service (destination port number), -as well as the requesting user. (See \fIsockd.conf\fP(5).) - -If the server host is multi-homed, i.e., having more than one network -interface and with its IP_FORWARDING turtned off, it must run a multi-homed -version of \fIsockd\fP, which requires another control file -\fB/etc/sockd.route\fP to decide which interface to use for connection -to any given destination host. See \fIsockd.route\fP(5). - -A program called \fItest_sockd_conf\fP is provided for you to check -your \fIsockd\fR configuration file(s). Be sure to use it everytime after -you modify the configuration file(s). - -\fIsockd\fR uses \fIsyslog\fR with facility \fBdaemon\fP and level -\fBnotice\fP to log its activities and errors. Typical lines look -like - -.nf -.in +1 -Apr 11 08:51:29 eon sockd[636]: connected -- Connect from don(don)@abc.edu to wxy.com (telnet) -Apr 11 09:24:59 eon sockd[636]: terminated -- Connect from don(don)@abc.edu to wxy.com (telnet) -Apr 11 09:24:59 eon sockd[636]: 1048 bytes from abc.edu, 285143 bytes from wxy.com -Jun 22 18:24:54 eon sockd[884]: refused -- Connect from sam(unknown)@big.com to small.com (ftp) -.in -1 -.fi - -In these lines, the first user-id is the one reported by the client program, -the second one (within the parentheses) is what is reported by \fIidentd\fP -on the client host. -These log lines usually appear in file \fB/var/adm/messages\fP though that -can be changed by modifying \fB/etc/syslog.conf\fP. (See \fIsyslogd\fR(8) -and \fIsyslog.conf\fR(5).) - -If you allow access to infosystems such as Gopher or WWW, -you should be aware that they by nature would tend to get connections -to hosts all over the world and would use not only Gopher and WWW ports -but possibly also ports for finger, telnet, ftp, nntp, etc. as well as -non-priveleged ports ( > 1023). -.SH OPTIONS -The options are mutually exclusive and thus may only be used one at a time. -.TP -.B\-ver -With this option, \fIsockd\fR prints its own version number, -whether it is a single-homed or multi-homed version, and whether -it supports clients that use Rrcmd(), and then quits. -.TP -.B\-I -Use \fIidentd\fR (RFC 1413) to verify the requester's user-id. Deny access if -connection to client's \fIidentd\fR fails or if the result does not match -the user-id reported by the client program. Client hosts without a properly -installed \fIidentd\fR daemon will not be served. User verification is -done before and in addition to the normal access control. -.TP -.B\-i -Similar to \fB-I\fP but more lenient. Access is denied only if client's -\fIidentd\fR reports a user-id that's different from what the client -program claims. -.PP -Log entries similar to the following are produced upon failure of -user-id verification: - -.nf -.in +1 -Apr 15 14:42:51 eon sockd[729]: cannot connect to identd on big.edu -Apr 15 14:42:51 eon sockd[729]: refused -- Connect from bob(unknown)@big.edu to xyz.com (ftp) -Jul 15 12:23:06 eon sockd[832]: *Alert*: real user is sam, not jim -Jul 15 12:23:06 eon sockd[832]: refused -- Connect from jim(sam)@abc.org to bad.place.com (WWW) -.in -1 -.fi -.SH FILES -\fB/etc/sockd.conf\fP, \fB/etc/inetd.conf\fP, \fB/etc/services\fP, -\fB/var/adm/messages\fP, \fB/etc/syslog.conf\fP -.SH SEE ALSO -\fIsocks_clients\fP(1), \fItest_sockd_conf\fP(8), \fIsockd.conf\fp(5), -\fIsockd.route\fP(5), \fIsocks.conf\fP(5) -.SH AUTHOR -.nf -David Koblas, koblas@sgi.com -Ying-Da Lee, ylee@syl.dl.nec.com diff --git a/network/socks/socks.cstc.4.2/doc/sockd.conf.5 b/network/socks/socks.cstc.4.2/doc/sockd.conf.5 deleted file mode 100644 index 19d1c2d0..00000000 --- a/network/socks/socks.cstc.4.2/doc/sockd.conf.5 +++ /dev/null @@ -1,195 +0,0 @@ -.TH SOCKD.CONF 5 "February 9, 1994" -.SH NAME -sockd.conf \- SOCKS server configuration file -.SH SYNOPSIS -\fB/etc/sockd.conf\fP -.SH DESCRIPTION -The file \fB/etc/sockd.conf\fP is used to control access -to SOCKS proxy server \fIsockd\fR and its services. (See \fIsockd\fP(8).) -Permission and denial of a service -request can be decided based on various combinations of the requesting -host, the destination host, the type of service (destination port number), -as well as the requesting user. A line in \fB/etc/sockd.conf\fP can be -up to 1023 characters long. Each line may contain the following fields -in the indicated order: - -.in +1 -\fIaction [\fB?=\fIuse_idend] [\fB*=\fIuserlist] src_addr src_mask [dst_addr dst_mask] [op dst_port] [ : shell_cmd ]\fR - -.in -1 -Spaces and tabs separate the fields. Fields enclosed in square brackets -are optional. Blank -lines are allowed. Except for lines that start with \fB#NO_IDENTD:\fP or -\fB#BAD_ID:\fP, everything from the first appearance of \fB#\fP to -the end of the line is considered comment and thus ignored by \fIsockd\fP -during normal validation. - -The \fIaction\fR field -must be either \fBpermit\fP or \fBdeny\fP -and indicates the action to be taken if a request matches the conditions -specified in that line. - -The \fIuse_identd\fR field, when present, must be \fBI\fP, \fBi\fP, or -\fBn\fP, and is used to specify whether \fIidentd\fR verification should be -employed for the current line. \fB?=I\fP demands the use of -\fIidentd\fR for verifying the user's identity, denying access if connection -to client's \fIidentd\fR fails or if the result does not match the user-id -reported by the client program. \fB?=i\fP also specifies the use of -\fIidentd\fR, but denies access only if client's \fIidentd\fR reports a user-id -different from what the client program claims. \fB?=n\fP turns off the -use of \fIidentd\fP. For the line in which these fields are used, they -override the global \fIidentd\fR setting, which is determined by options -\fB-I\fP and \fB-i\fP on the \fIsockd\fR command line. - -The \fIuserlist\fR field, when present, consists of -one or more user-ids or filenames, with comma as separator. No spaces -or tabs are allowed in the list. The user-ids should be ids of users on the -requesting host, not those on the destination host or the SOCKS server host. -The filenames must be full pathnames with the leading \fB/\fP. Inside -the specified files, user-ids may be listed one or several per line, -with any combination of blanks, tabs, and commas as separators. The -appearance of \fB#\fP marks the remainder of the line as comment. Each -line in the files may be up to 1023 characters long. -If the \fB*=\fIuserlist\fR field is omitted, the line applies to all user-ids. - -The \fIsrc_addr\fR and \fIdst_addr\fR fields specify IP addresses -of hosts, networks, or subnets in the usual dotted form, e.g., -\fB129.201.4.0\fP. The \fIsrc_mask\fR and \fIdst_mask\fR fields -are masks for the corresponding IP addresses. -Bits in these masks that are set to 0 indicate the bit positions -to be ignored during comparisons of IP addresses. -So, specifying 255.255.255.255 in the mask demands an exact match with the -specified IP address field, whereas 0.0.0.0 in the mask -causes a match no matter what IP address is specified. (NOTE: This is the -same way netmaks are usually interpreted, and is the opposite of the -interpretation in previous versions of \fIsockd\fP.) If the -\fIdst_addr dst_mask\fP pair is omitted, the line applies to all -destination hosts. - -The \fIop\fR field must be -\fBeq\fP, \fBneq\fP, \fBlt\fP, \fBgt\fP, \fBle\fP, or \fBge\fP, -for the condition of equal, not equal, less than, greater than, -less than or equal, and greater than or equal, respectively. -The \fIdst_port\fR field can be either a port number, e.g., 23, -or the equivalent service name as specified in the file /etc/services, -e.g., \fBtelnet\fP for port number 23. If this pair is omitted, the -line applies to all services, i.e., all destination port numbers. - -For example, consider the line - -.in +1 -permit *=root,clivep 128.103.4.10 255.255.255.255 179.200.20.0 255.255.255.0 le 1023 - -.in -1 -To match the conditions indicated in this line, a request must come -from a user named 'root' or 'clivep' on the host whose IP address is -128.103.4.10 exactly, the destination host must have 179.200.20 in the -first three bytes of its IP address (the last byte -doesn't matter), and the service must use a port number -less than or equal to 1023 on the destination host. Since the \fIaction\fR -field is \fBpermit\fP, such requests will be granted. - -When a request is received by \fIsockd\fR, it checks against the lines -in file \fB/etc/sockd.conf\fP, one line at a time. Once it finds a line -with conditions that are matched by the request, the request is either -granted or denied based on the \fIaction\fR field of that line. The -remaining lines of file \fB/etc/sockd.conf\fP are skipped. If no matching -line is found in the entire file, the request is denied. - -Be very careful how you order the lines in file \fB/etc/sockd.conf\fP. -The following two lines in the indicated order - -.nf -.in +1 -deny *=abxyz 128.140.13.24 0.0.0.0 -permit 128.140.13.24 0.0.0.0 - -.fi -.in -1 -disallow all requests by user 'abxyz' from host 128.140.13.24, but -allow all requests by other users from the same host. Switch the order -of the two lines and even requests by user 'abxyz' are granted. - -The \fIshell_cmd\fR field specifies a command string that is executed -when the conditions on that line are satisfied. The following substitutions -occur before the string is presented to the Borne shell for execution: -.nf -.in +1 - -%A -- replaced by the client host's domainname if known, by its IP address otherwise -%a -- replaced by the client host's IP address -%c -- replaced by "connect" or "bind", the command \fIsockd\fP is asked to execute -%p -- replaced by the process id of \fIsockd\fP -%S -- replaced by the service name (e.g., ftp) if known, by the destination port number otherwise -%s -- replaced by the destination port number -%U -- replaced by the user-id reported by \fIidentd\fP -%u -- replaced by the user-id reported by the client program -%Z -- replaced by the destination host's domainname if known, by its IP address otherwise -%z -- replaced by the destination host's IP address -%% -- replaced by a single % - -.fi -.in -1 -Several shell commands can be strung together in the usual way. For example, -.nf - -.in +1 -/usr/ucb/finger @%A | /usr/ucb/mail -s 'SOCKS: rejected %u@%A to %Z (%S)' root root@%A - -.in -1 -.fi -will \fIfinger\fP the client host and pipe the result into an email message -for superusers at the server host and the client host with an appropriate -Subject line. Most often this feature is used with a \fBdeny\fP line, but -it can be used with \fBpermit\fP also. - -Although there is an implied 'deny all' at the end of the configuration file, -you may supply one explicitly so as to take some specific action when requests -are so rejected, e.g., (in one continuous line), -.nf -.in +1 - -deny 0.0.0.0 0.0.0.0 : /usr/ucb/finger @%A | - /usr/ucb/mail -s 'SOCKS: rejected %u@%A to %Z (%S)' root root@%A - -.fi -.in -1 -You may also specify in \fB/etc/sockd.conf\fP commands to be executed when -\fIsockd\fP cannot connect to client's \fIidentd\fP or when the user-ids -reported by the client programs and the client's \fIidentd\fP do not match. -These special entries must have \fB#NO_IDENTD:\fP and \fB#BAD_ID:\fP at the very -beginning of the line, followed by the shell commands to be excuted. For -example: -.nf -.in +1 - -#NO_IDENTD: /usr/ucb/mail -s 'Please run identd on host %A' root@%A -#BAD_ID: finger @%A | /usr/ucb/mail -s '%U pretends to be %u on %A' root root@%A - -.fi -.in -1 -A program called \fItest_sockd_conf\fP is provided for you to check -your \fIsockd\fR configuration file. Be sure to use it everytime after -you modify the configuration file. See \fItest_sockd_conf\fP(8). - -Strictly speaking, \fIsockd\fP has no concept of inside/outside, it -does know which is the requesting host and which the destination -and that is the basis of its access control. Therefore it can be used -to facilitate -access from outside world into your internal networks as well. Needless to -say, you have to take extreme caution if you choose to do so. If you -don't need that kind of access, it is recommended that you specifically -deny such connections in \fBsokcd.conf\fR. For example, if the Class B -network 129.1 is your internal network, use - -.nf -.in +1 -deny 0.0.0.0 0.0.0.0 129.1.0.0 255.255.0.0 -.fi -.in -1 - -as the first line of your \fBsockd.conf\fP to protect your inside hosts -from all attempts of access from the outside world through SOCKS. -.SH SEE ALSO -\fIsockd\fP(8), \fIsockd.route\fP(5), \fItest_sockd_conf\fP(8), -\fIsocks.conf\fP(5), \fIsocks_clients\fP(1) diff --git a/network/socks/socks.cstc.4.2/doc/sockd.route.5 b/network/socks/socks.cstc.4.2/doc/sockd.route.5 deleted file mode 100644 index f09957b1..00000000 --- a/network/socks/socks.cstc.4.2/doc/sockd.route.5 +++ /dev/null @@ -1,79 +0,0 @@ -.TH SOCKD.ROUTE 5 "November 17, 1993" -.SH NAME -sockd.route \- Routing file for multi-homed SOCKS proxy server -.SH SYNOPSIS -\fB/etc/sockd.route\fP -.SH DESCRIPTION -The file \fB/etc/sockd.route\fP is used by a multi-homed SOCKS server -\fIsockd\fP to determine which of its network interfaces it should -use to reach a given destination host. - -A multi-homed host is a host with more than one network interfaces -and with its IP_FORWARDING turned off. Only the multi-homed version of -\fIsockd\fP can be run on such hosts. Hosts which have a single -network interface or that have enabled IP_FORWARDING -- even -with multiple network interfaces -- can run the single-homed version -of \fIsockd\fP, which requires no use of \fB/etc/sockd.route\fP. - -A line in the file can be up to 1024 characters long. Lines starting -with a `#' are comments. Non-comment lines must be of the form - -\fIif_addr dst_addr dst_mask\fR - -All three fields are required and are separated by spaces or tabs. -Each filed is specified in the usual dotted form of IP addresses, -e.g., 128.23.16.2. -\fIif_addr\fR must be the IP address of one of the network interfaces -on the SOCKS server host. The \fIdst_addr dst_mask\fR pair together -specify the destination IP address or a range of destination IP -addresses. Bits in \fIdst_mask\fP that are set to 0 indicate the -bit positions to be ignored during comparison of IP addresses. So, -specifying 255.255.255.255 in \fIdst_mask\fP demands an exact match -with \fIdst_addr\fP, whereas 0.0.0.0 in \fIdst_mask\fP causes a -matching with any given destination address regardless of what is -specified for \fIdst_addr\fP. - -When a multi-homed \fIsockd\fP receives a network request, it first -checks with \fB/etc/sockd.conf\fP to decide whether the request -should be allowed or denied. For an allowable request, \fIsockd\fP -then checks the given destination IP address against the \fIdst_addr -dst_mask\fP pair in \fB/etc/sockd.route\fP, one line at a line. Once -a match is found, the network interface of the corresponding -\fIif_addr\fR field is used for connection to the destination host. -Remaining lines in the file are skipped. Therefore the order of the -lines in the file is of extreme importance. If no match is found -throughout the file, a line indicating the error is produced using -\fIsyslog\fP with facility \fBdaemon\fP and level \fIerr\fP and -\fIsockd\fP then terminates. - -The program \fItest_sockd_conf\fP checks \fB/etc/sockd.conf\fR as well -as the regular configuration file \fB/etc/sockd.conf\fP. -See \fItest_sockd_conf\fP(8). - -.SH EXAMPLES -Suppose you have a dual-homed host with interface 129.1.2.3 connecting -to your internal Class B network 129.1, and interface 129.1.254.1 -connecting to the outside world. If you only use the SOCKS server -to provide connections to outside hosts, then the file \fB/etc/sockd.route\fP -only needs one line: - -.nf -.+1 -129.1.254.1 0.0.0.0 0.0.0.0 -.fi -.-1 - -If you also use the SOCKS server to provide connection to internal -hosts as well, then two lines would suffice: - -.nf -.+1 -129.1.2.3 129.1.0.0 255.255.0.0 -129.1.254.1 0.0.0.0 0.0.0.0 -.fi -.-1 - -Note that these two lines must be in the order given above. -.SH SEE ALSO -\fIsockd\fP(8), \fIsockd.route\fP(5), \fItest_sockd_conf\fP(8), -\fIsocks.conf\fP(5), \fIsocks_clients\fP(1) diff --git a/network/socks/socks.cstc.4.2/doc/socks.conf.5 b/network/socks/socks.cstc.4.2/doc/socks.conf.5 deleted file mode 100644 index b2241a84..00000000 --- a/network/socks/socks.cstc.4.2/doc/socks.conf.5 +++ /dev/null @@ -1,142 +0,0 @@ -.TH SOCKS.CONF 5 "February 9, 1994" -.SH NAME -.nf -socks.conf \- SOCKS clients configuration file -.fi -.SH SYNOPSIS -/etc/socks.conf -.SH DESCRIPTION -All SOCKS client programs use this file to determine whether to -use direct or proxy connection to a given destination host, and -to exert access control based on the destination host, the requested -service (port number on the destination host), and the effective user-id -of the requesting local user. If this file is absent, SOCKS clients will -only try direct connections, making them behave like their regular couterparts. - -Each line in the file may be up to 1024 characters long. -Lines starting with a \fB#\fP are comments. Non-comment lines must be -of one of the three forms: - -.nf -.+1 -\fBdeny \fI[\fB*=\fIuserlist] dst_addr dst_mask [op dst_port] [: shell_cmd]\fP -\fBdirect \fI[\fB*=\fIuserlist] dst_addr dst_mask [op dst_port] [: shell_cmd]\fP -\fBsockd \fI[\fB@=\fIserverlist] [\fB*=\fIuserlist] dst_addr dst_mask [op dst_port] [: shell_md]\fR -.-1 -.fi - -A \fBdeny\fP line tells the SOCKS clients when to reject a request. -A \fBdirect\fR lines tells when to use a direct connection. A \fBsockd\fR -line indicates when to use a proxy connection and, optionally, which -SOCKS proxy server or servers it should try. - -Spaces and tabs separate the fields. Fields enclosed in sqaure brackets -are optional. - -The \fIuserlist\fR field, when present, consists of -one or more user-ids or filenames, with comma as separator. No spaces -or tabs are allowed in the list. The user-ids should be ids of users on the -local host, not those on the destination host or the SOCKS server host. -The filenames must be full pathnames with the leading \fB/\fP. Inside -the specified files, user-ids may be listed one or several per line, -with any combination of blanks, tabs, and commas as separators. The -appearance of \fB#\fP marks the remainder of the line as comment. Each -line in the files may be up to 1023 characters long. -If the \fB*=\fIuserlist\fR field is omitted, the line applies to all user-ids. - -The \fIdst_addr dst_mask\fP pair together specify the destination IP address -or the range of destination IP addresses. They are both given in the -usual dotted form, e.g., 129.1.2.3. Bits in \fIdst_mask\fP that are set -to 0 indicate the bit positions which should be masked off (i.e., ignored) -during comparison of \fIdst_addr\fP and the actual destination IP address. -So specifying 255.255.255.255 in \fIdst_mask\fP demands an exact match -with \fIdst_addr\fP, whereas 0.0.0.0 in \fIdst_mask\fP causes an address -match no matter what is specified for \fIdst_addr\fP. (NOTE: This is the -same way netmasks are interpreted, but is the direct opposite of how the -address masks are used in cisco router's access-lists.) - -The \fIop\fP field must be \fBeq\fR, \fBneq\fR, \fBlt\fR, \fBgt\fR, -\fBle\fR, or \fBge\fR, for the condition of equal, not equal, less than, -greater than, less than or equal, and greater than or equal, respectively. -The \fIdst_port\fP field can be either a port number, e.g., 23, or the -equivalent service name as specified in file /etc/services, e.g., \fBtelnet\fR -for port number 23. If this pair is omitted, the line applies to all -services. - -The \fIserverlist\fP, which may only be used in a \fBsockd\fR line, -consists of one or more SOCKS proxy servers, which the client program should -try to use (in the indicated order) for establishing a proxy connection. -Only commas can be used as separator, no spaces -or tabs are allowed in the list. Domain names of the servers may be used -in the list, though it is probably more prudent to specify IP addresses. -If this field is omitted, the client program will use the -default SOCKS proxy server, which is determined by the environment variable -\fBSOCKS_SERVER\fR if it exists, or the name compiled into the SOCKS client -program otherwise. - -Consider - -.nf -.+1 -sockd @=1.2.3.4 *=boss,root 11.12.13.14 255.255.255.255 eq telnet -.-1 -.fi - -To match the condition indicated in this line, a request must come from -a local user whose effective id is either boss or root, the detination -IP address must be 11.12.13.14 exactly, and the service requested must -be telnet. In that case, connection to host 11.12.13.14 should be done -via a SOCKS proxy server on host 1.2.3.4. - -Every time a SOCKS client has to make a network connection, it checks -the pending request against the file \fB/etc/socks.conf\fR, one line at -a time. Once it finds a line with conditions that are matched by the -request, the action specified on that line is taken. The remaining -lines of file \fB/etc/socks.conf\fR are skipped. So the order of the -lines in the file is extremely important; switch two lines and you may -have entirely different results. If no matching line -is found throughout the file, the request is denied. - -The \fIshell_cmd\fR field specifies a command string that is executed -when the conditions on that line are satisfied. The following substitutions -occur before the string is presented to the Borne shell for execution: -.nf -.in +1 - -%A -- replaced by the client host's domainname if known, by its IP address otherwise -%a -- replaced by the client host's IP address -%c -- replaced by "connect" or "bind" -%p -- replaced by the process id of the client program -%S -- replaced by the service name (e.g., ftp) if known, by the destination port number otherwise -%s -- replaced by the destination port number -%U -- replaced by the user-id at login -%u -- replaced by the effective user-id -%Z -- replaced by the destination host's domainname if known, by its IP address otherwise -%z -- replaced by the destination host's IP address -%% -- replaced by a single % - -.fi -.in -1 -Several shell commands can be strung together in the usual way with `|', -`;', etc. - -Although there is an implied 'deny all' at the end of the control file, -you may supply one explicitly so as to take some specific action when requests -are so rejected, e.g., -.nf -.in +1 - -deny 0.0.0.0 0.0.0.0 : /usr/ucb/mail -s 'SOCKS: rejected %S from %u to %Z' root - -.fi -.in -1 -Unlike the previous version, connection to address 127.0.0.1 or 0.0.0.0 -is always done directly to localhost, so there is no need to specify -either of them in -\fB/etc/socks.conf\fP. -.SH ENVIRONMENT -\fBSOCKS_SERVER\fR, if defined, specifies the name or IP address of the -SOCKS proxy server host to use, overriding the default server -compiled into the programs. -.SH SEE ALSO -\fIsockd\fP(8), \fIsocks_clients\fP(1), \fIsockd.conf\fP(5) diff --git a/network/socks/socks.cstc.4.2/doc/socks_clients.1 b/network/socks/socks.cstc.4.2/doc/socks_clients.1 deleted file mode 100644 index 341b0902..00000000 --- a/network/socks/socks.cstc.4.2/doc/socks_clients.1 +++ /dev/null @@ -1,97 +0,0 @@ -.TH SOCKS_CLIENTS 1 "November 16, 1993" -.SH NAME -.nf -rfinger \- SOCKS client version of finger -rftp \- SOCKS client version of ftp -rtelnet \- SOCKS client version of telnet -rwhois \- SOCKS client version of whois -.fi -.SH SYNOPSIS -See the man pages on \fIfinger\fP(1), \fIftp\fP(1), \fItelnet\fP(1), -\fIwhois\fP(1). -.SH DESCRIPTION -These programs provide the well-known functionalities to hosts within -a firewall. Normally, when a firewall is constructed, IP-accessibility -across the firewall is cut off to reduce security risk to hosts within -the firewall. As a result, inside hosts can no longer use many of the -well-known tools directly to access the resources outside the firewall. - -These programs restore the convenience of the well-known tools while -maintaining the security requirement. Though the programs differ very -much from their counterparts in the use of the communication scheme, -they should behave almost indistinguishably to the users. Note though -that rftp does echo the password as you type it in if you are using -\fIanonymous\fP as log-in name. Unlike those of the previous versions, -these are "versatile" clinets, meaning that they can be used for -connections to inside hosts directly and to outside hosts via SOCKS -proxy servers. So they can be used as replacements of their traditional -counterparts. - -When any of these programs starts, if the environment variable -\fBSOCKS_BANNER\fR is defined, the program prints to \fBstderr\fP -its version number and -the name or IP address of its default SOCKS proxy server. -It then consults the configuration file \fB/etc/socks.conf\fP to -determine whether a request should be allowed or denied based on the -requesting user, the destination host, and the requested service. For -allowable requests, the configuration file also dictates whether -direct or proxy connection should be used to the given destination, -and optionally the actual SOCKS servers to use for the proxy connection. -See \fIsocks.conf\fP(5). If the file is absent, these programs will -only try direct connections to the destination hosts, making them -behaving like their regular counterparts. - -You can use environment variable \fBSOCKS_NS\fR to set the nameserver for -domainname resolutions. Be sure you use the IP address of the -nameserver you want to use, not its domainname. If \fBSOCKS_NS\fR doesn't -exist, the IP address defined by the symbol \fBSOCKS_DEFAULT_NS\fR -at compile time is used if the programs were compiled with that symbol -defined. Otherwise the nameservers specified in \fB/etc/resolv.conf\fR -are used. - -All the client programs uses \fIsyslog\fP with facility \fBdaemon\fR -and level \fBnotice\fR to log their activities. -These log lines usually appear in file \fB/var/adm/messages\fP though -that can be changed by modifying \fB/etc/syslog.conf\fR. (See -\fIsyslogd\fP(8) and \fIsyslog.conf\fP(5).) -Typical lines look like - -.nf -.in +1 -Apr 11 10:02:23 eon rfinger[631]: connect() from don(don) to abc.com (finger) using sockd at socksserv -May 10 08:39:07 eon rftp[603]: connect() directly from blue(blue) to xyz.edu (ftp) -May 10 08:39:09 eon rftp[603]: bind() directly from blue(blue) for xyz.edu (ftp) -May 18 13:31:19 eon rtelnet[830]: connect() from root(jon) to xyz.edu (telnet) using sockd at sockd2 -May 18 14:51:19 eon rtelnet[921]: refused -- connect() from jon(jon) to xyz.edu (telnet) -.in -1 -.fi - -Of the two user-ids appearing in each log line, the first is the -effective user-id when the program is invoked, the second (that -within the parentheses) is the one used at login. Access -control applies to the effective user-ids. -.SH SEE ALSO -\fIsockd\fP(8), \fIfinger\fP(1), \fIftp\fP(1), \fItelnet\fP(1), -\fIwhois\fP(1) -.SH ENVIRONMENT -\fBSOCKS_SERVER\fR, if defined, specifies the name or IP address of the -SOCKS proxy server host to use, overriding the default server -compiled into the programs. - -\fBSOCKS_NS\fR, if defined, specify the IP address of the domain nameserver -that should be used for name resolution, overriding both the definition -of symbol \fBSOCKS_DEFAULT_NS\fR and the file \fB/etc/resolv.conf\fR. - -\fBORIG_FINGER\fR, if defined, specified the (altered) full pathname of -the original -finger program, which should have been renamed before installing the -rfinger as the regular finger. The \fIrfinger\fP program invokes -the original \fIfinger\fP program to lookup information on local users. -Normally this name should be compiled directly into \fIrfinger\fP, avoiding -the need for this environment variable. Use \fBORIG_FINGER\FR only if -you want to override what is compiled into \fIrfinger\fP. - -.SH AUTHOR -David Koblas, koblas@netcom.com -.PP -Ying-Da Lee, ylee@syl.dl.nec.com diff --git a/network/socks/socks.cstc.4.2/doc/test_sockd_conf.8 b/network/socks/socks.cstc.4.2/doc/test_sockd_conf.8 deleted file mode 100644 index 9fccc295..00000000 --- a/network/socks/socks.cstc.4.2/doc/test_sockd_conf.8 +++ /dev/null @@ -1,200 +0,0 @@ -.TH TEST_SOCKD_CONF 8 "August 6, 1993" -.SH NAME -test_sockd_conf \- Test the configuration file of \fIsockd\fR proxy server -.SH SYNOPSIS -\fBtest_sockd_conf [ \-I | \-i | \-B ] [ \-R \fIroute_file\fB] [ \-C \fIsockd_conf\fB ] \fIuser src_addr dst_addr dst_port\fR -.SH DESCRIPTION -\fItest_sockd_conf\fR is used for testing whether your configuration file -for the \fIsockd\fR proxy server is set up correctly. See \fIsockd\fR(8) -and \fIsockd.conf\fP(5) for details on the proxy server and the format -of the configuration file. - -\fIsockd\fR uses the configuration file to determine whether a request -for its service should be granted or denied, based on who the requesting -user is, from which host the request originates, which host the -request is trying to reach, and to which port number the request -is trying to connect. It is not always obvious by looking at the -configuration file whether it indeed grants all legitimate service requests -and blocks all undesirable ones. You can use \fItest_sockd_conf\fR to -make sure that the configuration does what you want it to do. - -For the multi-homed version of \fIsockd\fP, this program also checks -the routing file \fI/etc/sockd.route\fP to indicated which interface -on the server host will be used to reach the destination host. See -\fIsockd.route\fP(5). - -\fIuser\fR is the id of an user on the request host. \fIsrc_addr\fR is -the IP address of the request host. \fIdst_addr\fR is the IP address of -the destination host. You may use domain names in place of the IP addresses -if your system can resolve the names properly. \fIdst_port\fR is the -port number on the destination host that the request wants to connect to. -It can be replaced by the equivalent services name as specified in -file \fB/etc/services\fP, e.g., \fBtelnet\fP and 23 are equivalent -in this field. - -These parameters together forms a hypothetical service request which -\fItest_sockd_conf\fR feeds to the access control mechanism of \fIsockd\fR. -\fItest_sockd_conf\fR echoes the aguments, then prints either the line in the -configuration file which matches the request if one is found or -an indication that access is denied if no match if found in the entire file. -If the matching line contains the optional shell command field, the command(s) -will be executed. The program also produces log entries similar to what -\fIsockd\fR does, which usually appear in file \fB/var/adm/messages\fP. -You can also test the special entries #NO_IDENTD: and #BAD_ID: by specifying -option \fB\-I\fP, \fB\-i\fP, or \fB\-B\fP. For multi-homed version, it also -search the routing file to decide which network interface should be used -for connection to the destination host. - -The program exits with code 1 if the request is permitted, 0 if denied. -If errors in the arguments are found, it exits with code -1. -.SH OPTION -.TP -\fB\-C\fI sockd_conf\fR -Use \fIsockd_conf\fR as the configuration file to be tested. File -\fB/etc/sockd.conf\fR is used by default. -.TP -.B\-I -Simulate the situation when \fIsockd\fR is run with option \fB\-I\fP and -the client host does not run \fIidentd\fP. -.TP -.B\-i -Simulate the situation when \fIsockd\fR is run with option \fB\-i\fP and -the client host does not run \fIidentd\fP. -.TP -.B\-B -Simulate the situation when \fIsockd\fR is run with either \fB\-I\fP or -\fB\-i\fP and the \fIidentd\fR on the client host reports a user-id -different from what the client program claims. -.TP -.B\-R\fI route_file\fR -Use \fIroute_file\fR as the routing file to be tested. File -\fB/etc/sockd.route\fR is used by default. This option is allowed only -with multi-homed version of SOCKS server. -.SH EXAMPLES -Assume that file \fB/etc/sockd.conf\fR consists of these lines: - -.nf -.in +1 -deny *=clyde 128.12.6.0 255.255.255.0 : /usr/ucb/mail -s 'Rejected SOCKS access by %u' root -permit *=root 128.12.6.4 255.255.255.255 137.12.0.0 255.255.0.0 -deny 128.12.0.0 255.255.0.0 eq telnet -permit 128.12.0.0 255.255.0.0 -#NO_IDENTD: /usr/ucb/mail -s 'please run identd on %A' root@%A -#BAD_ID: /usr/ucb/mail -s '%U pretends to be %u on %A' root - - -Also assume that the file \fB/etc/sockd.route\fR consists of these line: -129.10.1.2 10.0.0.0.0 255.0.0.0 -129.10.7.10 137.12.0.0 255.255.0.0 -129.10.254.1 0.0.0.0 0.0.0.0 -.in -1 - -Following are the results of a few tests. - -.nf -.in +1 -\fBtest_sockd_conf clyde 128.12.6.34 112.3.24.1 ftp\fR -USER:clyde, SRC:128.12.6.34, DST:112.3.24.1, PORT:21 -Line 1: deny *=clyde 128.12.6.0 255.255.255.0 : /usr/ucb/mail -s 'Rejected SOCKS access by %u' root -.in -1 -.fi -A mail message is sent to root with the subject line 'Rejected SOCKS -access by clyde'. -.in +1 -.nf - -\fBtest_sockd_conf root 128.12.6.4 137.12.4.15 telnet\fR -USER:root, SRC:128.12.6.4, DST:137.12.4.15, PORT:23 -Line 2: permit *=root 128.12.6.4 255.255.255.255 137.12.0.0 255.255.0.0 -==== Checking routing file (sockd.route)... -Line 2: 129.10.7.10 137.12.0.0 255.255.0.0 - -\fBtest_sockd_conf jane 128.12.2.13 137.12.4.15 telnet\fR -USER:jane, SRC:128.12.2.13, DST:137.12.4.15, PORT:23 -Line 3: deny 128.12.0.0 255.255.0.0 eq telnet - -\fBtest_sockd_conf jim 128.12.6.4 126.87.13.2 telnet\fR -USER:jim, SRC:128.12.6.4, DST:126.87.13.2, PORT:23 -Line 3: deny 128.12.0.0 255.255.0.0 eq telnet - -\fBtest_sockd_conf root 128.12.6.4 126.87.13.2 ftp\fR -USER:root, SRC:128.12.6.4, DST:126.87.13.2, PORT:21 -Line 4: permit 128.12.0.0 255.255.0.0 -==== Checking routing file (sockd.route)... -Line 3: 129.10.254.1 0.0.0.0 0.0.0.0 - -\fBtest_sockd_conf sam 128.12.36.7 10.53.23.1 70\fR -USER:sam, SRC:128.12.36.7, DST:10.53.23.1, PORT:70 -Line 4: permit 128.12.0.0 255.255.0.0 -==== Checking routing file (sockd.route)... -Line 1: 129.10.1.2 10.0.0.0 255.0.0.0 - -\fBtest_sockd_conf don 23.2.6.127 10.53.23.1 70\fR -USER:don, SRC:23.2.6.127, DST:10.53.23.1, PORT:70 - *** No match with any line. Access denied. - -\fBtest_sockd_conf clyde 128.12.1.62 112.3.24.1 ftp\fR -USER:clyde, SRC:128.12.1.62, DST:112.3.24.1, PORT:21 -Line 4: permit 128.12.0.0 255.255.0.0 -==== Checking routing file (sockd.route)... -Line 3: 129.10.254.1 0.0.0.0 0.0.0.0 - -\fBtest_sockd_conf -I joe 128.12.6.4 126.87.13.2 ftp\fR -USER:joe, SRC:128.12.6.4, DST:126.87.13.2, PORT:21 -Line 5: #NO_IDENTD: /usr/ucb/mail -s 'please run identd on %a' root@%A -Access denied: cannot verify user-id. -.in -1 -.fi -A mail message is sent to root of the host 128.12.6.4 with the -subject line 'please run identd on 128.12.6.4'. -.nf -.in +1 - -\fBtest_sockd_conf -i joe 128.12.6.4 126.87.13.2 ftp\fR -USER:joe, SRC:128.12.6.4, DST:126.87.13.2, PORT:21 -Line 5: #NO_IDENTD: /usr/ucb/mail -s 'please run identd on %a' root@%A -Line 4: permit 128.12.0.0 0.0.255.255 -==== Checking routing file (sockd.route)... -Line 3: 129.10.254.1 0.0.0.0 0.0.0.0 -.in -1 -.fi -A mail message is sent to root of the host 128.12.6.4 with the -subject line 'please run identd on 128.12.6.4'. -.nf -.in +1 - -\fBtest_sockd_conf -i jim 128.12.6.4 126.87.13.2 telnet\fR -USER:jim, SRC:128.12.6.4, DST:126.87.13.2, PORT:23 -Line 5: #NO_IDENTD: /usr/ucb/mail -s 'please run identd on %a' root@%A -Line 3: deny 128.12.0.0 0.0.255.255 eq telnet -.in -1 -.fi -A mail message is sent to root of the host 128.12.6.4 with the -subject line 'please run identd on 128.12.6.4'. -.nf -.in +1 - -\fBtest_sockd_conf -B joe 128.12.6.4 126.87.13.2 ftp\fR -USER:joe, SRC:128.12.6.4, DST:126.87.13.2, PORT:21 -Line 6: #BAD_ID: /usr/ucb/mail -s '%U pretends to be %u on %A' root -Access denied: bad user-id. -.in -1 -.fi -A mail message is sent to root with the -subject line 'unknown pretends to be joe on 128.12.6.4'. - -Note that lines in a configuration file may combine to act in a way -that could surprise you. Be sure you run through a thorough sequence -of tests after every modification. You may be caught -surprise if you only run tests on the types of -requests that you believe you are trying to affect. - -.SH FILES -\fB/etc/sockd.conf\fR, \fB/var/adm/messages\fP - -.SH SEE ALSO -\fIsockd\fR(8), \fIsockd.conf\fR(5), \fIsockd.route\fR(5), \fIsocks.conf\fR(5), -\fIsocks_clients\fR(1) - -.SH AUTHOR -Ying-Da Lee, ylee@syl.dl.nec.com diff --git a/network/socks/socks.cstc.4.2/include/bstring.h b/network/socks/socks.cstc.4.2/include/bstring.h deleted file mode 100644 index 9e36fa0c..00000000 --- a/network/socks/socks.cstc.4.2/include/bstring.h +++ /dev/null @@ -1,5 +0,0 @@ -/* for systems without bcopy(), bzero() and bcmp() */ -#include <string.h> -#define bcopy(b1,b2,len) memmove(b2, b1, (size_t)(len)) -#define bzero(b,len) memset(b, 0, (size_t)(len)) -#define bcmp(b1,b2,len) memcmp(b1, b2, (size_t)(len)) diff --git a/network/socks/socks.cstc.4.2/include/ptx-2.1.h b/network/socks/socks.cstc.4.2/include/ptx-2.1.h deleted file mode 100644 index f6ec5050..00000000 --- a/network/socks/socks.cstc.4.2/include/ptx-2.1.h +++ /dev/null @@ -1,32 +0,0 @@ -/* - * Argument type passed to the wait() call. If you don't know what it is, then - * leave it blank. The macro will place a pointer to the type for a cast... - * This will either be "union wait" or "int". - */ - -#define WAIT_ARG_TYPE int - -/* - * Argument type passed to the signal() call (second parameter). If you don't - * know what it is then don't define it.... this is placed in as a cast as-is. - */ - -#define SIGNAL_ARG_TYPE void(*)(int) - - -/* any additional missing headers */ - -#include <string.h> -#include <sys/stat.h> -#include <time.h> -#include <dirent.h> -#include <stdlib.h> - -/* any extra externs */ - -extern int h_errno; - -/* fix for missing gettimeofday() call */ - -#include <sys/procstats.h> -#define gettimeofday(t, tz) get_process_stats((t), PS_SELF, NULL, NULL) diff --git a/network/socks/socks.cstc.4.2/include/socks.h b/network/socks/socks.cstc.4.2/include/socks.h deleted file mode 100644 index eda1cf63..00000000 --- a/network/socks/socks.cstc.4.2/include/socks.h +++ /dev/null @@ -1,162 +0,0 @@ -/* - * Default SOCKS server host; you MUST set this for your site. - * This is overridden at run time by the contents of environment - * variable SOCKS_SERVER if it exists. - */ -#define SOCKS_DEFAULT_SERVER "SOCKS.server.for.your.site" - -/* - * Default Domain Nameserver for the SOCKS clients. - * Leave it undefined if all your client mechines can do general - * DNS lookup for all Internet hosts correctly with the DNS servers - * specified in /etc/resolv.conf. - * Otherwise, define it using the IP ADDRESS (NOT NAME!) of a DNS - * server which can resolve all Internet hosts and which is IP-reachable - * from your client machines. - * This is overriden at run time by the contents of environment - * variable SOCKS_NS if it exists. - */ -/* #define SOCKS_DEFAULT_NS "1.2.3.4" */ - -/* >>> jon r. luini <jonl@hal.com> */ -/* - * Default domain name to use for the resolver to use. - * Leave it undefined unless you run in an environment where - * you have a number of clients which will be running the socks - * utilities without the correct domain name specified in /etc/resolv.conf - * (or determined automatically by the system). If you try to run - * socks and it complains that it cannot lookup the local hostname, - * that is a good indication you need to define this appropriately. - * This is overriden at run time by the contents of environment - * variable SOCKS_DNAME if it exists. - */ -/* #define SOCKS_DEFAULT_DNAME "hal.COM" */ -/* <<< jon r. luini <jonl@hal.com> */ - -/* - * Make clients that connect through SOCKS server to destinations - * outside the firewall, but connect directly to destinations inside - * the firewall. You can then, for example, rename the regular 'telnet' - * to 'telnet.orig' and make a symbolic link for 'telnet' to point - * to 'rtelnet' and from then on use the command 'telnet' no matter - * whether the hosts you try to connect is inside or outside the - * firewall. - */ -#define VERSATILE_CLIENTS - -/* - * Full pathname of the regular 'finger' program. - * If you are making versatile clients, you will have to rename your - * regular 'finger' program to something else, e.g., from /usr/ucb/finger - * to /usr/ucb/finger.orig and the pathname you should use here is the - * new (altered) pathname, i.e., /usr/ucb/finger.orig. - */ -#define ORIG_FINGER "/usr/ucb/finger.orig" -/* Overridden at runtime by environment variable ORIG_FINGER if it exists. */ - -/* Control file for versatile clients */ -#define SOCKS_CONF "/etc/socks.conf" - -/* - * Default port number for SOCKS services. - * On the SOCKS server host, if the server is under inetd control, - * then the port must be specified in socks/tcp entry in /etc/services. - * For servers not under inetd control and for all clients, - * the port number is obtained from socks/tcp entry in /etc/services if - * it exists, otherwise the number defined by SOCKS_DEF_PORT will be used. - */ -#define SOCKS_DEF_PORT 1080 - -/* -** How long (in seconds) to keep a connection around while it is idle -*/ -#define SOCKS_TIMEOUT 2*60*60 /* 2hr in seconds */ - -/* How long before connection attempts timed out */ -#define CLIENT_CONN_TIMEOUT 60*2 /* 2 minutes */ -#define SOCKD_CONN_TIMEOUT 60*3 /* 3 minutes */ -/* You may have to adjust these to fit your network situation */ - -/* - * Where the config file lives on the SOCKS server host. - * This is the file that controls access to the SOCKS server - * and its services. - */ -#define SOCKD_CONF "/etc/sockd.conf" - -/* - * Define this if your SOCKS server is multi-homed (i.e., - * having two or more network interfaces) and is not behaving - * as a router (i.e., has its IP forwarding turned off). - * Leave it undefined otherwise. - */ -/* #define MULTIHOMED_SERVER */ - -/* - * For multi-homed servers, you must supply the file /etc/sockd.route - * to tell the program which interface to use for communicating with - * which destination networks/hosts. See sockd man pages for details. - * This has no effects if MULTIHOMED_SERVER is undefined. - */ -#define SOCKD_ROUTE_FILE "/etc/sockd.route" - -/* Current SOCKS protocol version */ -#define SOCKS_VERSION 4 - -#define CSTC_RELEASE "4.2 pre1" - -/* -** Response commands/codes -*/ -#define SOCKS_CONNECT 1 -#define SOCKS_BIND 2 -#define SOCKS_RESULT 90 -#define SOCKS_FAIL 91 -#define SOCKS_NO_IDENTD 92 /* Failed to connect to Identd on client machine */ -#define SOCKS_BAD_ID 93 /* Client's Identd reported a different user-id */ - -#if defined(__alpha) -typedef unsigned int u_int32; -#else -typedef unsigned long u_int32; -#endif - -typedef struct { - u_int32 host; /* in network byte order */ - unsigned short port; /* in network byte oreder */ - unsigned char version; - unsigned char cmd; -} Socks_t; - -/* - * Define NOT_THROUGH_INETD if you want a standalone SOCKS server, - * one which is not under the control of inetd. - * This is not recommended. - */ -/* #define NOT_THROUGH_INETD */ - -/* - * Maximum number of concurrent clients a SOCKS server will support. - * Meaningful only if the server is not under the control - * of inetd, i.e., when NOT_THROUGH_INETD is defined. - */ -#define MAX_CLIENTS 5 - -#ifdef SOLARIS -/* for bcopy(), bzero() and bcmp() */ -#include "bstring.h" -#endif - -/* Define NO_SYSLOG to suppress logging */ -/* -#define NO_SYSLOG - -#if defined(NO_SYSLOG) -# define syslog -# define openlog -#endif -*/ - -# define SYSLOG_FAC LOG_DAEMON -# define LOG_LOW LOG_NOTICE -# define LOG_HIGH LOG_ERR diff --git a/network/socks/socks.cstc.4.2/lib/Makefile b/network/socks/socks.cstc.4.2/lib/Makefile deleted file mode 100644 index 5c742544..00000000 --- a/network/socks/socks.cstc.4.2/lib/Makefile +++ /dev/null @@ -1,113 +0,0 @@ -#CC=gcc - -# Define RCMD and SUPPORT_RCMD if you want to use the library -# for rlogin, rsh, and rcp. -SUPPORT_RCMD=-DSUPPORT_RCMD -RCMD=Rrcmd.o - -# Comment out next macro to produce library compatible with -# clients SOCKSified for SOCKS.CSTC 4.1 and 4.0 -SHORTENED_RBIND=-DSHORTENED_RBIND - -# You should not have to define the next macro -#NO_GUESSING_REMHOST=-DNO_GUESSING_REMHOST - -# Directory into which socks_clients's man page files will be installed: -MAN_DEST_DIR=/usr/local/man - -# If you want to install the SOCKS library into /usr/locallib, -# uncomment the next line: -#LIB_DEST_DIR=/usr/locallib -# Installing the library in /usr/locallib makes it possible to -# use '-lsocks' with cc or ld command to search the library. -# /usr/lib and /lib may also be used instead of /usr/local/lib. - -# Remember to include -Dindex=strchr in OTHER_CFLAGS if -# you don't have index() (Sys-V camp) - -# SunOS should use -OTHER_CFLAGS= $(SHORTENED_RBIND) -#RANLIB=ranlib - -# IRIX should use -#OTHER_CFLAGS=-cckr $(SHORTENED_RBIND) -#RANLIB=/bin/true - -# AIX should use -#OTHER_CFLAGS=-D_BSD -D_NONSTD_TYPES -D_NO_PROTO -DAIX $(SHORTENED_RBIND) -#RANLIB=ranlib - -#For SOLARIS -#OTHER_CFLAGS=-DSOLARIS -Dindex=strchr -Drindex=strrchr -DUSE_DIRENT $(SHORTENED_RBIND) -#RANLIB=/bin/true - -# Interactive Systems Unix should use -# OTHER_CFLAGS = -DISC $(SHORTENED_RBIND) - -# LINUX should use -#CC=gcc -#RESOLV_LIB= -#OTHER_CFLAGS=-traditional -DLINUX $(SHORTENED_RBIND) - -# UnixWare should use -#RESOLV_LIB=-lresolv -lnsl -lsocket -#OTHER_CFLAGS= -DSOLARIS -Dindex=strchr -Drindex=strrchr -DUSE_DIRENT $(SHORTENED_RBIND) -#RANLIB=/bin/true -#INSTALL=bsdinstall - -# >>>---------------- Others: - -RANLIB=ranlib -# Systems that do not need (and thus don't have) ranlib should use -#RANLIB=/bin/true - -# <<<---------------- - -OPTIMIZE=-g -CFLAGS = -I../include ${OPTIMIZE} ${OTHER_CFLAGS} ${SUPPORT_RCMD} ${NO_GUESSING_REMHOST} - -# Comment out defintion of GETPASS if your system has problem -# compiling it. The version built into your system will be used. -# The getpass() function in most Unix systems truncate password -# after 8 characters; the version provided here does not. -# This only affects telnet and ftp with non-anonymous login. -# Ftp with anonymous login allows long passwords regardless -# of whether GETPASS is defined or not. -GETPASS=getpass.o - -# The 'install' command is assumed to be the BSD variety (using -m to -# set the file mode). If the default 'install' on your system doesn't -# do that, you have to either specify an alternative one in the line below -# (e.g., bsdinstall or /usr/ucb/install) or modify the install instructions. -INSTALL= install - -#============================================================================== - -OBJS = Rconnect.o SendGetDst.o saddrtoname.o porttoserv.o check_cconf.o \ - percent_x.o shell_cmd.o check_user.o $(GETPASS) $(RCMD) -SRCS = Rconnect.c SendGetDst.c saddrtoname.c porttoserv.c check_cconf.c \ - percent_x.c shell_cmd.c check_user.c getpass.c -INC =../include/socks.h -LIB = libsocks.a - -all: echocwd $(LIB) - -$(LIB): $(OBJS) $(INC) - rm -f $(LIB) - ar rc $(LIB) $(OBJS) - $(RANLIB) $(LIB) - -install: echocwd $(LIB) - -if [ -d $(LIB_DEST_DIR) ]; then \ - ($(INSTALL) -m 644 $(LIB) $(LIB_DEST_DIR); \ - $(RANLIB) -t $(LIB_DEST_DIR)/$(LIB)); fi - -install.man: echocwd - $(INSTALL) -m 444 ../doc/socks_clients.1 $(MAN_DEST_DIR)/man1 - $(INSTALL) -m 444 ../doc/socks.conf.5 $(MAN_DEST_DIR)/man5 - -clean: echocwd - rm -f $(OBJS) $(LIB) core - -echocwd: - @pwd diff --git a/network/socks/socks.cstc.4.2/lib/Rconnect.c b/network/socks/socks.cstc.4.2/lib/Rconnect.c deleted file mode 100644 index 460bbed8..00000000 --- a/network/socks/socks.cstc.4.2/lib/Rconnect.c +++ /dev/null @@ -1,867 +0,0 @@ -#include <sys/types.h> -#include <sys/time.h> -#include <sys/socket.h> -#include <netinet/in.h> -#include <sys/errno.h> -#include <stdio.h> -#include <netdb.h> -#include <arpa/nameser.h> -#include <resolv.h> -#include <pwd.h> -#include <syslog.h> -#if (defined(sun) && !defined(SOLARIS)) || defined(sgi) -#include <strings.h> -#else -#include <string.h> -#endif -#include "socks.h" -#ifdef LINUX -#include <linux/time.h> -#endif - -/* >>> K. Shackelford */ -#if defined(hpux) || defined(ultrix) || defined (__NetBSD__) || defined(AIX) || defined(__bsdi__) || defined(SCO) -extern int h_errno; -#endif -/* <<< K.Shackelford */ - -#include <signal.h> -#include <sys/wait.h> - -#define NAMELEN 128 -char socks_dst_name[NAMELEN], socks_dst_serv[NAMELEN]; -char socks_src_name[NAMELEN], socks_src_user[NAMELEN], socks_real_user[NAMELEN]; -char *socks_def_server; -char *socks_server; -char *socks_serverlist; - -char socks_cmd[] = "connect"; - -extern int errno; -extern char *getenv(); -extern char *getlogin(); -static struct sockaddr_in cursin; -u_int32 SocksHost; -static unsigned short socks_port; -static int socks_conn_sock = 0; -static int socks_conn_init = 0; -static unsigned short socks_conn_port = 0; -static u_int32 socks_conn_host = 0; -static int socks_conn_code = 0; -static unsigned short socks_last_conn_port = 0; -static u_int32 socks_last_conn_host = 0; -static int socks_init_done = 0; - -struct sockaddr_in socks_nsin; -static struct sockaddr_in me; -static struct passwd *pw; -static int direct = 0; - -extern char *porttoserv(); -extern char *saddrtoname(); - - -int check_result(code) -char code; -{ - switch (code) { - case SOCKS_FAIL: -/* - errno = ETIMEDOUT; -*/ - errno = ECONNREFUSED; - return -1; - case SOCKS_NO_IDENTD: - errno = ECONNREFUSED; - fprintf(stderr, "Error: SOCKS proxy server cannot connect to identd on your machine.\n"); - return -1; - case SOCKS_BAD_ID: - errno = ECONNREFUSED; - fprintf(stderr, "Error: user-id does not agree with the one reported by identd on your machine.\n"); - return -1; - default: - return 0; - } -} - -/* - SOCKSinit() must be called once in the application program. - */ - -SOCKSinit(Progname) -char *Progname; /* name of the calling program, "rfinger", "rftp", etc. */ -{ -#ifdef SOCKS_DEFAULT_NS - static char defaultNS[] = SOCKS_DEFAULT_NS; -#endif -#ifdef SOCKS_DEFAULT_DNAME - static char defaultDNAME[] = SOCKS_DEFAULT_DNAME; -#endif - static char defaultSERVER[] = SOCKS_DEFAULT_SERVER; - char *cp, *ns, *dp; - struct hostent *hp; - struct servent *sp; - int v,uid; - -/* >>> YDL 94/01/25 */ - if (socks_init_done) - return; - socks_init_done = 1; -/* <<< YDL 94/01/25 */ - socks_port = htons(SOCKS_DEF_PORT); - - bzero((char *)&cursin, sizeof(cursin)); - bzero((char *)&socks_nsin, sizeof(socks_nsin)); - bzero((char *)&me, sizeof(me)); - /* skip the path if included in Progname */ - if( (cp = rindex(Progname, '/')) == NULL) - cp = Progname; - else - cp++; - -#ifndef LOG_DAEMON - (void) openlog(cp, LOG_PID); -#else - (void) openlog(cp, LOG_PID, SYSLOG_FAC); -#endif - - gethostname(socks_src_name, sizeof(socks_src_name)); - if ( (hp = gethostbyname(socks_src_name)) == NULL ) { - fprintf (stderr, "gethostbyname(%s): error #%d\n", - socks_src_name, h_errno); - return (1); - } - bcopy(hp->h_addr_list[0], &me.sin_addr.s_addr, hp->h_length); - -#if !defined(DNS_THROUGH_NIS) - - if ((ns = getenv("SOCKS_NS")) == NULL) { -#ifdef SOCKS_DEFAULT_NS - ns = defaultNS; -#else - ; -#endif - } - if ((dp = getenv("SOCKS_DNAME")) == NULL) { -#ifdef SOCKS_DEFAULT_DNAME - dp = defaultDNAME; -#else - ; -#endif - } - - if ((ns != NULL) || (dp != NULL)) { - res_init(); -#ifdef sgi - sethostresorder("local:nis:bind"); -#endif - } - - if (ns != NULL) { -#ifdef ultrix - _res.ns_list[0].addr.sin_addr.s_addr = inet_addr(ns); -#else - _res.nsaddr_list[0].sin_addr.s_addr = inet_addr(ns); -#endif - _res.nscount = 1; - } - if (dp != NULL) { - strncpy(_res.defdname, dp, sizeof(_res.defdname)-1); - } - -/* >>> jon r. luini <jonl@hal.com> */ -/* -#ifdef SOCKS_DEFAULT_DNAME - bzero (_res.defdname, sizeof (_res.defdname)); - - if ( (cp = getenv("SOCKS_DNAME")) != NULL ) - { - strncpy (_res.defdname, cp, sizeof (_res.defdname)-1); - } - else - { - strncpy (_res.defdname, SOCKS_DEFAULT_DNAME, - sizeof (_res.defdname)-1); - } -#endif -*/ -/* <<< jon r. luini <jonl@hal.com> */ - -#endif /* #if !defined(DNS_THROUGH_NIS) */ - - if ((socks_def_server = getenv("SOCKS_SERVER")) == NULL) - socks_def_server = defaultSERVER; - socks_server = socks_def_server; - if ((cp = getenv("SOCKS_BANNER")) != NULL) { - fprintf(stderr, "CSTC version %s SOCKS client. Default SOCKS server: %s\n", - CSTC_RELEASE, socks_def_server); - } - - if ((hp = gethostbyname(socks_server)) == NULL) { - SocksHost = inet_addr(socks_server); - } else { - bcopy(hp->h_addr_list[0], &SocksHost, hp->h_length); - } - - if ((sp = getservbyname("socks", "tcp")) != NULL) - socks_port = sp->s_port; - - if ((cp = getlogin()) == NULL) { - if ((pw = getpwuid(uid=getuid())) == NULL) { - fprintf(stderr, "Unknown user-id %d\n",uid); - return (1); - } - cp = pw->pw_name; - } - strncpy(socks_real_user, cp, sizeof(socks_real_user)); - - if ((pw = getpwuid(uid=geteuid())) == NULL) { - fprintf(stderr, "Unknown user-id %d\n",uid); - return (1); - } - strncpy(socks_src_user, pw->pw_name, sizeof(socks_src_user)); - - socks_nsin.sin_family = AF_INET; - socks_nsin.sin_port = socks_port; - socks_nsin.sin_addr.s_addr = SocksHost; - -} - - -int connect_sockd(sock, lport) -int sock; -int *lport; -/* returns 0 if successfully connected to a SOCKS server, - returns -1 otherwise - */ -{ -#ifndef VERSATILE_CLIENTS - if (connect(sock, &socks_nsin, sizeof(struct sockaddr_in)) == 0) - return 0; - else { - syslog(LOG_LOW, "Failed to connect to sockd at %s: %m", - socks_server); - return -1; - } -#else /* Now the version when VERSATILE_CLIENTS is defined */ - int last = 0; - int new_sock; - struct hostent *hp; - - while (socks_server = socks_serverlist) { - if (socks_serverlist = index(socks_serverlist, ',')) - *socks_serverlist++ = '\0'; - if ((hp = gethostbyname(socks_server)) == NULL) - socks_nsin.sin_addr.s_addr = inet_addr(socks_server); - else - bcopy(hp->h_addr_list[0], &socks_nsin.sin_addr, hp->h_length); - if (connect(sock, (struct sockaddr *)&socks_nsin, sizeof(struct sockaddr_in)) == 0) - return 0; - else { -#ifdef SVR4 - if ((errno == EISCONN) || (errno == EINPROGRESS) || (errno == EAGAIN)) -#else - if ((errno == EISCONN) || (errno == EINPROGRESS)) -#endif - return -1; - syslog(LOG_LOW, "Failed to connect to sockd at %s: %m", - socks_server); - if (!(socks_serverlist)) { - return -1; - } -#if defined(SUPPORT_RCMD) - if ((*lport < IPPORT_RESERVED) && (*lport >= IPPORT_RESERVED/2)) - new_sock = rresvport(lport); - else - new_sock = socket(PF_INET, SOCK_STREAM, 0); -#else /* SUPPORT_RCMD is not defined */ - new_sock = socket(PF_INET, SOCK_STREAM, 0); -#endif /* #if defined(SUPPORT_RCMD) */ - if (new_sock < 0) { - return -1; - } - if (dup2(new_sock, sock) < 0) { - close(new_sock); - return -1; - } else { - close(new_sock); - } - } - } - errno = ECONNREFUSED; - return -1; -#endif /* #ifndef VERSATILE_CLIENTS */ - -} - -static int send_src_user(s, user) -int s; -char *user; -{ - char *p = user; - int i, n, ret; - fd_set fds; - int fdsbits = s + 1; - struct timeval timeout; - - i = strlen(user) + 1; - while ( i > 0) { - FD_ZERO(&fds); - FD_SET(s, &fds); - timeout.tv_sec = 15; - timeout.tv_usec = 0; - if ((ret = select(fdsbits, NULL, &fds, NULL, &timeout)) < 0) { - return(-1); - } - if (ret == 0) - continue; - if((n = write(s, p, i)) <= 0) { - return(-2); - } - p += n; - i -= n; - } - return(0); -} - - -static int socksC_proto(s, dst) -int s; -Socks_t *dst; -{ - int sta; - - if ((sta = SendDst(s, dst)) < 0) { - if (sta == -1) - perror("select in SendDst"); - else - perror("write in SendDst"); - return(sta); - } - if ((sta = send_src_user(s, socks_src_user)) < 0) { - if (sta == -1) - perror("select in send_src_user"); - else - perror("write in send_src_user"); - return(sta); - } - if ((sta = GetDst(s, dst)) < 0) { - if (sta == -1) - perror("select in GetDst"); - else - perror("read in GetDst"); - return(sta); - } - return(0); -} - -static void quit_C_proto() -{ - exit(SOCKS_FAIL); -} - -static void do_C_proto(sock, port, addr) -int sock; -unsigned short port; -u_int32 addr; -{ - Socks_t dst; - - signal(SIGALRM, quit_C_proto); - alarm(CLIENT_CONN_TIMEOUT); - dst.version = SOCKS_VERSION; - dst.cmd = SOCKS_CONNECT; - dst.port = port; - dst.host = addr; - if (socksC_proto(sock, &dst) < 0) { - alarm(0); - exit(SOCKS_FAIL); - } - alarm(0); - if ((dst.cmd == SOCKS_FAIL) || (dst.cmd == SOCKS_NO_IDENTD) - || (dst.cmd == SOCKS_BAD_ID)) { - exit(dst.cmd); - } - exit(SOCKS_RESULT); - -} - - -Rconnect(sock, sin, size) -int sock; -struct sockaddr_in *sin; -int size; -{ - Socks_t dst; - int i; - int res_ret, con_ret, con_errno; - int lport = 0; - - int status, wait_ret, child_pid; - - if (socks_init_done == 0) - SOCKSinit("SOCKSclient"); -#ifdef DEBUG -fprintf(stderr, "Rconnect 10\n"); -fprintf(stderr,"socks_conn_sock=%d, socks_conn_host=%ld, socks_conn_port=%d, socks_conn_init=%d\n", socks_conn_sock, socks_conn_host, socks_conn_port, socks_conn_init); -fprintf(stderr,"sock=%d, sin->sin_addr.s_addr=%ld, sin->sin_port=%d\n", sock, sin->sin_addr.s_addr, sin->sin_port); -#endif /* #ifdef DEBUG */ - - if ((sock != socks_conn_sock) || (sin->sin_port != socks_conn_port) - || (sin->sin_addr.s_addr != socks_conn_host)) { - if (socks_conn_init) - kill(socks_conn_init, SIGKILL); - socks_conn_code = 0; - socks_conn_init = 0; - strcpy(socks_cmd, "connect"); - saddrtoname(&sin->sin_addr, socks_dst_name, sizeof(socks_dst_name)); - porttoserv(sin->sin_port, socks_dst_serv, sizeof(socks_dst_serv)); -#ifdef DEBUG -fprintf(stderr, "Rconnect 100, Rconnect(%d, %s, %s)\n", sock, socks_dst_name, socks_dst_serv); -#endif /* #ifdef DEBUG */ - } else if (status = socks_conn_code) { - socks_conn_init = 0; - socks_conn_code = 0; - socks_conn_sock = 0; - socks_conn_port = 0; - socks_conn_host = 0; - res_ret = check_result(status); - if (status == SOCKS_RESULT) { - errno = EISCONN; - socks_last_conn_host = sin->sin_addr.s_addr; - socks_last_conn_port = sin->sin_port; - } else { - syslog(LOG_LOW, "Connection failed.\n"); - } - return(-1); - } else if (socks_conn_init) { -#ifdef DEBUG -fprintf(stderr, "Rconnect 200, Rconnect(%d, %s, %s)\n", sock, socks_dst_name, socks_dst_serv); -#endif /* #ifdef DEBUG */ - wait_ret = waitpid(socks_conn_init, &status, WNOHANG); - if (wait_ret == 0) { - errno = EALREADY; -#ifdef DEBUG -fprintf(stderr, "Rconnect 300, ret=-1, errno=EALREADY\n"); -#endif /* #ifdef DEBUG */ - return(-1); - } else if (wait_ret == socks_conn_init) { - socks_conn_init = 0; - socks_conn_code = 0; - socks_conn_sock = 0; - socks_conn_port = 0; - socks_conn_host = 0; - if (status & 0x00ff) { - kill(socks_conn_init, SIGKILL); - errno = ECONNREFUSED; -#ifdef DEBUG -fprintf(stderr, "Rconnect 400, ret=-1, errno=ECONNREFUSED\n"); -#endif /* #ifdef DEBUG */ - syslog(LOG_LOW, "Connection failed.\n"); - return(-1); - } else { - status = (status >> 8) & 0x00ff; - res_ret = check_result(status); -#ifdef DEBUG -fprintf(stderr, "Rconnect 500, ret=%d, status=%d\n", res_ret, status); -#endif /* #ifdef DEBUG */ - if (res_ret == 0) { - errno = EISCONN; - socks_last_conn_host = sin->sin_addr.s_addr; - socks_last_conn_port = sin->sin_port; - } else { - syslog(LOG_LOW, "Connection failed.\n"); - } - return(-1); - } - } else { - kill(socks_conn_init, SIGKILL); - errno = ECONNREFUSED; -#ifdef DEBUG -fprintf(stderr, "Rconnect 600, ret=-1, errno=ECONNREFUSED\n"); -#endif /* #ifdef DEBUG */ - socks_conn_init = 0; - socks_conn_code = 0; - socks_conn_sock = 0; - socks_conn_port = 0; - socks_conn_host = 0; - syslog(LOG_LOW, "Connection failed.\n"); - return(-1); - } - } - -#ifdef DEBUG -fprintf(stderr, "Rconnect 700, Rconnect(%d, %s, %s)\n", sock, socks_dst_name, socks_dst_serv); -#endif /* #ifdef DEBUG */ - -#ifdef VERSATILE_CLIENTS - direct = check_cconf(&me, sin); -#ifdef DEBUG -fprintf(stderr, "Rconnect() 800: direct = %d\n", direct); -#endif /* #ifdef DEBUG */ - if (direct < 0) { - syslog(LOG_LOW, "refused -- connect() from %s(%s) to %s (%s)", - socks_src_user, socks_real_user, socks_dst_name, socks_dst_serv); - errno = ECONNREFUSED; -#ifdef DEBUG -fprintf(stderr, "Rconnect 900, ret=-1, errno=EALREADY\n"); -#endif /* #ifdef DEBUG */ - return(-1); - } - - if (direct == 1) { - syslog(LOG_LOW, "connect() directly from %s(%s) to %s (%s)", - socks_src_user, socks_real_user, socks_dst_name, socks_dst_serv); - con_ret = connect(sock, (struct sockaddr *)sin, size); - if (con_ret == 0) { - socks_last_conn_host = sin->sin_addr.s_addr; - socks_last_conn_port = sin->sin_port; - } -#ifdef DEBUG -fprintf(stderr, "Rconnect 1000, ret=%d, ", con_ret); -perror(" "); -#endif /* #ifdef DEBUG */ - return(con_ret); - } -#endif /* #ifdef VERSATILE_CLIENTS */ - - con_ret = connect_sockd(sock, &lport); -#ifdef DEBUG - fprintf(stderr, "con_ret=connect_sockd()=%d", con_ret); - if(con_ret < 0) - perror(""); - else - fprintf(stderr,"\n"); -#endif /* #ifdef DEBUG */ - if (con_ret == 0) { - syslog(LOG_LOW, "connect() from %s(%s) to %s (%s) using sockd at %s", - socks_src_user, socks_real_user, socks_dst_name, socks_dst_serv, socks_server); - dst.version = SOCKS_VERSION; - dst.cmd = SOCKS_CONNECT; - dst.port = sin->sin_port; - dst.host = sin->sin_addr.s_addr; - if (socksC_proto(sock, &dst) < 0) { - return(-1); - } - res_ret = check_result(dst.cmd); -#ifdef DEBUG -fprintf(stderr, "Rconnect 1100, ret=%d, ", res_ret); -perror(" "); -#endif /* #ifdef DEBUG */ - if (res_ret == 0) { - socks_last_conn_host = sin->sin_addr.s_addr; - socks_last_conn_port = sin->sin_port; - } - return(res_ret); - } - if ((con_ret < 0) && (errno != EINPROGRESS)) { -#ifdef DEBUG -fprintf(stderr, "Rconnect 1200, ret=%d, ", con_ret); -perror(" "); -#endif /* #ifdef DEBUG */ - return(-1); - } -/* - con_errno = errno; -*/ - syslog(LOG_LOW, "connect() from %s(%s) to %s (%s) using sockd at %s", - socks_src_user, socks_real_user, socks_dst_name, socks_dst_serv, socks_server); - - switch (child_pid = fork()) { - case -1: - perror("fork()"); - errno = ECONNREFUSED; -#ifdef DEBUG -fprintf(stderr, "Rconnect 1300, ret=-1, "); -perror(" "); -#endif /* #ifdef DEBUG */ - return(-1); - case 0: - do_C_proto(sock, sin->sin_port, sin->sin_addr.s_addr); - default: - socks_conn_init = child_pid; - socks_conn_code = 0; - socks_conn_sock = sock; - socks_conn_port = sin->sin_port; - socks_conn_host = sin->sin_addr.s_addr; - errno = EINPROGRESS; -#ifdef DEBUG -fprintf(stderr, "Rconnect 1400, ret=-1 "); -perror(" "); -#endif /* #ifdef DEBUG */ - return(-1); - } -} - -/* >>> YDL 94/01/25 */ -#ifdef SHORTENED_RBIND -Rbind(sock, sin, size) -int sock; -struct sockaddr_in *sin; -int size; -#else -/* -** Set up a bind for a remote host, add fill 'cursin' in with the -** remote server information. -** If using reserved port, the port must have already been reserved -** through a rresvport() call. -*/ -Rbind(sock, sin, size, dsthost) -int sock; -struct sockaddr_in *sin; -int size; -u_int32 dsthost; /* as in sin_addr.s_addr */ -#endif /* #ifdef SHORTENED_RBIND */ -/* <<< YDL 94/01/25 */ -{ - Socks_t dst; - struct sockaddr_in psin; - int i; - int new_sock, lport; - u_int32 remhost; - int con_ret; - struct timeval tmo; - fd_set fds; - - if (socks_init_done == 0) - SOCKSinit("SOCKSclient"); - bzero((char *)&psin, sizeof(psin)); - lport = ntohs(sin->sin_port); - strcpy(socks_cmd, "bind"); -#ifdef SHORTENED_RBIND -# ifdef NO_GUESSING_REMHOST - remhost = 0L; - strcpy(socks_dst_name, "Unspecified.Host"); -# else - remhost = socks_last_conn_host; - saddrtoname(&remhost, socks_dst_name, sizeof(socks_dst_name)); -# endif /* # ifdef NO_GUESSING_REMHOST */ -#else - remhost = dsthost; - saddrtoname(&remhost, socks_dst_name, sizeof(socks_dst_name)); -#endif /* #ifdef SHORTENED_RBIND */ - porttoserv(socks_last_conn_port, socks_dst_serv, sizeof(socks_dst_serv)); -#ifdef DEBUG -fprintf(stderr, "Rbind 100, lport=%u, socks_dst_name=>%s<, socks_dst_serv=>%s<\n", lport, socks_dst_name, socks_dst_serv); -fprintf(stderr, "Rbind(%d, %s, %s)\n", sock, socks_dst_name, socks_dst_serv); -#endif /* #ifdef DEBUG */ - - psin.sin_addr.s_addr = remhost; - psin.sin_port = socks_last_conn_port; -#ifdef VERSATILE_CLIENTS - direct = check_cconf(&me, &psin); -#ifdef DEBUG -fprintf(stderr, "Rbind() 200, direct = %d\n", direct); -#endif /* #ifdef DEBUG */ - if (direct < 0) { - syslog(LOG_LOW, "Refused -- bind() from %s(%s) for %s (%s)", - socks_src_user, socks_real_user, socks_dst_name, socks_dst_serv); - errno = ECONNREFUSED; - return -1; - } - - if (direct == 1) { - syslog(LOG_LOW, "bind() directly from %s(%s) for %s (%s)", - socks_src_user, socks_real_user, socks_dst_name, socks_dst_serv); -#ifdef DEBUG -fprintf(stderr,"Rbind() 300, direct=1, lport=%u\n", lport); -#endif /* #ifdef DEBUG */ -#if defined(SUPPORT_RCMD) - if ((lport >= IPPORT_RESERVED) || (lport < IPPORT_RESERVED/2)) - return (bind(sock, (struct sockaddr *)sin, size)); - else - return 0; -#else /* SUPPORT_RCMD not defined */ - return (bind(sock, (struct sockaddr *)sin, size)); -#endif /* #if defined(SUPPORT_RCMD) */ - } -#endif /* #ifdef VERSATILE_CLIENTS */ - - con_ret = connect_sockd(sock, &lport); - if (con_ret == 0) { - ; -#ifdef SVR4 - } else if ((errno == EINPROGRESS) || (errno == EAGAIN)) { -#else - } else if (errno == EINPROGRESS) { -#endif - while (1) { - tmo.tv_sec = 0; - tmo.tv_usec = 100000; - FD_ZERO(&fds); - FD_SET(sock, &fds); - select(sock+1, NULL, &fds, NULL, &tmo); - con_ret = connect(sock, (struct sockaddr *)&socks_nsin, sizeof(struct sockaddr_in)); - if ((con_ret < 0) && (errno == EISCONN)) { - con_ret = 0; - break; -#if defined(SVR4) - } else if ((con_ret < 0) && ((errno == EALREADY) || - (errno == EAGAIN))) { -#else /* !defined(SVR4) */ - } else if ((con_ret < 0) && (errno == EALREADY)) { -#endif /* #if defined(SVR4) */ - continue; - } else - break; - } - } - if (con_ret < 0) { - syslog(LOG_LOW, "Failed -- bind() from %s(%s) for %s (%s)", - socks_src_user, socks_real_user, socks_dst_name, socks_dst_serv); - errno = ECONNREFUSED; - return -1; - } - syslog(LOG_LOW, "bind() from %s(%s) for %s (%s) using sockd at %s", - socks_src_user, socks_real_user, socks_dst_name, socks_dst_serv, socks_server); - - dst.version = SOCKS_VERSION; - dst.cmd = SOCKS_BIND; - dst.port = socks_last_conn_port; - dst.host = remhost; - if (socksC_proto(sock, &dst) < 0) - return(-1); - cursin.sin_family = AF_INET; - cursin.sin_port = dst.port; - if (ntohl(dst.host) == INADDR_ANY) - cursin.sin_addr.s_addr = socks_nsin.sin_addr.s_addr; - else - cursin.sin_addr.s_addr = dst.host; -/* - fprintf(stderr,"Rbind interface: %s, port: %u\n", - inet_ntoa(cursin.sin_addr), htons(cursin.sin_port)); -*/ - - return (check_result(dst.cmd)); -} - -/* -** Stub routine since the listen will have alread succeded on the -** server. -*/ -Rlisten(s, n) -int s, n; -{ -#ifdef DEBUG - fprintf(stderr, "direct=%d, Rlisten(%d, %d)\n", direct, s, n); -#endif -#ifdef VERSATILE_CLIENTS - if (direct) - return (listen(s, n)); -#endif /* #ifdef VERSATILE_CLIENTS */ - - return 0; -} - -/* -** Well we know where we got a connection from. -*/ -Rgetsockname(sock, sin, size) -int sock; -struct sockaddr_in *sin; -int *size; -{ -#ifdef DEBUG - saddrtoname(&sin->sin_addr, socks_dst_name, sizeof(socks_dst_name)); - porttoserv(sin->sin_port, socks_dst_serv, sizeof(socks_dst_serv)); - fprintf(stderr, "direct= %d, Rgetsockname(%d, %s, %s)\n", - direct, sock, socks_dst_name, socks_dst_serv); -#endif -#ifdef VERSATILE_CLIENTS - if (direct) - return (getsockname(sock, (struct sockaddr *)sin, size)); -#endif /* #ifdef VERSATILE_CLIENTS */ - - *size = sizeof(struct sockaddr_in); - *sin = cursin; - - return 0; -} - -/* -** Do an accept, which is really a select for some data on -** the present socket. -*/ -Raccept(sock, sin, size) -int sock; -struct sockaddr_in *sin; -int *size; -{ - fd_set fds; - Socks_t dst; - int fdsbits = sock + 1; - -#ifdef DEBUG - fprintf(stderr, "direct= %d, Raccept(%d, sin, size)\n", - direct, sock); -#endif - -#ifdef VERSATILE_CLIENTS - if (direct) - return(accept(sock, (struct sockaddr *)sin, size)); -#endif /* #ifdef VERSATILE_CLIENTS */ - - FD_ZERO(&fds); - FD_SET(sock, &fds); - - if (select(fdsbits, &fds, NULL, NULL, NULL) > 0) - if (FD_ISSET(sock, &fds)) { - GetDst(sock, &dst); - sin->sin_family = AF_INET; - sin->sin_port = dst.port; - sin->sin_addr.s_addr = dst.host; - return(dup(sock)); - } - return -1; -} - -int Rselect(width, readfds, writefds, exceptfds, timeout) -int width; -fd_set *readfds, *writefds, *exceptfds; -struct timeval *timeout; -{ - int wait_ret, status; - - if(!socks_conn_init ) { - return(select(width, readfds, writefds, exceptfds, timeout)); - } - - if (readfds != NULL) - FD_CLR(socks_conn_sock, readfds); - if (exceptfds != NULL) - FD_CLR(socks_conn_sock, exceptfds); - if ((writefds == NULL) || !FD_ISSET(socks_conn_sock, writefds)) - return(select(width, readfds, writefds, exceptfds, timeout)); - - wait_ret = waitpid(socks_conn_init, &status, WNOHANG); - if (wait_ret == 0) { - FD_CLR(socks_conn_sock, writefds); - return(select(width, readfds, writefds, exceptfds, timeout)); - } else if (wait_ret == socks_conn_init) { -/* - socks_conn_init = 0; - socks_conn_sock = 0; - socks_conn_port = 0; - socks_conn_host = 0; -*/ - if (status & 0x00ff) { - kill(socks_conn_init, SIGKILL); - socks_conn_init = 0; - socks_conn_code = SOCKS_FAIL; - } else { - status = (status >> 8) & 0x00ff; - if (status == SOCKS_RESULT) { - socks_last_conn_host = socks_conn_host; - socks_last_conn_port = socks_conn_port; - } - socks_conn_init = 0; - socks_conn_code = status; - } - } else { - kill(socks_conn_init, SIGKILL); - socks_conn_init = 0; - socks_conn_code = SOCKS_FAIL; - } - - return(select(width, readfds, writefds, exceptfds, timeout)); -} diff --git a/network/socks/socks.cstc.4.2/lib/Rrcmd.c b/network/socks/socks.cstc.4.2/lib/Rrcmd.c deleted file mode 100644 index e08f91e3..00000000 --- a/network/socks/socks.cstc.4.2/lib/Rrcmd.c +++ /dev/null @@ -1,254 +0,0 @@ -/* - * Copyright (c) 1983 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. - */ - -#if defined(LIBC_SCCS) && !defined(lint) -/*static char *sccsid = "from: @(#)rcmd.c 5.24 (Berkeley) 2/24/91";*/ -static char *rcsid = "$Id: rcmd.c,v 1.4 1993/12/05 14:42:26 deraadt Exp $"; -#endif /* LIBC_SCCS and not lint */ - -#include <sys/param.h> -#include <sys/socket.h> -#include <sys/stat.h> -#include <netinet/in.h> -#include <arpa/inet.h> -#include <signal.h> -#include <fcntl.h> -#include <netdb.h> -#include <pwd.h> -#include <errno.h> -#include <stdio.h> -#include <ctype.h> -#include <unistd.h> -#include <string.h> - -Rrcmd(ahost, rport, locuser, remuser, cmd, fd2p) - char **ahost; - u_short rport; -/* - const char *locuser, *remuser, *cmd; -*/ - char *locuser, *remuser, *cmd; - int *fd2p; -{ - int s, timo = 1, pid; - long oldmask; - struct sockaddr_in sin, from; - char c; - int lport = IPPORT_RESERVED - 1; - struct hostent hoste; - struct hostent *hp; - fd_set reads; - - pid = getpid(); - hp = gethostbyname(*ahost); - if (hp == 0) { - herror(*ahost); - return (-1); - } - bcopy(hp, &hoste, sizeof(struct hostent)); - hp = &hoste; - *ahost = hp->h_name; - oldmask = sigblock(sigmask(SIGURG)); - for (;;) { -#ifdef DEBUG -fprintf(stderr, "Rrcmd 100, lport = %d\n", lport); -#endif /* #ifdef DEBUG */ - s = rresvport(&lport); -#ifdef DEBUG -fprintf(stderr, "Rrcmd 200, s = %d\n", s); -#endif /* #ifdef DEBUG */ - if (s < 0) { - if (errno == EAGAIN) - fprintf(stderr, "socket: All ports in use\n"); - else - perror("rcmd: socket"); - sigsetmask(oldmask); - return (-1); - } -#ifdef DEBUG -fprintf(stderr, "Rrcmd 300\n"); -#endif /* #ifdef DEBUG */ -#if defined(hpux) - ioctl(s, FIOSSAIOOWN, pid); -#else /* hpux not defined */ - fcntl(s, F_SETOWN, pid); -#endif /* #if defined(hpux) */ - bzero((char *)&sin, sizeof sin); - sin.sin_family = hp->h_addrtype; - bcopy(hp->h_addr_list[0], (caddr_t)&sin.sin_addr, hp->h_length); - sin.sin_port = rport; -#ifdef DEBUG -fprintf(stderr, "Rrcmd 400, sin.sin_family=%d, sin.sin_port=%u, sin.sin_addr=%s\n",sin.sin_family, ntohs(sin.sin_port), inet_ntoa(sin.sin_addr)); -#endif /* #ifdef DEBUG */ - if (Rconnect(s, (struct sockaddr *)&sin, sizeof(sin)) >= 0) - break; -#ifdef DEBUG -fprintf(stderr, "Rrcmd 500, Rconnect failed\n"); -#endif /* #ifdef DEBUG */ - (void) close(s); - if (errno == EADDRINUSE) { - lport--; - continue; - } - if (errno == ECONNREFUSED && timo <= 16) { - sleep(timo); - timo *= 2; - continue; - } - if (hp->h_addr_list[1] != NULL) { - int oerrno = errno; - - fprintf(stderr, - "connect to address %s: ", inet_ntoa(sin.sin_addr)); - errno = oerrno; - perror(0); - hp->h_addr_list++; - bcopy(hp->h_addr_list[0], (caddr_t)&sin.sin_addr, - hp->h_length); - fprintf(stderr, "Trying %s...\n", - inet_ntoa(sin.sin_addr)); - continue; - } - perror(hp->h_name); - sigsetmask(oldmask); - return (-1); - } - lport--; -#ifdef DEBUG -fprintf(stderr, "Rrcmd 600, f2dp=%u\n", fd2p); -#endif /* #ifdef DEBUG */ - if (fd2p == 0) { - write(s, "", 1); - lport = 0; - } else { - char num[8]; - int s2 = rresvport(&lport), s3; - int len = sizeof (from); - struct sockaddr_in tsin; - int tlen = sizeof(tsin); - -#ifdef DEBUG -fprintf(stderr, "Rrcmd 650, lport=%u\n", lport); -#endif /* #ifdef DEBUG */ - if (s2 < 0) - goto bad; - tsin.sin_family = AF_INET; - tsin.sin_addr.s_addr = INADDR_ANY; - tsin.sin_port = htons((u_short)lport); -/* - s2 = socket(AF_INET, SOCK_STREAM, 0); -*/ - if (Rbind(s2, (struct sockaddr *)&tsin, sizeof(tsin), - sin.sin_addr.s_addr) < 0) { - perror("Rrcmd: Rbind() "); - (void) close(s2); - goto bad; - } - if (Rgetsockname(s2, (struct sockaddr *)&tsin, &tlen) < 0) { - perror("Rrcmd: Rgetsockname() "); - (void) close(s2); - goto bad; - } - Rlisten(s2, 1); -/* - (void) sprintf(num, "%d", lport); -*/ - (void) sprintf(num, "%u", ntohs(tsin.sin_port)); -#ifdef DEBUG -fprintf(stderr,"Rrcmd 800, num=>%s<\n", num); -#endif /* #ifdef DEBUG */ - if (write(s, num, strlen(num)+1) != strlen(num)+1) { - perror("write: setting up stderr"); - (void) close(s2); - goto bad; - } - FD_ZERO(&reads); - FD_SET(s, &reads); - FD_SET(s2, &reads); - errno = 0; - if (select(32, &reads, 0, 0, 0) < 1 || - !FD_ISSET(s2, &reads)) { - if (errno != 0) - perror("select: setting up stderr"); - else - fprintf(stderr, - "select: protocol failure in circuit setup.\n"); - (void) close(s2); - goto bad; - } -#ifdef DEBUG -fprintf(stderr,"Rrcmd 900, before Raccept()\n"); -#endif /* #ifdef DEBUG */ - s3 = Raccept(s2, (struct sockaddr *)&from, &len); - (void) close(s2); - if (s3 < 0) { - perror("accept"); - lport = 0; - goto bad; - } - *fd2p = s3; - from.sin_port = ntohs((u_short)from.sin_port); - if (from.sin_family != AF_INET || - from.sin_port >= IPPORT_RESERVED || - from.sin_port < IPPORT_RESERVED / 2) { - fprintf(stderr, - "socket: protocol failure in circuit setup.\n"); - goto bad2; - } - } - (void) write(s, locuser, strlen(locuser)+1); - (void) write(s, remuser, strlen(remuser)+1); - (void) write(s, cmd, strlen(cmd)+1); - if (read(s, &c, 1) != 1) { - perror(*ahost); - goto bad2; - } - if (c != 0) { - while (read(s, &c, 1) == 1) { - (void) write(2, &c, 1); - if (c == '\n') - break; - } - goto bad2; - } - sigsetmask(oldmask); - return (s); -bad2: - if (lport) - (void) close(*fd2p); -bad: - (void) close(s); - sigsetmask(oldmask); - return (-1); -} - diff --git a/network/socks/socks.cstc.4.2/lib/SendGetDst.c b/network/socks/socks.cstc.4.2/lib/SendGetDst.c deleted file mode 100644 index e119324a..00000000 --- a/network/socks/socks.cstc.4.2/lib/SendGetDst.c +++ /dev/null @@ -1,102 +0,0 @@ -#include <sys/types.h> -#include <sys/time.h> -#include "socks.h" -#if defined(DEBUG) -#include <sys/errno.h> -extern int errno; -#endif - -#define NULL ((char *)0) - -int SendDst(s, dst) -int s; -Socks_t *dst; -{ - char c[sizeof(Socks_t)]; - char *p = c; - int i = sizeof(Socks_t), n, ret; - fd_set fds; - int fdsbits = s + 1; - struct timeval timeout; - - c[0] = dst->version; - c[1] = dst->cmd; - bcopy(&dst->port, c+2, sizeof(dst->port)); - bcopy(&dst->host, c+2+sizeof(dst->port), sizeof(dst->host)); - - while ( i > 0) { - FD_ZERO(&fds); - FD_SET(s, &fds); - timeout.tv_sec = 15; - timeout.tv_usec = 0; - while ((ret = select(fdsbits, NULL, &fds, NULL, &timeout)) < 0) { -/* - perror("select in SendDst"); - exit(-1); -*/ -#if defined(DEBUG) - if (errno != EINTR) -#endif - return(-1); - } - if (ret == 0) - continue; - if((n = write(s, p, i)) <= 0) { -/* - perror("write in SendDst"); - exit(-1); -*/ - return (-2); - } - p += n; - i -= n; - } - return(0); -} - -int GetDst(s, dst) -int s; -Socks_t *dst; -{ - char c[sizeof(Socks_t)]; - char *p = c; - int i = sizeof(Socks_t), n, ret; - fd_set fds; - int fdsbits = s + 1; - struct timeval timeout; - - while ( i > 0) { - FD_ZERO(&fds); - FD_SET(s, &fds); - timeout.tv_sec = 15; - timeout.tv_usec = 0; - while ((ret = select(fdsbits, &fds, NULL, NULL, &timeout)) < 0) { -/* - perror("select in GetDst"); - exit(-1); -*/ -#if defined(DEBUG) - if (errno != EINTR) -#endif - return(-1); - } - if (ret == 0) - continue; - if((n = read(s, p, i)) <= 0) { -/* - perror("read in GetDst"); - exit(-1); -*/ - return(-2); - } - p += n; - i -= n; - } - - dst->version = c[0]; - dst->cmd = c[1]; - bcopy(c+2, &dst->port, sizeof(dst->port)); - bcopy(c+2+sizeof(dst->port), &dst->host, sizeof(dst->host)); - return(0); -} - diff --git a/network/socks/socks.cstc.4.2/lib/check_cconf.c b/network/socks/socks.cstc.4.2/lib/check_cconf.c deleted file mode 100644 index 23ba368b..00000000 --- a/network/socks/socks.cstc.4.2/lib/check_cconf.c +++ /dev/null @@ -1,258 +0,0 @@ -#include <sys/types.h> -#include <syslog.h> -#include <netinet/in.h> -#include <netdb.h> -#include <stdio.h> -#include <ctype.h> -/* >>> YDL, 93/10/26 */ -#if (defined(sun) && !defined(SOLARIS)) || defined(sgi) -#include <strings.h> -#else -#include <string.h> -#endif -/* <<< YDL< 93/10/26 */ -#include "socks.h" - -#define STREQ(a, b) (strcmp(a, b) == 0) - -#ifdef OLD_CONF_MASK -static char conf_mask[] = OLD_CONF_MASK; -#endif -char *socks_conf = SOCKS_CONF; -extern char *porttoserv(); -extern char *saddrtoname(); -extern void mkargs(); -extern int GetAddr(); -extern long GetPort(); -extern int check_user(); -extern char socks_src_user[]; -extern char *socks_server; -extern struct sockaddr_in socks_nsin; -extern u_int32 SocksHost; -extern char *socks_def_server; -extern char *socks_serverlist; - -check_cconf(src, dst) -/* Return 0 if sockd should be used, - 1 if direct connection should be made, - -1 if the connection request should be denied. - */ -struct sockaddr_in *src, *dst; -{ - FILE *fd; - static char buf[1024]; -#ifdef TEST - char temp[1024]; -#endif - char *bp; - int linenum = 0, direct; - char *argv[10]; - int argc; - u_int32 daddr, dmask; - unsigned short dport; - enum { e_lt, e_gt, e_eq, e_neq, e_le, e_ge, e_nil } tst; - char *userlist; - int next_arg; - unsigned short dst_sin_port = ntohs(dst->sin_port); - long p; - char *cmdp; - struct hostent *hp; - struct in_addr self; - - - self.s_addr = inet_addr("127.0.0.1"); - if ((dst->sin_addr.s_addr == self.s_addr) || (dst->sin_addr.s_addr == 0)) - return(1); - if ((fd = fopen(socks_conf, "r")) == NULL) - return(1); - - while (fgets(buf, sizeof(buf) - 1, fd) != NULL) { - linenum++; -#ifdef TEST - strcpy(temp, buf); -#endif - /* - ** Comments start with a '#' anywhere on the line - */ - cmdp = (char *)0; - if ((bp = index(buf, '\n')) != NULL) - *bp = '\0'; - for (bp = buf; *bp != '\0'; bp++) { - if (*bp == ':') { - *bp++ = '\0'; - cmdp = bp; - break; - } else if (*bp == '#') { - *bp = '\0'; - break; - } else if (*bp == '\t') - *bp = ' '; - } - - mkargs(buf, &argc, argv, 7); - if (argc == 0) - continue; - if ((argc < 3) || (argc > 7)) { -#ifdef TEST - printf("Invalid entry at line %d\n", linenum); -#else - syslog(LOG_LOW, "Invalid entry at line %d", linenum); -#endif - continue; - } - - next_arg = 1; - if (STREQ(argv[0], "sockd")) { - socks_serverlist = socks_def_server; - direct = 0; - if (strncmp(argv[next_arg], "@=", 2) == 0) { - socks_serverlist = argv[next_arg] + 2; - if(*socks_serverlist == '\0') -/* - socks_serverlist = (char *)0; -*/ - socks_serverlist = socks_def_server; - next_arg++; - } - } else if (strncmp(argv[0], "sockd@", 6) == 0) { - direct = 0; - socks_serverlist = argv[0] + 6; - if (*socks_serverlist == '\0') -/* - socks_serverlist = (char *)0; -*/ - socks_serverlist = socks_def_server; - } else if (STREQ(argv[0], "direct")) { - direct = 1; - } else if (STREQ(argv[0], "deny")) { - direct = -1; - } else { -#ifdef TEST - printf("Invalid sockd/direct/deny field at line %d\n", linenum); -#else - syslog(LOG_LOW, "Invalid sockd/direct/deny field at line %d", linenum); -#endif - continue; - } - - userlist = (char *)0; - if (strncmp(argv[next_arg], "*=", 2) == 0) { - if (argv[next_arg][2]) userlist = argv[next_arg] + 2; - next_arg++; - } - if(argc <= next_arg+1) { -#ifdef TEST - printf("Invalid entry at line %d\n", linenum); -#else - syslog(LOG_LOW, "Invalid entry at line %d", linenum); -#endif - continue; - } - GetAddr(argv[next_arg++], &daddr); - GetAddr(argv[next_arg++], &dmask); - if (argc > next_arg + 1) { - if (STREQ(argv[next_arg], "eq")) - tst = e_eq; - else if (STREQ(argv[next_arg], "neq")) - tst = e_neq; - else if (STREQ(argv[next_arg], "lt")) - tst = e_lt; - else if (STREQ(argv[next_arg], "gt")) - tst = e_gt; - else if (STREQ(argv[next_arg], "le")) - tst = e_le; - else if (STREQ(argv[next_arg], "ge")) - tst = e_ge; - else { -#ifdef TEST - printf("Invalid comparison at line %d\n", linenum); -#else - syslog(LOG_LOW, "Invalid comparison at line %d", linenum); -#endif - continue; - } - - if (((p = GetPort(argv[next_arg+1])) < 0) || - (p >= (1L << 16))) { -#ifdef TEST - printf("Invalid port number at line %d\n", linenum); -#else - syslog(LOG_LOW, "Invalid port number at line %d", linenum); -#endif - continue; - } else { - dport = p; - } - } else { - tst = e_nil; - dport = 0; - } - -#ifdef DEBUG - { - char msg[1024]; - if (userlist) - sprintf(msg,"%s %s 0x%08x 0x%08x %s %u", - argv[0], userlist, daddr, dmask, - tst == e_eq ? "==" : - tst == e_neq ? "!=" : - tst == e_lt ? "<" : - tst == e_gt ? ">" : - tst == e_le ? "<=" : - tst == e_ge ? ">=" : "NIL", - dport); - else - sprintf(msg,"%s 0x%08x 0x%08x %s %u", - argv[0], daddr, dmask, - tst == e_eq ? "==" : - tst == e_neq ? "!=" : - tst == e_lt ? "<" : - tst == e_gt ? ">" : - tst == e_le ? "<=" : - tst == e_ge ? ">=" : "NIL", - dport); - syslog(LOG_LOW, "%s", msg); - } -#endif - /* comparisons of port numbers must be done in host order */ - -#ifdef OLD_CONF_MASK - if((daddr & ~dmask) == (dst->sin_addr.s_addr & ~dmask) && -#else - if((daddr & dmask) == (dst->sin_addr.s_addr & dmask) && -#endif - check_user(userlist, socks_src_user)) { - if (tst == e_nil) - goto GotIt; - if ((tst == e_eq) && (dst_sin_port == dport)) - goto GotIt; - if ((tst == e_neq) && (dst_sin_port != dport)) - goto GotIt; - if ((tst == e_lt) && (dst_sin_port < dport)) - goto GotIt; - if ((tst == e_gt) && (dst_sin_port > dport)) - goto GotIt; - if ((tst == e_le) && (dst_sin_port <= dport)) - goto GotIt; - if ((tst == e_ge) && (dst_sin_port >= dport)) - goto GotIt; - } - } - - fclose(fd); -#ifdef TEST - printf("*** No match with any line. Access denied.\n"); -#endif - return -1; - -GotIt: -#ifdef TEST - printf("Line %d: %s", linenum, temp); -#endif - fclose(fd); - if (cmdp != (char *)0) - shell_cmd(cmdp, src, dst); - return direct; - -} - diff --git a/network/socks/socks.cstc.4.2/lib/check_user.c b/network/socks/socks.cstc.4.2/lib/check_user.c deleted file mode 100644 index c64a189d..00000000 --- a/network/socks/socks.cstc.4.2/lib/check_user.c +++ /dev/null @@ -1,175 +0,0 @@ -#include "socks.h" - -#include <netdb.h> -/* >>> K. Shackelford */ -#if defined(hpux) || defined(AIX) -#include <sys/types.h> -#include <netinet/in.h> -#endif -/* <<< K. Shackelford */ -#include <stdio.h> -#include <ctype.h> -/* >>> YDL, 93/10/26 */ -#if (defined(sun) && !defined(SOLARIS)) || defined(sgi) -#include <strings.h> -#else -#include <string.h> -#endif - -#ifdef SOLARIS -#include "bstring.h" -#endif - -/* <<< YDL< 93/10/26 */ -extern char *porttoserv(); -extern char *saddrtoname(); - -/* - * These functions are used by both Validate (for sockd) - * and check_cconf (for clients). - */ - -/* -** Simple 'mkargs' doesn't handle \, ", or '. -*/ -void mkargs(cp, argc, argv, max) -char *cp; -int *argc; -char *argv[]; -int max; -{ - *argc = 0; - while (isspace(*cp)) - cp++; - - while (*cp != '\0') { - argv[(*argc)++] = cp; - if (*argc >= max) - return; - - while (!isspace(*cp) && (*cp != '\0')) - cp++; - while (isspace(*cp)) - *cp++ = '\0'; - } -} - -/* -** Get address, either numeric or dotted quad, or hex. - * Result is in network byte order. -*/ -int GetAddr(name, addr) -char *name; -u_int32 *addr; -{ - struct hostent *hp; - struct netent *np; - - if ((hp = gethostbyname(name)) != NULL) { - bcopy(hp->h_addr_list[0], addr, sizeof(*addr)); - return *addr; - } - if ((np = getnetbyname(name)) != NULL) { - bcopy(&np->n_net, addr, sizeof(*addr)); - return *addr; - } - return *addr = inet_addr(name); -} - -long GetPort(name) -char *name; -/* result is in HOST byte order */ -{ - struct servent *sp; - - if ((sp = getservbyname(name, "tcp")) != NULL) { - return ntohs(sp->s_port); - } - if (!isdigit(*name)) - return -1; - return atol(name); -} - - -int check_user(userlist, src_user) - -char *userlist, *src_user; - -/* - * Unless userlist is a null pointer, in which case all users are - * allowed (return 1), otherwise - * userlist is a nonempty string containing userids separated by - * commas, no other separators are allowed in the string. - * 94/03/02: if userlist starts with '/', it specifies a file - * containing userids. - * - * Return 1 if src_user is in the userlist; - * return 0 if not, or if userfile cannot be open. - */ -{ - char *p, *q; - - if (!(p = userlist)) { - return 1; - } - do { - if (q = index(p, ',')) - *q++ = '\0'; - if (*p == '/') { - switch (check_userfile(p, src_user)) { - case 1: - return 1; - case -1: - return 0; - default: - ; - } - } else if (strcmp(p, src_user) == 0) { - return 1; - } - } while ( p = q); - - return 0; -} - -#include <string.h> -#include <syslog.h> - -int check_userfile(userfile, src_user) -char *userfile, *src_user; -/* return 1 if match, 0 otherwise */ -/* return -1 if cannot open file */ -{ - FILE *fd; -#define BUFLEN 1024 - static char buf[BUFLEN]; - char *bp; - - if ((fd = fopen(userfile, "r")) == NULL) { -/* -#ifdef MONITOR - sendto(mon_sd, &mon_msg, socks_type1_len, 0, mon_un_addr, mon_un_len); - failure_mon(MON_ERR_NO_USERFILE); -#endif -*/ - syslog(LOG_HIGH,"Unable to open userfile (%s)\n", userfile); - return (-1); - } - - while (fgets(buf, BUFLEN, fd) != NULL) { - if ((bp = index(buf, '\n')) != NULL) - *bp = '\0'; - if (( bp = index(buf, '#')) != NULL) - *bp = '\0'; - - for (bp = strtok(buf, " ,\t"); bp != NULL; - bp = strtok(NULL, " ,\t")) { - if (strcmp(bp, src_user) == 0) { - fclose(fd); - return 1; - } - } - } - fclose(fd); - return 0; -} diff --git a/network/socks/socks.cstc.4.2/lib/getpass.c b/network/socks/socks.cstc.4.2/lib/getpass.c deleted file mode 100644 index 61c8efde..00000000 --- a/network/socks/socks.cstc.4.2/lib/getpass.c +++ /dev/null @@ -1,128 +0,0 @@ -/* - * Copyright (c) 1988 The Regents of the University of California. - * All rights reserved. - * - * Redistribution and use in source and binary forms are permitted - * provided that the above copyright notice and this paragraph are - * duplicated in all such forms and that any documentation, - * advertising materials, and other materials related to such - * distribution and use acknowledge that the software was developed - * by the University of California, Berkeley. The name of the - * University 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 WITHOUT ANY EXPRESS OR - * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED - * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. - */ - -#if defined(LIBC_SCCS) && !defined(lint) -static char sccsid[] = "@(#)getpass.c based on 5.3 (Berkeley) 9/22/88"; -#endif /* LIBC_SCCS and not lint */ - -#if defined(__NetBSD__) -#define USE_OLD_TTY -#endif - -/* >>> Craig Metz */ -#if defined(LINUX) -#define SVR3 -#endif -/* <<< Craig Metz */ - -#if defined(SOLARIS) || defined(hpux) -#include <signal.h> -#include <sgtty.h> -#include <sys/ioctl.h> -#else -#ifdef SVR3 -#include <termio.h> -#else -#include <sys/ioctl.h> -#endif -#include <sys/signal.h> -#endif -#include <stdio.h> - -char * -getpass(prompt) - char *prompt; -{ -#ifdef SVR3 - struct termio term_struct; - tcflag_t svflagval; -#else - struct sgttyb ttyb; - int svflagval; -#endif - register int ch; - register char *p; - FILE *fp, *outfp; -#ifdef SOLARIS - sigset_t maskset; -#else - long omask; -#endif -#define PASSWD_LEN 128 - static char buf[PASSWD_LEN + 1]; - - /* - * read and write to /dev/tty if possible; else read from - * stdin and write to stderr. - */ - if ((outfp = fp = fopen("/dev/tty", "w+")) == NULL) { - outfp = stderr; - fp = stdin; - } -#ifdef SVR3 - (void)ioctl(fileno(fp), TCGETA, &term_struct); - svflagval = term_struct.c_lflag; - term_struct.c_lflag &= ~ECHO; -#else - (void)ioctl(fileno(fp), TIOCGETP, &ttyb); - svflagval = ttyb.sg_flags; - ttyb.sg_flags &= ~ECHO; -#endif - -#ifdef SOLARIS - if (sigprocmask(0, (sigset_t *)0, &maskset) || sighold(SIGINT)) { - perror("Can't block SIGINT in getpass() "); - exit(1); - } -#else - omask = sigblock(sigmask(SIGINT)); -#endif - -#ifdef SVR3 - (void)ioctl(fileno(fp), TCSETA, &term_struct); -#else - (void)ioctl(fileno(fp), TIOCSETP, &ttyb); -#endif - - fputs(prompt, outfp); - rewind(outfp); /* implied flush */ - for (p = buf; (ch = getc(fp)) != EOF && ch != '\n';) - if (p < buf + PASSWD_LEN) - *p++ = ch; - *p = '\0'; - (void)write(fileno(outfp), "\n", 1); -#ifdef SVR3 - term_struct.c_lflag = svflagval; - (void)ioctl(fileno(fp), TCSETA, &term_struct); -#else - ttyb.sg_flags = svflagval; - (void)ioctl(fileno(fp), TIOCSETP, &ttyb); -#endif - -#ifdef SOLARIS - if (sigprocmask(SIG_SETMASK, &maskset, (sigset_t *)0)) { - perror("Can't restore signal mask in getpass() "); - exit(1); - } -#else - (void)sigsetmask(omask); -#endif - if (fp != stdin) - (void)fclose(fp); - return(buf); -} - diff --git a/network/socks/socks.cstc.4.2/lib/percent_x.c b/network/socks/socks.cstc.4.2/lib/percent_x.c deleted file mode 100644 index db5d8760..00000000 --- a/network/socks/socks.cstc.4.2/lib/percent_x.c +++ /dev/null @@ -1,110 +0,0 @@ - /* - * percent_x() takes a string and performs %x subsitutions. - * It aborts the program when the result of - * expansion would overflow the output buffer. Because the result of %<char> - * expansion is typically passed on to a shell process, characters that may - * confuse the shell are replaced by underscores. - * - * Diagnostics are reported through syslog(3). - * - * Author: Wietse Venema, Eindhoven University of Technology, The Netherlands. - * - * Adapted for use with SOCKS by Ying-Da Lee, NEC Systems Lab, CSTC - * ylee@syl.dl.nec.com - * - */ - -#ifndef lint -static char sccsid[] = "@(#) percent_x.c 1.2 92/08/24 21:46:22"; -#endif - -/* System libraries. */ - -#include <sys/types.h> -#include <sys/socket.h> -#include <netinet/in.h> -#include <arpa/inet.h> -#include <stdio.h> -#include <syslog.h> -#include "socks.h" - -extern char *strncpy(); -extern char *strchr(); -extern void exit(); - -extern char socks_src_name[], socks_src_user[]; -extern char socks_real_user[]; -extern char socks_dst_name[], socks_dst_serv[]; -extern char socks_cmd[]; - -/* percent_x - do %<char> expansion, abort if result buffer is too small */ - -void percent_x(result, result_len, str, src, dst, pid) -char *result; -int result_len; -char *str; -struct sockaddr_in *src, *dst; -int pid; -{ - char *end = result + result_len - 1; /* end of result buffer */ - char *expansion; - int expansion_len; - char pid_buf[10]; - char port_buf[10]; - static char ok_chars[] = "1234567890!@%-_=+\\:,./\ -abcdefghijklmnopqrstuvwxyz\ -ABCDEFGHIJKLMNOPQRSTUVWXYZ"; - char *cp; - - /* - * %A: the client domainname if known, IP address otherwise - * %a: the client IP address - * %c: "connect" or "bind" - * %p: the daemon or client program process id - * %S: the service name (ftp, telnet,etc.) if known, port number otherwise - * %s: the destination port number - * %U: for sockd, this is the username as reported by identd; - * for client program, this is the name used at login - * %u: for sockd, this is the username as reported by the client program; - * for client program, this is the username of the effective userid - * %Z: the destination domainname if known, IP address otherwise - * %z: the destination IP address - * - * %% becomes a %, and %other is ignored. We terminate with a diagnostic if - * we would overflow the result buffer. Characters that may confuse the - * shell are mapped to underscores. - */ - - while (*str) { - if (*str == '%') { - str++; - expansion = - *str == 'A' ? (str++, socks_src_name) : - *str == 'a' ? (str++, inet_ntoa(src->sin_addr)) : - *str == 'c' ? (str++, socks_cmd) : - *str == 'p' ? (str++, sprintf(pid_buf, "%d", pid), pid_buf) : - *str == 'S' ? (str++, socks_dst_serv) : - *str == 's' ? (str++, sprintf(port_buf, "%u", ntohs(dst->sin_port)), port_buf) : - *str == 'U' ? (str++, socks_real_user) : - *str == 'u' ? (str++, socks_src_user) : - *str == 'Z' ? (str++, socks_dst_name) : - *str == 'z' ? (str++, inet_ntoa(dst->sin_addr)) : - *str == '%' ? (str++, "%") : - *str == 0 ? "" : (str++, ""); - expansion_len = strlen(expansion); - for (cp = expansion; *cp; cp++) - if (strchr(ok_chars, *cp) == 0) - *cp = '_'; - } else { - expansion = str++; - expansion_len = 1; - } - if (result + expansion_len >= end) { - syslog(LOG_HIGH, "shell command too long: %30s...", result); - exit(0); - } - strncpy(result, expansion, expansion_len); - result += expansion_len; - } - *result = 0; -} diff --git a/network/socks/socks.cstc.4.2/lib/porttoserv.c b/network/socks/socks.cstc.4.2/lib/porttoserv.c deleted file mode 100644 index 2da25bda..00000000 --- a/network/socks/socks.cstc.4.2/lib/porttoserv.c +++ /dev/null @@ -1,20 +0,0 @@ -#include <sys/types.h> -#include <sys/socket.h> -#include <netinet/in.h> -#include <netdb.h> - -char *porttoserv(sin_port, name, namelen) -int sin_port; /* port number in network byte order */ -char *name; -int namelen; -{ - struct servent *serv; - int port = ntohs(sin_port); - - if ((serv = getservbyport(port, "tcp")) != (struct servent *)0) - strncpy(name, serv->s_name, namelen); - else - sprintf(name, "%u", port); - return(name); -} - diff --git a/network/socks/socks.cstc.4.2/lib/saddrtoname.c b/network/socks/socks.cstc.4.2/lib/saddrtoname.c deleted file mode 100644 index aee0f56f..00000000 --- a/network/socks/socks.cstc.4.2/lib/saddrtoname.c +++ /dev/null @@ -1,19 +0,0 @@ -#include <sys/types.h> -#include <sys/socket.h> -#include <netinet/in.h> -#include <netdb.h> - -char *saddrtoname(addr, name, namelen) -struct in_addr *addr; -char *name; -int namelen; -{ - struct hostent *host; - - if ((host = gethostbyaddr((char *)addr, 4, AF_INET)) != (struct hostent *)0) - strncpy(name, host->h_name, namelen); - else - strncpy(name, inet_ntoa(*addr), namelen); - return(name); -} - diff --git a/network/socks/socks.cstc.4.2/lib/shell_cmd.c b/network/socks/socks.cstc.4.2/lib/shell_cmd.c deleted file mode 100644 index 579ca878..00000000 --- a/network/socks/socks.cstc.4.2/lib/shell_cmd.c +++ /dev/null @@ -1,112 +0,0 @@ - /* - * shell_cmd() takes a shell command template and performs %x substitutions. - * The result is executed - * by a /bin/sh child process, with standard input, standard output and - * standard error connected to /dev/null. - * - * Diagnostics are reported through syslog(3). - * - * Author: Wietse Venema, Eindhoven University of Technology, The Netherlands. - * - * Adapted for use with SOCKS by Ying-Da Lee, NEC Systems Lab, CSTC - * ylee@syl.dl.nec.com - * - */ - -#ifndef lint -static char sccsid[] = "@(#) shell_cmd.c 1.2 92/06/11 22:21:28"; -#endif - -/* System libraries. */ - -#include <sys/types.h> -#include <sys/param.h> -#include <netinet/in.h> -#include <stdio.h> -#include <syslog.h> -#include "socks.h" - -extern char *strncpy(); -extern void closelog(); -extern void exit(); - -/* Forward declarations. */ - -static void do_child(); - -/* shell_cmd - expand %<char> sequences and execute shell command */ - -void shell_cmd(string, src, dst) -char *string; -struct sockaddr_in *src, *dst; -{ - char cmd[BUFSIZ]; - static char alpha_num[] = "abcdefghijklmnopqrstuvwxyz\ -ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; - int child_pid; - int wait_pid; - int daemon_pid = getpid(); - - percent_x(cmd, sizeof(cmd), string, src, dst, daemon_pid); - if (strpbrk(cmd, alpha_num) == NULL) { - syslog(LOG_HIGH, "error -- shell command \"%s\" contains no alphanumeric characters.", cmd); - return; - } - - /* - * Most of the work is done within the child process, to minimize the - * risk of damage to the parent. - */ - - switch (child_pid = fork()) { - case -1: /* error */ - syslog(LOG_HIGH, "error -- shell_cmd fork() %m"); - break; - case 00: /* child */ - do_child(daemon_pid, cmd); - /* NOTREACHED */ - default: /* parent */ - while ((wait_pid = wait((int *) 0)) != -1 && wait_pid != child_pid) - /* void */ ; - } -} - -/* do_child - exec command with { stdin, stdout, stderr } to /dev/null */ - -static void do_child(daemon_pid, command) -int daemon_pid; -char *command; -{ - char *error = 0; - int tmp_fd; - - /* - * Close a bunch of file descriptors. The Ultrix inetd only passes stdin, - * but other inetd implementations set up stdout as well. Ignore errors. - */ - - closelog(); - for (tmp_fd = 0; tmp_fd < 10; tmp_fd++) - (void) close(tmp_fd); - - /* Set up new stdin, stdout, stderr, and exec the shell command. */ - - if (open("/dev/null", 2) != 0) { - error = "open /dev/null: %m"; - } else if (dup(0) != 1 || dup(0) != 2) { - error = "dup: %m"; - } else { - (void) execl("/bin/sh", "sh", "-c", command, (char *) 0); - error = "execl /bin/sh: %m"; - } - - /* We can reach the following code only if there was an error. */ - -#ifdef LOG_DAEMON - (void) openlog("sockd", LOG_PID, SYSLOG_FAC); -#else - (void) openlog("sockd", LOG_PID); -#endif - syslog(LOG_HIGH, "Cannot execute shell command for pid %d", daemon_pid); - exit(0); -} diff --git a/network/socks/socks.cstc.4.2/libident/Makefile b/network/socks/socks.cstc.4.2/libident/Makefile deleted file mode 100644 index 7b0c6e89..00000000 --- a/network/socks/socks.cstc.4.2/libident/Makefile +++ /dev/null @@ -1,93 +0,0 @@ -# -# Makefile for the libident library - -# Remember to include -Dindex=strchr in OTHER_CFLAGS if -# you don't have index() (Sys-V camp) - -# IRIX should have CCKR defined: -#OTHER_CFLAGS=-cckr -#RANLIB=/bin/true - -# AIX should use -#OTHER_CFLAGS=-D_BSD -D_NONSTD_TYPES -D_NO_PROTO -DAIX -#RANLIB=ranlib - -# Solaris should use -#OTHER_CFLAGS=-DSOLARIS -Dindex=strchr -Drindex=strrchr -DUSE_DIRENT -#RANLIB=/bin/true - -# Interactive Systems Unix should use -# OTHER_CFLAGS = -DISC - -# LINUX should use -#CC=gcc -#RESOLV_LIB= -#OTHER_CFLAGS=-traditional -DLINUX - -# UnixWare should use -#RESOLV_LIB=-lresolv -lnsl -lsocket -#OTHER_CFLAGS= -DSOLARIS -Dindex=strchr -Drindex=strrchr -DUSE_DIRENT -#RANLIB=/bin/true -#INSTALL=bsdinstall - -# >>>---------------- Others: - -# This is slightly tuned for a 4BSD system (like SunOS 4). -# For systems that do not need (and therefore don't have) 'ranlib', -# comment out the next line and use the line below. -RANLIB=ranlib -#RANLIB=/bin/true - -# <<<---------------- - -# Set LIBDIR, INCDIR, and MANDIR to the direcories into which -# the library (libident.a), the include file (ident.h), and -# the man pages should be installed, respectively. -# Comment out the correponding lines for the items you don't -# want installed. -# This is where you want to install the library -LIBDIR=/usr/local/lib -# And this is where the header file ident.h goes -INCDIR=/usr/local/include -# And the manual page -MANDIR=/usr/local/man/man3 - -OPTIMIZE=-g -CFLAGS = ${OPTIMIZE} $(OTHER_CFLAGS) - -# The 'install' command is assumed to be the BSD variety (using -m to -# set the file mode). If the default 'install' on your system doesn't -# do that, you have to either specify an alternative one in the line below -# (e.g., /usr/ucb/install) or modify the install instructions. -INSTALL= install - -#============================================================= -OBJS = ident.o id_open.o id_close.o id_query.o id_parse.o - -libident.a: echocwd $(OBJS) - -rm -f libident.a - ar cq libident.a $(OBJS) - $(RANLIB) libident.a - -ident.o: ident.c ident.h -id_open.o: id_open.c ident.h -id_close.o: id_close.c ident.h -id_query.o: id_query.c ident.h -id_parse.o: id_parse.c ident.h - -install: echocwd - -if [ -d $(LIBDIR) ]; then \ - ($(INSTALL) -m 644 libident.a $(LIBDIR); \ - $(RANLIB) -t $(LIBDIR)/libident.a); fi - -if [ -d $(INCDIR) ]; then \ - $(INSTALL) -m 644 ident.h $(INCDIR); fi - -install.man: echocwd - -if [ -d $(MANDIR) ]; then \ - $(INSTALL) -m 644 ident.3 $(MANDIR); fi - -clean: echocwd - -rm -f libident.a *~ core *.o \#* - -echocwd: - @pwd diff --git a/network/socks/socks.cstc.4.2/libident/README b/network/socks/socks.cstc.4.2/libident/README deleted file mode 100644 index 3fbfeb3b..00000000 --- a/network/socks/socks.cstc.4.2/libident/README +++ /dev/null @@ -1,16 +0,0 @@ -This is the second stab at a small library to interface to the Ident -protocol server. Maybe this will work correctly on some machines.. :-) - -The ident-tester.c file is a small daemon (to be started from Inetd) -that does an ident lookup on you if you telnet into it. Can be used -to verify that your Ident server is working correctly. - -I'm currently running this "ident-tester" on port 114 at lysator.liu.se -if you wish to test your server. - -/Peter Eriksson <pen@lysator.liu.se>, 1 Aug 1992 - -This library now contains some higher-level routines, as well as a -similar test program to test these (lookup-tester). - -/Pär Emanuelsson <pell@lysator.liu.se>, 4 April 1993 diff --git a/network/socks/socks.cstc.4.2/libident/id_close.c b/network/socks/socks.cstc.4.2/libident/id_close.c deleted file mode 100644 index 7f5a1b89..00000000 --- a/network/socks/socks.cstc.4.2/libident/id_close.c +++ /dev/null @@ -1,25 +0,0 @@ -/* -** id_close.c Close a connection to an IDENT server -** -** Author: Peter Eriksson <pen@lysator.liu.se> -*/ - -#include "ident.h" - -int id_close -#ifdef __STDC__ - (ident_t *id) -#else - (id) -ident_t *id; -#endif -{ - int res; - - res = close(id->fd); - free(id); - - return res; -} - - diff --git a/network/socks/socks.cstc.4.2/libident/id_open.c b/network/socks/socks.cstc.4.2/libident/id_open.c deleted file mode 100644 index dabf3e70..00000000 --- a/network/socks/socks.cstc.4.2/libident/id_open.c +++ /dev/null @@ -1,162 +0,0 @@ -/* -** id_open.c Establish/initiate a connection to an IDENT server -** -** Author: Peter Eriksson <pen@lysator.liu.se> -** Fixes: Pdr Emanuelsson <pell@lysator.liu.se> -*/ - - -#include <stdio.h> -#include <errno.h> -#include <memory.h> - -#include <sys/types.h> -#include <sys/socket.h> -#include <sys/wait.h> -#include <sys/time.h> -#include <sys/file.h> -#include <netinet/in.h> -#include <arpa/inet.h> - -/* SOLARIS */ -#if defined(__svr4__) || defined (SOLARIS) || defined(SCO) -#include <fcntl.h> -#endif - -/* LINUX */ -#ifdef LINUX -#include <unistd.h> -#include <stdlib.h> -#include <fcntl.h> -#ifdef FNDLEAY /*watch out for a ?typo? in fcntl.h !? */ -#define FNDELAY FNDLEAY -#endif - -/* - * Structure used for manipulating linger option. - */ -struct linger { - int l_onoff; /* option on/off */ - int l_linger; /* linger time */ -}; -#endif - - -#include "ident.h" - -extern void *malloc __P((int size)); - - -ident_t *id_open -#ifdef __STDC__ - (struct in_addr *laddr, struct in_addr *faddr, struct timeval *timeout) -#else - (laddr, faddr, timeout) -struct in_addr *laddr; -struct in_addr *faddr; -struct timeval *timeout; -#endif -{ - ident_t *id; - int res, tmperrno; - struct sockaddr_in sin_laddr, sin_faddr; - fd_set rs, ws, es; -#if !defined(SO_DONTLINGER) || defined(SOLARIS) - struct linger linger; -#endif - -#if defined(sgi) || defined (SOLARIS) - int on = 1; -#endif - - if ((id = (ident_t *) malloc(sizeof(*id))) == 0) - return 0; - - if ((id->fd = socket(AF_INET, SOCK_STREAM, 0)) < 0) - { - free(id); - return 0; - } - - if (timeout) - { - if ((res = fcntl(id->fd, F_GETFL, 0)) < 0) - goto ERROR; - - if (fcntl(id->fd, F_SETFL, res | FNDELAY) < 0) - goto ERROR; - } - -#if defined(SO_DONTLINGER) && !defined(SOLARIS) - if (setsockopt(id->fd, SOL_SOCKET, SO_DONTLINGER, 0, 0) < 0) - goto ERROR; -#else - linger.l_onoff = 0; - linger.l_linger = 0; - - if (setsockopt(id->fd, SOL_SOCKET, SO_LINGER, &linger, sizeof(linger)) < 0) - goto ERROR; -#endif - -#if defined(sgi) || defined(SOLARIS) - if (setsockopt(id->fd, SOL_SOCKET, SO_REUSEADDR, (char *)&on, - sizeof(on)) < 0) -#else - if (setsockopt(id->fd, SOL_SOCKET, SO_REUSEADDR, 0, 0) < 0) -#endif - goto ERROR; - - id->buf[0] = '\0'; - - memset(&sin_laddr, 0, sizeof(sin_laddr)); - sin_laddr.sin_family = AF_INET; - sin_laddr.sin_addr = *laddr; - sin_laddr.sin_port = 0; - - if (bind(id->fd, (struct sockaddr *)&sin_laddr, sizeof(sin_laddr)) < 0) - goto ERROR; - - memset(&sin_faddr, 0, sizeof(sin_faddr)); - sin_faddr.sin_family = AF_INET; - sin_faddr.sin_addr = *faddr; - sin_faddr.sin_port = htons(IDPORT); - - res = connect(id->fd, (struct sockaddr *)&sin_faddr, sizeof(sin_faddr)); - if (res < 0 && errno != EINPROGRESS) - goto ERROR; - - if (timeout) - { - FD_ZERO(&rs); - FD_ZERO(&ws); - FD_ZERO(&es); - FD_SET(id->fd, &rs); - FD_SET(id->fd, &ws); - FD_SET(id->fd, &es); - - if ((res = select(FD_SETSIZE, &rs, &ws, &es, timeout)) < 0) - goto ERROR; - - if (res == 0) - { - errno = ETIMEDOUT; - goto ERROR; - } - - if (FD_ISSET(id->fd, &es)) - goto ERROR; - - if (!FD_ISSET(id->fd, &rs) && !FD_ISSET(id->fd, &ws)) - goto ERROR; - } - - return id; - -ERROR: - tmperrno = errno; /* Save, so close() won't erase it */ - close(id->fd); - free(id); - errno = tmperrno; - return 0; -} - diff --git a/network/socks/socks.cstc.4.2/libident/id_parse.c b/network/socks/socks.cstc.4.2/libident/id_parse.c deleted file mode 100644 index 877ad7b3..00000000 --- a/network/socks/socks.cstc.4.2/libident/id_parse.c +++ /dev/null @@ -1,236 +0,0 @@ -/* -** id_parse.c Receive and parse a reply from an IDENT server -** -** Author: Peter Eriksson <pen@lysator.liu.se> -** Fiddling: Pär Emanuelsson <pell@lysator.liu.se> -*/ - -#include <stdio.h> -#include <errno.h> -#include <ctype.h> -#include <string.h> - -#include <sys/types.h> -#include <sys/wait.h> -#include <sys/time.h> - -#include "ident.h" - -/* >>> Ian Dunkin */ -#if defined(ultrix) || defined(AIX_PS2) -char *strdup(s) -char *s; -{ - char *malloc(); - static char *p; - - if ((p = malloc(strlen(s) + 1)) != NULL) - strcpy(p, s); - return(p); -} -#endif -/* <<< Ian Dunkin */ - -static char *xstrtok -#ifdef __STDC__ - (char *cp, char *cs, char *dc) -#else - (cp, cs, dc) -char *cp; -char *cs; -char *dc; -#endif -{ - static char *bp = 0; - - if (cp) - bp = cp; - - /* - ** No delimitor cs - return whole buffer and point at end - */ - if (!cs) - { - while (*bp) - bp++; - return cs; - } - - /* - ** Skip leading spaces - */ - while (isspace(*bp)) - bp++; - - /* - ** No token found? - */ - if (!*bp) - return 0; - - cp = bp; - while (*bp && !index(cs, *bp)) - bp++; - - /* - ** Remove trailing spaces - */ - *dc = *bp; - for (dc = bp-1; dc > cp && isspace(*dc); dc--) - ; - *++dc = '\0'; - - bp++; - - return cp; -} - - -int id_parse -#ifdef __STDC__ - (ident_t *id, - struct timeval *timeout, - int *lport, - int *fport, - char **identifier, - char **opsys, - char **charset) -#else - (id, timeout, lport, fport, identifier, opsys, charset) -ident_t *id; -struct timeval *timeout; -int *lport; -int *fport; -char **identifier; -char **opsys; -char **charset; -#endif -{ - char c, *cp, *tmp_charset; - fd_set rs; - int pos, res, lp, fp; - - errno = 0; - - tmp_charset = 0; - - if (!id) return -1; - if (lport) *lport = 0; - if (fport) *fport = 0; - if (identifier) *identifier = 0; - if (opsys) *opsys = 0; - if (charset) *charset = 0; - - pos = strlen(id->buf); - - if (timeout) - { - FD_ZERO(&rs); - FD_SET(id->fd, &rs); - - if ((res = select(FD_SETSIZE, &rs, (fd_set *)0, (fd_set *)0, timeout)) < 0) - return -1; - - if (res == 0) - { - errno = ETIMEDOUT; - return -1; - } - } - - while (pos < sizeof(id->buf) && - (res = read(id->fd, id->buf + pos, 1)) == 1 && - id->buf[pos] != '\n') - pos++; - - if (res < 0) - return -1; - - if (res == 0) - { - errno = ENOTCONN; - return -1; - } - - if (id->buf[pos] != '\n') - return 0; - - id->buf[pos++] = '\0'; - - /* - ** Get first field (<lport> , <fport>) - */ - cp = xstrtok(id->buf, ":", &c); - if (!cp) - return -2; - - if (sscanf(cp, " %d , %d", &lp, &fp) != 2) - { - if (identifier) *identifier = strdup(cp); - return -2; - } - - if (lport) *lport = lp; - if (fport) *fport = fp; - - /* - ** Get second field (USERID or ERROR) - */ - cp = xstrtok((char *)0, ":", &c); - if (!cp) - return -2; - - if (strcmp(cp, "ERROR") == 0) - { - cp = xstrtok((char *)0, "\n\r", &c); - if (!cp) - return -2; - - if (identifier) *identifier = strdup(cp); - - return 2; - } - else if (strcmp(cp, "USERID") == 0) - { - /* - ** Get first subfield of third field <opsys> - */ - cp = xstrtok((char *)0, ",:", &c); - if (!cp) - return -2; - - if (opsys) *opsys = strdup(cp); - - /* - ** We have a second subfield (<charset>) - */ - if (c == ',') - { - cp = xstrtok((char *)0, ":", &c); - if (!cp) - return -2; - - tmp_charset = cp; - if (charset) *charset = strdup(cp); - - /* - ** We have even more subfields - ignore them - */ - if (c == ',') - xstrtok((char *)0, ":", &c); - } - - if (tmp_charset && strcmp(tmp_charset, "OCTET") == 0) - cp = xstrtok((char *)0, (char *)0, &c); - else - cp = xstrtok((char *)0, "\n\r", &c); - - if (identifier) *identifier = strdup(cp); - return 1; - } - else - { - if (identifier) *identifier = strdup(cp); - return -3; - } -} diff --git a/network/socks/socks.cstc.4.2/libident/id_query.c b/network/socks/socks.cstc.4.2/libident/id_query.c deleted file mode 100644 index 41b94cf0..00000000 --- a/network/socks/socks.cstc.4.2/libident/id_query.c +++ /dev/null @@ -1,62 +0,0 @@ -/* -** id_query.c Transmit a query to an IDENT server -** -** Author: Peter Eriksson <pen@lysator.liu.se> -*/ - -#include <stdio.h> -#include <errno.h> -#include <signal.h> - -#include <sys/types.h> -#include <sys/wait.h> -#include <sys/time.h> - -#include "ident.h" - - -int id_query -#ifdef __STDC__ - (ident_t *id, int lport, int fport, struct timeval *timeout) -#else - (id, lport, fport, timeout) -ident_t *id; -int lport; -int fport; -struct timeval *timeout; -#endif -{ -#if defined(SOLARIS) || defined(_SEQUENT_) - void (*old_sig)(); -#else - void *old_sig; -#endif - int res; - char buf[80]; - fd_set ws; - - sprintf(buf, "%d , %d\r\n", lport, fport); - - if (timeout) - { - FD_ZERO(&ws); - FD_SET(id->fd, &ws); - - if ((res = select(FD_SETSIZE, (fd_set *)0, &ws, (fd_set *)0, timeout)) < 0) - return -1; - - if (res == 0) - { - errno = ETIMEDOUT; - return -1; - } - } - - old_sig = signal(SIGPIPE, SIG_IGN); - - res = write(id->fd, buf, strlen(buf)); - - signal(SIGPIPE, old_sig); - - return res; -} diff --git a/network/socks/socks.cstc.4.2/libident/ident-tester.c b/network/socks/socks.cstc.4.2/libident/ident-tester.c deleted file mode 100644 index 052e27ff..00000000 --- a/network/socks/socks.cstc.4.2/libident/ident-tester.c +++ /dev/null @@ -1,171 +0,0 @@ -/* -** ident-tester.c A small daemon that can be used to test Ident -** servers -** -** Author: Peter Eriksson <pen@lysator.liu.se>, 10 Aug 1992 -*/ - -#include <stdio.h> -#include <netdb.h> -#include <syslog.h> - -#include <sys/types.h> -#include <sys/socket.h> -#include <netinet/in.h> -#include <arpa/inet.h> - -#include "ident.h" - -/* -** Return the name of the connecting host, or the IP number as a string. -*/ -char *gethost(addr) - struct in_addr *addr; -{ - struct hostent *hp; - - - hp = gethostbyaddr(addr, sizeof(struct in_addr), AF_INET); - if (hp) - return hp->h_name; - else - return inet_ntoa(*addr); -} - - -main(argc,argv) - int argc; - char *argv[]; -{ - struct sockaddr_in laddr, faddr; - int len, res, lport, fport; - ident_t *id; - char *identifier, *opsys, *charset; - - - puts("Welcome to the IDENT server tester, version 1.7\r\n\r"); - fflush(stdout); - - len = sizeof(faddr); - getpeername(0, &faddr, &len); - - len = sizeof(laddr); - getsockname(0, &laddr, &len); - - printf("Connecting to Ident server at %s...\r\n", inet_ntoa(faddr.sin_addr)); - fflush(stdout); - -#ifdef LOG_LOCAL3 - openlog("tidentd", 0, LOG_LOCAL3); -#else - openlog("tidentd", 0); -#endif - - id = id_open(&laddr.sin_addr, &faddr.sin_addr, NULL); - if (!id) - { - perror("id_open()"); - fflush(stderr); - syslog(LOG_ERR, "Error: id_open(): host=%s, error=%m", - gethost(&faddr.sin_addr)); - exit(1); - } - - printf("Querying for lport %d, fport %d....\r\n", - (int) ntohs(faddr.sin_port), - (int) ntohs(laddr.sin_port)); - fflush(stdout); - - if (id_query(id, ntohs(faddr.sin_port), ntohs(laddr.sin_port), 0) < 0) - { - perror("id_query()"); - fflush(stderr); - syslog(LOG_ERR, "Error: id_query(): host=%s, error=%m", - gethost(&faddr.sin_addr)); - exit(1); - } - - printf("Reading response data...\r\n"); - fflush(stdout); - - res = id_parse(id, NULL, - &lport, &fport, - &identifier, - &opsys, - &charset); - - switch (res) - { - default: - perror("id_parse()"); - syslog(LOG_ERR, "Error: id_parse(): host=%s, error=%m", - gethost(&faddr.sin_addr)); - break; - - case -2: - syslog(LOG_ERR, "Error: id_parse(): host=%s, Parse Error: %s", - gethost(&faddr.sin_addr), - identifier ? identifier : "<no information available>"); - - if (identifier) - printf("Parse error on reply:\n \"%s\"\n", identifier); - else - printf("Unidentifiable parse error on reply.\n"); - break; - - case -3: - syslog(LOG_ERR, "Error: id_parse(): host=%s, Illegal reply type: %s", - gethost(&faddr.sin_addr), - identifier); - - printf("Parse error in reply: Illegal reply type: %s\n", identifier); - break; - - case 0: - syslog(LOG_ERR, "Error: id_parse(): host=%s, NotReady", - gethost(&faddr.sin_addr)); - puts("Not ready. This should not happen...\r"); - break; - - case 2: - syslog(LOG_INFO, "Reply: Error: host=%s, error=%s", - gethost(&faddr.sin_addr), identifier); - - printf("Error response is:\r\n"); - printf(" Lport........ %d\r\n", lport); - printf(" Fport........ %d\r\n", fport); - printf(" Error........ %s\r\n", identifier); - break; - - case 1: - if (charset) - syslog(LOG_INFO, - "Reply: Userid: host=%s, opsys=%s, charset=%s, userid=%s", - gethost(&faddr.sin_addr), opsys, charset, identifier); - else - syslog(LOG_INFO, "Reply: Userid: host=%s, opsys=%s, userid=%s", - gethost(&faddr.sin_addr), opsys, identifier); - - printf("Userid response is:\r\n"); - printf(" Lport........ %d\r\n", lport); - printf(" Fport........ %d\r\n", fport); - printf(" Opsys........ %s\r\n", opsys); - printf(" Charset...... %s\r\n", charset ? charset : "<not specified>"); - printf(" Identifier... %s\r\n", identifier); - - if (id_query(id, ntohs(faddr.sin_port), ntohs(laddr.sin_port), 0) >= 0) - { - if (id_parse(id, NULL, - &lport, &fport, - &identifier, - &opsys, - &charset) == 1) - printf(" Multiquery... Enabled\r\n"); - } - } - - fflush(stdout); - sleep(1); - exit(0); -} - diff --git a/network/socks/socks.cstc.4.2/libident/ident.3 b/network/socks/socks.cstc.4.2/libident/ident.3 deleted file mode 100644 index 8eb19658..00000000 --- a/network/socks/socks.cstc.4.2/libident/ident.3 +++ /dev/null @@ -1,276 +0,0 @@ -.\" Pär Emanuelsson <pell@lysator.liu.se> 1993-03-28 -.ds : \h'\w'u'u/5'\z"\h'-\w'e'u/5' -.TH IDENT 3N "4 April 1993" "Lysator ACS" -.SH NAME -ident_lookup, ident_id, ident_free, id_open, id_close, id_query, id_parse, -id_fileno \- query remote IDENT server -.SH SYNOPSIS -.nf -.B #include <ident.h> -.LP -.I High-level calls -.LP -.B IDENT *ident_lookup(int fd, int timeout) -.LP -.B char *ident_id(int fd, int timeout) -.LP -.B void ident_free(IDENT *id) -.LP -.I Low-level calls -.LP -.B id_t *id_open(laddr, faddr, timeout) -.B struct in_addr *laddr, *faddr; -.B struct timeval *timeout; -.LP -.B int id_close(id) -.B id_t *id; -.LP -.B id_query(id, lport, fport, timeout) -.B id_t *id; -.B int lport, fport; -.B struct timeval *timeout; -.LP -.B int id_parse(id, timeout, lport, fport, identifier, -.B opsys, charset) -.B id_t *id; -.B struct timeval *timeout; -.B int *lport, *fport; -.B char **identifier, **opsys, **charset; -.LP -.B int id_fileno(id) -.B id_t *id; -.fi -.SH DESCRIPTION -.LP -.B ident_lookup -tries to connect to a remote -.B IDENT -server to establish the identity of the peer connected on -.I fd, -which should be a socket file descriptor. -.I timeout -is the longest permissible time to block waiting for an answer, and is -given in seconds. A value of 0 (zero) means wait indefinitely (which in the -most extreme case will normally be until the underlying network times out). -.B ident_lookup -returns a pointer to an -.I IDENT -struct, which has the following contents: -.RS -.LP -.nf -.ft B -typedef struct { - int lport; /* Local port */ - int fport; /* Far (remote) port */ - char *identifier; /* Normally user name */ - char *opsys; /* OS */ - char *charset; /* Charset (what did you expect?) */ -} IDENT; -.ft R -.fi -.RE -.LP -For a full description of the different fields, refer to -.I RFC-1413. -.LP -All data returned by -.B ident_lookup -(including the -.SM IDENT -struct) points to malloc'd data, which can be freed with a call to -.B ident_free. -.B ident_lookup -returns 0 on error or timeout. Presently, this should normally be taken to -mean that the remote site is not running an -.SM IDENT -server, but it might naturally be caused by other network related problems -as well. -.B Note that -all fields of the -.SM IDENT -struct need not necessarily be set. -.LP -.B ident_id -takes the same parameters as -.B ident_lookup -but only returns a pointer to a malloc'd area containing the -.I identifier -string, which is probably the most wanted data from the -.SM IDENT -query. -.LP -.B ident_free -frees all data areas associated with the -.SM IDENT -struct pointed to by -.I id, -including the struct itself. -.LP -.ce -.I Low-level calls -.LP -The low-level calls can be used when greater flexibility is needed. For -example, if non-blocking I/O is needed, or multiple queries to the -same host are to be made. -.LP -.B id_open -opens a connection to the remote -.SM IDENT -server referred to by -.I faddr. -The timeout is specified by -.I timeout. -A null-pointer means wait indefinitely, while a pointer to a -zero-valued -.I timeval -struct sets non-blocking I/O, in the same way as for -.B select(2). -.B id_open -returns a pointer to an -.B id_t -datum, which is an opaque structure to be used as future reference -to the opened connection. When using non-blocking I/O it might however -be useful to access the underlying socket file descriptior, which -can be gotten at through the -.B id_fileno -macro described below. -.LP -.B id_close -closes the connection opened with -.B id_open -and frees all data associated with -.I id. -.LP -.B id_query -sends off a query to a remote -.SM IDENT -server. -.I lport -and -.I fport -are sent to the server to identify the connection for which -identification is needed. -.I timeout -is given as for -.B id_open. -If successful, -.B id_query -returns the number of bytes sent to the remote server. If not, -1 is -returned and -.B errno -is set. -.LP -.B id_parse -parses the reply to a query sent off by -.B id_query -and returns information to the locations pointed to by -.I lport, fport, identifier, opsys -and -.I charset. -For string data -.I (identifier, opsys -and -.I charset) -pointers to malloc'd space are returned. -.LP -.B id_parse -returns: -.RS -.TP - 1 -If completely successful. -.TP --3 -Illegal reply type from remote server. -.I identifier -is set to the illegal reply. -.TP --2 -Cannot parse the reply from the server. -.I identifier -is normally set to the illegal reply. -.TP --1 -On general errors or timeout. -.TP - 0 -When non-blocking mode is set and -.B id_parse -has not finished parsing the reply from the remote server. -.TP - 2 -Indicates the query/reply were successful, but the remote server -experienced some error. -.I identifier -is set to the error message from the remote server. -.RE -.LP -For all errors, -.I errno -is set as appropriate. -.LP -.B id_fileno -is a macro that takes an -.B id_t -handle and returns the actual socket file descriptor used for -the connection to the remote server. -.SH ERRORS -.TP 15 -ETIMEDOUT -The call timed out and non-blocking I/O was not set. -.SH EXAMPLES -.LP -Here's an example how to handle the reply from id_reply() in -the case that non-blocking I/O is set. Note that id_reply() will -return 0 as long as it's not finished parsing a reply. -.LP -.RS -.nf -.nj -int rcode; - - ... - -idp = id_open(...) - - ... - -while ((rcode = id_parse(idp, timeout, - &lport, &fport, &id, &op, &cs)) == 0) - ; - -if (rcode < 0) -{ - if (rcode == ETIMEDOUT) - foo(); /* Lookup timed out */ - else - bar(); /* Fatal error */ -} -else if (rcode == 1) -{ - /* Valid USERID protocol reply */ -} -else if (rcode == 2) -{ - /* Protocol ERROR reply */ -} -.fi -.RE -.SH SEE ALSO -RFC-1413, socket(2), select(2) -.SH AUTHORS -Peter Eriksson -.I <pen@lysator.liu.se> -.br -P\*:ar Emanuelsson -.I <pell@lysator.liu.se> -.SH BUGS -For -.B ident_lookup -and -.B ident_id -the blocking time in extreme cases might be as much as three times -the value given in the -.I timeout -parameter. diff --git a/network/socks/socks.cstc.4.2/libident/ident.c b/network/socks/socks.cstc.4.2/libident/ident.c deleted file mode 100644 index 335fb09e..00000000 --- a/network/socks/socks.cstc.4.2/libident/ident.c +++ /dev/null @@ -1,139 +0,0 @@ -/* -** ident.c High-level calls to the ident lib -** -** Author: Pär Emanuelsson <pell@lysator.liu.se> -*/ - -#include <stdio.h> -#include <string.h> -#include <errno.h> - -#include <sys/types.h> -#include <sys/socket.h> -#include <netinet/in.h> -#include <arpa/inet.h> -#include <sys/time.h> - -#include "ident.h" - -#if defined(AIX_PS2) || defined(ultrix) -extern char *strdup(char *); -#endif - -/* Do a complete ident query and return result */ - -IDENT *ident_lookup -#ifdef __STDC__ - (int fd, - int timeout) -#else - (fd, timeout) - int fd; int timeout; -#endif -{ - struct sockaddr_in localaddr, remoteaddr; - int len, res; - ident_t *id; - struct timeval timout; - IDENT *ident=0; - - len = sizeof(remoteaddr); - if (getpeername(fd, (struct sockaddr *)&remoteaddr, &len) < 0) - return 0; - - len = sizeof(localaddr); - if (getsockname(fd, (struct sockaddr *)&localaddr, &len) < 0) - return 0; - - timout.tv_sec = timeout; timout.tv_usec = 0; - - if (timeout) - id = id_open(&localaddr.sin_addr, &remoteaddr.sin_addr, &timout); - else - id = id_open(&localaddr.sin_addr, &remoteaddr.sin_addr, (struct timeval *)0); - - if (!id) { - errno = EINVAL; - return 0; - } - - if (timeout) - res = id_query(id, - ntohs(remoteaddr.sin_port), - ntohs(localaddr.sin_port), - &timout); - else - res = id_query(id, - ntohs(remoteaddr.sin_port), - ntohs(localaddr.sin_port), - (struct timeval *) 0); - - if (res < 0) { - id_close(id); - return 0; - } - - ident = (IDENT *) malloc(sizeof(IDENT)); - if (!ident) { - id_close(id); - return 0; - } - - if (timeout) - res = id_parse(id, &timout, - &ident->lport, - &ident->fport, - &ident->identifier, - &ident->opsys, - &ident->charset); - else - res = id_parse(id, (struct timeval *) 0, - &ident->lport, - &ident->fport, - &ident->identifier, - &ident->opsys, - &ident->charset); - - if (res != 1) { - free(ident); - id_close(id); - return 0; - } - - id_close(id); - return ident; /* At last! */ -} - -char *ident_id -#ifdef __STDC__ - (int fd, - int timeout) -#else -(fd, timeout) - int fd; int timeout; -#endif -{ - IDENT *ident; - char *id=0; - - ident = ident_lookup(fd, timeout); - if (ident && ident->identifier && *ident->identifier) - id = strdup(ident->identifier); - ident_free(ident); - return id; -} - -void ident_free -#ifdef __STDC__ - (IDENT *id) -#else - (id) - IDENT *id; -#endif -{ - if (!id) return; - if (id->identifier) free(id->identifier); - if (id->opsys) free(id->opsys); - if (id->charset) free(id->charset); - free(id); -} diff --git a/network/socks/socks.cstc.4.2/libident/ident.h b/network/socks/socks.cstc.4.2/libident/ident.h deleted file mode 100644 index d40bf568..00000000 --- a/network/socks/socks.cstc.4.2/libident/ident.h +++ /dev/null @@ -1,88 +0,0 @@ -/* -** ident.h -** -** Author: Peter Eriksson <pen@lysator.liu.se> -** Intruder: Pär Emanuelsson <pell@lysator.liu.se> -*/ - -#ifndef __IDENT_H__ -#define __IDENT_H__ - -#ifdef __P -# undef __P -#endif - -#ifdef __STDC__ -# define __P(AL) AL -#else -# define __P(AL) () -#endif - -/* - * Sigh, GCC v2 complains when using undefined struct tags - * in function prototypes... - */ -#if defined(__GNUC__) && !defined(IPPROTO_IP) -# define __STRUCT_IN_ADDR_P void * -#else -# define __STRUCT_IN_ADDR_P struct in_addr * -#endif - -#if defined(__GNUC__) && !defined(DST_NONE) -# define __STRUCT_TIMEVAL_P void * -#else -# define __STRUCT_TIMEVAL_P struct timeval * -#endif - - -#ifndef IDBUFSIZE -# define IDBUFSIZE 2048 -#endif - -#ifndef IDPORT -# define IDPORT 113 -#endif - -typedef struct -{ - int fd; - char buf[IDBUFSIZE]; -} ident_t; - -typedef struct { - int lport; /* Local port */ - int fport; /* Far (remote) port */ - char *identifier; /* Normally user name */ - char *opsys; /* OS */ - char *charset; /* Charset (what did you expect?) */ -} IDENT; /* For higher-level routines */ - -/* Low-level calls and macros */ -#define id_fileno(ID) ((ID)->fd) - -extern ident_t * id_open __P((__STRUCT_IN_ADDR_P laddr, - __STRUCT_IN_ADDR_P faddr, - __STRUCT_TIMEVAL_P timeout)); - -extern int id_close __P((ident_t *id)); - -extern int id_query __P((ident_t *id, - int lport, - int fport, - __STRUCT_TIMEVAL_P timeout)); - -extern int id_parse __P((ident_t *id, - __STRUCT_TIMEVAL_P timeout, - int *lport, - int *fport, - char **identifier, - char **opsys, - char **charset)); - -/* High-level calls */ -extern IDENT *ident_lookup __P((int fd, int timeout)); - -extern char *ident_id __P((int fd, int timeout)); - -void ident_free __P((IDENT *id)); -#endif diff --git a/network/socks/socks.cstc.4.2/libident/lookup-tester.c b/network/socks/socks.cstc.4.2/libident/lookup-tester.c deleted file mode 100644 index da55814b..00000000 --- a/network/socks/socks.cstc.4.2/libident/lookup-tester.c +++ /dev/null @@ -1,57 +0,0 @@ -/* -** lookup-tester.c Tests the high-level ident calls. -** -** Author: Pär Emanuelsson <pell@lysator.liu.se>, 28 March 1993 -*/ - -#include <stdio.h> -#include <sys/types.h> -#include <errno.h> - -#include "ident.h" - -main(argc,argv) - int argc; - char *argv[]; -{ - IDENT *ident; - char *user; - - chdir("/tmp"); - - puts("Welcome to the other IDENT server tester, version 1.0\r\n\r"); - - puts("Testing ident_lookup...\r\n\r"); - fflush(stdout); - - ident = ident_lookup(fileno(stdin), 30); - - if (!ident) - perror("ident"); - else { - printf("IDENT response is:\r\n"); - printf(" Lport........ %d\r\n", ident->lport); - printf(" Fport........ %d\r\n", ident->fport); - printf(" Opsys........ %s\r\n", ident->opsys); - printf(" Charset...... %s\r\n", - ident->charset ? ident->charset : "<not specified>"); - printf(" Identifier... %s\r\n", ident->identifier); - } - - ident_free(ident); - - puts("\r\nTesting ident_id...\r\n\r"); - fflush(stdout); - - user = ident_id(fileno(stdin), 30); - - if (user) - printf("IDENT response is identifier = %s\r\n", user); - else - puts("IDENT lookup failed!\r"); - - fflush(stdout); - sleep(1); - exit(0); -} - diff --git a/network/socks/socks.cstc.4.2/make.out b/network/socks/socks.cstc.4.2/make.out deleted file mode 100644 index fca9ebab..00000000 --- a/network/socks/socks.cstc.4.2/make.out +++ /dev/null @@ -1,121 +0,0 @@ -(cd lib; make CC="cc" GETPASS="getpass.o" \ - OPTIMIZE="-g" \ - RCMD="" SUPPORT_RCMD="" \ - DNS_THROUGH_NIS="" \ - OTHER_CFLAGS=" -DSHORTENED_RBIND -DCOMPAT " \ - RANLIB="ranlib") -/projects/insg/socks.cstc.4.2.pre1/lib -cc -I../include -g -DSHORTENED_RBIND -DCOMPAT -target sun4 -c Rconnect.c -cc -I../include -g -DSHORTENED_RBIND -DCOMPAT -target sun4 -c SendGetDst.c -cc -I../include -g -DSHORTENED_RBIND -DCOMPAT -target sun4 -c saddrtoname.c -cc -I../include -g -DSHORTENED_RBIND -DCOMPAT -target sun4 -c porttoserv.c -cc -I../include -g -DSHORTENED_RBIND -DCOMPAT -target sun4 -c check_cconf.c -cc -I../include -g -DSHORTENED_RBIND -DCOMPAT -target sun4 -c percent_x.c -cc -I../include -g -DSHORTENED_RBIND -DCOMPAT -target sun4 -c shell_cmd.c -cc -I../include -g -DSHORTENED_RBIND -DCOMPAT -target sun4 -c check_user.c -cc -I../include -g -DSHORTENED_RBIND -DCOMPAT -target sun4 -c getpass.c -rm -f libsocks.a -ar rc libsocks.a Rconnect.o SendGetDst.o saddrtoname.o porttoserv.o check_cconf.o percent_x.o shell_cmd.o check_user.o getpass.o -ranlib libsocks.a -(cd libident; make CC="cc" OTHER_CFLAGS=" -DSHORTENED_RBIND -DCOMPAT " \ - OPTIMIZE="-g" RANLIB="ranlib") -/projects/insg/socks.cstc.4.2.pre1/libident -cc -g -DSHORTENED_RBIND -DCOMPAT -target sun4 -c ident.c -cc -g -DSHORTENED_RBIND -DCOMPAT -target sun4 -c id_open.c -cc -g -DSHORTENED_RBIND -DCOMPAT -target sun4 -c id_close.c -cc -g -DSHORTENED_RBIND -DCOMPAT -target sun4 -c id_query.c -cc -g -DSHORTENED_RBIND -DCOMPAT -target sun4 -c id_parse.c -rm -f libident.a -ar cq libident.a ident.o id_open.o id_close.o id_query.o id_parse.o -ranlib libident.a -(cd sockd; make CC="cc" RESOLV_LIB="-lresolv" \ - OPTIMIZE="-g" \ - SOCKS_LIB="/projects/insg/socks.cstc.4.2.pre1/lib/libsocks.a" SUPPORT_RCMD="" \ - IDENT_LIB="/projects/insg/socks.cstc.4.2.pre1/libident/libident.a" \ - OTHER_CFLAGS=" -DSHORTENED_RBIND -DCOMPAT ") -/projects/insg/socks.cstc.4.2.pre1/sockd -cc -I../include -I../libident -g -DSHORTENED_RBIND -DCOMPAT -o sockd sockd.c /projects/insg/socks.cstc.4.2.pre1/lib/libsocks.a /projects/insg/socks.cstc.4.2.pre1/libident/libident.a -lresolv -cc -I../include -I../libident -g -DSHORTENED_RBIND -DCOMPAT -DTEST -o test_sockd_conf sockd.c /projects/insg/socks.cstc.4.2.pre1/lib/libsocks.a -lresolv -cc -I../include -I../libident -g -DSHORTENED_RBIND -DCOMPAT -o flip_cfmasks flip_cfmasks.c /projects/insg/socks.cstc.4.2.pre1/lib/libsocks.a -lresolv -(cd rfinger; make CC="cc" WHOIS_SERVER=-DWHOIS_SERVER\'=\"rs.internic.net\"\' \ - OPTIMIZE="-g" SOCKS="-Dconnect=Rconnect -Dgetsockname=Rgetsockname -Dlisten=Rlisten -Daccept=Raccept -Drcmd=Rrcmd -Dbind=Rbind -Dselect=Rselect" \ - RESOLV_LIB="-lresolv" SOCKS_LIB="/projects/insg/socks.cstc.4.2.pre1/lib/libsocks.a" \ - OTHER_CFLAGS=" -DSHORTENED_RBIND -DCOMPAT ") -/projects/insg/socks.cstc.4.2.pre1/rfinger -cc -I../include -g -DSHORTENED_RBIND -DCOMPAT -Dconnect=Rconnect -Dgetsockname=Rgetsockname -Dlisten=Rlisten -Daccept=Raccept -Drcmd=Rrcmd -Dbind=Rbind -Dselect=Rselect -target sun4 -c finger.c -cc -I../include -g -DSHORTENED_RBIND -DCOMPAT -Dconnect=Rconnect -Dgetsockname=Rgetsockname -Dlisten=Rlisten -Daccept=Raccept -Drcmd=Rrcmd -Dbind=Rbind -Dselect=Rselect -o rfinger finger.o /projects/insg/socks.cstc.4.2.pre1/lib/libsocks.a -lresolv -cc -DWHOIS_SERVER'="rs.internic.net"' -I../include -g -DSHORTENED_RBIND -DCOMPAT -Dconnect=Rconnect -Dgetsockname=Rgetsockname -Dlisten=Rlisten -Daccept=Raccept -Drcmd=Rrcmd -Dbind=Rbind -Dselect=Rselect -o rwhois finger.c /projects/insg/socks.cstc.4.2.pre1/lib/libsocks.a -lresolv -(cd rftp; make CC="cc" SOCKS_LIB="/projects/insg/socks.cstc.4.2.pre1/lib/libsocks.a" \ - OPTIMIZE="-g" SOCKS="-Dconnect=Rconnect -Dgetsockname=Rgetsockname -Dlisten=Rlisten -Daccept=Raccept -Drcmd=Rrcmd -Dbind=Rbind -Dselect=Rselect" \ - RESOLV_LIB="-lresolv" \ - OTHER_CFLAGS=" -DSHORTENED_RBIND -DCOMPAT ") -/projects/insg/socks.cstc.4.2.pre1/rftp -cc -I../include -g -DSHORTENED_RBIND -DCOMPAT -Dconnect=Rconnect -Dgetsockname=Rgetsockname -Dlisten=Rlisten -Daccept=Raccept -Drcmd=Rrcmd -Dbind=Rbind -Dselect=Rselect -target sun4 -c cmds.c -cc -I../include -g -DSHORTENED_RBIND -DCOMPAT -Dconnect=Rconnect -Dgetsockname=Rgetsockname -Dlisten=Rlisten -Daccept=Raccept -Drcmd=Rrcmd -Dbind=Rbind -Dselect=Rselect -target sun4 -c cmdtab.c -cc -I../include -g -DSHORTENED_RBIND -DCOMPAT -Dconnect=Rconnect -Dgetsockname=Rgetsockname -Dlisten=Rlisten -Daccept=Raccept -Drcmd=Rrcmd -Dbind=Rbind -Dselect=Rselect -target sun4 -c ftp.c -cc -I../include -g -DSHORTENED_RBIND -DCOMPAT -Dconnect=Rconnect -Dgetsockname=Rgetsockname -Dlisten=Rlisten -Daccept=Raccept -Drcmd=Rrcmd -Dbind=Rbind -Dselect=Rselect -target sun4 -c glob.c -cc -I../include -g -DSHORTENED_RBIND -DCOMPAT -Dconnect=Rconnect -Dgetsockname=Rgetsockname -Dlisten=Rlisten -Daccept=Raccept -Drcmd=Rrcmd -Dbind=Rbind -Dselect=Rselect -target sun4 -c main.c -cc -I../include -g -DSHORTENED_RBIND -DCOMPAT -Dconnect=Rconnect -Dgetsockname=Rgetsockname -Dlisten=Rlisten -Daccept=Raccept -Drcmd=Rrcmd -Dbind=Rbind -Dselect=Rselect -target sun4 -c ruserpass.c -cc -I../include -g -DSHORTENED_RBIND -DCOMPAT -Dconnect=Rconnect -Dgetsockname=Rgetsockname -Dlisten=Rlisten -Daccept=Raccept -Drcmd=Rrcmd -Dbind=Rbind -Dselect=Rselect -target sun4 -c domacro.c -cc -I../include -g -DSHORTENED_RBIND -DCOMPAT -Dconnect=Rconnect -Dgetsockname=Rgetsockname -Dlisten=Rlisten -Daccept=Raccept -Drcmd=Rrcmd -Dbind=Rbind -Dselect=Rselect -o rftp cmds.o cmdtab.o ftp.o glob.o main.o ruserpass.o domacro.o /projects/insg/socks.cstc.4.2.pre1/lib/libsocks.a -lresolv -(cd rtelnet; make CC="cc" OS="sun4.1" SOCKS_LIB="/projects/insg/socks.cstc.4.2.pre1/lib/libsocks.a" \ - OPTIMIZE="-g" SOCKS="-Dconnect=Rconnect -Dgetsockname=Rgetsockname -Dlisten=Rlisten -Daccept=Raccept -Drcmd=Rrcmd -Dbind=Rbind -Dselect=Rselect" \ - RESOLV_LIB="-lresolv" \ - OTHER_CFLAGS=" -DSHORTENED_RBIND -DCOMPAT ") -/projects/insg/socks.cstc.4.2.pre1/rtelnet -cd libtelnet; make sun4.1 CC="cc" OTHER_CFLAGS="-DSHORTENED_RBIND -DCOMPAT" SOCKS="-Dconnect=Rconnect -Dgetsockname=Rgetsockname -Dlisten=Rlisten -Daccept=Raccept -Drcmd=Rrcmd -Dbind=Rbind -Dselect=Rselect" SOCKS_LIB=/projects/insg/socks.cstc.4.2.pre1/lib/libsocks.a RESOLV_LIB="-lresolv" OPTIMIZE="-g" -make -f ../Config.local WHAT= CC=cc OPTIMIZE=-g SOCKS=-Dconnect=Rconnect -Dgetsockname=Rgetsockname -Dlisten=Rlisten -Daccept=Raccept -Drcmd=Rrcmd -Dbind=Rbind -Dselect=Rselect SOCKS_LIB=/projects/insg/socks.cstc.4.2.pre1/lib/libsocks.a RESOLV_LIB=-lresolv sun4.1 -make -f Makefile.generic \ - LIBS="/projects/insg/socks.cstc.4.2.pre1/lib/libsocks.a -ltermcap ../libtelnet/libtelnet.a -lresolv" \ - LIBPATH="/lib/libc.a /usr/lib/libtermcap.a \ - ../libtelnet/libtelnet.a" \ - DEST=/usr/ucb \ - DEFINES="-DFILIO_H -DTERMCAP -DUSE_TERMIO \ - -DKLUDGELINEMODE -DSTREAMS \ - -DAUTHENTICATE \ - -Dconnect=Rconnect -Dgetsockname=Rgetsockname -Dlisten=Rlisten -Daccept=Raccept -Drcmd=Rrcmd -Dbind=Rbind -Dselect=Rselect -DDIAGNOSTICS " \ - INCLUDES="-I.. -I../../include" \ - LIB_OBJ="getent.o strerror.o setenv.o herror.o" \ - LIB_SRC="getent.c strerror.c setenv.c herror.c" \ - AR=ar ARFLAGS=cq RANLIB=ranlib \ - LIBEXEC=/usr/etc/in.telnetd \ - CC="cc" LCCFLAGS="-g" -cc -g -DFILIO_H -DTERMCAP -DUSE_TERMIO -DKLUDGELINEMODE -DSTREAMS -DAUTHENTICATE -Dconnect=Rconnect -Dgetsockname=Rgetsockname -Dlisten=Rlisten -Daccept=Raccept -Drcmd=Rrcmd -Dbind=Rbind -Dselect=Rselect -DDIAGNOSTICS -I.. -I../../include -target sun4 -c auth.c -cc -g -DFILIO_H -DTERMCAP -DUSE_TERMIO -DKLUDGELINEMODE -DSTREAMS -DAUTHENTICATE -Dconnect=Rconnect -Dgetsockname=Rgetsockname -Dlisten=Rlisten -Daccept=Raccept -Drcmd=Rrcmd -Dbind=Rbind -Dselect=Rselect -DDIAGNOSTICS -I.. -I../../include -target sun4 -c encrypt.c -cc -g -DFILIO_H -DTERMCAP -DUSE_TERMIO -DKLUDGELINEMODE -DSTREAMS -DAUTHENTICATE -Dconnect=Rconnect -Dgetsockname=Rgetsockname -Dlisten=Rlisten -Daccept=Raccept -Drcmd=Rrcmd -Dbind=Rbind -Dselect=Rselect -DDIAGNOSTICS -I.. -I../../include -target sun4 -c genget.c -cc -g -DFILIO_H -DTERMCAP -DUSE_TERMIO -DKLUDGELINEMODE -DSTREAMS -DAUTHENTICATE -Dconnect=Rconnect -Dgetsockname=Rgetsockname -Dlisten=Rlisten -Daccept=Raccept -Drcmd=Rrcmd -Dbind=Rbind -Dselect=Rselect -DDIAGNOSTICS -I.. -I../../include -target sun4 -c misc.c -cc -g -DFILIO_H -DTERMCAP -DUSE_TERMIO -DKLUDGELINEMODE -DSTREAMS -DAUTHENTICATE -Dconnect=Rconnect -Dgetsockname=Rgetsockname -Dlisten=Rlisten -Daccept=Raccept -Drcmd=Rrcmd -Dbind=Rbind -Dselect=Rselect -DDIAGNOSTICS -I.. -I../../include -target sun4 -c enc_des.c -cc -g -DFILIO_H -DTERMCAP -DUSE_TERMIO -DKLUDGELINEMODE -DSTREAMS -DAUTHENTICATE -Dconnect=Rconnect -Dgetsockname=Rgetsockname -Dlisten=Rlisten -Daccept=Raccept -Drcmd=Rrcmd -Dbind=Rbind -Dselect=Rselect -DDIAGNOSTICS -I.. -I../../include -target sun4 -c getent.c -cc -g -DFILIO_H -DTERMCAP -DUSE_TERMIO -DKLUDGELINEMODE -DSTREAMS -DAUTHENTICATE -Dconnect=Rconnect -Dgetsockname=Rgetsockname -Dlisten=Rlisten -Daccept=Raccept -Drcmd=Rrcmd -Dbind=Rbind -Dselect=Rselect -DDIAGNOSTICS -I.. -I../../include -target sun4 -c strerror.c -cc -g -DFILIO_H -DTERMCAP -DUSE_TERMIO -DKLUDGELINEMODE -DSTREAMS -DAUTHENTICATE -Dconnect=Rconnect -Dgetsockname=Rgetsockname -Dlisten=Rlisten -Daccept=Raccept -Drcmd=Rrcmd -Dbind=Rbind -Dselect=Rselect -DDIAGNOSTICS -I.. -I../../include -target sun4 -c setenv.c -cc -g -DFILIO_H -DTERMCAP -DUSE_TERMIO -DKLUDGELINEMODE -DSTREAMS -DAUTHENTICATE -Dconnect=Rconnect -Dgetsockname=Rgetsockname -Dlisten=Rlisten -Daccept=Raccept -Drcmd=Rrcmd -Dbind=Rbind -Dselect=Rselect -DDIAGNOSTICS -I.. -I../../include -target sun4 -c herror.c -rm -f libtelnet.a -ar cq libtelnet.a auth.o encrypt.o genget.o misc.o enc_des.o getent.o strerror.o setenv.o herror.o -ranlib libtelnet.a -cd telnet; make sun4.1 CC="cc" OTHER_CFLAGS="-DSHORTENED_RBIND -DCOMPAT" SOCKS="-Dconnect=Rconnect -Dgetsockname=Rgetsockname -Dlisten=Rlisten -Daccept=Raccept -Drcmd=Rrcmd -Dbind=Rbind -Dselect=Rselect" SOCKS_LIB=/projects/insg/socks.cstc.4.2.pre1/lib/libsocks.a RESOLV_LIB="-lresolv" OPTIMIZE="-g" -make -f ../Config.local WHAT= CC=cc OPTIMIZE=-g SOCKS=-Dconnect=Rconnect -Dgetsockname=Rgetsockname -Dlisten=Rlisten -Daccept=Raccept -Drcmd=Rrcmd -Dbind=Rbind -Dselect=Rselect SOCKS_LIB=/projects/insg/socks.cstc.4.2.pre1/lib/libsocks.a RESOLV_LIB=-lresolv sun4.1 -make -f Makefile.generic \ - LIBS="/projects/insg/socks.cstc.4.2.pre1/lib/libsocks.a -ltermcap ../libtelnet/libtelnet.a -lresolv" \ - LIBPATH="/lib/libc.a /usr/lib/libtermcap.a \ - ../libtelnet/libtelnet.a" \ - DEST=/usr/ucb \ - DEFINES="-DFILIO_H -DTERMCAP -DUSE_TERMIO \ - -DKLUDGELINEMODE -DSTREAMS \ - -DAUTHENTICATE \ - -Dconnect=Rconnect -Dgetsockname=Rgetsockname -Dlisten=Rlisten -Daccept=Raccept -Drcmd=Rrcmd -Dbind=Rbind -Dselect=Rselect -DDIAGNOSTICS " \ - INCLUDES="-I.. -I../../include" \ - LIB_OBJ="getent.o strerror.o setenv.o herror.o" \ - LIB_SRC="getent.c strerror.c setenv.c herror.c" \ - AR=ar ARFLAGS=cq RANLIB=ranlib \ - LIBEXEC=/usr/etc/in.telnetd \ - CC="cc" LCCFLAGS="-g" -cc -g -I.. -I../../include -DFILIO_H -DTERMCAP -DUSE_TERMIO -DKLUDGELINEMODE -DSTREAMS -DAUTHENTICATE -Dconnect=Rconnect -Dgetsockname=Rgetsockname -Dlisten=Rlisten -Daccept=Raccept -Drcmd=Rrcmd -Dbind=Rbind -Dselect=Rselect -DDIAGNOSTICS -target sun4 -c authenc.c -cc -g -I.. -I../../include -DFILIO_H -DTERMCAP -DUSE_TERMIO -DKLUDGELINEMODE -DSTREAMS -DAUTHENTICATE -Dconnect=Rconnect -Dgetsockname=Rgetsockname -Dlisten=Rlisten -Daccept=Raccept -Drcmd=Rrcmd -Dbind=Rbind -Dselect=Rselect -DDIAGNOSTICS -target sun4 -c commands.c -cc -g -I.. -I../../include -DFILIO_H -DTERMCAP -DUSE_TERMIO -DKLUDGELINEMODE -DSTREAMS -DAUTHENTICATE -Dconnect=Rconnect -Dgetsockname=Rgetsockname -Dlisten=Rlisten -Daccept=Raccept -Drcmd=Rrcmd -Dbind=Rbind -Dselect=Rselect -DDIAGNOSTICS -target sun4 -c main.c -cc -g -I.. -I../../include -DFILIO_H -DTERMCAP -DUSE_TERMIO -DKLUDGELINEMODE -DSTREAMS -DAUTHENTICATE -Dconnect=Rconnect -Dgetsockname=Rgetsockname -Dlisten=Rlisten -Daccept=Raccept -Drcmd=Rrcmd -Dbind=Rbind -Dselect=Rselect -DDIAGNOSTICS -target sun4 -c network.c -cc -g -I.. -I../../include -DFILIO_H -DTERMCAP -DUSE_TERMIO -DKLUDGELINEMODE -DSTREAMS -DAUTHENTICATE -Dconnect=Rconnect -Dgetsockname=Rgetsockname -Dlisten=Rlisten -Daccept=Raccept -Drcmd=Rrcmd -Dbind=Rbind -Dselect=Rselect -DDIAGNOSTICS -target sun4 -c ring.c -cc -g -I.. -I../../include -DFILIO_H -DTERMCAP -DUSE_TERMIO -DKLUDGELINEMODE -DSTREAMS -DAUTHENTICATE -Dconnect=Rconnect -Dgetsockname=Rgetsockname -Dlisten=Rlisten -Daccept=Raccept -Drcmd=Rrcmd -Dbind=Rbind -Dselect=Rselect -DDIAGNOSTICS -target sun4 -c sys_bsd.c -cc -g -I.. -I../../include -DFILIO_H -DTERMCAP -DUSE_TERMIO -DKLUDGELINEMODE -DSTREAMS -DAUTHENTICATE -Dconnect=Rconnect -Dgetsockname=Rgetsockname -Dlisten=Rlisten -Daccept=Raccept -Drcmd=Rrcmd -Dbind=Rbind -Dselect=Rselect -DDIAGNOSTICS -target sun4 -c telnet.c -cc -g -I.. -I../../include -DFILIO_H -DTERMCAP -DUSE_TERMIO -DKLUDGELINEMODE -DSTREAMS -DAUTHENTICATE -Dconnect=Rconnect -Dgetsockname=Rgetsockname -Dlisten=Rlisten -Daccept=Raccept -Drcmd=Rrcmd -Dbind=Rbind -Dselect=Rselect -DDIAGNOSTICS -target sun4 -c terminal.c -cc -g -I.. -I../../include -DFILIO_H -DTERMCAP -DUSE_TERMIO -DKLUDGELINEMODE -DSTREAMS -DAUTHENTICATE -Dconnect=Rconnect -Dgetsockname=Rgetsockname -Dlisten=Rlisten -Daccept=Raccept -Drcmd=Rrcmd -Dbind=Rbind -Dselect=Rselect -DDIAGNOSTICS -target sun4 -c utilities.c -cc -o ../rtelnet -g -I.. -I../../include -DFILIO_H -DTERMCAP -DUSE_TERMIO -DKLUDGELINEMODE -DSTREAMS -DAUTHENTICATE -Dconnect=Rconnect -Dgetsockname=Rgetsockname -Dlisten=Rlisten -Daccept=Raccept -Drcmd=Rrcmd -Dbind=Rbind -Dselect=Rselect -DDIAGNOSTICS authenc.o commands.o main.o network.o ring.o sys_bsd.o telnet.o terminal.o utilities.o /projects/insg/socks.cstc.4.2.pre1/lib/libsocks.a -ltermcap ../libtelnet/libtelnet.a -lresolv diff --git a/network/socks/socks.cstc.4.2/rfinger/Makefile b/network/socks/socks.cstc.4.2/rfinger/Makefile deleted file mode 100644 index 120f2123..00000000 --- a/network/socks/socks.cstc.4.2/rfinger/Makefile +++ /dev/null @@ -1,97 +0,0 @@ -#CC=gcc - -# Directory into which rfinger and rwhois programs will be installed: -CLIENTS_BIN_DIR=/usr/local/bin - -# Directory into which man page files will be installed: -MAN_DEST_DIR=/usr/local/man - -# make SOCKSified client -SOCKS_LIB =../lib/libsocks.a -SOCKS=-DSOCKS -# or -#SOCKS=-Dconnect=Rconnect -Dgetsockname=Rgetsockname -Dlisten=Rlisten -Daccept=Raccept -Drcmd=Rrcmd -Dbind=Rbind -Dselect=Rselect - -# Remember to include -Dindex=strchr in OTHER_CFLAGS if -# you don't have index() (Sys-V camp) - -# SunOS should use -#RESOLV_LIB=-lresolv -OTHER_CFLAGS= $(SHORTENED_RBIND) - -# IRIX should use -#RESOLV_LIB=-lsun -#OTHER_CFLAGS=-cckr $(SHORTENED_RBIND) - -# AIX should use -#RESOLV_LIB=-lbsd -#OTHER_CFLAGS=-D_BSD -D_NONSTD_TYPES -D_NO_PROTO -DAIX $(SHORTENED_RBIND) - -# SOLARIS should use -#RESOLV_LIB=-lresolv -lnsl -lsocket -#OTHER_CFLAGS=-DSOLARIS -Dindex=strchr -Drindex=strrchr -DUSE_DIRENT $(SHORTENED_RBIND) - -# Interactive Systems Unix should use -# OTHER_CFLAGS = -DISC $(SHORTENED_RBIND) - -# LINUX should use -#CC=gcc -#RESOLV_LIB= -#OTHER_CFLAGS=-traditional -DLINUX $(SHORTENED_RBIND) - -# UnixWare should use -#RESOLV_LIB=-lresolv -lnsl -lsocket -#OTHER_CFLAGS= -DSOLARIS -Dindex=strchr -Drindex=strrchr -DUSE_DIRENT $(SHORTENED_RBIND) -#INSTALL=/usr/ucb/install - -# >>>---------------- Others: - -# Define RESOLV_LIB if your system (e.g., SunOS before 4.1.1) -# doesn't search resolver library automatically. -# Leave it undefined otherwise. -# If your compiler or loader complains about _res_init being -# an undefined symbol, then you must define RESOLV_LIB. -#RESOLV_LIB= -lresolv - -# <<<---------------- - -# The Internet Whois server; used to be nic.ddn.mil. -WHOIS_SERVER= -DWHOIS_SERVER'="rs.internic.net"' - -OPTIMIZE=-g -CFLAGS = -I../include ${OPTIMIZE} ${OTHER_CFLAGS} ${SOCKS} - -# The 'install' command is assumed to be the BSD variety (using -m to -# set the file mode). If the default 'install' on your system doesn't -# do that, you have to either specify an alternative one in the line below -# (e.g., /usr/ucb/install) or modify the install instructions. -INSTALL= install - -#============================================================================== - -OBJ = finger.o -SRC = finger.c - -all: echocwd rfinger rwhois - -rfinger: $(OBJ) $(SOCKS_LIB) - $(CC) $(CFLAGS) -o $@ $(OBJ) $(SOCKS_LIB) $(RESOLV_LIB) - -rwhois: $(SRC) $(SOCKS_LIB) - $(CC) $(WHOIS_SERVER) $(CFLAGS) -o $@ $(SRC) $(SOCKS_LIB) $(RESOLV_LIB) - -install: echocwd rfinger rwhois - $(INSTALL) -m 111 rfinger $(CLIENTS_BIN_DIR) - $(INSTALL) -m 111 rwhois $(CLIENTS_BIN_DIR) - -install.man: echocwd - $(INSTALL) -m 444 ../doc/socks_clients.1 $(MAN_DEST_DIR)/man1 - $(INSTALL) -m 444 ../doc/socks.conf.5 $(MAN_DEST_DIR)/man5 - $(INSTALL) -m 444 ../doc/rfinger.1 $(MAN_DEST_DIR)/man1 - $(INSTALL) -m 444 ../doc/rwhois.1 $(MAN_DEST_DIR)/man1 - -clean: echocwd - rm -f $(OBJ) rwhois rfinger core - -echocwd: - @pwd diff --git a/network/socks/socks.cstc.4.2/rfinger/finger.c b/network/socks/socks.cstc.4.2/rfinger/finger.c deleted file mode 100644 index 1c3809d3..00000000 --- a/network/socks/socks.cstc.4.2/rfinger/finger.c +++ /dev/null @@ -1,145 +0,0 @@ -#include <sys/types.h> -#include <sys/socket.h> -#include <netinet/in.h> -#include <netdb.h> -#include <stdio.h> -#include <sys/file.h> -#include <errno.h> -#include "socks.h" - -#if defined(SOCKS) -#define connect Rconnect -#endif - -extern int errno; -extern char *strrchr(); -char *Progname; -extern char *getenv(); - -main(argc, argv) -int argc; -char **argv; -{ - char buf[1024]; - unsigned long l; - struct sockaddr_in sin; - struct hostent *hp; - struct servent *sp; - extern int optind; - extern char *optarg; - int c, v, n, i; - int s; - extern int optind; - FILE *in; - char *cp; -#ifdef WHOIS_SERVER - char *service = "whois", *host = WHOIS_SERVER; -#else - char *service = "finger", *host = "localhost"; -#endif - struct in_addr dstaddr[21]; - - if ((Progname = strrchr(argv[0], '/')) == NULL) - Progname = argv[0]; - else - Progname++; - -#if defined(SOCKS) || defined(connect) - SOCKSinit(Progname); -#endif - -#ifdef WHOIS_SERVER - while ((i = getopt(argc,argv,"h:")) != EOF) { - switch (i) { - case 'h': - host = optarg; - break; - default: - fprintf(stderr,"Usage: %s [-h host] name\n", Progname); - exit(1); - } - } -#endif - - buf[0] = '\0'; -#if defined(LINUX) - for (i = 1; i < argc; i++) -#else - for (i = optind; i < argc; i++) -#endif - strcat(buf, argv[i]); - -#ifndef WHOIS_SERVER - if ((cp = strrchr(buf, '@')) != NULL) { - *cp = '\0'; - host = cp + 1; - } else { - if ((cp = getenv("ORIG_FINGER")) == NULL) - cp = ORIG_FINGER; - execvp(cp, argv); - fprintf(stderr, "Unable to run %s\n", cp); - exit(1); - } -#endif - - sin.sin_family = AF_INET; - - - if ((sp = getservbyname(service, "tcp")) == NULL) { - if ((v = atoi(service)) == 0) { - fprintf(stderr, "%s: unknown service '%s'\n", - Progname, service); - exit(1); - } - sin.sin_port = htons((short) v); - } else { - sin.sin_port = sp->s_port; - } - - if ((hp = gethostbyname(host)) == NULL) { - if ((l = inet_addr(host)) == -1) { - fprintf(stderr, "%s: unknown host '%s'\n", - Progname, host); - exit(1); - } -/* you are out of luck if your system doesn't use 2's complement in - integer representation */ - sin.sin_addr.s_addr = l ; - } else { - for (i = 0; (i < 20) && *hp->h_addr_list; - i++, hp->h_addr_list++) - bcopy(*hp->h_addr_list, &(dstaddr[i].s_addr), hp->h_length); - dstaddr[i].s_addr = 0; - i = 0; - sin.sin_addr.s_addr = dstaddr[i++].s_addr; - } - - if ((s = socket(AF_INET, SOCK_STREAM, 0)) < 0) { - fprintf(stderr, "%s: ", Progname); - perror("socket"); - exit(1); - } - - while (connect(s, &sin, sizeof(sin)) < 0) { - if ((errno == ETIMEDOUT) && (hp != NULL) && - ((sin.sin_addr.s_addr = dstaddr[i++].s_addr) != 0)) { - continue; - } - fprintf(stderr, "%s: ", Progname); - perror("connect"); - exit(1); - } - - strcat(buf, "\r\n"); - - if (write(s,buf,strlen(buf)) < 0) { - fprintf(stderr, "%s: ", Progname); - perror("write"); - } - - while ((n = read(s, buf, sizeof(buf) - 1)) > 0) { - write(1, buf, n); - } - - close(s); -} diff --git a/network/socks/socks.cstc.4.2/sockd/Makefile b/network/socks/socks.cstc.4.2/sockd/Makefile deleted file mode 100644 index f9c22cd9..00000000 --- a/network/socks/socks.cstc.4.2/sockd/Makefile +++ /dev/null @@ -1,105 +0,0 @@ -#CC=gcc - -SOCKS_LIB=../lib/libsocks.a -IDENT_LIB=../libident/libident.a - -# Directory into which sockd and test_sockd_conf programs -# will be installed: -SERVER_BIN_DIR=/usr/etc - -# Directory into which the man page files of sockd and test_sockd_conf -# will be installed: -MAN_DEST_DIR=/usr/local/man - -INC=../include/socks.h - -# Uncomment next line to support Rbind() without the extra 'remhost' arg. -SHORTENED_RBIND=-DSHORTENED_RBIND - -# Remember to include -Dindex=strchr in OTHER_CFLAGS if -# you don't have index() (Sys-V camp) - -# Define FOR_PS if your system is not SYSV and you want to have the -# command 'ps' show some details of sockd's activity. -FOR_PS=-DFOR_PS - -# SunOS should use -#RESOLV_LIB=-lresolv -OTHER_CFLAGS=$(SHORTENED_RBIND) - -# IRIX should use -#OTHER_CFLAGS=-cckr $(SHORTENED_RBIND) -#RESOLV_LIB=-lsun - -# HPUX should use -#OTHER_CFLAGS=-Ac $(SHORTENED_RBIND) - -# AIX should use -#RESOLV_LIB=-lbsd -#OTHER_CFLAGS=-D_BSD -D_NONSTD_TYPES -D_NO_PROTO -DAIX $(SHORTENED_RBIND) - -# SOLARIS should use -#RESOLV_LIB=-lresolv -lnsl -lsocket -#OTHER_CFLAGS=-DSOLARIS -Dindex=strchr -Drindex=strrchr -DUSE_DIRENT $(SHORTENED_RBIND) - -# Interactive Systems Unix should use -# OTHER_CFLAGS = -DISC $(SHORTENED_RBIND) - -# LINUX should use -#CC=gcc -#RESOLV_LIB= -#OTHER_CFLAGS=-traditional -DLINUX $(SHORTENED_RBIND) - -# UnixWare should use -#RESOLV_LIB=-lresolv -lnsl -lsocket -#OTHER_CFLAGS= -DSOLARIS -Dindex=strchr -Drindex=strrchr -DUSE_DIRENT $(SHORTENED_RBIND) -#RANLIB=/bin/true -#INSTALL=bsdinstall - -# define SUPPORT_RCMD to build a server that can handle SOCKSified -# rlogin, rsh, and rcp. -SUPPORT_RCMD=-DSUPPORT_RCMD - -OPTIMIZE=-g -CFLAGS = -I../include -I../libident ${OPTIMIZE} ${OTHER_CFLAGS} ${SUPPORT_RCMD} - -# The 'install' command is assumed to be the BSD variety (using -m to -# set the file mode). If the default 'install' on your system doesn't -# do that, you have to either specify an alternative one in the line below -# (e.g., /usr/ucb/install) or modify the install instructions. -INSTALL= install - -#================================================== - -SRC=sockd.c -OBJ=sockd.o -PROG=sockd test_sockd_conf flip_cfmasks - -all: echocwd $(PROG) - -sockd: $(SRC) $(INC) $(SOCKS_LIB) $(IDENT_LIB) - $(CC) $(CFLAGS) -o $@ $(SRC) $(SOCKS_LIB) $(IDENT_LIB) $(RESOLV_LIB) - -test_sockd_conf: $(SRC) $(INC) $(SOCKS_LIB) - $(CC) $(CFLAGS) -DTEST -o $@ $(SRC) $(SOCKS_LIB) $(RESOLV_LIB) - -flip_cfmasks: flip_cfmasks.c $(INC) $(SOCKS_LIB) - $(CC) $(CFLAGS) -o $@ flip_cfmasks.c $(SOCKS_LIB) $(RESOLV_LIB) - -install: echocwd sockd test_sockd_conf - $(INSTALL) -m 111 sockd $(SERVER_BIN_DIR) - $(INSTALL) -m 111 test_sockd_conf $(SERVER_BIN_DIR) - $(INSTALL) -m 111 flip_cfmasks $(SERVER_BIN_DIR) - -install.man: echocwd - $(INSTALL) -m 444 ../doc/sockd.8 $(MAN_DEST_DIR)/man8 - $(INSTALL) -m 444 ../doc/test_sockd_conf.8 $(MAN_DEST_DIR)/man8 - $(INSTALL) -m 444 ../doc/sockd.conf.5 $(MAN_DEST_DIR)/man5 - $(INSTALL) -m 444 ../doc/sockd.route.5 $(MAN_DEST_DIR)/man5 - - -clean: echocwd - rm -f $(OBJ) $(PROG) core - -echocwd: - @pwd diff --git a/network/socks/socks.cstc.4.2/sockd/flip_cfmasks.c b/network/socks/socks.cstc.4.2/sockd/flip_cfmasks.c deleted file mode 100644 index 0c0c8cc0..00000000 --- a/network/socks/socks.cstc.4.2/sockd/flip_cfmasks.c +++ /dev/null @@ -1,167 +0,0 @@ -/* -#include <sys/time.h> -#include <sys/socket.h> -#include <sys/signal.h> -#include <syslog.h> -#include <arpa/inet.h> -#include <sys/ioctl.h> -#include <netdb.h> -*/ -#include <sys/types.h> -#include <netinet/in.h> -#include <stdio.h> -/* -#include <ctype.h> -*/ -#include <string.h> -#include <sys/wait.h> -#include "socks.h" - -extern int GetAddr(); -extern char *inet_ntoa(); - -main(argc, argv) -int argc; -char *argv[]; -{ - FILE *infile, *outfile, *tempout; - char *tempfn; - static char buf[1024]; - char temp[1024]; - char lineout[1024]; - char *bp; - int linenum = 0; - struct in_addr smask, dmask; - char *cmdp, *commentp; - int child_pid, wait_pid, exitcode; - - if (argc != 3) { - fprintf(stderr," Usage: %s input_file output_file\n", argv[0]); - exit(1); - } - - if ((infile = fopen(argv[1], "r")) == NULL) { - fprintf(stderr,"Unable to open input file %s\n", argv[1]); - exit(1); - } - - if ((tempout = fopen(tempfn = tmpnam(NULL), "w")) == NULL) { - fprintf(stderr, "Unable to create temporary file.\n"); - exit(1); - } - - while (fgets(buf, sizeof(buf) - 1, infile) != NULL) { - linenum++; - /* - ** Comments start with a '#' anywhere on the line - */ - cmdp = (char *)0; - commentp = (char *)0; - if ((bp = strchr(buf, '\n')) != NULL) - *bp = '\0'; - strcpy(temp, buf); - for (bp = buf; *bp; bp++) { - if (*bp == ':') { - *bp++ = '\0'; - cmdp = bp; - break; - } else if (*bp == '#') { - *bp++ = '\0'; - commentp = bp; - break; - } - } - if ((bp = strtok(buf, " \t")) == NULL) { - fprintf(tempout,"%s\n", temp); - continue; - } - - strcpy(lineout, bp); - if ((bp = strtok(NULL, " \t")) == NULL) - goto badline; - strcat(lineout, "\t"); - strcat(lineout, bp); - if (strncmp(bp, "@=", 2) == 0) { - if ((bp = strtok(NULL, " \t")) == NULL) - goto badline; - strcat(lineout, "\t"); - strcat(lineout, bp); - } - if (strncmp(bp, "*=", 2) == 0) { - if ((bp = strtok(NULL, " \t")) == NULL) - goto badline; - strcat(lineout, "\t"); - strcat(lineout, bp); - } - if ((bp = strtok(NULL, " \t")) == NULL) - goto badline; - GetAddr(bp, &smask); - smask.s_addr = ~smask.s_addr; - strcat(lineout, " "); - strcat(lineout, inet_ntoa(smask)); - if ((bp = strtok(NULL, " \t")) == NULL) - goto printline; - if (strcmp(bp, "eq") && strcmp(bp, "neq") && strcmp(bp, "lt") - && strcmp(bp, "gt") && strcmp(bp, "le") - && strcmp(bp, "ge")) { - strcat(lineout, "\t"); - strcat(lineout, bp); - if ((bp = strtok(NULL, " \t")) == NULL) - goto badline; - GetAddr(bp, &dmask); - dmask.s_addr = ~dmask.s_addr; - strcat(lineout, " "); - strcat(lineout, inet_ntoa(dmask)); - } - if ((bp = strtok(NULL, " \t")) == NULL) - goto printline; - strcat(lineout, "\t"); - strcat(lineout, bp); - if ((bp = strtok(NULL, " \t")) == NULL) - goto badline; - strcat(lineout, " "); - strcat(lineout, bp); -printline: - if (cmdp != NULL) { - strcat(lineout, " :"); - strcat(lineout, cmdp); - } - if (commentp != NULL) { - strcat(lineout, " #"); - strcat(lineout, commentp); - } - fprintf(tempout, "%s\n", lineout); - continue; - -badline: - fprintf(stderr, "Invalid entry at line %d:\n%s\n", linenum, temp); - fprintf(tempout, "%s\n", temp); - continue; - } - - fclose(infile); - fclose(tempout); - -/* Fork to do cp */ - switch (child_pid = fork()) { - case 0: - sprintf(lineout, "cp %s %s", tempfn, argv[2]); - execl("/bin/sh", "sh", "-c", lineout, (char *)0); - case -1: - fprintf(stderr,"Uable to save to file %s. Results saved in file %s\n", argv[2], tempfn); - exit(1); - default: - while ((wait_pid = wait(&exitcode)) != -1 && wait_pid != child_pid) - ; - if (exitcode) { - fprintf(stderr,"Uable to save to file %s. Results saved in file %s\n", argv[2], tempfn); - exit(1); - } - unlink(tempfn); - exit(0); - } - - - -} - diff --git a/network/socks/socks.cstc.4.2/sockd/sockd.c b/network/socks/socks.cstc.4.2/sockd/sockd.c deleted file mode 100644 index 5364cf67..00000000 --- a/network/socks/socks.cstc.4.2/sockd/sockd.c +++ /dev/null @@ -1,1182 +0,0 @@ -#include <sys/types.h> -#include <sys/time.h> -#include <sys/socket.h> -#include <sys/signal.h> -#include <syslog.h> -#include <netinet/in.h> -#include <arpa/inet.h> -#include <sys/ioctl.h> -#include <netdb.h> -#include <stdio.h> -#include <ctype.h> -#if (defined(sun) && !defined(SOLARIS)) || defined(sgi) -#include <strings.h> -#else -#include <string.h> -#endif -#if defined(SUPPORT_RCMD) -#include <fcntl.h> -#endif -#include "socks.h" - -#include "ident.h" -#define IDENTD_TIMEOUT 15 /* 15 seconds */ -static int use_identd = 0; - -#define STREQ(a, b) (strcmp(a, b) == 0) - -char socks_cmd[] = "connect"; - -#ifdef OLD_CONF_MASK -static char conf_mask[] = OLD_CONF_MASK; -#endif -static char *sockd_conf = SOCKD_CONF; -static char server_version[] = "4.1"; -static unsigned short socks_port; -static unsigned short socks_client_port; -extern char *porttoserv(); -extern char *saddrtoname(); -extern void mkargs(); -extern int GetAddr(); -extern long GetPort(); -extern int check_user(); -#define NAMELEN 128 -char socks_src_name[NAMELEN], socks_src_user[NAMELEN]; -char socks_real_user[NAMELEN]; -char socks_dst_name[NAMELEN], socks_dst_serv[NAMELEN]; - -static char log_msg[1024]; - -#ifdef DEBUG -static char buf[1024]; -#endif - -#ifndef TEST - - static u_int32 from_in = 0L, from_out = 0L; - -/* -** Current version for response messages -*/ -int Version = 0; - -void die() -{ - syslog(LOG_LOW, "timed-out -- %s", log_msg); - exit(1); -} - - -#ifdef FOR_PS -main(argc, argv, envp) -int argc; -char *argv[]; -char *envp[]; -#else /* FOR_PS not defined */ -main(argc, argv) -int argc; -char *argv[]; -#endif /* #ifdef FOR_PS */ -{ - char c; - int inp, in, out, nindex=0; - int i, n, len = sizeof(struct sockaddr_in); - struct sockaddr_in sin, from, dstsin; - int fromlen = sizeof(struct sockaddr_in); - Socks_t dst; - int one = 1; - struct servent *sp; - int permit; - -#if defined(FOR_PS) && !defined(SYSV) -#define MAXUSERENVIRON 100 - char *UserEnviron[MAXUSERENVIRON+1]; /* saved user environment */ - extern char **environ; - char ps_buf[1024]; - char **Argv = NULL; /* pointer to argument vector */ - char *LastArgv = NULL; /* end of argv */ -#define newstr(s) strcpy(malloc(strlen(s) + 1), s) - - for (i = 0; i < MAXUSERENVIRON && envp[i] != NULL; i++) - UserEnviron[i] = newstr(envp[i]); - UserEnviron[i] = NULL; - environ = UserEnviron; - - /* - ** Save start and extent of argv for setproctitle. - */ - - Argv = argv; - if (i > 0) - LastArgv = envp[i - 1] + strlen(envp[i - 1]); - else - LastArgv = argv[argc - 1] + strlen(argv[argc - 1]); -#endif /* FOR_PS && !SYSV */ - - socks_port = htons(SOCKS_DEF_PORT); - bzero((char *)&sin, sizeof(sin)); - bzero((char *)&from, sizeof(from)); - bzero((char *)&dstsin, sizeof(dstsin)); - - if (argc >= 2) { - if (strcmp(argv[1],"-ver") == 0) { -#ifdef MULTIHOMED_SERVER - printf("\tCSTC multi-homed SOCKS proxy server version %s.\n", CSTC_RELEASE); -#else /* MULTIHOMED_SERVER not defined */ - printf("\tCSTC single-homed SOCKS proxy server version %s.\n", CSTC_RELEASE); -#endif /* #ifdef MULTIHOMED_SERVER */ - -#if defined(SUPPORT_RCMD) - printf("\tSupports clients that use Rrcmd().\n"); -#else /* SUPPORT_RCMD not defined */ - printf("\tDoes not support clients that use Rrcmd().\n"); -#endif /* #if defined(SUPPORT_RCMD) */ - exit(1); - } else if (strcmp(argv[1], "-i") == 0) - use_identd = 1; - else if (strcmp(argv[1], "-I") == 0) - use_identd = 2; /* strict use of identd */ - else ; - } - strcpy(socks_real_user,"unknown"); - - if ((sp = getservbyname("socks", "tcp")) != NULL) - socks_port = sp->s_port; - -#ifndef LOG_DAEMON - (void) openlog("sockd", LOG_PID); -#else - (void) openlog("sockd", LOG_PID, SYSLOG_FAC); -#endif - -#ifdef NOT_THROUGH_INETD - inp = socket(AF_INET, SOCK_STREAM, 0); - sin.sin_family = AF_INET; - sin.sin_port = socks_port; - sin.sin_addr.s_addr = htonl(INADDR_ANY); - - if (bind(inp, &sin, sizeof(sin)) < 0) { - syslog(LOG_LOW, "error -- main bind() %m"); - exit(1); - } - - if (listen(inp, MAX_CLIENTS) < 0) { - syslog(LOG_LOW, "error -- main listen() %m"); - exit(1); - } - - if ((in = accept(inp, &sin, &len)) < 0) { - syslog(LOG_LOW, "error -- main accept() %m"); - exit(1); - } -#else - in = dup(0); -#endif - - if (getpeername(in, (struct sockaddr *)&from, &fromlen) < 0) { - syslog(LOG_LOW, "error -- unable to get client address."); - exit(1); - } - socks_client_port = ntohs(from.sin_port); -#ifdef DEBUG - syslog(LOG_LOW, "socks_client_port=%u", socks_client_port); -#endif /* #ifdef DEBUG */ - - saddrtoname(&from.sin_addr, socks_src_name, sizeof(socks_src_name)); - - if (GetDst(in, &dst) < 0) { - syslog(LOG_LOW, "Error in GetDst: %m; from host %s", socks_src_name); - exit(1); - } - - if (dst.version != SOCKS_VERSION) { - syslog(LOG_LOW, "error -- wrong version (0x%2x) from host %s.", - dst.version, socks_src_name); - exit(1); - } - - if (dst.cmd != SOCKS_CONNECT && dst.cmd != SOCKS_BIND) { - syslog(LOG_LOW, "error -- undefined command (0x%2x) from host %s", - dst.cmd, socks_src_name); - exit(1); - } - - dstsin.sin_family = AF_INET; - dstsin.sin_addr.s_addr = dst.host; - dstsin.sin_port = dst.port; - - while (read(in, &c, 1) == 1) - if (c == '\0') - break; - else { - if (nindex < sizeof(socks_src_user) - 1) - socks_src_user[nindex++] = c; - } - socks_src_user[nindex] = '\0'; - if (dstsin.sin_addr.s_addr == 0) - strcpy(socks_dst_name, "Unspecified.Host"); - else - saddrtoname(&dstsin.sin_addr, socks_dst_name, sizeof(socks_dst_name)); - porttoserv(dstsin.sin_port, socks_dst_serv, sizeof(socks_dst_serv)); - - permit = Validate(&from, &dstsin, in, use_identd); - if (dst.cmd == SOCKS_CONNECT) { - strcpy(socks_cmd, "connect"); - sprintf(log_msg, "Connect from %s(%s)@%s to %s (%s)", - socks_src_user, socks_real_user, socks_src_name, socks_dst_name, socks_dst_serv); -#ifdef FOR_PS - sprintf(ps_buf, "%s: %s(c) to %s", - socks_src_user, socks_dst_serv, socks_dst_name); - setproctitle(ps_buf, Argv, LastArgv); -#endif /* #ifdef FOR_PS */ - - } else { - strcpy(socks_cmd, "bind"); - sprintf(log_msg, "Bind from %s(%s)@%s for %s", - socks_src_user, socks_real_user, socks_src_name, socks_dst_name, socks_dst_serv); -#ifdef FOR_PS - sprintf(ps_buf, "%s: %s(b) to %s", - socks_src_user, socks_dst_serv, socks_dst_name); - setproctitle(ps_buf, Argv, LastArgv); -#endif /* #ifdef FOR_PS */ - } - if (permit == 1) - ; - else if (permit == 0) { - syslog(LOG_LOW, "refused -- %s", log_msg); - exit(1); - } else if (permit == -1) { - syslog(LOG_LOW, "cannot connect to identd on %s", socks_src_name); - } else if (permit == -2) { - syslog(LOG_LOW, "refused -- %s", log_msg); - syslog(LOG_LOW, "cannot connect to identd on %s", socks_src_name); - dst.cmd = SOCKS_NO_IDENTD; - SendDst(in, &dst); - exit(1); - } else if (permit == -3) { - syslog(LOG_LOW, "refused -- %s", log_msg); - syslog(LOG_LOW, "*Alert*: real user is %s, not %s", socks_real_user, socks_src_user); - dst.cmd = SOCKS_BAD_ID; - SendDst(in, &dst); - exit(1); - } else { - syslog(LOG_HIGH, "refused -- %s", log_msg); - syslog(LOG_HIGH, "Unexpected result from Validate"); - exit(1); - } - - -#ifdef DEBUG - strcpy(buf, inet_ntoa(from.sin_addr)); - syslog(LOG_LOW,"USER:%s, SRC:%s, DST:%s, PORT:%u", - socks_src_user, buf, inet_ntoa(dstsin.sin_addr), - ntohs(dstsin.sin_port)); -#endif - - /* - ** Kill a connecting off if bind or connect takes too - ** long to complete - */ - signal(SIGALRM, die); - /*alarm(60*5);*/ /* 5 minutes */ - alarm(60*2); - - if (dst.cmd == SOCKS_CONNECT) { - DoConnect(in, &dst); - } - if (dst.cmd == SOCKS_BIND) { - DoNewBind(in, &dst); - } -} - -socks_fail(str, in, ndst) -char *str; -int in; -Socks_t *ndst; -{ - syslog(LOG_LOW, "failed -- %s. Error code: %s %m", log_msg, str); - ndst->cmd = SOCKS_FAIL; - SendDst(in, ndst); - exit(1); -} - - -/* -** Actually connect a socket to the outside world, -*/ -DoConnect(in, dst) -int in; -Socks_t *dst; -{ - int out; - struct sockaddr_in sin; - Socks_t ndst; - int outport = IPPORT_RESERVED - 1; - int turnon = 1; - - bzero((char *)&sin, sizeof(sin)); -#if defined(SO_OOBINLINE) - setsockopt(in, SOL_SOCKET, SO_OOBINLINE, &turnon, sizeof(turnon)); -#endif -#if defined(SUPPORT_RCMD) -#ifdef DEBUG - syslog(LOG_LOW, "DoConnect(): client port=%u", socks_client_port); -#endif /* #ifdef DEBUG */ - if ((socks_client_port < IPPORT_RESERVED) && - (socks_client_port >= IPPORT_RESERVED/2)) { - if ((out = rresvport(&outport)) < 0) - socks_fail("rresvport()", in, &ndst); -#if defined(hpux) - ioctl(out, FIOSSAIOOWN, getpid()); -#else /* hpux not defined */ - fcntl(out, F_SETOWN, getpid()); -#endif /* #if defined(hpux) */ - } else if ((out = socket(AF_INET, SOCK_STREAM, 0)) < 0) - socks_fail("socket()", in, &ndst); -#else /* SUPPORT_RCMD is not defined */ - if ((out = socket(AF_INET, SOCK_STREAM, 0)) < 0) - socks_fail("socket()", in, &ndst); -#endif /* #if defined(SUPPORT_RCMD) */ - - sin.sin_family = AF_INET; - sin.sin_port = dst->port; - sin.sin_addr.s_addr = dst->host; - - ndst.version = Version; - ndst.cmd = SOCKS_RESULT; - - if (connect(out, (struct sockaddr *)&sin, sizeof(struct sockaddr_in)) < 0) - socks_fail("connect()", in, &ndst); - - syslog(LOG_LOW, "connected -- %s", log_msg); -#if defined(SO_OOBINLINE) - setsockopt(out, SOL_SOCKET, SO_OOBINLINE, &turnon, sizeof(turnon)); -#endif - SendDst(in, &ndst); - Pump(in, out); - syslog(LOG_LOW, "terminated -- %s.", log_msg); - syslog(LOG_LOW, "%lu bytes from %s, %lu bytes from %s", from_in, socks_src_name, from_out, socks_dst_name); -} - -/* -** Set up a socket to be connected to from the outside world. -** diffrence between this an the Version1 protocal is that -** the socket has to be bound from a specific host that -** is passed. -*/ -DoNewBind(in, dst) -int in; -Socks_t *dst; -{ - u_int32 sockd_route(); - int new, out, len = sizeof(struct sockaddr_in); - struct sockaddr_in sin; - Socks_t ndst; - char dsthost[16]; - char socks_dst_name[NAMELEN], socks_dst_serv[NAMELEN]; - int outport = IPPORT_RESERVED - 1; - int turnon = 1; - - bzero((char *)&sin, sizeof(sin)); -#if defined(SO_OOBINLINE) - setsockopt(in, SOL_SOCKET, SO_OOBINLINE, &turnon, sizeof(turnon)); -#endif - - sin.sin_family = AF_INET; - ndst.version = Version; - ndst.cmd = SOCKS_RESULT; - sin.sin_port = htons(0); -#ifdef MULTIHOMED_SERVER - sin.sin_addr.s_addr = sockd_route(dst->host); -#else - sin.sin_addr.s_addr = htonl(INADDR_ANY); -#endif - -#if defined(SUPPORT_RCMD) -#ifdef DEBUG - syslog(LOG_LOW, "DoNewBind(): client port=%u", socks_client_port); -#endif /* #ifdef DEBUG */ - if ((socks_client_port < IPPORT_RESERVED) && (socks_client_port >= IPPORT_RESERVED/2)){ - if((out = rresvport(&outport)) < 0) - socks_fail("rresrvport()", in, &ndst); -#ifdef DEBUG - syslog(LOG_LOW, "DoNewBind(): outport=%d", outport); -#endif /* #ifdef DEBUG */ -#if defined(hpux) - ioctl(out, FIOSSAIOOWN, getpid()); -#else /* hpux not defined */ - fcntl(out, F_SETOWN, getpid()); -#endif /* #if defined(hpux) */ - sin.sin_port = htons((short)outport); -#ifdef DEBUG - syslog(LOG_LOW, "DoNewBind(): sin.sin_addr=%s, sin.sin_port=%u", - inet_ntoa(sin.sin_addr), ntohs(sin.sin_port)); -#endif /* #ifdef DEBUG */ - } else { -#endif /* #if defined(SUPPORT_RCMD) */ - if ((out = socket(AF_INET, SOCK_STREAM, 0)) < 0) - socks_fail("socket()", in, &ndst); - - if (bind(out, (struct sockaddr *)&sin, sizeof(sin)) < 0) - socks_fail("bind()", in, &ndst); - if (getsockname(out, (struct sockaddr *)&sin, &len) < 0) - socks_fail("getsockname()", in, &ndst); -#if defined(SUPPORT_RCMD) - } -#endif /* if defined(SUPPORT_RCMD) */ - - ndst.port = sin.sin_port; - ndst.host = sin.sin_addr.s_addr; - - if (listen(out, 1) < 0) - socks_fail("listen()", in, &ndst); - -#if defined(SO_OOBINLINE) - setsockopt(new, SOL_SOCKET, SO_OOBINLINE, &turnon, sizeof(turnon)); -#endif - SendDst(in, &ndst); - - len = sizeof(struct sockaddr_in); - if ((new = accept(out, (struct sockaddr *)&sin, &len)) < 0) - socks_fail("accept()", in, &ndst); - close(out); - - if (sin.sin_addr.s_addr == 0) - strcpy(socks_dst_name, "Unspecified.Host"); - else - saddrtoname(&sin.sin_addr, socks_dst_name, sizeof(socks_dst_name)); - porttoserv(sin.sin_port, socks_dst_serv, sizeof(socks_dst_serv)); - -#ifdef SHORTENED_RBIND - if ((dst->host != 0L) && (sin.sin_addr.s_addr != dst->host)) { -#else - if (sin.sin_addr.s_addr != dst->host) { -#endif -/* -#if defined(SOLARIS) || defined(NeXT) || defined(_SEQUENT_) -*/ - { - struct in_addr inaddr; - - inaddr.s_addr = dst->host; - strncpy(dsthost, inet_ntoa(inaddr), sizeof(dsthost)); - } -/* -#else - strncpy(dsthost, inet_ntoa(&dst->host), sizeof(dsthost)); -#endif -*/ - syslog(LOG_LOW, "failed -- %s. Error: connected to wrong host %s (%s)", - log_msg, socks_dst_name, socks_dst_serv); - ndst.cmd = SOCKS_FAIL; - SendDst(in, &ndst); - exit(1); - } - - syslog(LOG_LOW, "connected -- %s (%s)", log_msg, socks_dst_serv); - ndst.port = sin.sin_port; - ndst.host = sin.sin_addr.s_addr; - SendDst(in, &ndst); - Pump(in, new); - syslog(LOG_LOW, "terminated -- %s (%s).", log_msg, socks_dst_serv); - syslog(LOG_LOW, "%lu bytes from %s, %lu bytes from %s", from_in, socks_src_name, from_out, socks_dst_name); -} - -/* -** Now just pump the packets/character through.. -*/ -Pump(in, out) -int in, out; -{ - static char buf[4096]; - fd_set fds; - int n, fdsbits; - static struct timeval tout = { SOCKS_TIMEOUT, 0 }; -/* >>> Andy McFadden fadden@uts.amdahl.com */ - struct linger ling; /* for linger */ - int length; /* for linger */ - - alarm(0); - - /* - * ATM: use SO_LINGER so it won't hang up on client - */ - ling.l_onoff = 1; /* turn it on */ - ling.l_linger = /*3*/ 10; - length = sizeof(ling); - if (setsockopt(in, SOL_SOCKET, SO_LINGER, &ling, length) < 0) - perror("setsockopt (SO_LINGER) in"); - if (setsockopt(out, SOL_SOCKET, SO_LINGER, &ling, length) < 0) - perror("setsockopt (SO_LINGER) out"); -/* <<< Andy McFadden fadden@uts.amdahl.com */ - - FD_ZERO(&fds); - if (in > out) - fdsbits = in + 1; - else - fdsbits = out +1; - - while (1) { - tout.tv_sec = SOCKS_TIMEOUT; - tout.tv_usec = 0; - FD_SET(in, &fds); - FD_SET(out, &fds); - if ((n = select(fdsbits, &fds, NULL,NULL, &tout)) > 0) { - if (FD_ISSET(in, &fds)) { - if ((n = read(in, buf, sizeof buf)) > 0) { - from_in += n; - if (write(out, buf, n) < 0) { - goto bad; - } - } else { - goto bad; - } - } - if (FD_ISSET(out, &fds)) { - if ((n = read(out, buf, sizeof buf)) > 0) { - from_out += n; - if (write(in, buf, n) < 0) { - goto bad; - } - } else { - goto bad; - } - } - } else { - if (n != 0) - syslog(LOG_LOW, "select %m\n"); - goto bad; - } - } - -bad: - ; /* Make the goto happy */ -} - - -#ifdef FOR_PS - -/* -** SETPROCTITLE -- set process title for ps -** -** Parameters: -** fmt -- a printf style format string. -** a, b, c -- possible parameters to fmt. -** -** Returns: -** none. -** -** Side Effects: -** Clobbers argv of our main procedure so ps(1) will -** display the title. -** -** Stolen from IDA Sendmail - I don't think it's UCB code. -*/ - -/*VARARGS1*/ -setproctitle(buf, Argv, LastArgv) -char *buf; -char **Argv, *LastArgv; -{ -#if defined(FOR_PS) && !defined(SYSV) - register char *p; - register int i; - - /* make ps print "(sockd)" */ - p = Argv[0]; - *p++ = '-'; - - i = strlen(buf); - if (i > LastArgv - p - 2) - { - i = LastArgv - p - 2; - buf[i] = '\0'; - } - (void) strcpy(p, buf); - p += i; - while (p < LastArgv) - *p++ = ' '; -#endif /* FOR_PS && !SYSV */ -} -#endif /* #ifdef FOR_PS */ - -#endif /* #ifndef TEST */ - -#ifdef MULTIHOMED_SERVER - -static char *sockd_route_file = SOCKD_ROUTE_FILE; - -u_int32 sockd_route(dsthost) -u_int32 dsthost; -{ - FILE *fd; - static char buf[1024]; -#ifdef TEST - char temp[1024]; -#endif - char *bp; - int linenum = 0; - char *argv[3]; - int argc; - u_int32 interface, destip, destmask; - -#ifdef TEST - fprintf(stderr,"==== Checking routing file (%s)...\n", sockd_route_file); -#endif - - if ((fd = fopen(sockd_route_file, "r")) == NULL) { -#ifdef TEST - fprintf(stderr, "Unable to open routing file (%s)\n", sockd_route_file); - return(0); -#else - syslog(LOG_HIGH, "Unable to open routing file (%s)", sockd_route_file); - exit(1); -#endif - } - - while (fgets(buf, sizeof(buf) - 1, fd) != NULL) { - linenum++; -#ifdef TEST - strcpy(temp, buf); -#endif - /* Comment starts with # anywhere in the line */ - if ((bp = index(buf, '\n')) != NULL) - *bp ='\0'; - for (bp = buf; *bp; bp++ ) { - if (*bp == '#') { - *bp = '\0'; - break; - } else if (*bp == '\t') - *bp = ' '; - } - mkargs(buf, &argc, argv, 3); - if (argc == 0) - continue; - if (argc != 3) { -#ifdef TEST - fprintf(stderr, "Invalid entry at line %d\n", linenum); -#else - syslog(LOG_LOW, "Invalid entry at line %d", linenum); -#endif - continue; - } - GetAddr(argv[0], &interface); - GetAddr(argv[1], &destip); - GetAddr(argv[2], &destmask); -#ifdef OLD_CONF_MASK - if ((destip & ~destmask) == (dsthost & ~destmask)) { -#else - if ((destip & destmask) == (dsthost & destmask)) { -#endif -#ifdef TEST - fprintf(stderr, "Line %d: %s", linenum, temp); -#endif - fclose(fd); - return(interface); - } - } - fclose(fd); -#ifdef TEST -/* -# if defined(SOLARIS) || defined(NeXT) || defined(_SEQUENT_) -*/ - { - struct in_addr inaddr; - - inaddr.s_addr = dsthost; - fprintf(stderr, "***Cannot find appropriate interface to communicate with %s\n", inet_ntoa(inaddr)); - } -/* -# else - fprintf(stderr, "***Cannot find appropriate interface to communicate with %s\n", inet_ntoa(&dsthost)); -# endif -*/ - return(0); -#else -/* -# if defined(SOLARIS) || defined(NeXT) || defined(_SEQUENT_) -*/ - { - struct in_addr inaddr; - - inaddr.s_addr = dsthost; - syslog(LOG_HIGH, "***Cannot find appropriate interface to communicate with %s\n", inet_ntoa(inaddr)); - } -/* -# else - syslog(LOG_HIGH, "***Cannot find appropriate interface to communicate with %s\n", inet_ntoa(&dsthost)); -# endif -*/ - exit(1); -#endif -} - -#endif /* #ifdef MULTIHOMED_SERVER */ - -check_sp_conf(fd, s, src, dst) -FILE *fd; -char *s; -struct sockaddr_in *src, *dst; -{ - char buf[1024], *p; -#ifdef TEST - int linenum = 0; -#endif - while (fgets(buf, sizeof(buf) - 1, fd) != NULL) { - if ((p = index(buf, '\n')) != NULL) - *p = '\0'; -#ifdef TEST - linenum++; -#endif - if (strncmp(s, buf, strlen(s)) == 0) { -#ifdef TEST - fprintf(stderr,"Line %d: %s\n", linenum, buf); -#endif - shell_cmd(buf+strlen(s), src, dst); - break; - } - } - return; -} - -Validate(src, dst, in, identd) -struct sockaddr_in *src, *dst; -int in; -int identd; -{ - FILE *fd; - static char buf[1024]; -#ifdef TEST - char temp[1024]; -#endif - char *bp; - int linenum = 0, permit; - char *argv[10]; - int argc; - u_int32 saddr, smask, daddr, dmask; - unsigned short dport; - enum { e_lt, e_gt, e_eq, e_neq, e_le, e_ge, e_nil } tst; - char *userlist; - int next_arg; - unsigned short dst_sin_port = ntohs(dst->sin_port); /* dst->sin_port in host byte order */ - long p; - char *cmdp; - int use_identd; - IDENT *ident_lookup(), *idp; - - - if ((fd = fopen(sockd_conf, "r")) == NULL) { -#ifdef TEST - fprintf(stderr,"Unable to open config file (%s)\n", sockd_conf); -#else /* #ifdef TEST */ - syslog(LOG_HIGH, "Unable to open config file (%s)", sockd_conf); -#endif /* #ifdef TEST */ - - return 0; - } - while (fgets(buf, sizeof(buf) - 1, fd) != NULL) { - linenum++; - use_identd = identd; -#ifdef TEST - strcpy(temp, buf); -#endif - /* - ** Comments start with a '#' anywhere on the line - */ - cmdp = (char *)0; - if ((bp = index(buf, '\n')) != NULL) - *bp = '\0'; - for (bp = buf; *bp != '\0'; bp++) { - if (*bp == ':') { - *bp++ = '\0'; - cmdp = bp; - break; - } else if (*bp == '#') { - *bp = '\0'; - break; - } else if (*bp == '\t') - *bp = ' '; - } - - mkargs(buf, &argc, argv, 8); - if (argc == 0) - continue; - if ((argc < 3) || (argc > 9)) { -#ifdef TEST - fprintf(stderr, "Invalid entry at line %d\n", linenum); -#else - syslog(LOG_LOW, "Invalid entry at line %d", linenum); -#endif - continue; - } - - if (STREQ(argv[0], "permit")) { - permit = 1; - } else if (STREQ(argv[0], "deny")) { - permit = 0; - } else { -#ifdef TEST - fprintf(stderr, "Invalid permit/deny field at line %d\n", linenum); -#else - syslog(LOG_LOW, "Invalid permit/deny field at line %d", linenum); -#endif - continue; - } - - userlist = (char *)0; - next_arg = 1; - - if (strncmp(argv[next_arg], "?=", 2) == 0) { - switch (argv[next_arg++][2]) { -#ifdef TEST - case 'I': - case 'i': - break; -#else /* TEST not defined */ - case 'I': - use_identd = 2; - break; - case 'i': - use_identd = 1; - break; -#endif /* #ifdef TEST */ - case 'n': - case '\0': - use_identd = 0; - break; - default: -#ifdef TEST - fprintf(stderr, "Invalid ?= field at line %d\n", linenum); -#else - syslog(LOG_LOW, "Invalid ?= field at line %d", linenum); -#endif - continue; - } - } - if (strncmp(argv[next_arg], "*=", 2) == 0) { - if (argv[next_arg][2]) userlist = argv[next_arg] + 2; - next_arg++; - } - if(argc <= next_arg+1) { -#ifdef TEST - fprintf(stderr, "Invalid entry at line %d\n", linenum); -#else - syslog(LOG_LOW, "Invalid entry at line %d", linenum); -#endif - continue; - } - - GetAddr(argv[next_arg++], &saddr); - GetAddr(argv[next_arg++], &smask); - - if ((argc > next_arg + 1) && - !(STREQ(argv[next_arg], "eq") || STREQ(argv[next_arg], "neq") || - STREQ(argv[next_arg], "lt") || STREQ(argv[next_arg], "gt") || - STREQ(argv[next_arg], "le") || STREQ(argv[next_arg], "ge"))) { - GetAddr(argv[next_arg++], &daddr); - GetAddr(argv[next_arg++], &dmask); - - } else { - daddr = 0; -#ifdef OLD_CONF_MASK - dmask = ~0; -#else - dmask = 0; -#endif - } - if (argc > next_arg + 1) { - if (STREQ(argv[next_arg], "eq")) - tst = e_eq; - else if (STREQ(argv[next_arg], "neq")) - tst = e_neq; - else if (STREQ(argv[next_arg], "lt")) - tst = e_lt; - else if (STREQ(argv[next_arg], "gt")) - tst = e_gt; - else if (STREQ(argv[next_arg], "le")) - tst = e_le; - else if (STREQ(argv[next_arg], "ge")) - tst = e_ge; - else { -#ifdef TEST - fprintf(stderr, "Invalid comparison at line %d\n", linenum); -#else - syslog(LOG_LOW, "Invalid comparison at line %d", linenum); -#endif - continue; - } - - if (((p = GetPort(argv[next_arg+1])) < 0) || - (p >= (1L << 16))) { -#ifdef TEST - fprintf(stderr, "Invalid port number at line %d\n", linenum); -#else - syslog(LOG_LOW, "Invalid port number at line %d", linenum); -#endif - continue; - } else { - dport = p; - } - } else { - tst = e_nil; - dport = 0; - } - -#ifdef DEBUG - { - char msg[1024]; - if (userlist) - sprintf(msg,"%s %s 0x%08x 0x%08x 0x%08x 0x%08x %s %u", - permit ? "permit" : "deny", - userlist, - saddr, smask, daddr, dmask, - tst == e_eq ? "==" : - tst == e_neq ? "!=" : - tst == e_lt ? "<" : - tst == e_gt ? ">" : - tst == e_le ? "<=" : - tst == e_ge ? ">=" : "NIL", - dport); - else - sprintf(msg,"%s 0x%08x 0x%08x 0x%08x 0x%08x %s %u", - permit ? "permit" : "deny", - saddr, smask, daddr, dmask, - tst == e_eq ? "==" : - tst == e_neq ? "!=" : - tst == e_lt ? "<" : - tst == e_gt ? ">" : - tst == e_le ? "<=" : - tst == e_ge ? ">=" : "NIL", - dport); - syslog(LOG_LOW, "%s", msg); - } -#endif - /* comparisons of port numbers must be done in host order */ - -#ifdef OLD_CONF_MASK - if((saddr & ~smask) == (src->sin_addr.s_addr & ~smask) && - (daddr & ~dmask) == (dst->sin_addr.s_addr & ~dmask) && -#else - if((saddr & smask) == (src->sin_addr.s_addr & smask) && - (daddr & dmask) == (dst->sin_addr.s_addr & dmask) && -#endif - check_user(userlist, socks_src_user)) { - if (tst == e_nil) - goto GotIt; - if ((tst == e_eq) && (dst_sin_port == dport)) - goto GotIt; - if ((tst == e_neq) && (dst_sin_port != dport)) - goto GotIt; - if ((tst == e_lt) && (dst_sin_port < dport)) - goto GotIt; - if ((tst == e_gt) && (dst_sin_port > dport)) - goto GotIt; - if ((tst == e_le) && (dst_sin_port <= dport)) - goto GotIt; - if ((tst == e_ge) && (dst_sin_port >= dport)) - goto GotIt; - } - } - - fclose(fd); -#ifdef TEST - fprintf(stderr, "*** No match with any line. Access denied.\n"); -#endif - return 0; - -GotIt: -#ifdef TEST - fprintf(stderr, "Line %d: %s", linenum, temp); - fseek(fd, 0L, 0); - if(permit && use_identd) - permit = use_identd; - if (permit == -3) - check_sp_conf(fd, "#BAD_ID:", src, dst); - else if ((permit == -1) || (permit == -2)) - check_sp_conf(fd, "#NO_IDENTD:", src, dst); - -#else /* # TEST not defined */ - if ((use_identd == 0) || (permit == 0)) { - fclose(fd); - if (cmdp != (char *)0) { - shell_cmd(cmdp, src, dst); - } - return permit; - } - fseek(fd, 0L, 0); - if ((idp = ident_lookup(in, IDENTD_TIMEOUT)) == ((IDENT *)0)) { - check_sp_conf(fd, "#NO_IDENTD:", src, dst); - permit = -use_identd; - } else { - strncpy(socks_real_user, idp->identifier, sizeof(socks_real_user)); - if (strcmp(socks_src_user, socks_real_user)) { -#if defined(SUPPORT_RCMD) - if ((socks_client_port >= IPPORT_RESERVED) || - (socks_client_port < IPPORT_RESERVED/2) || - strcmp(socks_src_user, "root")) { -#endif /* #if defined(SUPPORT_RCMD) */ - permit = -3; -#if defined(SUPPORT_RCMD) - } -#endif /* #if defined(SUPPORT_RCMD) */ - } - } - ident_free(idp); -#endif /* #ifdef TEST */ - fclose(fd); - if ((permit >= -1) && cmdp) - shell_cmd(cmdp, src, dst); - return permit; -} - -/*-------------------------------------------------*/ - -#ifdef TEST - -char *testpname; - -error_and_quit() -{ -#ifdef MULTIHOMED_SERVER - fprintf(stderr, "Usage:\n%s [-i] [-I] [-B] [-R route_file] [-C conf_file] user src_addr dst_addr {service,port}\n", testpname); -#else - fprintf(stderr, "Usage:\n%s [-i] [-I] [-B] [-C conf_file] user src_addr dst_addr {service,port}\n", testpname); -#endif - exit(-1); -} - -main(argc, argv) -int argc; -char *argv[]; - -/* - * test_sockd_conf [-i] [-I] [-B] [-R route_file] [-C conf_file] user src_addr dst_addr {service,port} - * - * Prints out the line in configuration file that are examined and - * whether the access is permitted or denied. Sets exit status code - * to 1 for permit, 0 for deny, -1 for error in command line. - */ - -{ - int next = 1; - long p; - u_short port; - struct sockaddr_in from, dstsin; - char log_msg[1024]; - char command = SOCKS_CONNECT; - int sim_id = 0; - char buf[1024]; - int permit; - int in = 0; - - bzero((char *)&from, sizeof(from)); - bzero((char *)&dstsin, sizeof(dstsin)); - if(testpname = rindex(argv[0], '/')) - ++testpname; - else - testpname = argv[0]; - - while (--argc && (argv[next][0] == '-')) { - switch (argv[next++][1]) { - case 'B': - sim_id = -3; - break; - case 'C': - if (--argc) { - sockd_conf =argv[next++]; - break; - } else - error_and_quit(); - case 'I': - sim_id = -2; - break; -#ifdef MULTIHOMED_SERVER - case 'R': - if (--argc) { - sockd_route_file =argv[next++]; - break; - } else - error_and_quit(); -#endif - case 'i': - sim_id = -1; - break; - default: - error_and_quit(); - } - } - - if (argc != 4) - error_and_quit(); - - strncpy(socks_src_user, argv[next++], sizeof(socks_src_user)); - GetAddr(argv[next++], &from.sin_addr.s_addr); - GetAddr(argv[next++], &dstsin.sin_addr.s_addr); - if (((p = GetPort(argv[next])) < 0) || (p >= (1L << 16))) { - fprintf(stderr, "%s: Unknown service or illegal port number '%s'\n",testpname, argv[next]); - exit(-1); - } - dstsin.sin_port = htons(port = p); - - if (sim_id) - strcpy(socks_real_user,"unknown"); - else - strcpy(socks_real_user, socks_src_user); - - saddrtoname(&from.sin_addr, socks_src_name, sizeof(socks_src_name)); - saddrtoname(&dstsin.sin_addr, socks_dst_name, sizeof(socks_dst_name)); - porttoserv(dstsin.sin_port, socks_dst_serv, sizeof(socks_dst_serv)); - sprintf(log_msg, "connect from %s(%s)@%s to %s (%s)", - socks_src_user, socks_real_user, socks_src_name, socks_dst_name, socks_dst_serv); -#ifdef LOG_DAEMON - openlog(testpname, LOG_PID, SYSLOG_FAC); -#else - openlog(testpname, LOG_PID); -#endif - - strcpy(buf, inet_ntoa(from.sin_addr)); - fprintf(stderr, "USER:%s, SRC:%s, DST:%s, PORT:%u\n", - socks_src_user, buf, inet_ntoa(dstsin.sin_addr), - ntohs(dstsin.sin_port)); - - permit = Validate(&from, &dstsin, in, sim_id); - - switch (permit) { - case 0: - syslog(LOG_LOW, "refused -- %s", log_msg); - exit(0); - case -3: - syslog(LOG_LOW, "*Alert*: real user is %s, not %s", socks_real_user, socks_src_user); - syslog(LOG_LOW, "refused -- %s", log_msg); - fprintf(stderr, "Access denied: bad user-id.\n"); - exit(0); - case -2: - syslog(LOG_LOW, "cannot connect to identd on %s", socks_src_name); - syslog(LOG_LOW, "refused -- %s", log_msg); - fprintf(stderr, "Access denied: cannot verify user-id.\n"); - exit(0); - case -1: - syslog(LOG_LOW, "cannot connect to identd on %s", socks_src_name); - break; - case 1: - break; - default: - syslog(LOG_HIGH, "refused -- %s", log_msg); - syslog(LOG_HIGH, "Unexpected result from Validate"); - exit(0); - } -#ifdef MULTIHOMED_SERVER - if (sockd_route(dstsin.sin_addr.s_addr)) { -#endif /* #ifdef MULTIHOMED_SERVER */ - syslog(LOG_LOW, "connected -- %s", log_msg); - exit(1); -#ifdef MULTIHOMED_SERVER - } else { - syslog(LOG_LOW, "refused -- %s", log_msg); - exit(0); - } -#endif /* #ifdef MULTIHOMED_SERVER */ - -} - -#endif /* #ifdef TEST */ diff --git a/network/socks/socks.cstc.4.2/sockd/sockd.conf.sample b/network/socks/socks.cstc.4.2/sockd/sockd.conf.sample deleted file mode 100644 index 00a9f9cc..00000000 --- a/network/socks/socks.cstc.4.2/sockd/sockd.conf.sample +++ /dev/null @@ -1,5 +0,0 @@ -# replace 'client_IP' below with an actual IP address before trying it -permit client_IP 255.255.255.255 -deny 0.0.0.0 0.0.0.0 : /usr/ucb/finger @%A | /usr/ucb/mail -s 'SOCKD: rejected -- from %u@%A to host %Z (service %S)' root -#BAD_ID: /usr/ucb/finger @%A | /usr/ucb/mail -s '%U pretends to be %u on host %A' root@%A root -#NO_IDENTD: /usr/ucb/mail -s 'Please run identd on %A' %u@%A root@%A diff --git a/network/socks/socks.cstc.4.2/sockd/test.csh b/network/socks/socks.cstc.4.2/sockd/test.csh deleted file mode 100755 index 9eb44a96..00000000 --- a/network/socks/socks.cstc.4.2/sockd/test.csh +++ /dev/null @@ -1,154 +0,0 @@ -#! /bin/csh - -echo "deny *=bonnie,clyde 128.12.6.0 255.255.255.0 : /usr/ucb/mail -s 'Rejected SOCKS access by %u' $USER" >! junk.conf -echo 'permit *=ylee 128.12.6.4 255.255.255.255 137.12.0.0 255.255.0.0' >> junk.conf -echo 'deny 128.12.0.0 255.255.0.0 eq telnet' >> junk.conf -echo 'permit 128.12.0.0 255.255.0.0' >> junk.conf -echo "#NO_IDENTD: /usr/ucb/mail -s 'please run identd on %A' $USER" >> junk.conf -echo "#BAD_ID: /usr/ucb/mail -s '%U pretends to be %u on %A' $USER" >> junk.conf -# -set prog=./test_sockd_conf - -strings $prog |egrep -s route_file -if ( $status != 0 ) then - set aa=1 - set opt="" -else - set aa=0 - set opt = (-R junk.route) - echo "129.10.1.2 10.0.0.0 255.0.0.0" >! junk.route - echo "129.10.7.10 137.12.0.0 255.255.0.0" >> junk.route - echo "129.10.254.1 0.0.0.0 0.0.0.0" >> junk.route -endif - -set a=($prog $opt -C junk.conf clyde 128.12.6.34 112.3.24.1 ftp) -echo $a -$a -echo '-------------- should produce:' -echo "USER:clyde, SRC:128.12.6.34, DST:112.3.24.1, PORT:21" -echo "Line 1: deny *=bonnie,clyde 128.12.6.0 255.255.255.0 : /usr/ucb/mail -s 'Rejected SOCKS access by %u' $USER" -echo "A mail message is sent to $USER with the subject line 'Rejected SOCKS" -echo "access by clyde'." -echo "================================================" - -set a=($prog $opt -C junk.conf ylee 128.12.6.4 137.12.4.15 telnet) -echo $a -$a -echo '-------------- should produce:' -echo "USER:ylee, SRC:128.12.6.4, DST:137.12.4.15, PORT:23" -echo 'Line 2: permit *=ylee 128.12.6.4 255.255.255.255 137.12.0.0 255.255.0.0' -if ( $aa == 0 ) then - echo "==== Checking routing file (junk.route)..." - echo "Line 2: 129.10.7.10 137.12.0.0 255.255.0.0" -endif -echo "================================================" - -set a=($prog $opt -C junk.conf jane 128.12.2.13 137.12.4.15 telnet) -echo $a -$a -echo '-------------- should produce:' -echo "USER:jane, SRC:128.12.2.13, DST:137.12.4.15, PORT:23" -echo "Line 3: deny 128.12.0.0 255.255.0.0 eq telnet" -echo "================================================" - -set a=($prog $opt -C junk.conf jim 128.12.6.4 126.87.13.2 telnet) -echo $a -$a -echo '-------------- should produce:' -echo "USER:jim, SRC:128.12.6.4, DST:126.87.13.2, PORT:23" -echo "Line 3: deny 128.12.0.0 255.255.0.0 eq telnet" -echo "================================================" - -set a=($prog $opt -C junk.conf ylee 128.12.6.4 126.87.13.2 ftp) -echo $a -$a -echo '-------------- should produce:' -echo "USER:ylee, SRC:128.12.6.4, DST:126.87.13.2, PORT:21" -echo "Line 4: permit 128.12.0.0 255.255.0.0" -if ( $aa == 0 ) then - echo "==== Checking routing file (junk.route)..." - echo "Line 3: 129.10.254.1 0.0.0.0 0.0.0.0" -endif -echo "================================================" - -set a=($prog $opt -C junk.conf sam 128.12.36.7 10.53.23.1 70) -echo $a -$a -echo '-------------- should produce:' -echo "USER:sam, SRC:128.12.36.7, DST:10.53.23.1, PORT:70" -echo "Line 4: permit 128.12.0.0 255.255.0.0" -if ( $aa == 0 ) then - echo "==== Checking routing file (junk.route)..." - echo "Line 1: 129.10.1.2 10.0.0.0 255.0.0.0" -endif -echo "================================================" - -set a=($prog $opt -C junk.conf don 23.2.6.127 10.53.23.1 70) -echo $a -$a -echo '-------------- should produce:' -echo "USER:don, SRC:23.2.6.127, DST:10.53.23.1, PORT:70" -echo "*** No match with any line. Access denied." -echo "================================================" - -set a=($prog $opt -C junk.conf clyde 128.12.1.62 112.3.24.1 ftp) -echo $a -$a -echo '-------------- should produce:' -echo "USER:clyde, SRC:128.12.1.62, DST:112.3.24.1, PORT:21" -echo "Line 4: permit 128.12.0.0 255.255.0.0" -if ( $aa == 0 ) then - echo "==== Checking routing file (junk.route)..." - echo "Line 3: 129.10.254.1 0.0.0.0 0.0.0.0" -endif -echo "================================================" - -set a=($prog $opt -C junk.conf -I joe 128.12.6.4 126.87.13.2 ftp) -echo $a -$a -echo '-------------- should produce:' -echo "USER:joe, SRC:128.12.6.4, DST:126.87.13.2, PORT:21" -echo "Line 4: permit 128.12.0.0 255.255.0.0" -echo "Line 5: #NO_IDENTD: /usr/ucb/mail -s 'please run identd on %a' $USER" -echo "Access denied: cannot verify user-id." -echo "A mail message is sent to $USER of the host 128.12.6.4 with the" -echo "subject line 'please run identd on 128.12.6.4'." -echo "================================================" - -set a=($prog $opt -C junk.conf -i joe 128.12.6.4 126.87.13.2 ftp) -echo $a -$a -echo '-------------- should produce:' -echo "USER:joe, SRC:128.12.6.4, DST:126.87.13.2, PORT:21" -echo "Line 4: permit 128.12.0.0 0.0.255.255" -echo "Line 5: #NO_IDENTD: /usr/ucb/mail -s 'please run identd on %a' $USER" -if ( $aa == 0 ) then - echo "==== Checking routing file (junk.route)..." - echo "Line 3: 129.10.254.1 0.0.0.0 0.0.0.0" -endif -echo "A mail message is sent to $USER of the host 128.12.6.4 with the" -echo "subject line 'please run identd on 128.12.6.4'." -echo "================================================" - -set a=($prog $opt -C junk.conf -i jim 128.12.6.4 126.87.13.2 telnet) -echo $a -$a -echo '-------------- should produce:' -echo "USER:jim, SRC:128.12.6.4, DST:126.87.13.2, PORT:23" -#echo "Line 5: #NO_IDENTD: /usr/ucb/mail -s 'please run identd on %a' $USER" -echo "Line 3: deny 128.12.0.0 0.0.255.255 eq telnet" -echo "A mail message is sent to $USER of the host 128.12.6.4 with the" -echo "subject line 'please run identd on 128.12.6.4'." -echo "================================================" - -set a=($prog $opt -C junk.conf -B joe 128.12.6.4 126.87.13.2 ftp) -echo $a -$a -echo '-------------- should produce:' -echo "USER:joe, SRC:128.12.6.4, DST:126.87.13.2, PORT:21" -echo "Line 4: permit 128.12.0.0 255.255.0.0" -echo "Line 6: #BAD_ID: /usr/ucb/mail -s '%U pretends to be %u on %A' $USER" -echo "Access denied: bad user-id." -echo "A mail message is sent to $USER with the" -echo "subject line 'unknown pretends to be joe on 128.12.6.4'." -echo "================================================" diff --git a/network/taxon1/taxon2/taxext.h b/network/taxon1/taxon2/taxext.h index 50e02839..d20266a2 100644 --- a/network/taxon1/taxon2/taxext.h +++ b/network/taxon1/taxon2/taxext.h @@ -31,6 +31,9 @@ * * * $Log: taxext.h,v $ +* Revision 1.5 2005/08/08 18:03:27 soussov +* adds extern C +* * Revision 1.4 2001/09/28 15:53:15 soussov * tax1e_maxTaxId() added * @@ -53,6 +56,10 @@ #include <taxinc.h> #include <treemgr.h> +#ifdef __cplusplus +extern "C" { /* } */ +#endif + /*------------------------------------- Get pointer to partial taxonomy tree You can call this function after tax1_init() @@ -118,4 +125,8 @@ Int4 tax1e_needUpdate(OrgRefPtr inp_orgRef); */ Int4 tax1e_maxTaxId(); +#ifdef __cplusplus +/* { */ } +#endif + #endif diff --git a/network/taxon1/taxon2/tc2proc.c b/network/taxon1/taxon2/tc2proc.c index baf0bc02..d6c968d0 100644 --- a/network/taxon1/taxon2/tc2proc.c +++ b/network/taxon1/taxon2/tc2proc.c @@ -1,5 +1,5 @@ /*----------------*/ -/* $Id: tc2proc.c,v 1.36 2005/04/04 21:32:13 soussov Exp $ */ +/* $Id: tc2proc.c,v 1.38 2005/07/25 18:07:44 lavr Exp $ */ /*----------------*/ #include <stdlib.h> @@ -1201,7 +1201,7 @@ static OrgNamePtr bldOrgName(TreeCursorPtr cursor, int* is_species_out, if(tnp != NULL) { rank= tnp->flags & 0xFF; if(rank != 0) { - is_species= (rank >= SpeciesRank) ? 1 : 0; + is_species= (rank > SpeciesRank) ? 1 : 0; break; } } @@ -1842,7 +1842,7 @@ Taxon1DataPtr tax1_lookup(OrgRefPtr inp_orgRef, int merge) tax_id= txc_findByOrg(inp_orgRef, &hitName); - //tax_id= tax1_getTaxIdByOrgRef(inp_orgRef); + /*tax_id= tax1_getTaxIdByOrgRef(inp_orgRef);*/ if(tax_id <= 0) return NULL; db_orgRef= s_tax1_getOrgRef(tax_id, &is_species, NULL, NULL); if(db_orgRef == NULL) return NULL; diff --git a/network/taxon1/taxon2/txclient.h b/network/taxon1/taxon2/txclient.h index 8060d02f..9fd89493 100644 --- a/network/taxon1/taxon2/txclient.h +++ b/network/taxon1/taxon2/txclient.h @@ -31,6 +31,9 @@ * * * $Log: txclient.h,v $ +* Revision 1.8 2005/08/08 18:03:27 soussov +* adds extern C +* * Revision 1.7 2003/03/05 21:32:00 soussov * new lookup procedure * @@ -71,6 +74,10 @@ #include <objfeat.h> #endif +#ifdef __cplusplus +extern "C" { /* } */ +#endif + typedef struct t_TXC_Name { Int4 tax_id; Uint1 class_cde; @@ -179,5 +186,8 @@ _subspecPtr tax_SSget(Int4 tax_id, _subspecPtr ssrec); tax_OrgModPtr tax_SSgetLegal(Int4 tax_id); Int4 tax_SSgetNodes(Uint1 stype, CharPtr sname, Uint1 mode, Int4Ptr* ids); +#ifdef __cplusplus +/* { */ } +#endif #endif diff --git a/network/taxon1/taxon2/txcommon.h b/network/taxon1/taxon2/txcommon.h index 45e7a6de..462b09f6 100644 --- a/network/taxon1/taxon2/txcommon.h +++ b/network/taxon1/taxon2/txcommon.h @@ -31,6 +31,9 @@ * * * $Log: txcommon.h,v $ +* Revision 1.6 2005/08/08 18:03:27 soussov +* adds extern C +* * Revision 1.5 2001/09/18 16:55:38 soussov * switching to the new ASN * @@ -60,6 +63,10 @@ #include <ncbi.h> +#ifdef __cplusplus +extern "C" { /* } */ +#endif + #define TAX_DIV_TXT 0 #define TAX_DIV_CDE 1 #define TAX_DIV_COM 2 @@ -233,4 +240,8 @@ Boolean tax_dumpGCs(void (*dmpFunc)(VoidPtr, Int2, CharPtr), VoidPtr usrData); Boolean tax_matchName(CharPtr orgName, CharPtr str, Int4 mode); Int4 tax_getTaxId4GI(Int4 gi); +#ifdef __cplusplus +/* { */ } +#endif + #endif diff --git a/network/wwwblast/Src/test/run.pl b/network/wwwblast/Src/test/run.pl index 28a75d23..052f7379 100755 --- a/network/wwwblast/Src/test/run.pl +++ b/network/wwwblast/Src/test/run.pl @@ -22,8 +22,9 @@ my $time = &GetTimeCmd(); my $oldbin = "/net/blast012/export/home/web/public/htdocs/BLAST/bl2seq/$app"; #my $oldbin = "../wblast2.REAL.old"; + chomp(my $basedir = `pwd`); -my $newbin = "$basedir/../$app"; +my $newbin = "$basedir/$app"; my $out = "out"; @@ -33,7 +34,7 @@ if (not -e "$out") { my %Tests; -if ($app eq "wblast2.REAL") { +if ($app eq "wblast2.REAL" or $app eq "wblast2_cs.REAL") { $Tests{'blastp'} = "\"ONE=129295&TWO=XP_222492.2&FILTER=1&PROGRAM=blastp\""; $Tests{'blastn'} = "\"ONE=555&TWO=101&FILTER=1&PROGRAM=blastn\""; @@ -57,12 +58,14 @@ if ($app eq "wblast2.REAL") { # short-subject-blastn finds one hit. $Tests{'short-subject-discmb'} = "\"PROGRAM=blastn&ONE=AE003820&SSEQ=aggacctcatcagcctcaaa&WORD=11&EXPECT=10000&MEGABLAST=yes\""; $Tests{'short-subject-blastn'} = "\"PROGRAM=blastn&ONE=AE003820&SSEQ=aggacctcatcagcctcaaa&WORD=11&EXPECT=10000\""; + $Tests{'bare-fasta'} = "\"PROGRAM=blastn&SEQ=agcctggtaggctgcagtccatggggtcacacagagtcggacatgactgagcgacttcac&SSEQ=agcctggtaggctgcaatccatggggtcgctagagtcggacacgactgagcgacttcac&PROGRAM=blastn&FILTER=1\""; } else { if ($app eq "blast_cs.REAL") { } } + foreach $test (keys %Tests) { print "\nTest ", $test, ""; print "\n----------------\n"; diff --git a/network/wwwblast/Src/wblast2.c b/network/wwwblast/Src/wblast2.c index bbc39b94..ec6830ed 100644 --- a/network/wwwblast/Src/wblast2.c +++ b/network/wwwblast/Src/wblast2.c @@ -1,4 +1,4 @@ -/* $Id: wblast2.c,v 1.22 2005/05/16 14:36:59 coulouri Exp $ +/* $Id: wblast2.c,v 1.25 2005/08/19 15:53:50 coulouri Exp $ * =========================================================================== * * PUBLIC DOMAIN NOTICE @@ -27,12 +27,21 @@ * * Initial Creation Date: 10/23/2000 * -* $Revision: 1.22 $ +* $Revision: 1.25 $ * * File Description: * BLAST 2 Sequences CGI program * * $Log: wblast2.c,v $ +* Revision 1.25 2005/08/19 15:53:50 coulouri +* correct grammar +* +* Revision 1.24 2005/07/29 22:19:30 dondosha +* If no Entrez client case, treat all sequences as FASTA +* +* Revision 1.23 2005/07/28 16:37:49 coulouri +* remove dead code +* * Revision 1.22 2005/05/16 14:36:59 coulouri * delayed declarations are not allowed in c * @@ -233,7 +242,7 @@ #include <blastpat.h> #ifndef BL2SEQ_STANDALONE -#include <qblastnet.h> +#include <Liburlapi/qblastnet.h> #endif #ifndef USE_OLD_BLAST @@ -423,15 +432,6 @@ static SeqAnnotPtr tie_next_annot(SeqAnnotPtr head, SeqAnnotPtr next) return head; } -static void AbortPage(CharPtr mess) -{ - printf("<TITLE>ERROR</TITLE>\n"); - printf("<h2>\n"); - printf("<img src='images/confused.gif' align=middle>\n"); - printf("%s</h2>\n", mess); - exit(1); -} - #ifndef BL2SEQ_STANDALONE/* No logging for the standalone WWW Server version */ typedef struct LogInfo { CharPtr filename; @@ -777,7 +777,7 @@ static void Blast2SeqMainPage(CharPtr warning, CharPtr seq1, CharPtr seq2, CharP printf("</textarea>\n"); } printf("<BR>\n"); - printf("or download from file <INPUT type=file name=\"seqfile1\">"); + printf("or upload FASTA file <INPUT type=file name=\"seqfile1\">"); printf("<HR>\n"); #ifdef NCBI_ENTREZ_CLIENT printf("<font color=ff0000>Sequence 2</font><BR>\n Enter accession, GI or sequence in FASTA format \n"); @@ -796,7 +796,7 @@ static void Blast2SeqMainPage(CharPtr warning, CharPtr seq1, CharPtr seq2, CharP printf("</textarea>\n"); } printf("<BR>\n"); - printf("or download from file <INPUT type=file name=\"seqfile2\">"); + printf("or upload FASTA file <INPUT type=file name=\"seqfile2\">"); printf("<BR>\n"); printf("<INPUT TYPE=\"submit\" VALUE=\"Align\">\n"); @@ -890,189 +890,6 @@ static CharPtr NumToGun(int n) return str; } -static int get_int(CharPtr val) -{ - CharPtr ch=NULL; - - if (val != NULL) { - ch = val + 1; - while (isspace(*ch)) { - ch++; - } - if (*ch == '\0') { - return 0; - } - return (atoi(ch)); - } - return 0; -} -static FloatHi get_double(CharPtr val) -{ - CharPtr ch=NULL; - - if (val != NULL) { - ch = val + 1; - while (isspace(*ch)) { - ch++; - } - if (*ch == '\0') { - return 0; - } - return (atof(ch)); - } - return 0; -} - -static CharPtr get_char(CharPtr val) -{ - CharPtr ch=NULL; - - if (val != NULL) { - ch = val + 1; - while (isspace(*ch)) { - ch++; - } - if (*ch == '\0') { - ch = NULL; - } - } - return ch; -} - -static Boolean sum_for_DenseDiag(DenseDiagPtr ddp, AlignSumPtr asp) -/* special for blast 2 sequences */ -{ - SeqInt msi, tsi; - SeqLoc sl; - Int2 i; - Int4 x1, x2, y1, y2; - Uint1 m_res, t_res; - SeqPortPtr m_spp, t_spp; - - if(ddp == NULL || asp == NULL) - return FALSE; - x1 = ddp->starts [0]; - y1 = ddp->starts [1]; - x2 = x1 + ddp->len - 1; - y2 = y1 + ddp->len - 1; - msi.id = ddp->id; - msi.from = x1; - msi.to = x2; - if(ddp->strands != NULL) - msi.strand = (ddp->strands == NULL) ? 0 : ddp->strands[0]; - sl.choice = SEQLOC_INT; - sl.data.ptrvalue = &msi; - m_spp = SeqPortNewByLoc(&sl, - (asp->is_aa) ? Seq_code_ncbieaa : Seq_code_iupacna); - - tsi.id = ddp->id; - tsi.from = y1; - tsi.to = y2; - if(ddp->strands != NULL) - tsi.strand = (ddp->strands == NULL) ? 0 : ddp->strands[1]; - sl.choice = SEQLOC_INT; - sl.data.ptrvalue = &tsi; - - t_spp = SeqPortNewByLoc(&sl, - (asp->is_aa) ? Seq_code_ncbieaa : Seq_code_iupacna); - - for(i = 0; i < ddp->len; ++i) { - m_res = SeqPortGetResidue(m_spp); - if (!IS_residue(m_res)) { - continue; - } - t_res = SeqPortGetResidue(t_spp); - if (!IS_residue(t_res)) { - continue; - } - if(m_res == t_res) { - ++(asp->identical); - } else if(asp->matrix != NULL && asp->is_aa) { - if(asp->matrix[m_res][t_res] > 0) - ++(asp->positive); - } - } - - if (!asp->is_aa && ddp->strands) { - asp->m_strand = ddp->strands[0]; - asp->t_strand = ddp->strands[1]; - } - asp->totlen = ddp->len; - - SeqPortFree(m_spp); - SeqPortFree(t_spp); - return TRUE; -} - -static Boolean sum_for_DenseSeg(DenseSegPtr dsp, AlignSumPtr asp) -{ -/* special for blast 2 sequences */ - SeqInt msi, tsi; - SeqLoc sl; - Int2 i; - Int4 j, x1, x2, y1, y2; - Uint1 m_res, t_res; - SeqPortPtr m_spp, t_spp; - - if(dsp == NULL || asp == NULL) - return FALSE; - for(i = 0; i < dsp->numseg; ++i) { - x1 = dsp->starts[2*i]; - y1 = dsp->starts[2*i+1]; - x2 = x1 + dsp->lens[i] -1; - y2 = y1 + dsp->lens[i] -1; - msi.id = dsp->ids; - msi.from = x1; - msi.to = x2; - msi.strand = (dsp->strands == NULL) ? 0 : dsp->strands[2*i]; - if (x1 != -1) { - sl.choice = SEQLOC_INT; - sl.data.ptrvalue = &msi; - m_spp = SeqPortNewByLoc(&sl, (asp->is_aa) ? Seq_code_ncbieaa - : Seq_code_iupacna); - } else - m_spp = NULL; - tsi.id = dsp->ids->next; - tsi.from = y1; - tsi.to = y2; - tsi.strand = (dsp->strands == NULL) ? 0 : - dsp->strands[2*i+1]; - if (y1 != -1) { - sl.choice = SEQLOC_INT; - sl.data.ptrvalue = &tsi; - t_spp = SeqPortNewByLoc(&sl, (asp->is_aa) ? Seq_code_ncbieaa : Seq_code_iupacna); - } else - t_spp = NULL; - if (x1 == -1 || y1 == -1) { - asp->gaps += dsp->lens[i]; - } else { - for(j = 0; j < dsp->lens[i]; ++j) { - m_res = SeqPortGetResidue(m_spp); - if (!IS_residue(m_res)) { - continue; - } - t_res = SeqPortGetResidue(t_spp); - if (!IS_residue(m_res)) { - continue; - } - if(m_res == t_res) { - ++(asp->identical); - } else if(asp->matrix != NULL && asp->is_aa) { - if(asp->matrix[m_res][t_res] >0) - ++(asp->positive); - } - } - } - asp->totlen += dsp->lens[i]; - SeqPortFree(m_spp); - SeqPortFree(t_spp); - } - asp->m_strand = msi.strand; - asp->t_strand = tsi.strand; - - return TRUE; -} - /** Frees the part of the byte store list that has not been used for replacement * of Bioseq data. */ @@ -1550,52 +1367,6 @@ static void DrawRectAlign(PrymPtr PNTR rect, Int2 k, Int2 color, Int2 height, In } } -static void PrintRectAlign(PrymPtr PNTR rect, Int2 k, Int2 color, Int2 height, Int2 index) -{ - Int2 l; - - for (l=0; l < k; l++) { - if (rect[l]->len <= 0) { - continue; - } - if (rect[l]->len-1 == 0) { - rect[l]->len++; - } - if (rect[l]->color == -1) { - printf("images/0.gif"); - printf(" width=%d>", rect[l]->len); - } else if (rect[l]->color == 3) { - if (rect[l+1]->color == rect[l]->color) { - printf("images/3.gif"); - printf(" width=%d", rect[l]->len); - } else { - printf("images/3.gif"); - printf(" width=%d>", rect[l]->len-1); - } - } else if (rect[l]->color == 0) { - if (rect[l+1] && rect[l+1]->color != -1) { - printf(" width=%d>", rect[l]->len-1); - } else { - printf(" width=%d>", rect[l]->len); - } - } else if (rect[l]->len > 0) { - if (rect[l+1]->color == rect[l]->color) { - if (index != -1) { - printf(" RECT:width=%d></a>", rect[l]->len); - } else { - printf(" RECT:width=%d>", rect[l]->len); - } - } else { - if (index != -1) { - printf(" RECT width=%d></a>", rect[l]->len-1); - } else { - printf("RECT width=%d>", rect[l]->len-1); - } - } - } - } -} - #define LOCAL_BUFLEN 255 static BioseqPtr @@ -2017,6 +1788,13 @@ static int get_sequence_type(char *querystr) /* If query starts with '>', then it is a FASTA with defline */ if (*querystr == '>') return FASTA_WITH_DEFLINE; + + /* If Entrez client is unavailable, accessions or gis cannot be entered, + so always treat sequence input as FASTA. */ +#ifndef NCBI_ENTREZ_CLIENT + return BARE_FASTA; +#endif + for (remainder = querystr; !IS_NEWLINE(*remainder); remainder++) ; length = remainder - querystr; @@ -2067,7 +1845,7 @@ static int get_sequence_type(char *querystr) //6. Returns pointer to the entered sequence(raw or accession) static char * GetAndFormatEnteredSequence(WWWBlastInfoPtr theInfo,int seqNbr,int *seq_type) { - CharPtr seq=NULL, c, chptr, sbuf; + CharPtr seq=NULL, c, chptr = NULL, sbuf; static Char seqEntryName[5],seqFileEntryName[9],blastReqEntryName[4]; @@ -2170,7 +1948,7 @@ Int2 Main(void) FloatHi expect; Boolean is_prot=FALSE, is_aa1=FALSE, is_aa2=FALSE, is_na1=TRUE, is_na2=TRUE; CharPtr seq_1=NULL, seq_2=NULL, chptr; - CharPtr sq_1=NULL, sq_2=NULL, sbuf, progname; + CharPtr sq_1=NULL, sq_2=NULL, progname; CharPtr accessionOrGi_1=NULL,accessionOrGi_2=NULL; CharPtr seq1EntryData, seq2EntryData; @@ -2183,7 +1961,7 @@ Int2 Main(void) BLAST_MatrixPtr blast_matrix = NULL; SeqPortPtr spp; Uint1 code1, code2; - ValNodePtr vnp, error_return=NULL; + ValNodePtr error_return=NULL; FloatHi scalex, scaley; DenseDiagPtr ddp; DenseSegPtr dsp; @@ -2197,7 +1975,6 @@ Int2 Main(void) Uint1 align_type; ValNodePtr other_returns, mask = NULL, mask_head = NULL; CharPtr buffer = NULL; - BLAST_KarlinBlkPtr ka_params=NULL, ka_gap_params=NULL; TxDfDbInfoPtr dbinfo = NULL; BlastTimeKeeper time_keeper; int seq_1_type = UNDEFINED_SEQ_TYPE, seq_2_type = UNDEFINED_SEQ_TYPE; @@ -2869,13 +2646,11 @@ Int2 Main(void) k = CreateRectAlign(sap, rect, rectY, scalex, scaley, len1, len2, color, from, ffrom, to, tto); DrawRectAlign(rect, k, color, 9, index); - /* PrintRectAlign(rect, k, color, 9, index);*/ printf("<BR>\n"); DrawRectAlign(rectY, k, color, 9, index); MemFree(rect); MemFree(rectY); - /* PrintRectAlign(rectY, k, color, 9, index);*/ printf("<BR><BR>\n"); index++; } @@ -3057,10 +2832,10 @@ Int2 Main(void) color = 1; index = 0; - printf("<font color=#FF0000>NOTE:</font>The statistics (bitscore and expect value) is calculated based on the size of nr database<BR><BR>\n"); + printf("<font color=#FF0000>NOTE:</font>Bitscore and expect value are calculated based on the size of the nr database.<BR><BR>\n"); if (align_type == blast_type_blastn) - printf("<font color=#FF0000>NOTE:</font>If protein translation is reversed, please repeat the search with reverse strand of the query sequence<BR><BR>\n"); + printf("<font color=#FF0000>NOTE:</font>If protein translation is reversed, please repeat the search with reverse strand of the query sequence.<BR><BR>\n"); for (sat=hsat; sat != NULL; sat=satnext) { satnext=sat->next; |